File size: 117,005 Bytes
049b896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00def04
049b896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from 'react';
import { ShieldCheck, PlusCircle, Settings, Users, FolderOpen, Trash2, Zap, Trophy, History, RefreshCw, Radio, Check, X, Award, MessageSquare, Newspaper, Flame } from 'lucide-react';
import { auth, db } from '../firebase';
import { collection, addDoc, getDocs, deleteDoc, doc, updateDoc, onSnapshot } from 'firebase/firestore';
import { Language } from '../translations';

interface AdminPanelProps {
  currentLanguage?: Language;
}

export const AdminPanel: React.FC<AdminPanelProps> = ({ currentLanguage = 'UZ' }) => {
  const isUz = currentLanguage === 'UZ';
  const isRu = currentLanguage === 'RU';

  // Inline localization helper
  const t = (en: string, uz: string, ru: string): string => {
    if (isUz) return uz;
    if (isRu) return ru;
    return en;
  };

  const currentEmail = auth.currentUser?.email || 'musabekqurbonov10@gmail.com';

  // State arrays fetched for management
  const [activeTab, setActiveTab] = useState<'database' | 'teams' | 'tournaments' | 'live' | 'results' | 'proleague' | 'feedbacks' | 'cybermatches'>('database');
  const [liveMatches, setLiveMatches] = useState<any[]>([]);
  const [teams, setTeams] = useState<any[]>([]);
  const [tournaments, setTournaments] = useState<any[]>([]);
  const [feedbacks, setFeedbacks] = useState<any[]>([]);
  const [cyberMatches, setCyberMatches] = useState<any[]>([]);
  const [news, setNews] = useState<any[]>([]);
  const [results, setResults] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [successMsg, setSuccessMsg] = useState<string>('');
  const [confirmModal, setConfirmModal] = useState<{
    title: string;
    message: string;
    onConfirm: () => void;
  } | null>(null);

  const askConfirm = (title: string, message: string, onConfirm: () => void) => {
    setConfirmModal({ title, message, onConfirm });
  };

  // Form states - Teams
  const [teamName, setTeamName] = useState('');
  const [teamTag, setTeamTag] = useState('');
  const [teamLogo, setTeamLogo] = useState('');
  const [teamGame, setTeamGame] = useState('mlbb');

  // Form states - Tournaments
  const [tourneyTitle, setTourneyTitle] = useState('');
  const [tourneyGame, setTourneyGame] = useState('mlbb');
  const [tourneyPrize, setTourneyPrize] = useState('$5,000');
  const [tourneySlots, setTourneySlots] = useState('16');
  const [tourneyFee, setTourneyFee] = useState('Free');
  const [tourneyImage, setTourneyImage] = useState('');

  // Form states - Live Matches
  const [liveTourneyName, setLiveTourneyName] = useState('');
  const [liveGame, setLiveGame] = useState('mlbb');
  const [liveTeamAName, setLiveTeamAName] = useState('');
  const [liveTeamALogo, setLiveTeamALogo] = useState('⚔️');
  const [liveTeamBName, setLiveTeamBName] = useState('');
  const [liveTeamBLogo, setLiveTeamBLogo] = useState('🛡️');
  const [liveStream, setLiveStream] = useState('https://www.youtube.com/embed/dQw4w9WgXcQ');

  // Form states - News Articles
  const [newsTitle, setNewsTitle] = useState('');
  const [newsSummary, setNewsSummary] = useState('');
  const [newsContent, setNewsContent] = useState('');
  const [newsImage, setNewsImage] = useState('');
  const [newsCategory, setNewsCategory] = useState('Pro Matches');

  // Form states - Cyber Matches (Schedule Taqvim)
  const [cyberGameName, setCyberGameName] = useState('Mobile Legends');
  const [cyberDateTime, setCyberDateTime] = useState('2026-06-25 18:00');
  const [cyberTeamAName, setCyberTeamAName] = useState('');
  const [cyberTeamALogo, setCyberTeamALogo] = useState('');
  const [cyberTeamBName, setCyberTeamBName] = useState('');
  const [cyberTeamBLogo, setCyberTeamBLogo] = useState('');
  const [cyberStatus, setCyberStatus] = useState<'upcoming' | 'live' | 'finished'>('upcoming');

  // Form states - Pro Liga
  const [proTeamName, setProTeamName] = useState('');
  const [proTeamTag, setProTeamTag] = useState('');
  const [proTeamLogo, setProTeamLogo] = useState('');
  const [proMatchesPlayed, setProMatchesPlayed] = useState(2);
  const [proMatchesWon, setProMatchesWon] = useState(1);
  const [proDraws, setProDraws] = useState(1);
  const [proLosses, setProLosses] = useState(0);
  const [proGoals, setProGoals] = useState('3-0');
  const [proPoints, setProPoints] = useState(4);
  const [proRank, setProRank] = useState(1);
  const [editingProTeamId, setEditingProTeamId] = useState<string | null>(null);

  // File Upload to Base64 utility helper
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>, setLogoState: (val: string) => void) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onloadend = () => {
      setLogoState(reader.result as string);
    };
    reader.readAsDataURL(file);
  };

  // Load matches & teams in real time for admin context
  useEffect(() => {
    const unsubLive = onSnapshot(collection(db, 'live_matches'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setLiveMatches(list);
    });

    const unsubTeams = onSnapshot(collection(db, 'teams'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setTeams(list);
    });

    const unsubTourneys = onSnapshot(collection(db, 'tournaments'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setTournaments(list);
    });

    const unsubFeedbacks = onSnapshot(collection(db, 'feedbacks'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setFeedbacks(list);
    });

    const unsubCyber = onSnapshot(collection(db, 'cyber_matches'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setCyberMatches(list);
    });

    const unsubNews = onSnapshot(collection(db, 'news'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setNews(list);
    });

    const unsubResults = onSnapshot(collection(db, 'results'), (snap) => {
      const list: any[] = [];
      snap.forEach(d => list.push({ id: d.id, ...d.data() }));
      setResults(list);
    });

    return () => {
      unsubLive();
      unsubTeams();
      unsubTourneys();
      unsubFeedbacks();
      unsubCyber();
      unsubNews();
      unsubResults();
    };
  }, []);

  const triggerToast = (msg: string) => {
    setSuccessMsg(msg);
    setTimeout(() => setSuccessMsg(''), 4000);
  };

  // Safe Wipe Database helper (Reset all database collections to 0 items)
  const handleWipeDatabase = async () => {
    askConfirm(
      t('Reset Database', 'Ma\'lumotlar bazasini tozalash', 'Сброс Базы Данных'),
      t(
        'Are you sure you want to CLEAR all results, teams, live matches, tournaments, brackets, and news? This action is irreversible!',
        'Haqiqatdan ham hamma natijalarni, jamoalarni va jonli o\'yinlarni TOZALAB 0 dan boshlamoqchimisiz? Ushbu amal qaytarilmaydi!',
        'Вы уверены, что хотите стереть все результаты, команды, живые матчи, турниры, турнирные сетки и новости? Это действие необратимо!'
      ),
      async () => {
        setLoading(true);
        try {
          // Wipe live matches
          const liveSnap = await getDocs(collection(db, 'live_matches'));
          for (const d of liveSnap.docs) {
            await deleteDoc(doc(db, 'live_matches', d.id));
          }

          // Wipe teams
          const teamSnap = await getDocs(collection(db, 'teams'));
          for (const d of teamSnap.docs) {
            await deleteDoc(doc(db, 'teams', d.id));
          }

          // Wipe tournaments
          const tourneySnap = await getDocs(collection(db, 'tournaments'));
          for (const d of tourneySnap.docs) {
            await deleteDoc(doc(db, 'tournaments', d.id));
          }

          // Wipe results
          const resSnap = await getDocs(collection(db, 'results'));
          for (const d of resSnap.docs) {
            await deleteDoc(doc(db, 'results', d.id));
          }

          // Wipe brackets
          const bracketSnap = await getDocs(collection(db, 'brackets'));
          for (const d of bracketSnap.docs) {
            await deleteDoc(doc(db, 'brackets', d.id));
          }

          // Wipe cyber matches
          const cyberSnap = await getDocs(collection(db, 'cyber_matches'));
          for (const d of cyberSnap.docs) {
            await deleteDoc(doc(db, 'cyber_matches', d.id));
          }

          // Wipe news
          const newsSnap = await getDocs(collection(db, 'news'));
          for (const d of newsSnap.docs) {
            await deleteDoc(doc(db, 'news', d.id));
          }

          triggerToast('Tizimdagi barcha ma\'lumotlar muvaffaqiyatli TOZALANDI. Hamma narsa 0 dan boshlandi!');
        } catch (e) {
          console.error(e);
          triggerToast('Ma\'lumotlarni o\'chirishda xatolik yuz berdi.');
        } finally {
          setLoading(false);
        }
      }
    );
  };

  // Seed Clean Starter Entities (Standard entries starting at score 0, win rate 0 etc.)
  const handleSeedStarters = async () => {
    setLoading(true);
    try {
      // 1. Seed tournaments (0 registered/fresh)
      const freshTourneys = [
        {
          title: 'Cyber Arena Pro MLBB Season 4',
          gameId: 'mlbb',
          gameTitle: 'Mobile Legends: Bang Bang',
          coverImage: 'https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=600&auto=format&fit=crop',
          category: 'team',
          prizePool: '$10,000',
          prizeDistribution: [
            { place: '1st Place', prize: '$5,000' },
            { place: '2nd Place', prize: '$3,000' },
            { place: '3rd Place', prize: '$2,000' }
          ],
          slotsTotal: 16,
          slotsFilled: 0,
          startDate: '2026-06-25',
          startTime: '18:00',
          status: 'upcoming',
          entryFee: 'Free',
          rules: ['Matches played v5 on active tournament draft rules.', 'Cheating is forbidden.'],
          requirements: ['Team registered dynamically.', 'No penalties active on member accounts.']
        },
        {
          title: 'Neon Rush Solo Aim Duel',
          gameId: 'valorant',
          gameTitle: 'Valorant',
          coverImage: 'https://images.unsplash.com/photo-1538481199705-c710c4e965fc?q=80&w=600&auto=format&fit=crop',
          category: 'solo',
          prizePool: '$3,500',
          prizeDistribution: [
            { place: '1st Place', prize: '$1,800' },
            { place: '2nd Place', prize: '$1,000' },
            { place: '3rd Place', prize: '$700' }
          ],
          slotsTotal: 32,
          slotsFilled: 0,
          startDate: '2026-06-29',
          startTime: '17:00',
          status: 'upcoming',
          entryFee: 'Free',
          rules: ['1v1 speed brackets, first to 10 points wins.'],
          requirements: ['Average account level 30 or higher.']
        }
      ];

      for (const t of freshTourneys) {
        await addDoc(collection(db, 'tournaments'), t);
      }

      // 2. Seed clean teams (starting from 0 wins, 0 losses, 0 points!)
      const freshTeams = [
        {
          name: 'Cyber Gladiator Elite',
          tag: 'CGE',
          logo: '🐉',
          rank: 1,
          winRate: 0,
          matchesPlayed: 0,
          matchesWon: 0,
          points: 0,
          gameType: 'mlbb',
          members: [
            { id: 'sm1', username: 'Sher_uzb', role: 'Captain', avatar: '🎮', country: 'UZ' },
            { id: 'sm2', username: 'Nurbek_Pro', role: 'Sniper', avatar: '🎯', country: 'UZ' }
          ]
        },
        {
          name: 'Tashkent Cyber Giants',
          tag: 'TCG',
          logo: '⚡',
          rank: 2,
          winRate: 0,
          matchesPlayed: 0,
          matchesWon: 0,
          points: 0,
          gameType: 'mlbb',
          members: [
            { id: 'sm3', username: 'Alisher99', role: 'Captain', avatar: '🧙‍♂️', country: 'UZ' },
            { id: 'sm4', username: 'Doniyor_ML', role: 'Carry', avatar: '🐉', country: 'UZ' }
          ]
        },
        {
          name: 'Apex Stars Navoiy',
          tag: 'ASN',
          logo: '🦊',
          rank: 3,
          winRate: 0,
          matchesPlayed: 0,
          matchesWon: 0,
          points: 0,
          gameType: 'valorant',
          members: [
            { id: 'sm5', username: 'Nav_Sniper', role: 'Captain', avatar: '🥷', country: 'UZ' }
          ]
        }
      ];

      for (const team of freshTeams) {
        await addDoc(collection(db, 'teams'), team);
      }

      // 3. Seed starter live match (0-0, real-time ready)
      const starterLive = {
        tournamentTitle: 'Desert Strike Pro League UZ',
        gameId: 'mlbb',
        teamA: { name: 'Cyber Gladiator Elite', logo: '🐉', score: 0 },
        teamB: { name: 'Tashkent Cyber Giants', logo: '⚡', score: 0 },
        status: 'live',
        time: 'Round 1 - Bo3 Series',
        streamUrl: 'https://www.youtube.com/embed/dQw4w9WgXcQ'
      };

      await addDoc(collection(db, 'live_matches'), starterLive);

      triggerToast('Boshlang\'ich toza ma\'lumotlar yuklandi! Hamma narsa 0 natija va ko\'rsatgichlar bilan yoqildi.');
    } catch (e) {
      console.error(e);
      triggerToast('Ma\'lumotlarni yuborishda xatolik yuz berdi.');
    } finally {
      setLoading(false);
    }
  };

  // Add / Edit Pro Liga team handler
  const handleAddProTeam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!proTeamName) return;
    setLoading(true);
    try {
      const payload = {
        name: proTeamName,
        tag: (proTeamTag || proTeamName.substring(0, 3)).toUpperCase(),
        logo: proTeamLogo || '🟢',
        rank: Number(proRank) || 1,
        winRate: Number(proMatchesPlayed) > 0 ? Math.round((Number(proMatchesWon) / Number(proMatchesPlayed)) * 100) : 0,
        matchesPlayed: Number(proMatchesPlayed) || 0,
        matchesWon: Number(proMatchesWon) || 0,
        draws: Number(proDraws) || 0,
        losses: Number(proLosses) || 0,
        goals: proGoals || '0-0',
        points: Number(proPoints) || 0,
        gameType: 'pro_league',
        members: []
      };

      if (editingProTeamId) {
        await updateDoc(doc(db, 'teams', editingProTeamId), payload);
        triggerToast(`"${proTeamName}" jamoasi muvaffaqiyatli yangilandi!`);
        setEditingProTeamId(null);
      } else {
        await addDoc(collection(db, 'teams'), payload);
        triggerToast(`"${proTeamName}" jamoasi muvaffaqiyatli ro'yxatga olindi!`);
      }

      // Reset
      setProTeamName('');
      setProTeamTag('');
      setProTeamLogo('🟢');
      setProMatchesPlayed(2);
      setProMatchesWon(1);
      setProDraws(1);
      setProLosses(0);
      setProGoals('3-0');
      setProPoints(4);
      setProRank(1);
    } catch (err) {
      console.error(err);
      triggerToast('Tizimda saqlash jarayonida muammo yuz berdi.');
    } finally {
      setLoading(false);
    }
  };

  // Seed default 10 teams based exactly on the image
  const handleSelfSeedProLiga = async () => {
    setLoading(true);
    try {
      // Clear out any existing pro_league teams to avoid duplicates
      const snap = await getDocs(collection(db, 'teams'));
      for (const d of snap.docs) {
        if (d.data().gameType === 'pro_league') {
          await deleteDoc(doc(db, 'teams', d.id));
        }
      }

      const defaultProLiga = [
        { name: 'Neftchi', logo: '🟢', tag: 'NEF', rank: 1, matchesPlayed: 2, matchesWon: 1, draws: 1, losses: 0, goals: '3-0', points: 4, gameType: 'pro_league', members: [] },
        { name: 'Aral Samali', logo: '🔴', tag: 'ARS', rank: 2, matchesPlayed: 2, matchesWon: 1, draws: 1, losses: 0, goals: '4-2', points: 4, gameType: 'pro_league', members: [] },
        { name: 'Xorazm', logo: '🔵', tag: 'XOR', rank: 3, matchesPlayed: 2, matchesWon: 1, draws: 1, losses: 0, goals: '3-2', points: 4, gameType: 'pro_league', members: [] },
        { name: 'Olimpik', logo: '🟡', tag: 'OLI', rank: 4, matchesPlayed: 2, matchesWon: 1, draws: 1, losses: 0, goals: '2-1', points: 4, gameType: 'pro_league', members: [] },
        { name: 'Dinamo', logo: '🔵', tag: 'DIN', rank: 5, matchesPlayed: 1, matchesWon: 1, draws: 0, losses: 0, goals: '2-1', points: 3, gameType: 'pro_league', members: [] },
        { name: 'Buxoro', logo: '🔵', tag: 'BUX', rank: 6, matchesPlayed: 1, matchesWon: 1, draws: 0, losses: 0, goals: '2-1', points: 3, gameType: 'pro_league', members: [] },
        { name: 'Istiqlol', logo: '🔴', tag: 'IST', rank: 7, matchesPlayed: 1, matchesWon: 0, draws: 0, losses: 1, goals: '1-2', points: 0, gameType: 'pro_league', members: [] },
        { name: 'Oq-tepa', logo: '⚪', tag: 'OQT', rank: 8, matchesPlayed: 2, matchesWon: 0, draws: 0, losses: 2, goals: '2-4', points: 0, gameType: 'pro_league', members: [] },
        { name: 'Shurtan', logo: '⚪', tag: 'SHU', rank: 9, matchesPlayed: 1, matchesWon: 0, draws: 0, losses: 1, goals: '1-3', points: 0, gameType: 'pro_league', members: [] },
        { name: 'Yangiyer', logo: '🔴', tag: 'YAN', rank: 10, matchesPlayed: 2, matchesWon: 0, draws: 0, losses: 2, goals: '1-5', points: 0, gameType: 'pro_league', members: [] },
      ];

      for (const t of defaultProLiga) {
        await addDoc(collection(db, 'teams'), t);
      }

      triggerToast("Rasmda keltirilgan 10 ta jamoa va statistikalari real vaqtda yaratildi!");
    } catch (err) {
      console.error(err);
      triggerToast('Ma\'lumotlarni yuklashda xatolik.');
    } finally {
      setLoading(false);
    }
  };

  // Add customized Team Franchise
  const handleAddTeam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!teamName || !teamTag) return;
    setLoading(true);
    try {
      await addDoc(collection(db, 'teams'), {
        name: teamName,
        tag: teamTag.toUpperCase(),
        logo: teamLogo,
        rank: teams.length + 1,
        winRate: 0,
        matchesPlayed: 0,
        matchesWon: 0,
        points: 0,
        gameType: teamGame,
        members: [
          { id: 'm-' + Date.now(), username: 'Admin_Recruit', role: 'Member', avatar: '👨‍🎤', country: 'UZ' }
        ]
      });

      triggerToast(`"${teamName}" jamoasi muvaffaqiyatli qo'shildi! Ko'rsatgichlari: 0 wins / Played.`);
      setTeamName('');
      setTeamTag('');
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // Add customized Tournament
  const handleAddTournament = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!tourneyTitle) return;
    setLoading(true);
    try {
      const gameLabels: Record<string, string> = {
        mlbb: 'Mobile Legends: Bang Bang',
        valorant: 'Valorant',
        cs2: 'Counter-Strike 2',
        lol: 'League of Legends',
        pubgm: 'PUBG Mobile'
      };

      const cleanedAmt = String(tourneyPrize).replace(/[^0-9]/g, '');
      const numPrize = isNaN(parseInt(cleanedAmt, 10)) ? 1000 : parseInt(cleanedAmt, 10);
      const generatedDist = [
        { place: '1st Place', prize: `$${Math.round(numPrize * 0.5).toLocaleString()}` },
        { place: '2nd Place', prize: `$${Math.round(numPrize * 0.3).toLocaleString()}` },
        { place: '3rd Place', prize: `$${Math.round(numPrize * 0.2).toLocaleString()}` }
      ];

      await addDoc(collection(db, 'tournaments'), {
        title: tourneyTitle,
        gameId: tourneyGame,
        gameTitle: gameLabels[tourneyGame] || 'Esports Game',
        coverImage: tourneyImage || 'https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=600&auto=format&fit=crop',
        category: 'team',
        prizePool: tourneyPrize,
        prizeDistribution: generatedDist,
        slotsTotal: Number(tourneySlots),
        slotsFilled: 0,
        startDate: new Date().toLocaleDateString('en-CA'),
        startTime: '19:00',
        status: 'upcoming',
        entryFee: tourneyFee,
        rules: ['Matches played on default maps.', 'Fair play mandatory.'],
        requirements: ['Registered squad on active season.']
      });

      triggerToast(`"${tourneyTitle}" turniri 0/0 ishtirokchi bilan rejalashtirildi!`);
      setTourneyTitle('');
      setTourneyImage('');
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  // Schedule / Start Live Match
  const handleAddLiveMatch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!liveTeamAName || !liveTeamBName) return;
    setLoading(true);
    try {
      await addDoc(collection(db, 'live_matches'), {
        tournamentTitle: liveTourneyName || 'Cyber Championship Season 4',
        gameId: liveGame,
        teamA: { name: liveTeamAName, logo: liveTeamALogo, score: 0 },
        teamB: { name: liveTeamBName, logo: liveTeamBLogo, score: 0 },
        status: 'live',
        time: 'Bo3 Series - Round 1',
        streamUrl: liveStream
      });

      triggerToast(`"${liveTeamAName}" vs "${liveTeamBName}" jonli matchi muvaffaqiyatli yoqildi!`);
      setLiveTeamAName('');
      setLiveTeamBName('');
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };



  // Add cyber matches to calendar/schedule taqvim
  const handleAddCyberMatch = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!cyberTeamAName || !cyberTeamBName) return;
    setLoading(true);
    try {
      await addDoc(collection(db, 'cyber_matches'), {
        gameName: cyberGameName,
        dateTime: cyberDateTime,
        teamA: { name: cyberTeamAName, logo: cyberTeamALogo || '🛡️', votes: 0 },
        teamB: { name: cyberTeamBName, logo: cyberTeamBLogo || '⚔️', votes: 0 },
        status: cyberStatus
      });

      triggerToast(t('New scheduled match added!', 'Yangi o\'yin taqvimga muvaffaqiyatli qo\'shildi!', 'Новый матч успешно добавлен в расписание!'));
      setCyberTeamAName('');
      setCyberTeamBName('');
      setCyberTeamALogo('');
      setCyberTeamBLogo('');
    } catch (err) {
      console.error(err);
      triggerToast('Xatolik yuz berdi.');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteCyberMatch = async (id: string) => {
    // Optimistic UI update: remove item instantly from local state
    setCyberMatches(prev => prev.filter(match => match.id !== id));
    try {
      await deleteDoc(doc(db, 'cyber_matches', id));
      triggerToast(t('Match deleted successfully.', 'O\'yin taqvimdan muvaffaqiyatli o\'chirildi.', 'Матч успешно удален.'));
    } catch (err) {
      console.error(err);
      triggerToast('O\'yinni o\'chirishda xatolik.');
    }
  };

  // Add news articles
  const handleAddNews = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newsTitle || !newsContent) return;
    setLoading(true);
    try {
      await addDoc(collection(db, 'news'), {
        title: newsTitle,
        summary: newsSummary || newsContent.slice(0, 100) + '...',
        content: newsContent,
        image: newsImage || 'https://images.unsplash.com/photo-1542751371-adc38448a05e?q=80&w=800&auto=format&fit=crop',
        category: newsCategory,
        publishedAt: new Date().toISOString().split('T')[0],
        views: Math.floor(Math.random() * 80) + 12
      });

      triggerToast(t('News article published!', 'Yangi yangilik muvaffaqiyatli chop etildi!', 'Новость успешно опубликована!'));
      setNewsTitle('');
      setNewsSummary('');
      setNewsContent('');
      setNewsImage('');
    } catch (err) {
      console.error(err);
      triggerToast('Yangilik chop etishda xatolik yuz berdi.');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteNews = async (id: string) => {
    // Optimistic UI update: remove item instantly from local state
    setNews(prev => prev.filter(item => item.id !== id));
    try {
      await deleteDoc(doc(db, 'news', id));
      triggerToast(t('News deleted successfully.', 'Yangilik muvaffaqiyatli o\'chirildi.', 'Новость успешно удалена.'));
    } catch (err) {
      console.error(err);
      triggerToast('Yangilikni o\'chirishda xatolik.');
    }
  };

  // Scoreboard Adjustments inside Live Match Director
  const handleUpdateLiveScore = async (matchId: string, team: 'A' | 'B', change: number, matchData: any) => {
    try {
      const matchDocRef = doc(db, 'live_matches', matchId);
      const scoreA = matchData.teamA?.score || 0;
      const scoreB = matchData.teamB?.score || 0;

      if (team === 'A') {
         const nextScore = Math.max(0, scoreA + change);
         await updateDoc(matchDocRef, { 'teamA.score': nextScore });
      } else {
         const nextScore = Math.max(0, scoreB + change);
         await updateDoc(matchDocRef, { 'teamB.score': nextScore });
      }
    } catch (err) {
      console.error(err);
    }
  };

  // Complete & Settle live match (Moves to 'results' and deletes from 'live_matches')
  const handleSettleLiveMatch = async (match: any) => {
    const scoreA = match.teamA?.score || 0;
    const scoreB = match.teamB?.score || 0;
    askConfirm(
      t('Settle Match', 'Matchni yakunlash', 'Завершить Матч'),
      `Ushbu jonli matchni hisob ${scoreA}-${scoreB} bilan yakunlab, turnir natijalariga qo'shishni tasdiqlaysizmi?`,
      async () => {
        setLoading(true);
        try {
          // Log to Completed Results collection
          await addDoc(collection(db, 'results'), {
            tournament: match.tournamentTitle || 'Cyber Arena Pro',
            game: match.gameId === 'mlbb' ? 'Mobile Legends' : match.gameId === 'valorant' ? 'Valorant' : 'PUBG Mobile',
            stage: match.time || 'Final Series',
            date: new Date().toLocaleDateString('uz-UZ'),
            teamA: { 
              name: match.teamA?.name || 'Team A', 
              logo: match.teamA?.logo || '⚔️', 
              score: scoreA, 
              isWinner: scoreA > scoreB 
            },
            teamB: { 
              name: match.teamB?.name || 'Team B', 
              logo: match.teamB?.logo || '🛡️', 
              score: scoreB, 
              isWinner: scoreB > scoreA 
            }
          });

          // Remove from live queue
          await deleteDoc(doc(db, 'live_matches', match.id));

          triggerToast('Jonli match yakunlandi va natijalarga ketma-ket qo\'shildi!');
        } catch (err) {
          console.error(err);
        } finally {
          setLoading(false);
        }
      }
    );
  };

  // Remove individual elements
  const handleDeleteItem = async (col: string, id: string) => {
    // Perform instant optimistic updates to local state
    if (col === 'teams') {
      setTeams(prev => prev.filter(x => x.id !== id));
    } else if (col === 'live_matches') {
      setLiveMatches(prev => prev.filter(x => x.id !== id));
    } else if (col === 'tournaments') {
      setTournaments(prev => prev.filter(x => x.id !== id));
    } else if (col === 'feedbacks') {
      setFeedbacks(prev => prev.filter(x => x.id !== id));
    } else if (col === 'results') {
      setResults(prev => prev.filter(x => x.id !== id));
    }

    try {
      await deleteDoc(doc(db, col, id));
      triggerToast(t('Element deleted successfully.', 'Element muvaffaqiyatli o\'chirildi.', 'Элемент успешно удален.'));
    } catch (err) {
      console.error(err);
      triggerToast('O\'chirishda xatolik yuz berdi.');
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 py-8 space-y-8 font-sans w-full text-left self-start" id="admin-panel-premium">
      
      {/* Toast Notification */}
      {successMsg && (
        <div className="fixed top-8 right-8 z-50 bg-emerald-500 border border-emerald-400 text-white px-6 py-4 rounded-xl shadow-xl flex items-center gap-2 animate-in slide-in-from-top-4 duration-300">
          <Check className="w-5 h-5 text-white bg-emerald-600 rounded-full p-0.5" />
          <span className="text-xs font-bold uppercase tracking-wider">{successMsg}</span>
        </div>
      )}

      {/* Admin Head Deck */}
      <div className="bg-[#0b0c14]/80 border border-cyan-500/10 p-6 rounded-2xl flex flex-col lg:flex-row lg:items-center justify-between gap-6 relative overflow-hidden backdrop-blur-md">
        <div className="absolute top-0 right-0 w-80 h-80 bg-cyan-500/5 rounded-full blur-3xl pointer-events-none" />
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 bg-cyan-950/40 text-cyan-400 rounded-xl flex items-center justify-center border border-cyan-500/20 shadow">
            <ShieldCheck className="w-6 h-6 animate-pulse text-cyan-400" />
          </div>
          <div>
            <h2 className="text-sm font-mono font-black text-cyan-400 uppercase tracking-widest flex items-center gap-1.5">
              <span>{t("SECURITY PROTOCOL 1.0", "XAVFSIZLIK PROTOKOLI 1.0", "ПРОТОКОЛ БЕЗОПАСНОСТИ 1.0")}</span>
              <span className="w-2 h-2 rounded-full bg-emerald-400 animate-ping" />
            </h2>
            <p className="text-white text-xs mt-0.5">
              {t("Logged in: ", "Tizimga kirgan: ", "Авторизован: ")} <strong className="text-cyan-300 font-mono font-medium">{currentEmail}</strong>
            </p>
          </div>
        </div>

        {/* Global Tab Deck inside Admin only */}
        <div className="flex flex-wrap gap-1 bg-white/5 p-1 rounded-xl border border-white/5 text-[11px] font-mono font-bold">
          <button
            onClick={() => setActiveTab('database')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'database' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Settings className="w-3.5 h-3.5" /> {t("Core Database", "Asosiy Baza", "Основная БД")}
          </button>
          <button
            onClick={() => setActiveTab('teams')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'teams' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Users className="w-3.5 h-3.5" /> {t("Teams", "Jamoalar", "Команды")} ({teams.length})
          </button>
          <button
            onClick={() => setActiveTab('tournaments')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'tournaments' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Trophy className="w-3.5 h-3.5" /> {t("Tourneys", "Turnirlar", "Турниры")} ({tournaments.length})
          </button>
          <button
            onClick={() => setActiveTab('live')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'live' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Radio className="w-3.5 h-3.5" /> {t("Live Matches", "Jonli Matchlar", "Матчи Live")} ({liveMatches.length})
          </button>
          <button
            onClick={() => setActiveTab('cybermatches')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'cybermatches' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Radio className="w-3.5 h-3.5 text-pink-400" /> {t("Match Calendar", "O'yinlar Taqvimi", "Календарь Игр")} ({cyberMatches.length})
          </button>
          <button
            onClick={() => setActiveTab('results')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'results' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Newspaper className="w-3.5 h-3.5 text-cyan-400" /> {t("News & Results", "Yangiliklar & Natijalar", "Новости и Результаты")} ({news.length + results.length})
          </button>
          <button
            onClick={() => setActiveTab('proleague')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'proleague' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <Award className="w-3.5 h-3.5 text-purple-400" /> {t("Pro Liga", "Pro Liga", "Про-Лига")} ({teams.filter(t => t.gameType === 'pro_league' || t.gameType === 'pro').length})
          </button>
          <button
            onClick={() => setActiveTab('feedbacks')}
            className={`px-3 py-1.5 rounded transition-all cursor-pointer flex items-center gap-1 ${
              activeTab === 'feedbacks' ? 'bg-cyan-600/80 text-white border border-cyan-500/20' : 'text-slate-400 hover:text-slate-250'
            }`}
          >
            <MessageSquare className="w-3.5 h-3.5 text-amber-400" /> {t("Feedback", "Fikr-mulohazalar", "Отзывы")} ({feedbacks.length})
          </button>
        </div>
      </div>

      {/* CORE DATABASE WIPE & SEED UTILITIES */}
      {activeTab === 'database' && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 animate-in fade-in duration-300">
          
          <div className="bg-[#0b0c14]/40 border border-white/5 rounded-2xl p-6 space-y-4">
            <h3 className="text-sm font-bold text-white uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Trash2 className="w-4 h-4 text-red-400" /> {t("Database Reset Control (Wipe to 0)", "Baza Ma'lumotlarini Tozalash (0 gacha)", "Сброс Базы Данных (до 0)")}
            </h3>
            <p className="text-xs text-slate-400 leading-relaxed">
              Tizimdagi barcha natijalar, jamoalar va live oʻyinlarni butunlay tozalash. Hamma narsani 0 dan boshlash uchun ushbu tugmani bosing. Bu foydalanuvchi interfeysidagi barcha ma'lumotlarni mutlaqo bo'sh holga keltiradi.
            </p>
            <div className="pt-2">
              <button
                disabled={loading}
                onClick={handleWipeDatabase}
                className="w-full sm:w-auto px-6 py-3 bg-red-950/40 hover:bg-red-900/60 text-red-300 border border-red-500/30 rounded-xl text-xs font-black uppercase tracking-wider font-mono cursor-pointer transition-all disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {loading ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
                {t("WIPE DATABASE TO 0 (Tizimni Tozalash)", "BAZANI MUTLAQ TOZALASH (0 GA)", "ОЧИСТИТЬ ВСЮ БД ДО 0")}
              </button>
            </div>
          </div>

          <div className="bg-[#0b0c14]/40 border border-white/5 rounded-2xl p-6 space-y-4">
            <h3 className="text-sm font-bold text-white uppercase tracking-wider font-mono flex items-center gap-1.5">
              <Zap className="w-4 h-4 text-cyan-400" /> {t("Seeding Starters Utility", "Boshlang'ich Ma'lumotlarni Yuklash", "Загрузить Начальные Данные")}
            </h3>
            <p className="text-xs text-slate-400 leading-relaxed">
              Ma'lumotlar o'chirilgandan so'ng yoki tajriba qilish uchun tizimga 0 balli yangi boshlangʻich jamoalar turnirlar va 1 ta live oʻyinni bir bosishda qoʻshadi. O'zbekiston kiber arenalari baseline statistikalari uchun moslangan.
            </p>
            <div className="pt-2">
              <button
                disabled={loading}
                onClick={handleSeedStarters}
                className="w-full sm:w-auto px-6 py-3 bg-cyan-950/40 hover:bg-cyan-900/40 text-cyan-300 border border-cyan-500/30 rounded-xl text-xs font-black uppercase tracking-wider font-mono cursor-pointer transition-all disabled:opacity-50 flex items-center justify-center gap-2 animate-pulse"
              >
                {loading ? <RefreshCw className="w-4 h-4 animate-spin" /> : <PlusCircle className="w-4 h-4" />}
                {t("LOAD SEED STARTERS (0 MATCHES/fresh structures)", "BOSHLANG'ICH TARKIBLARNI YUKLASH", "ЗАГРУЗИТЬ СТАРТОВЫЕ ДАННЫЕ")}
              </button>
            </div>
          </div>

        </div>
      )}

      {/* TEAM MANAGEMENT */}
      {activeTab === 'teams' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Add team panel */}
          <form onSubmit={handleAddTeam} className="lg:col-span-5 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4">
            <h3 className="text-xs font-black text-cyan-400 uppercase tracking-widest font-mono">
              🛡️ {t("Register New Team Franchise", "Yangi Jamoa Franshizasini Ro'yxatdan O'tkazish", "Регистрация Новой Франшизы")}
            </h3>

            <div className="space-y-1.5 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("FRANCHISE NAME", "FRANSHIZA NOMI", "НАЗВАНИЕ ФРАНШИЗЫ")}</label>
              <input
                type="text"
                value={teamName}
                onChange={e => setTeamName(e.target.value)}
                placeholder="e.g. Tashkent Wolves"
                className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50 uppercase"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("TAG PREFIX", "TAG PREFIKSI", "ПРЕФИКС ТЕГА")}</label>
                <input
                  type="text"
                  maxLength={4}
                  value={teamTag}
                  onChange={e => setTeamTag(e.target.value)}
                  placeholder="e.g. TW"
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50 uppercase"
                  required
                />
              </div>
            </div>

            <div className="space-y-3 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("TEAM LOGO (DEVICE UPLOAD)", "JAMOA LOGOTIPI (QURILMADAN YUKLASH)", "ЛОГОТИП КОМАНДЫ (С УСТРОЙСТВА)")}</label>
              <label className="relative flex items-center justify-center border border-dashed border-cyan-500/30 hover:border-cyan-500 bg-cyan-500/5 hover:bg-cyan-500/10 rounded-xl py-3 px-4 cursor-pointer transition-all h-[44px] overflow-hidden group">
                <input
                  type="file"
                  accept="image/*"
                  onChange={e => handleImageUpload(e, setTeamLogo)}
                  className="hidden"
                />
                <div className="flex items-center gap-1.5 text-cyan-400 group-hover:text-cyan-300">
                  <PlusCircle className="w-4 h-4" />
                  <span className="font-bold text-xs uppercase tracking-wider">{t("UPLOAD FILE", "RASM TANLASH", "ВЫБРАТЬ ФАЙЛ")}</span>
                </div>
              </label>

              {teamLogo && (
                <div className="mt-2 bg-black/45 border border-white/5 rounded-xl p-3 flex items-center justify-between gap-3">
                  <div className="flex items-center gap-2">
                    <span className="text-slate-400 text-[10px] uppercase font-mono">{t("Active Logo:", "Hozirgi logo:", "Выбранный логотип:")}</span>
                    <div className="w-10 h-10 rounded-lg bg-[#020205] border border-white/10 p-1 flex items-center justify-center shrink-0">
                      {teamLogo.startsWith('data:') || teamLogo.startsWith('http') ? (
                        <img src={teamLogo} className="w-full h-full object-contain" alt="" />
                      ) : (
                        <span className="text-lg">{teamLogo}</span>
                      )}
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => setTeamLogo('🛡️')}
                    className="p-1 px-2.5 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 text-[9px] rounded hover:text-red-300 transition-colors uppercase font-mono tracking-widest cursor-pointer"
                  >
                    {t("Reset", "Dastlabki", "Сбросить")}
                  </button>
                </div>
              )}
            </div>

            <div className="space-y-1.5 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("SPORT GAME TYPE", "KIBERSPORT O'YINI TURI", "ТИП ИГРЫ")}</label>
              <select
                value={teamGame}
                onChange={e => setTeamGame(e.target.value)}
                className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
              >
                <option value="mlbb">Mobile Legends (MLBB)</option>
                <option value="valorant">Valorant</option>
                <option value="cs2">Counter-Strike 2</option>
                <option value="lol">League of Legends</option>
              </select>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 bg-cyan-600 hover:bg-cyan-500 text-white text-xs font-bold uppercase tracking-wider rounded-xl cursor-pointer shadow transition-all active:scale-95 flex items-center justify-center gap-1"
            >
              <PlusCircle className="w-4 h-4" /> {t("REGISTER FRANCHISE", "FRANSHIZANI RO'YXATDAN O'TKAZISH", "ЗАРЕГИСТРИРОВАТЬ ФРАНШИЗУ")}
            </button>
          </form>

          {/* List existing teams */}
          <div className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/5 rounded-2xl overflow-hidden shadow-lg">
            <div className="p-4 bg-white/5 border-b border-white/5">
              <h4 className="text-xs font-bold text-white uppercase tracking-wider font-mono">
                {t("Active Rosters / Franchises Ledger", "Tizimdagi Faol Jamoalar / Franshizalar Reyestri", "Реестр Активных Франшиз")}
              </h4>
            </div>

            <div className="p-4">
              {teams.length === 0 ? (
                <div className="text-center py-8 text-slate-500 text-xs font-mono">JAMOALAR RO'YXATI BO'SH. MA'LUMOTLAR 0 DAN BOSHLANGAN.</div>
              ) : (
                <div className="divide-y divide-white/5 max-h-[400px] overflow-y-auto">
                  {teams.map(team => (
                    <div key={team.id} className="py-3 flex justify-between items-center text-xs">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-lg bg-black/40 border border-white/10 flex items-center justify-center overflow-hidden">
                          {team.logo && (team.logo.startsWith('data:') || team.logo.startsWith('http')) ? (
                            <img src={team.logo} className="w-full h-full object-contain" alt="" />
                          ) : (
                            <span className="text-lg">{team.logo || "🎮"}</span>
                          )}
                        </div>
                        <div>
                          <strong className="text-white uppercase tracking-wide">{team.name}</strong>
                          <span className="text-[9px] text-slate-450 text-cyan-400 font-mono block uppercase">{t("Game: ", "O'yin: ", "Игра: ")}{team.gameType} | PTS: {team.points || 0}</span>
                        </div>
                      </div>
                      <button
                        onClick={() => handleDeleteItem('teams', team.id)}
                        className="p-1 px-2.5 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 text-[10px] rounded hover:text-red-300 transition-colors uppercase font-mono tracking-widest cursor-pointer"
                      >
                        {t("Delete", "O'chirish", "Удалить")}
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

        </div>
      )}

      {/* TOURNAMENT MANAGEMENT */}
      {activeTab === 'tournaments' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Add tournament */}
          <form onSubmit={handleAddTournament} className="lg:col-span-5 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4">
            <h3 className="text-xs font-black text-cyan-400 uppercase tracking-widest font-mono">
              🏆 {t("Release Tournament Draft (0 Registered)", "Yangi Turnir Reyestrini Chiqarish", "Создать Черновик Турнира")}
            </h3>

            <div className="space-y-1.5 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("TOURNAMENT TITLE", "TURNIR NOMI", "НАЗВАНИЕ ТУРНИРА")}</label>
              <input
                type="text"
                value={tourneyTitle}
                onChange={e => setTourneyTitle(e.target.value)}
                placeholder="e.g. Cyber Cup Uzbekistan 2026"
                className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50 uppercase"
                required
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("DISCIPLINE", "YO'NALISH (O'YIN)", "ДИСЦИПЛИНА")}</label>
                <select
                  value={tourneyGame}
                  onChange={e => setTourneyGame(e.target.value)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
                >
                  <option value="mlbb">MLBB</option>
                  <option value="valorant">Valorant</option>
                  <option value="cs2">CS2</option>
                  <option value="lol">LoL</option>
                  <option value="pubgm">PUBG Mobile</option>
                </select>
              </div>

              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("PRIZE POOL", "MUKOFOT JAMG'ARMASI", "ПРИЗОВОЙ ФОНД")}</label>
                <input
                  type="text"
                  value={tourneyPrize}
                  onChange={e => setTourneyPrize(e.target.value)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50"
                  required
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("SLOTS LIMIT", "SLOTLAR CHEKLOVI", "ЛИМИТ СЛОТОВ")}</label>
                <input
                  type="text"
                  value={tourneySlots}
                  onChange={e => setTourneySlots(e.target.value)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50"
                  required
                />
              </div>

              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("ENTRY FEE", "KIRISH TO'LOVI", "ВЗНОС")}</label>
                <input
                  type="text"
                  value={tourneyFee}
                  onChange={e => setTourneyFee(e.target.value)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none focus:border-cyan-500/50"
                  required
                />
              </div>
            </div>

            <div className="space-y-1.5 text-left font-mono">
              <label className="text-[10px] text-slate-400 font-bold uppercase">{t("TOURNAMENT COVER IMAGE (DEVICE)", "TURNIR MUQOVASI RASMI (QURILMADAN)", "ОБЛОЖКА ТУРНИРА (С УСТРОЙСТВА)")}</label>
              
              <label className="relative flex items-center justify-center border border-dashed border-cyan-500/30 hover:border-cyan-500 bg-cyan-500/5 hover:bg-cyan-500/10 rounded-xl py-3 px-3 cursor-pointer transition-all h-[44px] overflow-hidden group">
                <input
                  type="file"
                  accept="image/*"
                  onChange={e => handleImageUpload(e, setTourneyImage)}
                  className="hidden"
                />
                <div className="flex items-center gap-1.5 text-cyan-400 group-hover:text-cyan-300">
                  <PlusCircle className="w-4 h-4" />
                  <span className="font-bold text-[10px] uppercase tracking-wider">{t("UPLOAD COVER IMAGE", "QURILMADAN RASM YUKLASH", "ЗАГРУЗИТЬ ОБЛОЖКУ")}</span>
                </div>
              </label>

              {tourneyImage && (
                <div className="relative h-24 w-full rounded-xl overflow-hidden bg-[#020205] border border-white/10 mt-2">
                  <img src={tourneyImage} className="w-full h-full object-cover" alt="" />
                  <button
                    type="button"
                    onClick={() => setTourneyImage('')}
                    className="absolute top-2 right-2 p-1.5 rounded-full bg-black/80 text-red-400 hover:text-red-500 hover:bg-black transition-colors cursor-pointer border border-white/5"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                </div>
              )}
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 bg-cyan-600 hover:bg-cyan-500 text-white text-xs font-bold uppercase tracking-wider rounded-xl cursor-pointer shadow transition-all active:scale-95 flex items-center justify-center gap-1"
            >
              <PlusCircle className="w-4 h-4" /> {t("PLOT UPCOMING TOURNAMENT", "REJALASHTIRILGAN TURNIRNI CHIQARISH", "ОПУБЛИКОВАТЬ ТУРНИР")}
            </button>
          </form>

          {/* List tournaments */}
          <div className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/5 rounded-2xl overflow-hidden shadow-lg">
            <div className="p-4 bg-white/5 border-b border-white/5">
              <h4 className="text-xs font-bold text-white uppercase tracking-wider font-mono">
                {t("Drafted Upcoming & Ended Tourneys", "Rejalashtirilgan Kelgusi va Yakunlangan Turnirlar", "Запланированные и Завершенные Турниры")}
              </h4>
            </div>
            <div className="p-4">
              {tournaments.length === 0 ? (
                <div className="text-center py-8 text-slate-500 text-xs font-mono">TURNIRLAR RO'YXATI BO'SH. MA'LUMOTLAR 0 DAN BOSHLANGAN.</div>
              ) : (
                <div className="divide-y divide-white/5 max-h-[400px] overflow-y-auto">
                  {tournaments.map(tourney => (
                    <div key={tourney.id} className="py-3 flex justify-between items-center text-xs">
                      <div>
                        <strong className="text-white uppercase tracking-wide block truncate max-w-[280px]">{tourney.title}</strong>
                        <span className="text-[9px] text-cyan-400 font-mono block uppercase">{t("Game: ", "O'yin: ", "Игра: ")}{tourney.gameTitle} | Fee: {tourney.entryFee} | Max: {tourney.slotsTotal} Slots</span>
                      </div>
                      <button
                        onClick={() => handleDeleteItem('tournaments', tourney.id)}
                        className="p-1 px-2.5 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 text-[10px] rounded hover:text-red-300 transition-colors uppercase font-mono tracking-widest cursor-pointer"
                      >
                        {t("Delete", "O'chirish", "Удалить")}
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

        </div>
      )}

      {/* LIVE MATCHES MANAGEMENT */}
      {activeTab === 'live' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Add live match */}
          <form onSubmit={handleAddLiveMatch} className="lg:col-span-5 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4">
            <h3 className="text-xs font-black text-cyan-400 uppercase tracking-widest font-mono">
              📡 {t("BROADCAST NEW LIVE MATCH", "YANGI JONLI O'YINNI BOSHLASH", "ЗАПУСТИТЬ НОВЫЙ LIVE МАТЧ")}
            </h3>

            <div className="space-y-1.5 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("TOURNAMENT CONTEXT", "TURNIR MATNI / MAQSADI", "КОНТЕКСТ ТУРНИРА")}</label>
              <input
                type="text"
                value={liveTourneyName}
                onChange={e => setLiveTourneyName(e.target.value)}
                placeholder="e.g. Cyber Championship Series"
                className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none"
              />
            </div>

            <div className="space-y-1.5 text-left">
              <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("GAME TYPE", "O'YIN TURI", "ТИП ИГРЫ")}</label>
              <select
                value={liveGame}
                onChange={e => setLiveGame(e.target.value)}
                className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
              >
                <option value="mlbb">MLBB</option>
                <option value="valorant">Valorant</option>
                <option value="cs2">CS2</option>
              </select>
            </div>

            {/* Competitors selects */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border border-white/5 p-4 rounded-xl bg-black/35">
              <div className="space-y-3 text-left">
                <span className="text-[10px] text-cyan-400 font-mono font-bold uppercase tracking-wider block">{t("TEAM A (HOME)", "A JAMOA (MEZBON)", "КОМАНДА А (ХОЗЯЕВА)")}</span>
                <select
                  value={teams.find(t => t.name === liveTeamAName)?.id || ''}
                  onChange={e => {
                    const selectedTeam = teams.find(t => t.id === e.target.value);
                    if (selectedTeam) {
                      setLiveTeamAName(selectedTeam.name);
                      setLiveTeamALogo(selectedTeam.logo || '');
                    } else {
                      setLiveTeamAName('');
                      setLiveTeamALogo('');
                    }
                  }}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-2.5 px-3 text-xs text-white focus:outline-none cursor-pointer"
                  required
                >
                  <option value="">{t("-- SELECT TEAM A --", "-- A JAMOANI TANLASH --", "-- ВЫБРАТЬ КОМАНДУ А --")}</option>
                  {teams.map(team => (
                    <option key={team.id} value={team.id}>
                      {team.name} {team.tag ? `(${team.tag})` : ''} — {team.gameType?.toUpperCase() || 'PRO LEAGUE'}
                    </option>
                  ))}
                </select>

                {liveTeamAName && (
                  <div className="flex items-center gap-2.5 p-2 bg-white/[0.02] border border-white/5 rounded-xl">
                    <div className="w-8 h-8 rounded bg-black/60 border border-white/10 p-0.5 flex items-center justify-center overflow-hidden shrink-0">
                      {liveTeamALogo && (liveTeamALogo.startsWith('data:') || liveTeamALogo.startsWith('http')) ? (
                        <img src={liveTeamALogo} className="w-full h-full object-contain" alt="" />
                      ) : (
                        <span className="text-sm">{liveTeamALogo || '⚔️'}</span>
                      )}
                    </div>
                    <div className="text-left">
                      <span className="text-[9px] text-slate-500 uppercase font-mono block">{t("Selected Team A", "Tanlangan A Jamoa", "Выбранная Команда А")}</span>
                      <span className="text-xs font-bold text-white uppercase">{liveTeamAName}</span>
                    </div>
                  </div>
                )}
              </div>

              <div className="space-y-3 text-left">
                <span className="text-[10px] text-purple-400 font-mono font-bold uppercase tracking-wider block">{t("TEAM B (AWAY)", "B JAMOA (MEHMON)", "КОМАНДА Б (ГОСТИ)")}</span>
                <select
                  value={teams.find(t => t.name === liveTeamBName)?.id || ''}
                  onChange={e => {
                    const selectedTeam = teams.find(t => t.id === e.target.value);
                    if (selectedTeam) {
                      setLiveTeamBName(selectedTeam.name);
                      setLiveTeamBLogo(selectedTeam.logo || '');
                    } else {
                      setLiveTeamBName('');
                      setLiveTeamBLogo('');
                    }
                  }}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-2.5 px-3 text-xs text-white focus:outline-none cursor-pointer"
                  required
                >
                  <option value="">{t("-- SELECT TEAM B --", "-- B JAMOANI TANLASH --", "-- ВЫБРАТЬ КОМАНДУ Б --")}</option>
                  {teams.map(team => (
                    <option key={team.id} value={team.id}>
                      {team.name} {team.tag ? `(${team.tag})` : ''} — {team.gameType?.toUpperCase() || 'PRO LEAGUE'}
                    </option>
                  ))}
                </select>

                {liveTeamBName && (
                  <div className="flex items-center gap-2.5 p-2 bg-white/[0.02] border border-white/5 rounded-xl">
                    <div className="w-8 h-8 rounded bg-black/60 border border-white/10 p-0.5 flex items-center justify-center overflow-hidden shrink-0">
                      {liveTeamBLogo && (liveTeamBLogo.startsWith('data:') || liveTeamBLogo.startsWith('http')) ? (
                        <img src={liveTeamBLogo} className="w-full h-full object-contain" alt="" />
                      ) : (
                        <span className="text-sm">{liveTeamBLogo || '🛡️'}</span>
                      )}
                    </div>
                    <div className="text-left">
                      <span className="text-[9px] text-slate-500 uppercase font-mono block">{t("Selected Team B", "Tanlangan B Jamoa", "Выбранная Команда Б")}</span>
                      <span className="text-xs font-bold text-white uppercase">{liveTeamBName}</span>
                    </div>
                  </div>
                )}
              </div>
            </div>

              <div className="space-y-1.5 text-left">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("STREAM EMBED URL (YOUTUBE)", "TRANSLYATSIYA EMBED SILKASI (YOUTUBE)", "ССЫЛКА НА ТРАНСЛЯЦИЮ (YOUTUBE)")}</label>
                <input
                  type="text"
                  value={liveStream}
                  onChange={e => setLiveStream(e.target.value)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none"
                />
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 bg-cyan-600 hover:bg-cyan-500 text-white text-xs font-bold uppercase tracking-wider rounded-xl cursor-pointer shadow transition-all active:scale-95 flex items-center justify-center gap-1"
              >
                <Radio className="w-4 h-4" /> {t("BROADCAST COMPETE LIVE", "JONLI TRANSLYATSIYANI BOSHLASH", "ЗАПУСТИТЬ ТРАНСЛЯЦИЮ")}
              </button>
            </form>

            {/* Live Matches Director Desk */}
            <div className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/5 rounded-2xl overflow-hidden shadow-lg">
              <div className="p-4 bg-white/5 border-b border-white/5 flex justify-between items-center">
                <h4 className="text-xs font-bold text-white uppercase tracking-wider font-mono flex items-center gap-1">
                  <Radio className="w-4 h-4 text-red-500 animate-pulse" /> {t("Live Matches Director Desk", "Jonli Matchlarni Boshqarish Paneli", "Панель Режиссера Живых Матчей")}
                </h4>
                <span className="text-[9px] text-slate-450 font-mono text-cyan-400">{t("REAL-TIME CONTROLLER", "REAL VAQT NAZORATCHISI", "КОНТРОЛЛЕР РЕАЛЬНОГО ВРЕМЕНИ")}</span>
              </div>

              <div className="p-4 space-y-4">
                {liveMatches.length === 0 ? (
                  <div className="text-center py-12 text-slate-500 text-xs font-mono">JONLI O'YINLAR YO'Q (DATABASE EMPTY). ELEMENT QO'SHING YOKI DATABASE TUGMASIDAN SEED BO'LIMINI TANLANG.</div>
                ) : (
                  <div className="space-y-4 max-h-[500px] overflow-y-auto pr-1">
                    {liveMatches.map(lm => (
                      <div key={lm.id} className="bg-black/45 p-4 rounded-xl border border-white/5 flex flex-col gap-4 text-xs">
                        
                        {/* Header match info */}
                        <div className="flex justify-between items-center pb-2 border-b border-white/5 text-[10px] font-mono text-slate-400 uppercase font-bold">
                          <span>{lm.tournamentTitle || 'Esports Cup'}</span>
                          <span className="text-red-400 tracking-widest flex items-center gap-1">
                            <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-ping" />
                            {t("LIVE SCOREBOARD", "JONLI HISOB DOSKASI", "ТАБЛО СЧЕТА LIVE")}
                          </span>
                        </div>

                        {/* Interactive score counters */}
                        <div className="flex items-center justify-between px-2">
                          {/* Team A */}
                          <div className="flex flex-col items-center gap-2">
                            <div className="flex items-center gap-1.5">
                              <div className="w-6 h-6 rounded bg-black/40 border border-white/10 flex items-center justify-center overflow-hidden">
                                {lm.teamA?.logo && (lm.teamA.logo.startsWith('data:') || lm.teamA.logo.startsWith('http')) ? (
                                  <img src={lm.teamA.logo} className="w-full h-full object-contain" alt="" />
                                ) : (
                                  <span className="text-sm">{lm.teamA?.logo || "⚔️"}</span>
                                )}
                              </div>
                              <span className="font-extrabold text-white text-sm">{lm.teamA?.name || "Team A"}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <button
                                onClick={() => handleUpdateLiveScore(lm.id, 'A', -1, lm)}
                                className="w-6 h-6 bg-white/5 border border-white/10 rounded flex items-center justify-center text-xs text-white font-bold cursor-pointer hover:bg-white/15"
                              >
                                -
                              </button>
                              <span className="font-black text-2xl text-cyan-400 min-w-8 text-center">{lm.teamA?.score ?? 0}</span>
                              <button
                                onClick={() => handleUpdateLiveScore(lm.id, 'A', 1, lm)}
                                className="w-6 h-6 bg-white/5 border border-white/10 rounded flex items-center justify-center text-xs text-white font-bold cursor-pointer hover:bg-white/15"
                              >
                                +
                              </button>
                            </div>
                          </div>

                          <div className="text-slate-500 font-mono font-bold text-xs">V / S</div>

                          {/* Team B */}
                          <div className="flex flex-col items-center gap-2">
                            <div className="flex items-center gap-1.5">
                              <div className="w-6 h-6 rounded bg-black/40 border border-white/10 flex items-center justify-center overflow-hidden">
                                {lm.teamB?.logo && (lm.teamB.logo.startsWith('data:') || lm.teamB.logo.startsWith('http')) ? (
                                  <img src={lm.teamB.logo} className="w-full h-full object-contain" alt="" />
                                ) : (
                                  <span className="text-sm">{lm.teamB?.logo || "🛡️"}</span>
                                )}
                              </div>
                              <span className="font-extrabold text-white text-sm">{lm.teamB?.name || "Team B"}</span>
                            </div>
                            <div className="flex items-center gap-1">
                              <button
                                onClick={() => handleUpdateLiveScore(lm.id, 'B', -1, lm)}
                                className="w-6 h-6 bg-white/5 border border-white/10 rounded flex items-center justify-center text-xs text-white font-bold cursor-pointer hover:bg-white/15"
                              >
                                -
                              </button>
                              <span className="font-black text-2xl text-purple-400 min-w-8 text-center">{lm.teamB?.score ?? 0}</span>
                              <button
                                onClick={() => handleUpdateLiveScore(lm.id, 'B', 1, lm)}
                                className="w-6 h-6 bg-white/5 border border-white/10 rounded flex items-center justify-center text-xs text-white font-bold cursor-pointer hover:bg-white/15"
                              >
                                +
                              </button>
                            </div>
                          </div>
                        </div>

                        {/* Settlement / Complete direct CTA */}
                        <div className="flex gap-2 pt-2 border-t border-white/5">
                          <button
                            onClick={() => handleSettleLiveMatch(lm)}
                            className="flex-1 py-1.5 bg-emerald-950/40 hover:bg-emerald-900/60 text-emerald-300 border border-emerald-500/20 rounded text-[10px] uppercase font-bold tracking-widest cursor-pointer transition-colors"
                          >
                            {t("SETTLE & COMPLETED RESULTS", "YAKUNLASH VA NATIJALARGA QO'SHISH", "ЗАВЕРШИТЬ И ЗАПИСАТЬ РЕЗУЛЬТАТ")}
                          </button>
                          <button
                            onClick={() => handleDeleteItem('live_matches', lm.id)}
                            className="py-1.5 px-3 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 rounded text-[10px] uppercase font-bold tracking-widest cursor-pointer transition-colors"
                          >
                            {t("Delete", "O'chirish", "Удалить")}
                          </button>
                        </div>

                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

          </div>

      )}

      {/* GAMES NEWS & UPDATES PUBLISHER */}
      {activeTab === 'results' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Create News Form */}
          <form onSubmit={handleAddNews} className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-5 text-left">
            <div className="pb-2 border-b border-white/5 flex items-center justify-between">
              <div>
                <h3 className="text-sm font-black text-cyan-400 uppercase tracking-widest font-mono flex items-center gap-1.5">
                  <Newspaper className="w-5 h-5 text-cyan-400" /> {t("Publish New Article / Update", "Yangi Ma'lumot / Yangilik Chop Etish", "Опубликовать Новую Статью")}
                </h3>
                <p className="text-slate-400 text-[10px] mt-0.5">Ushbu yangilik sahifadagi O'yinlar Yangiliklari bo'limida barcha foydalanuvchilarga ko'rinadi.</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="space-y-1.5">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("ARTICLE TITLE", "YANGILIK SARLAVHASI", "ЗАГОЛОВОК СТАТЬИ")}</label>
                <input
                  type="text"
                  value={newsTitle}
                  onChange={e => setNewsTitle(e.target.value)}
                  placeholder={t("e.g. Major Pro League Season Final Champions", "Masalan: Pro Liga Chempionlari aniqlandi", "напр. Финал Чемпионата Про Лиги")}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:ring-1 focus:ring-cyan-500 focus:outline-none"
                  required
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("CATEGORY / TAG", "TOIFA / TEG", "КАТЕГОРИЯ")}</label>
                  <select
                    value={newsCategory}
                    onChange={e => setNewsCategory(e.target.value)}
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
                  >
                    <option value="Pro Matches">{t("Pro Matches", "Pro O'yinlar", "Про-Матчи")}</option>
                    <option value="Tournament Results">{t("Tournament Results", "Turnir Natijalari", "Результаты Турниров")}</option>
                    <option value="Platform news">{t("Platform News", "Platforma Yangiliklari", "Новости Платформы")}</option>
                    <option value="CS2">Counter-Strike 2</option>
                    <option value="Valorant">Valorant</option>
                    <option value="Mobile Legends">Mobile Legends</option>
                    <option value="PUBG Mobile">PUBG Mobile</option>
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("NEWS IMAGE (UPLOAD DEVICE)", "RASYMNI YUKLASH (QURILMADAN)", "ОБЛОЖКА НОВОСТИ")}</label>
                  <input
                    type="file"
                    accept="image/*"
                    onChange={e => handleImageUpload(e, setNewsImage)}
                    className="w-full text-xs text-slate-400 bg-black/55 border border-white/10 rounded-xl py-2 px-3 focus:outline-none cursor-pointer"
                  />
                </div>
              </div>

              {newsImage && (
                <div className="relative h-28 w-full rounded-xl overflow-hidden bg-[#020205] border border-white/10">
                  <img src={newsImage} className="w-full h-full object-cover" alt="" />
                  <button
                    type="button"
                    onClick={() => setNewsImage('')}
                    className="absolute top-2 right-2 p-1 rounded-full bg-black/80 text-red-400 hover:text-red-500 border border-white/5 cursor-pointer"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                </div>
              )}

              <div className="space-y-1.5">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("BRIEF SUMMARY", "QISQA TA'RIFI (KIRISH)", "КРАТКОЕ ОПИСАНИЕ")}</label>
                <textarea
                  value={newsSummary}
                  onChange={e => setNewsSummary(e.target.value)}
                  placeholder={t("Brief summary to display on news card...", "Yangilik kartasida chiqadigan qisqa matn...", "Краткое введение на карточке новости...")}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none h-16 resize-none"
                  required
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("ARTICLE BODY (FULL CONTENT)", "TO'LIQ YANGILIK MATNI", "ПОЛНЫЙ ТЕКСТ СТАТЬИ")}</label>
                <textarea
                  value={newsContent}
                  onChange={e => setNewsContent(e.target.value)}
                  placeholder={t("Write complete article body or patch notes...", "Yangilik yoki e'lonning to'liq tafsilotini yozing...", "Напишите полный текст новости или патч-ноут...")}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none h-44 resize-none"
                  required
                />
              </div>
            </div>

            <div className="pt-3 flex justify-end">
              <button
                type="submit"
                disabled={loading}
                className="px-8 py-3 bg-gradient-to-r from-cyan-600 to-purple-600 hover:from-cyan-500 hover:to-purple-500 text-white text-xs font-black uppercase tracking-wider rounded-xl cursor-pointer shadow-lg transition-all flex items-center gap-1.5 active:scale-95"
              >
                <PlusCircle className="w-4 h-4" /> {t("PUBLISH ARTICLE (Chop Etish)", "YANGILIKNI CHOP ETISH", "ОПУБЛИКОВАТЬ СТАТЬЮ")}
              </button>
            </div>
          </form>

          {/* News List */}
          <div className="lg:col-span-5 space-y-6">
            <div className="bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4 text-left">
              <h3 className="text-xs font-black text-purple-400 uppercase tracking-widest font-mono border-b border-white/5 pb-2">
                {t("PUBLISHED ARTICLES LIST", "YUKLANGAN YANGILIKLAR RO'YHATI", "СПИСОК ОПУБЛИКОВАННЫХ НОВОСТЕЙ")} ({news.length})
              </h3>

              {news.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs">
                  {t("No custom news uploaded yet. Displaying fallback mock data in news feed.", "Hozircha yangilik yuklanmagan. Tizimda standart yangiliklar ko'rsatilmoqda.", "Нет опубликованных новостей.")}
                </div>
              ) : (
                <div className="space-y-3 max-h-[300px] overflow-y-auto pr-1">
                  {news.map((item) => (
                    <div key={item.id} className="p-3 bg-[#020205]/60 border border-white/5 rounded-xl flex items-center justify-between gap-3 hover:border-purple-500/20 transition-all">
                      <div className="flex items-center gap-2.5 min-w-0">
                        <div className="w-12 h-12 rounded-lg bg-black/50 overflow-hidden border border-white/10 shrink-0">
                          <img src={item.image} className="w-full h-full object-cover" alt="" />
                        </div>
                        <div className="min-w-0">
                          <h4 className="text-xs font-bold text-white truncate uppercase font-mono">{item.title}</h4>
                          <span className="text-[9px] text-purple-400 font-mono font-bold uppercase tracking-widest bg-purple-500/10 px-1.5 py-0.5 rounded block w-max mt-1">{item.category}</span>
                        </div>
                      </div>
                      <button
                        onClick={() => handleDeleteNews(item.id)}
                        className="p-2 bg-red-500/10 hover:bg-red-500/25 border border-red-500/20 rounded-lg text-red-400 hover:text-red-500 cursor-pointer"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Completed Match Results List */}
            <div className="bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4 text-left">
              <h3 className="text-xs font-black text-cyan-400 uppercase tracking-widest font-mono border-b border-white/5 pb-2">
                {t("SETTLED MATCH RESULTS", "YAKUNLANGAN O'YINLAR NATIJALARI", "РЕЗУЛЬТАТЫ ЗАВЕРШЕННЫХ МАТЧЕЙ")} ({results.length})
              </h3>

              {results.length === 0 ? (
                <div className="p-8 text-center text-slate-500 text-xs">
                  {t("No completed matches recorded yet. Settle live matches to generate results.", "Hozircha yakunlangan o'yinlar mavjud emas. Natija yaratish uchun jonli o'yinlarni yakunlang.", "Нет завершенных матчей.")}
                </div>
              ) : (
                <div className="space-y-3 max-h-[350px] overflow-y-auto pr-1">
                  {results.map((res) => (
                    <div key={res.id} className="p-3 bg-[#020205]/60 border border-white/5 rounded-xl flex items-center justify-between gap-3 hover:border-cyan-500/20 transition-all">
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-1.5 mb-1 text-[9px] font-mono">
                          <span className="font-black text-cyan-400 uppercase tracking-wider">{res.game}</span>
                          <span className="text-slate-500">{res.date}</span>
                        </div>
                        <div className="flex items-center justify-between bg-black/30 p-1.5 rounded border border-white/5 text-[11px] font-mono">
                          <div className="flex items-center gap-1.5 truncate">
                            {res.teamA?.logo && (res.teamA.logo.startsWith('data:') || res.teamA.logo.startsWith('http')) ? (
                              <img src={res.teamA.logo} className="w-3.5 h-3.5 object-contain" alt="" />
                            ) : (
                              <span>{res.teamA?.logo || "⚔️"}</span>
                            )}
                            <span className={res.teamA?.isWinner ? "font-bold text-emerald-400" : "text-slate-300"}>{res.teamA?.name}</span>
                          </div>
                          <span className="font-bold text-white">{res.teamA?.score ?? 0}</span>
                        </div>
                        <div className="flex items-center justify-between bg-black/30 p-1.5 rounded border border-white/5 text-[11px] font-mono mt-1">
                          <div className="flex items-center gap-1.5 truncate">
                            {res.teamB?.logo && (res.teamB.logo.startsWith('data:') || res.teamB.logo.startsWith('http')) ? (
                              <img src={res.teamB.logo} className="w-3.5 h-3.5 object-contain" alt="" />
                            ) : (
                              <span>{res.teamB?.logo || "🛡️"}</span>
                            )}
                            <span className={res.teamB?.isWinner ? "font-bold text-emerald-400" : "text-slate-300"}>{res.teamB?.name}</span>
                          </div>
                          <span className="font-bold text-white">{res.teamB?.score ?? 0}</span>
                        </div>
                      </div>
                      <button
                        onClick={() => handleDeleteItem('results', res.id)}
                        className="p-2 bg-red-500/10 hover:bg-red-500/25 border border-red-500/20 rounded-lg text-red-400 hover:text-red-500 cursor-pointer shrink-0"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

        </div>
      )}

      {/* CYBER MATCHES TAQVIM CALENDAR SCHEDULER */}
      {activeTab === 'cybermatches' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Create Scheduled Match form */}
          <form onSubmit={handleAddCyberMatch} className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-5 text-left">
            <div className="pb-2 border-b border-white/5">
              <h3 className="text-sm font-black text-cyan-400 uppercase tracking-widest font-mono flex items-center gap-1.5">
                <Flame className="w-5 h-5 text-pink-400" /> {t("Schedule Upcoming Cyber Match", "Yangi Kiber O'yin Qo'shish (Jadvalga)", "Добавить Кибер-Матч в Расписание")}
              </h3>
              <p className="text-slate-400 text-[10px] mt-0.5">Yangi o'yinlarni qo'shganda, u O'yinlar Taqvimi (taqvim) bo'limida ovoz berish imkoniyati bilan paydo bo'ladi.</p>
            </div>

            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("GAME NAME", "O'YIN TURI / DISCIPLINE", "ДИСЦИПЛИНА")}</label>
                  <select
                    value={cyberGameName}
                    onChange={e => setCyberGameName(e.target.value)}
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
                  >
                    <option value="Mobile Legends">Mobile Legends</option>
                    <option value="Dota 2">Dota 2</option>
                    <option value="Counter-Strike 2">Counter-Strike 2</option>
                    <option value="Valorant">Valorant</option>
                    <option value="PUBG Mobile">PUBG Mobile</option>
                    <option value="Free Fire">Free Fire</option>
                  </select>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("DATE & TIME", "SANA VA VAQT", "ДАТА И ВРЕМЯ")}</label>
                  <input
                    type="text"
                    value={cyberDateTime}
                    onChange={e => setCyberDateTime(e.target.value)}
                    placeholder="e.g. 2026-06-25 18:00"
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-4 text-xs text-white focus:outline-none"
                    required
                  />
                </div>
              </div>

              {/* TEAM A CREATION AREA */}
              <div className="p-4 rounded-xl bg-cyan-500/5 border border-cyan-500/10 space-y-3">
                <h4 className="text-[10px] text-cyan-400 font-mono font-bold uppercase">{t("TEAM A (COMPETITOR 1)", "A JAMOA TAFSILOTLARI", "КОМАНДА А")}</h4>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <input
                    type="text"
                    value={cyberTeamAName}
                    onChange={e => setCyberTeamAName(e.target.value)}
                    placeholder={t("Team A Name (e.g. Spirit)", "A Jamoa Nomi (masalan, Spirit)", "Имя Команды А")}
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-2 px-3 text-xs text-white focus:outline-none"
                    required
                  />

                  <div className="space-y-1">
                    <label className="text-[9px] text-slate-400 block uppercase font-mono">{t("TEAM LOGO (DEVICE)", "JAMOA RAMZI (QURILMADAN)", "ЛОГОТИП КОМАНДЫ А")}</label>
                    <input
                      type="file"
                      accept="image/*"
                      onChange={e => handleImageUpload(e, setCyberTeamALogo)}
                      className="w-full text-xs text-slate-400 cursor-pointer"
                    />
                  </div>
                </div>

                {cyberTeamALogo && (
                  <div className="w-12 h-12 rounded-lg bg-black/60 border border-white/10 p-1 flex items-center justify-center">
                    <img src={cyberTeamALogo} className="w-full h-full object-contain" alt="" />
                  </div>
                )}
              </div>

              {/* TEAM B CREATION AREA */}
              <div className="p-4 rounded-xl bg-purple-500/5 border border-purple-500/10 space-y-3">
                <h4 className="text-[10px] text-purple-400 font-mono font-bold uppercase">{t("TEAM B (COMPETITOR 2)", "B JAMOA TAFSILOTLARI", "КОМАНДА Б")}</h4>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <input
                    type="text"
                    value={cyberTeamBName}
                    onChange={e => setCyberTeamBName(e.target.value)}
                    placeholder={t("Team B Name (e.g. Gaimin)", "B Jamoa Nomi (masalan, Gaimin)", "Имя Команды Б")}
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-2 px-3 text-xs text-white focus:outline-none"
                    required
                  />

                  <div className="space-y-1">
                    <label className="text-[9px] text-slate-400 block uppercase font-mono">{t("TEAM LOGO (DEVICE)", "JAMOA RAMZI (QURILMADAN)", "ЛОГОТИП КОМАНДЫ Б")}</label>
                    <input
                      type="file"
                      accept="image/*"
                      onChange={e => handleImageUpload(e, setCyberTeamBLogo)}
                      className="w-full text-xs text-slate-400 cursor-pointer"
                    />
                  </div>
                </div>

                {cyberTeamBLogo && (
                  <div className="w-12 h-12 rounded-lg bg-black/60 border border-white/10 p-1 flex items-center justify-center">
                    <img src={cyberTeamBLogo} className="w-full h-full object-contain" alt="" />
                  </div>
                )}
              </div>

              <div className="space-y-1.5">
                <label className="text-[10px] text-slate-400 font-bold uppercase font-mono">{t("MATCH STATUS", "O'YIN HOLATI (STATUS)", "СТАТУС МАТЧА")}</label>
                <select
                  value={cyberStatus}
                  onChange={e => setCyberStatus(e.target.value as any)}
                  className="w-full bg-black/55 border border-white/10 rounded-xl py-3 px-3 text-xs text-white focus:outline-none cursor-pointer"
                >
                  <option value="upcoming">{t("Upcoming (Kutilayotgan)", "Upcoming (Kutilayotgan)", "Upcoming (Ожидается)")}</option>
                  <option value="live">{t("Live (Jonli)", "Live (Jonli Efir)", "Live (Прямой эфир)")}</option>
                  <option value="finished">{t("Finished (Yakunlangan)", "Finished (Yakunlangan)", "Finished (Завершен)")}</option>
                </select>
              </div>

            </div>

            <div className="pt-3 flex justify-end">
              <button
                type="submit"
                disabled={loading}
                className="px-8 py-3 bg-gradient-to-r from-emerald-600 to-teal-500 hover:from-emerald-500 hover:to-teal-400 text-white text-xs font-black uppercase tracking-wider rounded-xl cursor-pointer shadow transition-all active:scale-95 flex items-center justify-center gap-1.5"
              >
                <PlusCircle className="w-4 h-4" /> {t("SCHEDULE MATCH (O'yin Qo'shish)", "O'YINNI TAQVIMGA QO'SHISH", "ДОБАВИТЬ МАТЧ")}
              </button>
            </div>
          </form>

          {/* Matches List */}
          <div className="lg:col-span-5 bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4 text-left">
            <h3 className="text-xs font-black text-pink-400 uppercase tracking-widest font-mono border-b border-white/5 pb-2">
              {t("SCHEDULED MATCHES", "TAQVIMDAGI O'YINLAR RO'YHATI", "СПИСОК МАТЧЕЙ В РАСПИСАНИИ")} ({cyberMatches.length})
            </h3>

            {cyberMatches.length === 0 ? (
              <div className="p-8 text-center text-slate-500 text-xs">
                {t("No matches created yet. Use the form to schedule high-tier tournament games!", "Hozircha hech qanday o'yin yaratilmagan. O'yinlarni qo'shish uchun formadan foydalaning!", "Расписание матчей пусто.")}
              </div>
            ) : (
              <div className="space-y-3 max-h-[550px] overflow-y-auto pr-1">
                {cyberMatches.map((match) => (
                  <div key={match.id} className="p-3 bg-[#020205]/60 border border-white/5 rounded-xl flex items-center justify-between gap-3 hover:border-pink-500/25 transition-all">
                    <div className="min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="text-[9px] font-black uppercase tracking-wider text-pink-400">{match.gameName}</span>
                        <span className="text-[8px] px-1.5 py-0.5 rounded bg-white/5 text-slate-400 font-mono">{match.status}</span>
                      </div>
                      <div className="mt-1 text-xs text-white font-bold flex items-center gap-1 truncate uppercase font-mono">
                        <span>{match.teamA.name}</span>
                        <span className="text-[10px] text-slate-500 font-normal">vs</span>
                        <span>{match.teamB.name}</span>
                      </div>
                      <span className="text-[9px] text-slate-500 font-mono mt-0.5 block">{match.dateTime}</span>
                    </div>
                    <button
                      onClick={() => handleDeleteCyberMatch(match.id)}
                      className="p-2 bg-red-500/10 hover:bg-red-500/25 border border-red-500/20 rounded-lg text-red-400 hover:text-red-500 cursor-pointer shrink-0"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>

        </div>
      )}

      {/* PRO LIGA MANAGEMENT */}
      {activeTab === 'proleague' && (
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start animate-in fade-in duration-300">
          
          {/* Form Side */}
          <div className="lg:col-span-5 space-y-4">
            <form onSubmit={handleAddProTeam} className="bg-[#0b0c14]/40 border border-white/10 p-6 rounded-2xl space-y-4 text-left">
              <div className="border-b border-white/5 pb-3 flex justify-between items-center">
                <h3 className="text-xs font-black text-purple-400 uppercase tracking-widest font-mono">
                  {editingProTeamId ? t("⚡ Edit Pro Liga Team", "⚡ Pro Liga Jamoasini Tahrirlash", "⚡ Редактировать Команду Про-Лиги") : t("🛡️ Add Pro Liga New Team", "🛡️ Pro Liga Yangi Jamoa Qo'shish", "🛡️ Добавить Команду Про-Лиги")}
                </h3>
                {editingProTeamId && (
                  <button
                    type="button"
                    onClick={() => {
                      setEditingProTeamId(null);
                      setProTeamName('');
                      setProTeamTag('');
                      setProTeamLogo('🟢');
                      setProMatchesPlayed(2);
                      setProMatchesWon(1);
                      setProDraws(1);
                      setProLosses(0);
                      setProGoals('3-0');
                      setProPoints(4);
                      setProRank(1);
                    }}
                    className="text-[10px] text-rose-400 uppercase tracking-wider hover:underline"
                  >
                    {t("Cancel", "Bekor qilish", "Отмена")}
                  </button>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5 font-mono text-left">
                  <label className="text-[10px] text-slate-400 font-bold uppercase block">{t("TEAM NAME", "JAMOA NOMI", "НАЗВАНИЕ КОМАНДЫ")}</label>
                  <input
                    type="text"
                    value={proTeamName}
                    onChange={e => setProTeamName(e.target.value)}
                    placeholder="Masalan: Neftchi"
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-2.5 px-3 text-xs text-white uppercase focus:border-purple-500/50 focus:outline-none"
                    required
                  />
                </div>

                <div className="space-y-1.5 font-mono text-left">
                  <label className="text-[10px] text-slate-400 font-bold uppercase block">{t("TAG (PREFIX)", "TAG (PREFIKS)", "ТЕГ (ПРЕФИКС)")}</label>
                  <input
                    type="text"
                    value={proTeamTag}
                    onChange={e => setProTeamTag(e.target.value)}
                    placeholder="Masalan: NEF"
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-2.5 px-3 text-xs text-white uppercase focus:border-purple-500/50 focus:outline-none"
                    maxLength={4}
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5 font-mono text-left">
                  <label className="text-[10px] text-slate-400 font-bold uppercase block">{t("TEAM LOGO (DEVICE UPLOAD)", "JAMOA LOGOTIPI (QURILMADAN YUKLASH)", "ЛОГОТИП КОМАНДЫ (С УСТРОЙСТВА)")}</label>
                  <label className="relative flex items-center justify-center border border-dashed border-purple-500/30 hover:border-purple-500 bg-purple-500/5 hover:bg-purple-500/10 rounded-xl py-2.5 px-3 cursor-pointer transition-all h-[44px] overflow-hidden group">
                    <input
                      type="file"
                      accept="image/*"
                      onChange={e => handleImageUpload(e, setProTeamLogo)}
                      className="hidden"
                    />
                    <div className="flex items-center gap-1.5 text-purple-400 group-hover:text-purple-300">
                      <PlusCircle className="w-4 h-4" />
                      <span className="font-bold text-[10px] uppercase tracking-wider">{t("UPLOAD FILE", "RASM TANLASH", "ВЫБРАТЬ ФАЙЛ")}</span>
                    </div>
                  </label>
                  {proTeamLogo && (
                    <div className="mt-2 bg-black/45 border border-white/5 rounded-xl p-2 flex items-center justify-between gap-3">
                      <div className="flex items-center gap-2">
                        <span className="text-slate-400 text-[10px] uppercase font-mono">{t("Active:", "Hozirgi:", "Выбран:")}</span>
                        <div className="w-8 h-8 rounded-lg bg-black/60 border border-white/10 p-0.5 flex items-center justify-center overflow-hidden shrink-0">
                          {proTeamLogo.startsWith('data:') || proTeamLogo.startsWith('http') ? (
                            <img src={proTeamLogo} className="w-full h-full object-contain" alt="" />
                          ) : (
                            <span className="text-sm">{proTeamLogo}</span>
                          )}
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={() => setProTeamLogo('')}
                        className="p-1 px-2 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 text-[9px] rounded hover:text-red-300 transition-colors uppercase font-mono tracking-widest cursor-pointer"
                      >
                        {t("Reset", "Dastlabki", "Сбросить")}
                      </button>
                    </div>
                  )}
                </div>

                <div className="space-y-1.5 font-mono text-left">
                  <label className="text-[10px] text-slate-400 font-bold uppercase block">{t("RANK (ORDER NUMBER)", "RANK (TARTIB RAQAMI)", "РАНГ (ПОРЯДКОВЫЙ НОМЕР)")}</label>
                  <input
                    type="number"
                    value={proRank}
                    onChange={e => setProRank(Number(e.target.value))}
                    className="w-full bg-black/55 border border-white/10 rounded-xl py-2.5 px-3 text-xs text-white focus:outline-none"
                    required
                  />
                </div>
              </div>

              {/* STATS DECK */}
              <div className="p-3 bg-white/[0.02] border border-white/5 rounded-xl space-y-3">
                <span className="text-[10px] text-purple-400 font-bold font-mono uppercase tracking-wider block">{t("GAME CORRELATED STATISTICS", "O'YIN STATISTIKALARI", "СТАТИСТИКА МАТЧЕЙ")}</span>
                
                <div className="grid grid-cols-3 gap-2 text-xs font-mono">
                  <div className="space-y-1">
                    <span className="text-[9px] text-slate-400 block uppercase">{t("G (GAME)", "O' (O'YIN)", "И (ИГР)")}</span>
                    <input
                      type="number"
                      value={proMatchesPlayed}
                      onChange={e => setProMatchesPlayed(Number(e.target.value))}
                      className="w-full bg-black/40 border border-white/10 p-1.5 rounded text-center text-white text-xs"
                      min={0}
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[9px] text-slate-400 block uppercase">{t("W (WIN)", "G' (G'ALABA)", "В (ПОБЕД)")}</span>
                    <input
                      type="number"
                      value={proMatchesWon}
                      onChange={e => setProMatchesWon(Number(e.target.value))}
                      className="w-full bg-black/40 border border-white/10 p-1.5 rounded text-center text-white text-xs"
                      min={0}
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[9px] text-slate-400 block uppercase">{t("D (DRAW)", "D' (DURANG)", "Н (НИЧЬИ)")}</span>
                    <input
                      type="number"
                      value={proDraws}
                      onChange={e => setProDraws(Number(e.target.value))}
                      className="w-full bg-black/40 border border-white/10 p-1.5 rounded text-center text-white text-xs"
                      min={0}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-2 text-xs font-mono pt-2">
                  <div className="space-y-1">
                    <span className="text-[9px] text-slate-400 block uppercase">{t("L (LOSSES)", "M' (MAG'LUBIYAT)", "П (ПОРАЖЕНИЙ)")}</span>
                    <input
                      type="number"
                      value={proLosses}
                      onChange={e => setProLosses(Number(e.target.value))}
                      className="w-full bg-black/40 border border-white/10 p-1.5 rounded text-center text-white text-xs"
                      min={0}
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[9px] text-slate-400 block uppercase">{t("+/- (GOAL DIFFERENCE)", "+/- (GOAL NISBATI)", "+/- (РАЗНИЦА ГОЛОВ)")}</span>
                    <input
                      type="text"
                      value={proGoals}
                      onChange={e => setProGoals(e.target.value)}
                      placeholder="e.g. 3-0"
                      className="w-full bg-black/40 border border-white/10 p-1.5 rounded text-center text-white text-xs"
                    />
                  </div>
                  <div className="space-y-1">
                    <span className="text-[9px] text-cyan-400 block uppercase">{t("PTS (POINTS)", "O (OCHKO)", "О (ОЧКИ)")}</span>
                    <input
                      type="number"
                      value={proPoints}
                      onChange={e => setProPoints(Number(e.target.value))}
                      className="w-full bg-[#1e1b4b]/55 border border-purple-500/20 p-1.5 rounded text-center text-cyan-400 text-xs font-black"
                      min={0}
                    />
                  </div>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full py-3 bg-purple-600 hover:bg-purple-500 text-white text-xs font-black uppercase tracking-wider rounded-xl cursor-pointer shadow transition-all active:scale-95 flex items-center justify-center gap-1.5"
              >
                <PlusCircle className="w-4 h-4" /> {editingProTeamId ? t("UPDATE", "YANGILASH", "ОБНОВИТЬ") : t("REGISTER / ADD", "QAID ETISH / QO'SHISH", "ЗАРЕГИСТРИРОВАТЬ / ДОБАВИТЬ")}
              </button>
            </form>

          </div>

          {/* List Display Side */}
          <div className="lg:col-span-7 bg-[#0b0c14]/40 border border-white/5 rounded-2xl overflow-hidden shadow-lg text-left">
            <div className="p-4 bg-white/5 border-b border-white/10 flex justify-between items-center bg-purple-950/20">
              <h4 className="text-xs font-black text-white uppercase tracking-wider font-mono">
                {t("Pro Liga Rosters Registry", "Pro Liga Jamoalari Registri", "Реестр Команд Про-Лиги")} ({teams.filter(team => team.gameType === 'pro_league' || team.gameType === 'pro').length})
              </h4>
              <span className="text-[9px] text-slate-400 font-mono">{t("REAL-TIME CLOUD DATABASE", "BULUTLI BAZA READY", "ОБЛАЧНАЯ БД READY")}</span>
            </div>

            <div className="p-4">
              {teams.filter(team => team.gameType === 'pro_league' || team.gameType === 'pro').length === 0 ? (
                <div className="text-center py-10 text-slate-500 text-xs font-mono space-y-2">
                  <p>{t("Currently the Pro Liga database is empty.", "Hozirgi vaqtda Pro Liga ma'lumotlar bazasi butunlay bo'sh.", "В настоящее время база данных Про-Лиги пуста.")}</p>
                  <p className="text-[10px] text-purple-400">{t("Please add teams manually using the form.", "Iltimos, formadan foydalanib jamoalarni qo'lda qo'shing.", "Пожалуйста, добавьте команды вручную через форму.")}</p>
                </div>
              ) : (
                <div className="divide-y divide-white/5 max-h-[500px] overflow-y-auto space-y-2.5 pr-1">
                  {teams.filter(team => team.gameType === 'pro_league' || team.gameType === 'pro')
                    .sort((a,b) => (a.rank || 0) - (b.rank || 0))
                    .map(team => (
                      <div key={team.id} className="p-3 bg-white/[0.02] border border-white/5 rounded-xl flex justify-between items-center text-xs">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg bg-black/40 border border-white/10 flex items-center justify-center overflow-hidden">
                            {team.logo && (team.logo.startsWith('data:') || team.logo.startsWith('http')) ? (
                              <img src={team.logo} className="w-full h-full object-contain" alt="" />
                            ) : (
                              <span className="text-lg">{team.logo || "🟢"}</span>
                            )}
                          </div>
                          <div>
                            <span className="text-xs text-slate-400 font-mono">#{team.rank || '-'} {t("RANK", "O'RINI", "РАНГ")}</span>
                            <strong className="text-white uppercase tracking-wide block text-sm">{team.name} <span className="text-xs font-normal text-slate-500 font-sans">({team.tag})</span></strong>
                            <span className="text-[10px] text-purple-400 font-mono block uppercase">
                              {t("G", "O'", "И")}:{team.matchesPlayed ?? 0} | {t("W", "G'", "В")}:{team.matchesWon ?? 0} | {t("D", "D'", "Н")}:{team.draws ?? 0} | {t("L", "M'", "П")}:{team.losses ?? 0} | +/-: {team.goals || '0-0'} | {t("PTS", "Ochko", "Очки")}: <strong className="text-cyan-400">{team.points ?? 0}</strong>
                            </span>
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-2 shrink-0">
                          {/* EDIT LINK */}
                          <button
                            type="button"
                            onClick={() => {
                              setEditingProTeamId(team.id);
                              setProTeamName(team.name || '');
                              setProTeamTag(team.tag || '');
                              setProTeamLogo(team.logo || '🟢');
                              setProMatchesPlayed(team.matchesPlayed ?? 2);
                              setProMatchesWon(team.matchesWon ?? 1);
                              setProDraws(team.draws ?? 1);
                              setProLosses(team.losses ?? 0);
                              setProGoals(team.goals || '3-0');
                              setProPoints(team.points ?? 4);
                              setProRank(team.rank ?? 1);
                            }}
                            className="px-2.5 py-1.5 bg-purple-900/40 hover:bg-purple-800/60 border border-purple-500/20 text-purple-300 hover:text-white text-[10px] rounded uppercase font-mono tracking-wider transition-colors cursor-pointer"
                          >
                            {t("Edit", "Tahrirlash", "Редактировать")}
                          </button>
                          
                          {/* DELETE LINK */}
                          <button
                            type="button"
                            onClick={() => {
                              handleDeleteItem('teams', team.id);
                            }}
                            className="p-1 px-2 text-rose-400 hover:bg-rose-950/40 hover:text-rose-300 transition-colors uppercase font-mono tracking-widest cursor-pointer"
                          >
                            ×
                          </button>
                        </div>
                      </div>
                    ))}
                </div>
              )}
            </div>
          </div>

        </div>
      )}

      {/* USER FEEDBACK & BUG REPORTS */}
      {activeTab === 'feedbacks' && (
        <div className="bg-[#0b0c14]/40 border border-white/5 rounded-2xl p-6 space-y-6 animate-in fade-in duration-300 text-left">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-white/5 pb-4">
            <div>
              <h3 className="text-sm font-bold text-white uppercase tracking-wider font-mono flex items-center gap-1.5">
                <MessageSquare className="w-5 h-5 text-amber-400" /> {t("User Feedback & Bug Reports", "Fikr-mulohazalar va xatoliklar hisboti", "Отзывы пользователей и баг-репорты")}
              </h3>
              <p className="text-xs text-slate-400 mt-1">
                {t("Review bug reports, improvement suggestions, and feature requests submitted by the community.", "Jamiyat tomonidan yuborilgan xatoliklar va takliflarni ko'rib chiqing.", "Проверяйте отчёты об ошибках и предложения, отправленные сообществом.")}
              </p>
            </div>
            
            <span className="px-3 py-1 bg-amber-500/10 border border-amber-500/20 text-amber-400 text-xs rounded-full font-mono">
              {feedbacks.length} {t("Total submissions", "Jami yuborilgan", "Всего записей")}
            </span>
          </div>

          {feedbacks.length === 0 ? (
            <div className="text-center py-16 text-slate-500 text-xs font-mono border border-dashed border-white/5 rounded-xl">
              {t("NO FEEDBACK RECEIVED YET", "XATOLIK VA TAKLIFLAR YO'Q", "ОТЗЫВОВ И БАГ-РЕПОРТОВ ПОКА НЕТ")}
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {feedbacks.map((item) => (
                <div key={item.id} className="bg-white/[0.02] border border-white/5 rounded-xl p-5 hover:border-white/10 transition-all flex flex-col justify-between relative overflow-hidden">
                  {/* Accent tag based on feedback type */}
                  <div className="absolute top-0 right-0">
                    <span className={`text-[9px] uppercase tracking-wider font-mono px-3 py-1 rounded-bl-lg font-bold ${
                      item.type === 'bug' 
                        ? 'bg-rose-500/20 border-l border-b border-rose-500/20 text-rose-400' 
                        : 'bg-cyan-500/20 border-l border-b border-cyan-500/20 text-cyan-400'
                    }`}>
                      {item.type === 'bug' ? t("BUG REPORT", "XATOLIK", "БАГ-РЕПОРТ") : t("SUGGESTION", "TAKLIF", "ПРЕДЛОЖЕНИЕ")}
                    </span>
                  </div>

                  <div className="space-y-3">
                    <h4 className="text-white text-sm font-bold tracking-wide pr-24 uppercase truncate">
                      {item.title}
                    </h4>

                    <p className="text-xs text-slate-300 leading-relaxed font-sans whitespace-pre-wrap">
                      {item.description}
                    </p>
                  </div>

                  <div className="mt-5 pt-4 border-t border-white/5 flex items-center justify-between text-[11px] font-mono">
                    <div className="text-slate-400">
                      <span className="text-slate-500 text-[10px] block">{t("Submitted by:", "Yuboruvchi:", "Отправитель:")}</span>
                      <strong className="text-slate-300 text-xs">{item.senderName || 'Anonymous'}</strong>
                      {item.senderEmail && (
                        <span className="block text-[10px] text-slate-500 lowercase mt-0.5">{item.senderEmail}</span>
                      )}
                    </div>

                    <div className="text-right flex flex-col items-end gap-2">
                      <span className="text-slate-500 text-[9px]">
                        {item.timestamp ? new Date(item.timestamp).toLocaleString() : t("Unknown time", "Noma'lum vaqt", "Неизвестное время")}
                      </span>

                      <button
                        onClick={() => handleDeleteItem('feedbacks', item.id)}
                        className="px-2.5 py-1 bg-red-950/20 hover:bg-red-900/40 border border-red-500/20 text-red-400 hover:text-red-300 rounded text-[10px] uppercase font-mono tracking-wider transition-colors cursor-pointer"
                      >
                        {t("Dismiss", "O'chirish", "Удалить")}
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Custom Confirmation Modal */}
      {confirmModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md" id="custom-confirm-modal">
          <div className="bg-[#0b0c16] border border-white/10 rounded-2xl p-6 max-w-md w-full shadow-2xl space-y-4 text-left">
            <h3 className="text-lg font-bold text-white uppercase tracking-wider font-mono flex items-center gap-2">
              ⚠️ {confirmModal.title}
            </h3>
            <p className="text-slate-300 text-sm leading-relaxed">
              {confirmModal.message}
            </p>
            <div className="flex items-center justify-end gap-3 pt-2">
              <button
                type="button"
                onClick={() => setConfirmModal(null)}
                className="px-4 py-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-xl text-slate-300 hover:text-white text-xs font-bold uppercase tracking-widest cursor-pointer transition-all"
              >
                {t("Cancel", "Bekor qilish", "Отмена")}
              </button>
              <button
                type="button"
                onClick={() => {
                  confirmModal.onConfirm();
                  setConfirmModal(null);
                }}
                className="px-5 py-2 bg-red-600 hover:bg-red-700 text-white rounded-xl text-xs font-bold uppercase tracking-widest cursor-pointer transition-all shadow-lg shadow-red-600/25"
              >
                {t("Confirm", "Tasdiqlash", "Подтвердить")}
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
};