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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
import React, { useState, useEffect, useRef } from 'react';
import { 
  BarChart2, 
  Users, 
  MessageSquare, 
  ShieldAlert, 
  Mic, 
  LogOut, 
  LogIn, 
  Activity, 
  Search, 
  Settings, 
  Lock,
  Volume2,
  RefreshCw,
  Clock,
  Trash2,
  UserCheck
} from 'lucide-react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  RadialLinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js';
import { Line, Radar } from 'react-chartjs-2';

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  RadialLinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

// 3D Galaxy Chatter Orbit Visualization
function ChatterOrbit({ chatters }) {
  const canvasRef = useRef(null);
  const containerRef = useRef(null);
  const particlesRef = useRef(new Map());
  const avatarRef = useRef(null);

  useEffect(() => {
    // Load Avatar via backend proxy (avoids CORS issues with decapi.me)
    if (!avatarRef.current) {
      const img = new Image();
      img.src = '/api/avatar/winx_prinx';
      img.onload = () => { avatarRef.current = img; };
      img.onerror = () => console.warn('[ChatterOrbit] Avatar load failed');
    }
  }, []);

  useEffect(() => {
    const safeChatters = Array.isArray(chatters) ? chatters : [];
    
    safeChatters.forEach(c => {
      const username = c.username || c.display_name || 'unknown';
      if (!particlesRef.current.has(username)) {
        const isLurker = !c.has_chatted && !(c.message_count > 0);
        // All particles go on the ring — tight band around ring radius ±8%
        const ringNoise = (Math.random() - 0.5) * 0.16;
        const radiusNorm = 1.0 + ringNoise;
          
        particlesRef.current.set(username, {
          username,
          displayName: c.display_name || username,
          angle: Math.random() * Math.PI * 2,
          radiusNorm,
          speed: (0.0003 + Math.random() * 0.0004) * (Math.random() > 0.5 ? 1 : -1),
          isMod: c.is_mod,
          isSub: c.is_sub,
          isLurker,
          messageCount: c.message_count || 0,
          isStreamer: username.toLowerCase() === 'winx_prinx',
        });
      } else {
        const p = particlesRef.current.get(username);
        const isLurker = !c.has_chatted && !(c.message_count > 0);
        p.isLurker = isLurker;
        p.messageCount = c.message_count || p.messageCount;
        p.isMod = c.is_mod || p.isMod;
        p.isSub = c.is_sub || p.isSub;
      }
    });
  }, [chatters]);

  useEffect(() => {
    const canvas = canvasRef.current;
    const container = containerRef.current;
    if (!canvas || !container) return;
    const ctx = canvas.getContext('2d');
    let animationId;

    const HEIGHT = 320;

    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      const rect = container.getBoundingClientRect();
      canvas.width = rect.width * dpr;
      canvas.height = HEIGHT * dpr;
      canvas.style.width = `${rect.width}px`;
      canvas.style.height = `${HEIGHT}px`;
      ctx.scale(dpr, dpr);
    };
    resize();
    window.addEventListener('resize', resize);

    let hoverName = null;
    let hoverX = 0;
    let hoverY = 0;
    let mouseX = -9999;
    let mouseY = -9999;

    const handleMouseMove = (e) => {
      const rect = canvas.getBoundingClientRect();
      mouseX = e.clientX - rect.left;
      mouseY = e.clientY - rect.top;
    };
    const handleMouseLeave = () => { mouseX = -9999; mouseY = -9999; };
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('mouseleave', handleMouseLeave);

    const animate = () => {
      const width = canvas.width / (window.devicePixelRatio || 1);
      const height = HEIGHT;
      const cx = width / 2;
      const cy = height / 2;

      // Ring fills most of the canvas
      const RX = width * 0.44;
      const RY = height * 0.36;
      const TILT = RY / RX;

      // Solid near-black background
      ctx.fillStyle = '#08080f';
      ctx.fillRect(0, 0, width, height);

      const particles = Array.from(particlesRef.current.values());

      hoverName = null;

      // Update positions
      particles.forEach(p => {
        p.angle += p.speed;
        const r = p.radiusNorm * RX;
        p.x = cx + Math.cos(p.angle) * r;
        p.y = cy + Math.sin(p.angle) * r * TILT;
        p.depth = (Math.sin(p.angle) * TILT + TILT) / (2 * TILT); // 0=back, 1=front

        if (p.isStreamer) {
          p.baseSize = 5;
          p.color = '#A370F7';
        } else if (p.isLurker) {
          p.baseSize = 1;
          p.color = null;
        } else {
          p.baseSize = Math.min(4, 1.5 + Math.log10((p.messageCount || 0) + 1) * 1.2);
          p.color = p.isMod ? '#00F5D4' : p.isSub ? '#FF007F' : '#c8c8d8';
        }
        p.drawSize = p.baseSize;
      });

      // Sort back-to-front
      particles.sort((a, b) => a.depth - b.depth);

      // Draw particles
      particles.forEach(p => {
        const alpha = p.isLurker
          ? 0.15 + p.depth * 0.45
          : 0.5 + p.depth * 0.5;

        let color;
        if (p.isLurker) {
          const brightness = Math.round(160 + p.depth * 60);
          color = `rgba(${brightness},${brightness},${brightness + 20},${alpha})`;
        } else {
          color = p.color;
        }

        const dist = Math.hypot(mouseX - p.x, mouseY - p.y);
        if (dist < p.drawSize + 6) {
          hoverName = p.displayName;
          hoverX = p.x;
          hoverY = p.y;
          p.drawSize = Math.max(p.drawSize * 2.5, 5);
        }

        ctx.globalAlpha = p.isLurker ? 1 : alpha;
        ctx.shadowBlur = 0;

        if (!p.isLurker && (p.isMod || p.isSub || p.isStreamer)) {
          ctx.shadowBlur = 6;
          ctx.shadowColor = color;
        }

        ctx.beginPath();
        ctx.arc(p.x, p.y, p.drawSize, 0, Math.PI * 2);
        ctx.fillStyle = color;
        ctx.fill();
      });
      ctx.globalAlpha = 1;
      ctx.shadowBlur = 0;

      // Draw Avatar on top
      ctx.save();
      ctx.beginPath();
      ctx.arc(cx, cy, 26, 0, Math.PI * 2);
      ctx.closePath();
      ctx.shadowColor = '#9147ff';
      ctx.shadowBlur = 24;
      ctx.strokeStyle = 'rgba(145, 71, 255, 0.9)';
      ctx.lineWidth = 2.5;
      ctx.stroke();
      ctx.shadowBlur = 0;
      ctx.clip();
      if (avatarRef.current) {
        ctx.drawImage(avatarRef.current, cx - 26, cy - 26, 52, 52);
      } else {
        ctx.fillStyle = '#6441A5';
        ctx.fill();
      }
      ctx.restore();

      // Hover tooltip
      if (hoverName) {
        ctx.shadowBlur = 0;
        ctx.globalAlpha = 1;
        ctx.font = 'bold 11px Inter, sans-serif';
        const tw = ctx.measureText(hoverName).width;
        const tx = Math.min(hoverX + 12, width - tw - 20);
        const ty = hoverY - 30 < 5 ? hoverY + 20 : hoverY - 30;
        ctx.fillStyle = 'rgba(18,18,24,0.92)';
        ctx.beginPath();
        if (ctx.roundRect) ctx.roundRect(tx - 4, ty, tw + 16, 22, 5);
        else ctx.rect(tx - 4, ty, tw + 16, 22);
        ctx.fill();
        ctx.strokeStyle = 'rgba(145,71,255,0.5)';
        ctx.lineWidth = 1;
        ctx.stroke();
        ctx.fillStyle = '#efeff1';
        ctx.fillText(hoverName, tx + 4, ty + 15);
      }

      animationId = requestAnimationFrame(animate);
    };

    animate();

    return () => {
      cancelAnimationFrame(animationId);
      canvas.removeEventListener('mousemove', handleMouseMove);
      canvas.removeEventListener('mouseleave', handleMouseLeave);
      window.removeEventListener('resize', resize);
    };
  }, []);

  return (
    <div ref={containerRef} style={{ display: 'flex', flexDirection: 'column', width: '100%', position: 'relative' }}>
      <canvas ref={canvasRef} style={{ borderRadius: '8px', display: 'block', width: '100%' }} />
      <div style={{ position: 'absolute', bottom: '10px', right: '12px', fontSize: '11px', color: 'rgba(180,180,200,0.7)', display: 'flex', gap: '14px' }}>
        <span><span style={{ display: 'inline-block', width: '6px', height: '6px', background: 'rgba(200,200,220,0.5)', borderRadius: '50%', marginRight: '4px'}}></span>Зрители</span>
        <span><span style={{ display: 'inline-block', width: '6px', height: '6px', background: '#c8c8d8', borderRadius: '50%', marginRight: '4px'}}></span>Чатеры</span>
        <span><span style={{ display: 'inline-block', width: '6px', height: '6px', background: '#FF007F', borderRadius: '50%', marginRight: '4px'}}></span>Сабы</span>
        <span><span style={{ display: 'inline-block', width: '6px', height: '6px', background: '#00F5D4', borderRadius: '50%', marginRight: '4px'}}></span>Модеры</span>
      </div>
    </div>
  );
}

// Fallback to local port 3000 in development, or use VITE_API_URL if configured, otherwise same origin
const API_BASE = import.meta.env.VITE_API_URL || (import.meta.env.DEV ? 'http://localhost:3000' : '');
const TWITCH_CHANNEL = 'winx_prinx';

export default function App() {
  const [activeTab, setActiveTab] = useState('overview');
  const [streams, setStreams] = useState([]);
  const [selectedStreamId, setSelectedStreamId] = useState('all');
  const [auth, setAuth] = useState({ loggedIn: false, user: null });
  const [twitchConfigured, setTwitchConfigured] = useState(true);
  const [loading, setLoading] = useState(true);
  const [serverStatus, setServerStatus] = useState('connecting'); // 'connecting' | 'online' | 'offline'

  // Statistics State
  const [chatters, setChatters] = useState([]);
  const [chattersSearch, setChattersSearch] = useState('');
  const [voiceWords, setVoiceWords] = useState([]);
  const [chatWords, setChatWords] = useState([]);
  const [wordType, setWordType] = useState('voice'); // 'voice' or 'chat'
  const [activityData, setActivityData] = useState([]);
  const [modActions, setModActions] = useState([]);
  const [modSummary, setModSummary] = useState([]);
  
  // RPG Mod Profiles
  const [modProfiles, setModProfiles] = useState([]);
  const [selectedMod, setSelectedMod] = useState(null);
  const [syncingVods, setSyncingVods] = useState(false);
  const [isRacing, setIsRacing] = useState(false);

  // Admin State
  const [adminStats, setAdminStats] = useState(null);
  const [loadingAdminStats, setLoadingAdminStats] = useState(false);
  const [cleaningStreams, setCleaningStreams] = useState(false);
  const [adminSelectedStreamId, setAdminSelectedStreamId] = useState('');
  const [editTitle, setEditTitle] = useState('');
  const [editCategory, setEditCategory] = useState('');
  const [savingMetadata, setSavingMetadata] = useState(false);
  const [deletingStream, setDeletingStream] = useState(false);

  // Auto-refresh timer for live stream
  const pollIntervalRef = useRef(null);
  const raceIntervalRef = useRef(null);

  const fetchAdminStats = async () => {
    setLoadingAdminStats(true);
    try {
      const res = await fetch(`${API_BASE}/api/admin/stats`, { credentials: 'include' });
      if (res.status === 200) {
        const data = await res.json();
        if (data.success) {
          setAdminStats(data.stats);
        }
      }
    } catch (e) {
      console.error('Error fetching admin stats:', e);
    } finally {
      setLoadingAdminStats(false);
    }
  };

  // Fetch admin stats when switching to admin tab
  useEffect(() => {
    if (activeTab === 'admin') {
      fetchAdminStats();
      if (streams && streams.length > 0 && !adminSelectedStreamId) {
        setAdminSelectedStreamId(streams[0].id.toString());
      }
    }
  }, [activeTab, streams]);

  // Sync edit fields when admin selection changes
  useEffect(() => {
    if (adminSelectedStreamId) {
      const stream = streams.find(s => s.id === parseInt(adminSelectedStreamId));
      if (stream) {
        setEditTitle(stream.title || '');
        setEditCategory(stream.category || '');
      } else {
        setEditTitle('');
        setEditCategory('');
      }
    } else {
      setEditTitle('');
      setEditCategory('');
    }
  }, [adminSelectedStreamId, streams]);

  const checkServerHealth = async () => {
    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 6000);
      
      const res = await fetch(`${API_BASE}/api/health`, { signal: controller.signal });
      clearTimeout(timeoutId);
      
      if (res.ok) {
        setServerStatus('online');
        return true;
      }
    } catch (e) {
      console.warn('Backend connection healthcheck failed:', e);
    }
    return false;
  };

  const pingServer = async () => {
    const ok = await checkServerHealth();
    if (ok) {
      fetchAuthStatus();
      fetchStreams();
    } else {
      setServerStatus('offline');
    }
  };

  // Check Auth on Mount & Server connection status loop
  useEffect(() => {
    let active = true;
    let timer = null;

    const runPingLoop = async () => {
      if (!active) return;
      const ok = await checkServerHealth();
      if (active) {
        if (ok) {
          fetchAuthStatus();
          fetchStreams();
          timer = setTimeout(runPingLoop, 30000);
        } else {
          setServerStatus('offline');
          timer = setTimeout(runPingLoop, 6000);
        }
      }
    };

    runPingLoop();

    return () => {
      active = false;
      if (timer) clearTimeout(timer);
    };
  }, []);

  // Fetch stats when selected stream changes
  useEffect(() => {
    if (selectedStreamId && serverStatus === 'online') {
      fetchAllStats();
      
      // Setup polling if the selected stream is live (end_time is null)
      const selectedStream = streams.find(s => s.id === parseInt(selectedStreamId));
      const isLive = selectedStream && !selectedStream.end_time;

      if (isLive || selectedStreamId === 'all') {
        startPolling();
      } else {
        stopPolling();
      }
    }
    return () => stopPolling();
  }, [selectedStreamId, streams, serverStatus]);

  const startPolling = () => {
    stopPolling();
    pollIntervalRef.current = setInterval(() => {
      fetchAllStats(false); // poll silently without loading spinner
    }, 15000); // refresh every 15s
  };

  const stopPolling = () => {
    if (pollIntervalRef.current) {
      clearInterval(pollIntervalRef.current);
      pollIntervalRef.current = null;
    }
  };

  // Optimize polling based on page visibility (pause if tab is backgrounded)
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        stopPolling();
      } else if (document.visibilityState === 'visible' && selectedStreamId && serverStatus === 'online') {
        fetchAllStats(false);
        const selectedStream = streams.find(s => s.id === parseInt(selectedStreamId));
        const isLive = selectedStream && !selectedStream.end_time;
        if (isLive || selectedStreamId === 'all') {
          startPolling();
        }
      }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [selectedStreamId, streams, serverStatus]);

  const fetchAuthStatus = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/auth/status`, { credentials: 'include' });
      const data = await res.json();
      setTwitchConfigured(data.twitchConfigured !== false);
      if (data.loggedIn) {
        setAuth({ loggedIn: true, user: data.user });
      } else {
        setAuth({ loggedIn: false, user: null });
      }
    } catch (e) {
      console.error('Auth check failed:', e);
    }
  };

  const fetchStreams = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/streams`);
      const data = await res.json();
      setStreams(data);
    } catch (e) {
      console.error('Failed to fetch streams:', e);
    }
  };

  const getUrl = (endpoint, params = {}) => {
    if (selectedStreamId !== 'all') {
      params.stream_id = selectedStreamId;
    }
    const query = new URLSearchParams(params).toString();
    return `${API_BASE}${endpoint}${query ? '?' + query : ''}`;
  };

  const fetchAllStats = async (showSpinner = true) => {
    if (showSpinner) setLoading(true);

    try {
      // 1. Top Chatters
      const chattersRes = await fetch(getUrl('/api/stats/chatters'));
      const chattersData = await chattersRes.json();
      setChatters(Array.isArray(chattersData) ? chattersData : []);

      // 2. Spoken voice words
      const voiceRes = await fetch(getUrl('/api/stats/words', { type: 'voice', limit: 60 }));
      const voiceData = await voiceRes.json();
      setVoiceWords(Array.isArray(voiceData) ? voiceData : []);

      // 3. Written chat words by streamer
      const chatWordsRes = await fetch(getUrl('/api/stats/words', { type: 'chat', limit: 60 }));
      const chatWordsData = await chatWordsRes.json();
      setChatWords(Array.isArray(chatWordsData) ? chatWordsData : []);

      // 4. Activity chart (only if stream is selected)
      if (selectedStreamId !== 'all') {
        const activityRes = await fetch(getUrl('/api/stats/activity'));
        const activityData = await activityRes.json();
        setActivityData(Array.isArray(activityData) ? activityData : []);
      } else {
        setActivityData([]);
      }

      // 5. Fetch moderator actions if authorized
      if (!twitchConfigured || (auth.loggedIn && (auth.user?.role === 'streamer' || auth.user?.role === 'moderator' || auth.user?.role === 'admin'))) {
        const modRes = await fetch(getUrl('/api/stats/moderators', { limit: 100 }), { credentials: 'include' });
        const modData = await modRes.json();
        setModActions(Array.isArray(modData) ? modData : []);

        const summaryRes = await fetch(getUrl('/api/stats/moderators/summary'), { credentials: 'include' });
        const summaryData = await summaryRes.json();
        setModSummary(Array.isArray(summaryData) ? summaryData : []);

        const profilesRes = await fetch(getUrl('/api/stats/moderators/profiles'), { credentials: 'include' });
        const profilesData = await profilesRes.json();
        setModProfiles(Array.isArray(profilesData) ? profilesData : []);
        if (profilesData && profilesData.length > 0) {
          setSelectedMod(prev => prev ? profilesData.find(p => p.moderator === prev.moderator) || profilesData[0] : profilesData[0]);
        }
      }
    } catch (e) {
      console.error('Error fetching statistics:', e);
    } finally {
      if (showSpinner) setLoading(false);
    }
  };

  const startGraphRace = () => {
    if (activityData.length === 0) return;
    if (raceIntervalRef.current) clearInterval(raceIntervalRef.current);
    
    const originalData = [...activityData];
    setActivityData([]);
    setIsRacing(true);
    
    let currentIndex = 0;
    raceIntervalRef.current = setInterval(() => {
      if (currentIndex >= originalData.length) {
        clearInterval(raceIntervalRef.current);
        setIsRacing(false);
        return;
      }
      setActivityData(prev => [...prev, originalData[currentIndex]]);
      currentIndex++;
    }, 150);
  };

  const handleLogin = () => {
    window.location.href = `${API_BASE}/api/auth/twitch`;
  };

  const handleLogout = async () => {
    try {
      await fetch(`${API_BASE}/api/auth/logout`, { credentials: 'include' });
      setAuth({ loggedIn: false, user: null });
      setModActions([]);
      setModSummary([]);
      setActiveTab('overview');
    } catch (e) {
      console.error('Logout failed:', e);
    }
  };

  const activeStream = streams.find(s => !s.end_time);

  // Helper to format dates
  const formatDate = (isoString) => {
    if (!isoString) return '';
    const date = new Date(isoString);
    return date.toLocaleString('ru-RU', { 
      day: 'numeric', 
      month: 'short', 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  // KPI Metrics Calculation
  const totalMessages = chatters.reduce((acc, curr) => acc + curr.message_count, 0);
  const totalUniqueChatters = chatters.length;
  const topChatter = chatters[0]?.display_name || '—';
  const totalVoiceWords = voiceWords.reduce((acc, curr) => acc + curr.word_count, 0);
  const totalModActionsCount = modActions.length;

  const statsSummary = {
    messages: totalMessages,
    uniqueChatters: totalUniqueChatters,
    mostActiveChatter: topChatter,
    voiceWordsCount: totalVoiceWords,
    modActionsCount: totalModActionsCount
  };

  // Chart Setup
  const chartLabels = activityData.map(d => {
    const date = new Date(d.timestamp);
    return date.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
  });

  const chartDataConfig = {
    labels: chartLabels.length > 0 ? chartLabels : ['Нет данных'],
    datasets: [
      {
        fill: true,
        label: 'Сообщений в 5 мин',
        data: activityData.map(d => d.message_count),
        borderColor: '#9146FF',
        backgroundColor: 'rgba(145, 70, 255, 0.1)',
        tension: 0.4,
        pointBackgroundColor: '#9146FF',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: '#9146FF',
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: '#18181B',
        borderColor: '#2F2F35',
        borderWidth: 1,
        titleColor: '#EFeff1',
        bodyColor: '#ADADB8',
        padding: 10,
        displayColors: false,
      }
    },
    scales: {
      x: {
        grid: {
          color: '#2F2F35',
        },
        ticks: {
          color: '#ADADB8',
          font: { size: 10 }
        }
      },
      y: {
        grid: {
          color: '#2F2F35',
        },
        ticks: {
          color: '#ADADB8',
          font: { size: 10 }
        }
      }
    }
  };

  return (
    <div className="app-container">
      {/* Header */}
      <header className="app-header">
        <div className="brand-section">
          <BarChart2 size={28} className="brand-logo" />
          <h1 className="brand-name">winx_prinx</h1>
          <span className="channel-tag">Analytics</span>

          {/* Live stream badge */}
          {activeStream ? (
            <div className="status-indicator" style={{ marginLeft: '1rem' }}>
              <span className="status-dot live"></span>
              <span style={{ color: '#ff0000', fontSize: '0.75rem' }}>В ЭФИРЕ</span>
            </div>
          ) : (
            <div className="status-indicator" style={{ marginLeft: '1rem' }}>
              <span className="status-dot offline"></span>
              <span style={{ color: 'var(--color-text-muted)', fontSize: '0.75rem' }}>ОФФЛАЙН</span>
            </div>
          )}

          {/* Stream Selector — compact, in header */}
          <div className="header-stream-selector">
            <select
              className="select-input select-input--compact"
              value={selectedStreamId}
              onChange={(e) => setSelectedStreamId(e.target.value)}
            >
              <option value="all">За всё время</option>
              {streams.map(s => (
                <option key={s.id} value={s.id}>
                  {s.title} ({formatDate(s.start_time)}{!s.end_time ? ' · Live' : ''})
                </option>
              ))}
            </select>
          </div>
        </div>

        <div className="header-controls">
          {/* Navigation Tabs */}
          <nav className="nav-tabs">
            <button 
              className={`tab-btn ${activeTab === 'overview' ? 'active' : ''}`}
              onClick={() => setActiveTab('overview')}
            >
              <Activity size={16} /> Обзор
            </button>
            <button 
              className={`tab-btn ${activeTab === 'chatters' ? 'active' : ''}`}
              onClick={() => setActiveTab('chatters')}
            >
              <Users size={16} /> Зрители
            </button>
            <button 
              className={`tab-btn ${activeTab === 'words' ? 'active' : ''}`}
              onClick={() => setActiveTab('words')}
            >
              <Mic size={16} /> Словарь частот
            </button>
            <button 
              className={`tab-btn ${activeTab === 'moderator' ? 'active' : ''}`}
              onClick={() => setActiveTab('moderator')}
            >
              <ShieldAlert size={16} /> Модерация
            </button>
            {(auth.user?.role === 'streamer' || auth.user?.role === 'admin' || !twitchConfigured) && (
              <button 
                className={`tab-btn ${activeTab === 'admin' ? 'active' : ''}`}
                onClick={() => setActiveTab('admin')}
              >
                <Settings size={16} /> Админка
              </button>
            )}
          </nav>

          {/* Refresh + User Profile */}
          <div className="user-profile">
            <button
              className="btn btn-refresh"
              onClick={() => { fetchStreams(); fetchAllStats(); }}
              disabled={loading}
              title="Обновить данные"
            >
              <RefreshCw size={14} className={loading ? 'spin' : ''} />
              Обновить
            </button>
            {!twitchConfigured ? (
              <span className="badge badge-mod" style={{ padding: '0.5rem 1rem', fontSize: '0.85rem', background: '#232329', border: '1px solid #2F2F35', color: '#00F5D4' }}>
                Локальный режим
              </span>
            ) : auth.loggedIn ? (
              <>
                <div className="user-info">
                  <div className="user-name">{auth.user.displayName}</div>
                  <div className="user-role">
                    {auth.user?.role === 'streamer' ? 'Стример' : auth.user?.role === 'admin' ? 'Админ' : auth.user?.role === 'moderator' ? 'Модератор' : 'Зритель'}
                  </div>
                </div>
                <button className="btn btn-secondary" onClick={handleLogout}>
                  <LogOut size={16} /> Выйти
                </button>
              </>
            ) : (
              <button className="btn" onClick={handleLogin}>
                <LogIn size={16} /> Войти через Twitch
              </button>
            )}
          </div>
        </div>
      </header>

      {/* Main Dashboard Panel */}
      <main className="dashboard-content">

        {serverStatus !== 'online' ? (
          <div className="connection-overlay-container" style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            minHeight: '60vh',
            padding: '2rem',
            textAlign: 'center',
            background: 'rgba(20, 20, 27, 0.4)',
            backdropFilter: 'blur(8px)',
            WebkitBackdropFilter: 'blur(8px)',
            borderRadius: 'var(--radius-lg)',
            border: '1px solid var(--color-border)',
            margin: '2rem auto',
            maxWidth: '600px',
            boxShadow: '0 8px 32px 0 rgba(0, 0, 0, 0.37)',
            animation: 'fadeIn 0.4s ease-out'
          }}>
            {serverStatus === 'connecting' ? (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1.5rem' }}>
                <div className="spinner" style={{
                  width: '50px',
                  height: '50px',
                  borderRadius: '50%',
                  border: '3px solid rgba(145, 70, 255, 0.1)',
                  borderTopColor: 'var(--color-brand)',
                  animation: 'spin 1s linear infinite'
                }}></div>
                <h2 style={{ fontSize: '1.4rem', fontWeight: 600, color: 'var(--color-text-main)', margin: 0 }}>
                  Подключение к серверу аналитики...
                </h2>
                <p style={{ color: 'var(--color-text-muted)', fontSize: '0.88rem', margin: 0, lineHeight: 1.6 }}>
                  Сервер бэкенда на Render автоматически засыпает после 15 минут неактивности. Пробуждение сервера занимает около 30–50 секунд. Пожалуйста, подождите.
                </p>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1.5rem' }}>
                <div style={{
                  width: '60px',
                  height: '60px',
                  borderRadius: '50%',
                  backgroundColor: 'rgba(255, 73, 73, 0.1)',
                  border: '1px solid rgba(255, 73, 73, 0.2)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#FF4949',
                  fontSize: '1.8rem'
                }}>⚠️</div>
                <h2 style={{ fontSize: '1.4rem', fontWeight: 600, color: 'var(--color-text-main)', margin: 0 }}>
                  Бэкенд недоступен
                </h2>
                <p style={{ color: 'var(--color-text-muted)', fontSize: '0.88rem', margin: 0, lineHeight: 1.6 }}>
                  Не удалось установить соединение с сервером. Возможно, сервер временно отключен, обновляется или ваш провайдер блокирует подключение.
                </p>
                <button 
                  className="btn btn-refresh" 
                  onClick={() => {
                    setServerStatus('connecting');
                    pingServer();
                  }}
                  style={{
                    padding: '0.6rem 1.5rem',
                    fontSize: '0.85rem',
                    backgroundColor: 'var(--color-brand)',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 'var(--radius-md)',
                    cursor: 'pointer',
                    fontWeight: 600,
                    transition: 'background-color 0.2s',
                    marginTop: '0.5rem'
                  }}
                >
                  <RefreshCw size={14} style={{ marginRight: '8px' }} />
                  Повторить попытку
                </button>
              </div>
            )}
          </div>
        ) : loading ? (
          <div className="status-msg">
            <RefreshCw size={48} className="status-msg-icon spin" />
            <p>Загрузка аналитики...</p>
          </div>
        ) : (
          <>
            {/* OVERVIEW TAB */}
            {activeTab === 'overview' && (
              <div className="tab-content">
                {/* Stats row */}
                <div className="grid-4col" style={{ marginBottom: '2rem' }}>
                  <div className="stat-card" style={{ '--accent-color': 'var(--color-brand)' }}>
                    <div className="stat-card-inner">
                      <div style={{ minWidth: 0, flex: 1, marginRight: '0.5rem' }}>
                        <div className="stat-label">Сообщений в чате</div>
                        <div className="stat-value">{statsSummary.messages.toLocaleString()}</div>
                      </div>
                      <div className="stat-icon-wrapper"><MessageSquare size={22} style={{ color: 'var(--color-brand)' }} /></div>
                    </div>
                  </div>
                  <div className="stat-card" style={{ '--accent-color': 'var(--color-text-accent)' }}>
                    <div className="stat-card-inner">
                      <div style={{ minWidth: 0, flex: 1, marginRight: '0.5rem' }}>
                        <div className="stat-label">Уникальных зрителей</div>
                        <div className="stat-value">{statsSummary.uniqueChatters.toLocaleString()}</div>
                      </div>
                      <div className="stat-icon-wrapper"><Users size={22} style={{ color: 'var(--color-text-accent)' }} /></div>
                    </div>
                  </div>
                  <div className="stat-card" style={{ '--accent-color': '#ff007f' }}>
                    <div className="stat-card-inner">
                      <div style={{ minWidth: 0, flex: 1, marginRight: '0.5rem' }}>
                        <div className="stat-label">Самый активный чатер</div>
                        <div 
                          className="stat-value" 
                          title={statsSummary.mostActiveChatter || ''}
                          style={{ 
                            fontSize: (statsSummary.mostActiveChatter || '').length > 15 ? '1.05rem' : '1.25rem', 
                            letterSpacing: '-0.02em', 
                            overflow: 'hidden', 
                            textOverflow: 'ellipsis', 
                            whiteSpace: 'nowrap' 
                          }}
                        >
                          {statsSummary.mostActiveChatter || '—'}
                        </div>
                      </div>
                      <div className="stat-icon-wrapper"><Users size={22} style={{ color: '#ff007f' }} /></div>
                    </div>
                  </div>
                  <div className="stat-card" style={{ '--accent-color': '#00f5d4' }}>
                    <div className="stat-card-inner">
                      <div style={{ minWidth: 0, flex: 1, marginRight: '0.5rem' }}>
                        <div className="stat-label">Распознано слов (голос)</div>
                        <div className="stat-value">{statsSummary.voiceWordsCount.toLocaleString()}</div>
                      </div>
                      <div className="stat-icon-wrapper"><Mic size={22} style={{ color: '#00f5d4' }} /></div>
                    </div>
                  </div>
                </div>

                <div className="grid-2col" style={{ gridTemplateColumns: '2fr 1fr' }}>
                  {/* Activity graph */}
                  <div className="panel">
                    <div className="panel-header">
                      <h3 className="panel-title"><Activity size={20} /> Активность чата</h3>
                      <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
                        <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)' }}>выберите конкретный стрим для графика</span>
                        {activityData.length > 0 && (
                          <button 
                            className="btn btn-secondary" 
                            style={{ fontSize: '0.75rem', padding: '0.3rem 0.6rem' }} 
                            onClick={startGraphRace}
                            disabled={isRacing}
                          >
                            <Activity size={12} className={isRacing ? "pulse" : ""} /> {isRacing ? 'Гонка идет...' : 'Запустить гонку'}
                          </button>
                        )}
                      </div>
                    </div>
                    {selectedStreamId === 'all' ? (
                      <div className="status-msg" style={{ height: '300px' }}>
                        <BarChart2 size={36} className="status-msg-icon" />
                        <p>Для просмотра временного графика выберите конкретный стрим в верхнем меню</p>
                      </div>
                    ) : activityData.length === 0 ? (
                      <div className="status-msg" style={{ height: '300px' }}>
                        <MessageSquare size={36} className="status-msg-icon" />
                        <p>В этом стриме пока не было сообщений</p>
                      </div>
                    ) : (
                      <div className="chart-container">
                        <Line data={chartDataConfig} options={chartOptions} />
                      </div>
                    )}
                  </div>

                  {/* Quick Words list */}
                  <div className="panel">
                    <div className="panel-header">
                      <h3 className="panel-title">
                        <Mic size={18} style={{ color: 'var(--color-text-accent)' }} /> Голос стримера (Топ)
                      </h3>
                    </div>
                    {voiceWords.length === 0 ? (
                      <div className="status-msg" style={{ height: '300px', padding: '1rem' }}>
                        <Mic size={28} className="status-msg-icon" />
                        <p>Слова пока не распознаны. Запустите local_worker на ПК.</p>
                      </div>
                    ) : (
                      <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', maxHeight: '320px', overflowY: 'auto', paddingRight: '4px' }}>
                        {voiceWords.slice(0, 7).map((w, idx) => (
                          <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0.75rem', backgroundColor: 'var(--color-bg-base)', border: '1px solid var(--color-border)', borderRadius: '6px', alignItems: 'center' }}>
                            <span style={{ fontWeight: 600, color: 'var(--color-text-main)' }}>#{idx+1} {w.word}</span>
                            <span className="badge badge-streamer">{w.word_count} раз</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}

            {/* CHATTERS TAB */}
            {activeTab === 'chatters' && (
              <div className="grid-2col tab-content" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))', gap: '1.5rem', alignItems: 'start' }}>
                <div className="panel">
                  <div className="panel-header">
                    <h3 className="panel-title"><Users size={20} /> Орбита зрителей</h3>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'center', padding: '1rem 0' }}>
                    <ChatterOrbit chatters={chatters} />
                  </div>
                </div>

                <div className="panel">
                  <div className="panel-header">
                    <h3 className="panel-title"><Users size={20} /> Лидеры чата по активности</h3>
                    <div className="search-container">
                      <Search size={16} className="search-icon" />
                      <input 
                        type="text" 
                        className="search-input" 
                        placeholder="Поиск зрителя..."
                        value={chattersSearch}
                        onChange={(e) => setChattersSearch(e.target.value)}
                      />
                    </div>
                  </div>

                  {chatters.length === 0 ? (
                    <div className="status-msg">
                      <Users size={40} className="status-msg-icon" />
                      <p>Нет данных о зрителях для этого периода</p>
                    </div>
                  ) : (
                    <div className="table-wrapper">
                      <table className="data-table">
                        <thead>
                          <tr>
                            <th>Место</th>
                            <th>Никнейм</th>
                            <th>Роли</th>
                            <th>Сообщений</th>
                          </tr>
                        </thead>
                        <tbody>
                          {chatters
                            .filter(c => {
                              const disp = c.display_name || c.username || '';
                              const user = c.username || '';
                              return disp.toLowerCase().includes(chattersSearch.toLowerCase()) || 
                                     user.toLowerCase().includes(chattersSearch.toLowerCase());
                            })
                            .map((c, idx) => (
                              <tr key={idx} className="chatter-row">
                                <td style={{ fontWeight: 700, width: '80px', color: idx < 3 ? 'var(--color-brand)' : 'var(--color-text-muted)' }}>
                                  #{idx + 1}
                                </td>
                                <td style={{ fontWeight: 600 }}>{c.display_name || c.username || '—'}</td>
                                <td>
                                  <div style={{ display: 'flex', gap: '0.4rem' }}>
                                    {(c.username || '').toLowerCase() === TWITCH_CHANNEL && (
                                      <span className="badge badge-streamer">Стример</span>
                                    )}
                                    {c.is_mod ? <span className="badge badge-mod">Мод</span> : null}
                                    {c.is_sub ? <span className="badge badge-sub">Саб</span> : null}
                                  </div>
                                </td>
                                <td style={{ fontWeight: 700, color: 'var(--color-text-accent)' }}>
                                  {c.message_count.toLocaleString()}
                                </td>
                              </tr>
                            ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* WORDS TAB */}
            {activeTab === 'words' && (
              <div className="panel tab-content">
                <div className="panel-header">
                  <h3 className="panel-title"><Mic size={20} /> Частотный словарь</h3>
                  
                  <div className="nav-tabs" style={{ background: 'var(--color-bg-base)', padding: '0.2rem', borderRadius: '8px', border: '1px solid var(--color-border)' }}>
                    <button 
                      className={`tab-btn ${wordType === 'voice' ? 'active' : ''}`}
                      onClick={() => setWordType('voice')}
                      style={{ fontSize: '0.8rem', padding: '0.4rem 0.8rem' }}
                    >
                      <Volume2 size={14} /> Из Голоса (Whisper)
                    </button>
                    <button 
                      className={`tab-btn ${wordType === 'chat' ? 'active' : ''}`}
                      onClick={() => setWordType('chat')}
                      style={{ fontSize: '0.8rem', padding: '0.4rem 0.8rem' }}
                    >
                      <MessageSquare size={14} /> Из Чата (Текстом)
                    </button>
                  </div>
                </div>

                <p style={{ color: 'var(--color-text-muted)', fontSize: '0.85rem', marginBottom: '1.5rem', marginTop: '-0.75rem' }}>
                  {wordType === 'voice' 
                    ? 'Слова, которые стример произнес в микрофон (распознанные через Whisper на локальном ПК).' 
                    : 'Слова, которые зрители написали в текстовый чат Twitch.'}
                </p>

                {(() => {
                  const currentWordsList = wordType === 'voice' 
                    ? (Array.isArray(voiceWords) ? voiceWords : []) 
                    : (Array.isArray(chatWords) ? chatWords : []);
                  if (currentWordsList.length === 0) {
                    return (
                      <div className="status-msg">
                        <Mic size={40} className="status-msg-icon" />
                        <p>Нет собранных слов для выбранного стрима</p>
                      </div>
                    );
                  }
                                    const counts = currentWordsList.map(x => x.word_count);
                  const maxCount = Math.max(...counts, 1);
                  const minCount = Math.min(...counts, 1);

                  // Helper for Russian pluralization
                  const getRussianPlural = (count) => {
                    const lastDigit = count % 10;
                    const lastTwoDigits = count % 100;
                    if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
                      return 'раз';
                    }
                    if (lastDigit === 1) {
                      return 'раз';
                    }
                    if (lastDigit >= 2 && lastDigit <= 4) {
                      return 'раза';
                    }
                    return 'раз';
                  };

                  // Color assignment based on word frequency: purple gradient
                  const getWordColor = (count) => {
                    const scale = maxCount === minCount ? 1 : (count - minCount) / (maxCount - minCount);
                    // Scale saturation from 35% (desaturated/white-lavender) to 100% (saturated purple)
                    const sat = Math.round(35 + scale * 65);
                    // Scale lightness from 92% (light/white-ish) to 60% (vivid deep purple)
                    const light = Math.round(92 - scale * 32);
                    return `hsl(265, ${sat}%, ${light}%)`;
                  };

                  // Layout calculations with collision avoidance on stretched elliptical spiral
                  const placedBoxes = [];
                  const laidOutWords = [];
                  
                  const stretchX = 2.8; 
                  const stretchY = 1.0;
                  const paddingX = 12; 
                  const paddingY = 8; 
                  const remToPx = 16;

                  // Identify center group: words with count within 500 of the max count,
                  // but ONLY if the top count is >= 500. Also cap center group size to at most 3 words.
                  const centerGroupWords = currentWordsList.filter((w, idx) => 
                    idx === 0 || (maxCount >= 500 && (maxCount - w.word_count) < 500 && idx < 3)
                  );
                  const otherWordsList = currentWordsList.filter((w, idx) => 
                    !(idx === 0 || (maxCount >= 500 && (maxCount - w.word_count) < 500 && idx < 3))
                  );
                  
                  const maxOtherCount = otherWordsList.length > 0 ? Math.max(...otherWordsList.map(x => x.word_count)) : 1;
                  const minOtherCount = otherWordsList.length > 0 ? Math.min(...otherWordsList.map(x => x.word_count)) : 1;
                  const minCenterCount = Math.min(...centerGroupWords.map(x => x.word_count));

                  // Function to estimate word width factor based on wide/narrow letters
                  const getWordWidthFactor = (word) => {
                    let factor = 0;
                    const wideChars = /[мжшщыюяwm]/i;
                    const narrowChars = /[ilj1!|т]/i;
                    for (const char of word) {
                      if (wideChars.test(char)) {
                        factor += 0.75;
                      } else if (narrowChars.test(char)) {
                        factor += 0.35;
                      } else {
                        factor += 0.55;
                      }
                    }
                    return factor;
                  };

                  for (let i = 0; i < currentWordsList.length; i++) {
                    const w = currentWordsList[i];
                    const isCenterGroup = i === 0 || (maxCount >= 500 && (maxCount - w.word_count) < 500 && i < 3);
                    
                    let fontSize;
                    let fontWeight;
                    let scaleValue = 0;

                    if (isCenterGroup) {
                      // Scale font size within center group: ranges from 4.5rem to 6.2rem
                      const centerScale = maxCount === minCenterCount ? 1 : (w.word_count - minCenterCount) / (maxCount - minCenterCount);
                      fontSize = 4.5 + centerScale * 1.7;
                      fontWeight = '900';
                      scaleValue = centerScale;
                    } else {
                      // Scale font size within other words: ranges from 1.1rem to 3.2rem
                      const scale = maxOtherCount === minOtherCount ? 1 : (w.word_count - minOtherCount) / (maxOtherCount - minOtherCount);
                      scaleValue = Math.pow(scale, 1.4);
                      fontSize = 1.1 + scaleValue * 2.1;
                      fontWeight = fontSize > 2.0 ? '700' : (fontSize > 1.4 ? '600' : '500');
                    }
                    
                    // Precise width calculation based on custom width factors
                    const wordWidth = fontSize * getWordWidthFactor(w.word) * remToPx;
                    const wordHeight = fontSize * 1.1 * remToPx;
                    
                    let x = 0;
                    let y = 0;
                    
                    // Generate a stable hash for the word to randomize angle and jitter
                    let hash = 0;
                    for (let j = 0; j < w.word.length; j++) {
                      hash = w.word.charCodeAt(j) + ((hash << 5) - hash);
                    }
                    hash = Math.abs(hash);

                    // Search for position starting from r = 0.
                    // Since center group words are processed first, they cluster tightly around (0,0).
                    let found = false;
                    const rStep = 1.1; 
                    
                    for (let attempt = 0; attempt < 1200; attempt++) {
                      const startAngle = (hash % 100) * 0.06283; // 0 to 2*PI
                      const angle = startAngle + attempt * 0.15;
                      const r = (i === 0 && attempt === 0) ? 0 : (45 + rStep * attempt);
                      
                      x = r * Math.cos(angle) * stretchX;
                      y = r * Math.sin(angle) * stretchY;
                      
                      // Add coordinate noise/jitter (except for the absolute top word at the center)
                      if (r > 0) {
                        x += Math.sin(hash * 0.5 + attempt) * 6;
                        y += Math.cos(hash * 0.8 + attempt) * 4;
                      }
                      
                      let collision = false;
                      for (const box of placedBoxes) {
                        const halfW1 = wordWidth / 2;
                        const halfH1 = wordHeight / 2;
                        const halfW2 = box.w / 2;
                        const halfH2 = box.h / 2;
                        
                        if (Math.abs(x - box.x) < (halfW1 + halfW2 + paddingX) &&
                            Math.abs(y - box.y) < (halfH1 + halfH2 + paddingY)) {
                          collision = true;
                          break;
                        }
                      }
                      
                      if (!collision) {
                        found = true;
                        break;
                      }
                    }
                    
                    placedBoxes.push({ x: x, y: y, w: wordWidth, h: wordHeight });
                    
                    const color = getWordColor(w.word_count);
                    
                    // Floating parameters
                    const duration = 4.5 + (i % 3) + (i % 4) * 0.4; // 4.5s to 8.5s
                    const delay = -((i * 1.3) % 7); // negative delay to start asynchronously
                    const amount = 3 + (i % 4); // 3px to 6px float amount
                    
                    laidOutWords.push({
                      word: w.word,
                      count: w.word_count,
                      x: Math.round(x),
                      y: Math.round(y),
                      fontSize: `${fontSize}rem`,
                      fontWeight: fontWeight,
                      color: color,
                      scale: scaleValue,
                      isCenterGroup: isCenterGroup,
                      duration: `${duration}s`,
                      delay: `${delay}s`,
                      amount: `${amount}px`
                    });
                  }

                  return (
                    <div className="word-galaxy-container">
                      {laidOutWords.map((w, idx) => (
                        <div
                          key={idx}
                          className="word-galaxy-tag"
                          style={{
                            '--x': `${w.x}px`,
                            '--y': `${w.y}px`,
                            '--float-duration': w.duration,
                            '--float-delay': w.delay,
                            '--float-amount': w.amount,
                            fontSize: w.fontSize,
                            fontWeight: w.fontWeight,
                            color: w.color,
                            opacity: 0.95, // High opacity so purple colors are bright and vivid
                            zIndex: w.isCenterGroup ? 25 : Math.round(10 + w.scale * 15)
                          }}
                        >
                          {w.word}
                          <div className="word-tooltip">
                            {w.count} {getRussianPlural(w.count)}
                          </div>
                        </div>
                      ))}
                    </div>
                  );
                })()}
              </div>
            )}

            {/* ADMIN TAB */}
            {activeTab === 'admin' && (
              <div className="tab-content">
                        <h2 style={{ fontSize: '1.5rem', fontWeight: 700, marginBottom: '1.5rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                          <Settings size={24} style={{ color: 'var(--color-brand)' }} /> Панель администратора
                        </h2>

                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '1.5rem', marginBottom: '2rem' }}>
                          
                          {/* Left: Stream management */}
                          <div className="panel" style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                            <div className="panel-header">
                              <h3 className="panel-title">Управление стримами</h3>
                            </div>

                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
                              <label style={{ fontSize: '0.85rem', fontWeight: 600, color: 'var(--color-text-muted)' }}>Выбрать стрим для редактирования или удаления:</label>
                              <select 
                                className="dark-input"
                                value={adminSelectedStreamId}
                                onChange={(e) => setAdminSelectedStreamId(e.target.value)}
                              >
                                <option value="">-- Выберите стрим --</option>
                                {streams.map((stream) => (
                                  <option key={stream.id} value={stream.id}>
                                    {stream.title || 'Без названия'} ({new Date(stream.start_time).toLocaleDateString('ru-RU')} {new Date(stream.start_time).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })})
                                  </option>
                                ))}
                              </select>
                            </div>

                            {(() => {
                              const activeStream = streams.find(s => s.id === parseInt(adminSelectedStreamId));
                              if (!activeStream) return (
                                <div style={{ padding: '1.5rem', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>
                                  Выберите стрим в выпадающем списке выше для выполнения действий.
                                </div>
                              );

                              const isLive = !activeStream.end_time;
                              const statusLabel = 
                                activeStream.backfill_status === 'completed' ? 'Импортирован полностью' :
                                activeStream.backfill_status === 'pending' ? 'В очереди воркера (ожидание)' :
                                activeStream.backfill_status === 'live' ? 'В эфире (live)' : activeStream.backfill_status;

                              const statusColor = 
                                activeStream.backfill_status === 'completed' ? 'var(--color-success, #00f2fe)' :
                                activeStream.backfill_status === 'pending' ? 'var(--color-warning, #f1c40f)' : 'var(--color-primary)';

                              return (
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
                                  <div style={{ fontSize: '0.8rem', padding: '0.75rem', background: 'rgba(255,255,255,0.02)', borderRadius: '6px', border: '1px solid var(--color-border)' }}>
                                    <p style={{ margin: '0 0 0.4rem 0' }}><strong>ID сессии:</strong> {activeStream.id}</p>
                                    <p style={{ margin: '0 0 0.4rem 0' }}><strong>Статус импорта VOD:</strong> <span style={{ color: statusColor, fontWeight: 'bold' }}>{statusLabel}</span></p>
                                    <p style={{ margin: '0 0 0.4rem 0' }}><strong>Twitch VOD ID:</strong> {activeStream.twitch_vod_id || 'Отсутствует'}</p>
                                    <p style={{ margin: 0 }}><strong>Начало:</strong> {new Date(activeStream.start_time).toLocaleString('ru-RU')}</p>
                                  </div>

                                  {/* Edit Metadata */}
                                  <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', padding: '1rem', background: 'rgba(255,255,255,0.01)', borderRadius: '6px', border: '1px solid rgba(255,255,255,0.03)' }}>
                                    <h4 style={{ margin: 0, fontSize: '0.9rem', fontWeight: 600 }}>Редактирование названия / категории</h4>
                                    
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
                                      <label style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>Название стрима:</label>
                                      <input 
                                        type="text"
                                        className="dark-input"
                                        value={editTitle}
                                        onChange={(e) => setEditTitle(e.target.value)}
                                      />
                                    </div>

                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.4rem' }}>
                                      <label style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>Категория (игра):</label>
                                      <input 
                                        type="text"
                                        className="dark-input"
                                        value={editCategory}
                                        onChange={(e) => setEditCategory(e.target.value)}
                                      />
                                    </div>

                                    <button 
                                      className="btn btn-secondary" 
                                      style={{ width: '100%', padding: '0.5rem', marginTop: '0.25rem' }}
                                      disabled={savingMetadata || !editTitle.trim()}
                                      onClick={async () => {
                                        setSavingMetadata(true);
                                        try {
                                          const res = await fetch(`${API_BASE}/api/streams/${activeStream.id}`, {
                                            method: 'PUT',
                                            headers: { 'Content-Type': 'application/json' },
                                            body: JSON.stringify({ title: editTitle, category: editCategory }),
                                            credentials: 'include'
                                          });
                                          const data = await res.json();
                                          if (data.success) {
                                            alert('Метаданные стрима успешно обновлены!');
                                            fetchStreams();
                                          } else {
                                            alert(`Ошибка: ${data.error}`);
                                          }
                                        } catch (e) {
                                          alert('Ошибка при обновлении метаданных.');
                                        } finally {
                                          setSavingMetadata(false);
                                        }
                                      }}
                                    >
                                      {savingMetadata ? 'Сохранение...' : 'Сохранить изменения'}
                                    </button>
                                  </div>

                                  {/* VOD Actions (Only if VOD is present) */}
                                  {activeStream.twitch_vod_id && (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                                      <h4 style={{ margin: 0, fontSize: '0.9rem', fontWeight: 600 }}>Действия импорта VOD:</h4>
                                      <div style={{ display: 'flex', gap: '0.5rem' }}>
                                        <button
                                          className="btn btn-secondary"
                                          style={{ flex: 1, fontSize: '0.75rem', padding: '0.5rem' }}
                                          onClick={async () => {
                                            if (!confirm(`Запустить заполнение пропусков для стрима "${activeStream.title}"? Воркер докачает пропущенный чат и Whisper-речь.`)) return;
                                            try {
                                              const res = await fetch(`${API_BASE}/api/streams/reset-backfill`, {
                                                method: 'POST',
                                                headers: { 'Content-Type': 'application/json' },
                                                body: JSON.stringify({ streamId: activeStream.id, mode: 'gap_fill' }),
                                                credentials: 'include'
                                              });
                                              const data = await res.json();
                                              if (data.success) {
                                                alert('Статус сброшен на "ожидание". Воркер скоро начнет дозаполнение!');
                                                fetchStreams();
                                              } else {
                                                alert(`Ошибка: ${data.error}`);
                                              }
                                            } catch (e) {
                                              alert('Ошибка при запуске дозаполнения VOD.');
                                            }
                                          }}
                                        >
                                          Заполнить пропуски VOD
                                        </button>
                                        <button
                                          className="btn btn-secondary"
                                          style={{ flex: 1, fontSize: '0.75rem', padding: '0.5rem' }}
                                          onClick={async () => {
                                            if (!confirm(`Внимание: это полностью удалит сохраненные сообщения чата и слова Whisper для стрима "${activeStream.title}" и заново запустит весь импорт VOD с 0-й секунды. Вы уверены?`)) return;
                                            try {
                                              const res = await fetch(`${API_BASE}/api/streams/reset-backfill`, {
                                                method: 'POST',
                                                headers: { 'Content-Type': 'application/json' },
                                                body: JSON.stringify({ streamId: activeStream.id, mode: 'full_rebuild' }),
                                                credentials: 'include'
                                              });
                                              const data = await res.json();
                                              if (data.success) {
                                                alert('Данные очищены. Стрим поставлен на полный переимпорт воркером!');
                                                fetchStreams();
                                              } else {
                                                alert(`Ошибка: ${data.error}`);
                                              }
                                            } catch (e) {
                                              alert('Ошибка при запуске переимпорта.');
                                            }
                                          }}
                                        >
                                          Полный переимпорт VOD
                                        </button>
                                      </div>
                                    </div>
                                  )}

                                  {/* Delete Button */}
                                  <div style={{ borderTop: '1px solid var(--color-border)', paddingTop: '1rem', marginTop: '0.5rem' }}>
                                    <button
                                      className="btn btn-danger"
                                      style={{ 
                                        width: '100%', 
                                        display: 'flex', 
                                        alignItems: 'center', 
                                        justifyContent: 'center', 
                                        gap: '0.4rem',
                                        backgroundColor: 'rgba(231, 76, 60, 0.15)',
                                        color: '#e74c3c',
                                        border: '1px solid rgba(231, 76, 60, 0.3)',
                                        borderRadius: '4px',
                                        cursor: 'pointer',
                                        padding: '0.6rem'
                                      }}
                                      disabled={deletingStream}
                                      onClick={async () => {
                                        if (!confirm(`ВНИМАНИЕ: Вы уверены, что хотите полностью УДАЛИТЬ стрим "${activeStream.title}"? Это действие сотрет всю связанную статистику (чат, слова Whisper, модерацию) из базы данных навсегда и безвозвратно!`)) return;
                                        if (!confirm(`ПОСЛЕДНЕЕ ПРЕДУПРЕЖДЕНИЕ: Вы действительно хотите стереть стрим ID ${activeStream.id} из базы? Восстановление невозможно.`)) return;
                                        
                                        setDeletingStream(true);
                                        try {
                                          const res = await fetch(`${API_BASE}/api/streams/${activeStream.id}`, {
                                            method: 'DELETE',
                                            credentials: 'include'
                                          });
                                          const data = await res.json();
                                          if (data.success) {
                                            alert('Стрим успешно удален из базы данных!');
                                            setAdminSelectedStreamId('');
                                            fetchStreams();
                                          } else {
                                            alert(`Ошибка: ${data.error}`);
                                          }
                                        } catch (e) {
                                          alert('Ошибка при удалении стрима.');
                                        } finally {
                                          setDeletingStream(false);
                                        }
                                      }}
                                    >
                                      <Trash2 size={16} /> Удалить стрим полностью
                                    </button>
                                  </div>
                                </div>
                              );
                            })()}
                          </div>

                          {/* Right: Global actions and Stats */}
                          <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
                            
                            {/* Global Actions Panel */}
                            <div className="panel">
                              <div className="panel-header">
                                <h3 className="panel-title">Глобальные действия</h3>
                              </div>
                              <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
                                
                                {/* Twitch VOD Sync */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingBottom: '0.75rem', borderBottom: '1px solid var(--color-border)' }}>
                                  <div>
                                    <h4 style={{ margin: 0, fontSize: '0.85rem', fontWeight: 600 }}>Синхронизация Twitch VOD</h4>
                                    <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--color-text-muted)' }}>Запросить последние 20 архивов из Twitch API.</p>
                                  </div>
                                  <button 
                                    className="btn btn-secondary"
                                    style={{ fontSize: '0.75rem', padding: '0.4rem 0.8rem' }}
                                    disabled={syncingVods}
                                    onClick={async () => {
                                      setSyncingVods(true);
                                      try {
                                        const res = await fetch(`${API_BASE}/api/streams/sync-vods`, { method: 'POST', credentials: 'include' });
                                        const data = await res.json();
                                        if (data.success) {
                                          alert(`Успешно импортировано ${data.count} стримов!`);
                                          fetchStreams();
                                        } else {
                                          alert(`Ошибка: ${data.error}`);
                                        }
                                      } catch (e) {
                                        alert('Ошибка при синхронизации VOD.');
                                      } finally {
                                        setSyncingVods(false);
                                      }
                                    }}
                                  >
                                    <RefreshCw size={12} className={syncingVods ? "spin" : ""} /> {syncingVods ? 'Синхронизация...' : 'Синхронизировать VOD'}
                                  </button>
                                </div>

                                {/* Database Cleanup */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                  <div>
                                    <h4 style={{ margin: 0, fontSize: '0.85rem', fontWeight: 600 }}>Очистить пустые стримы</h4>
                                    <p style={{ margin: 0, fontSize: '0.7rem', color: 'var(--color-text-muted)' }}>Удалить сессии с 0 сообщениями и 0 слов.</p>
                                  </div>
                                  <button 
                                    className="btn btn-secondary"
                                    style={{ fontSize: '0.75rem', padding: '0.4rem 0.8rem' }}
                                    disabled={cleaningStreams}
                                    onClick={async () => {
                                      if (!confirm('Вы действительно хотите удалить все пустые стримы (в которых нет ни сообщений в чате, ни распознанных слов)? Это очистит тестовый мусор из списка.')) return;
                                      setCleaningStreams(true);
                                      try {
                                        const res = await fetch(`${API_BASE}/api/admin/cleanup`, { method: 'POST', credentials: 'include' });
                                        const data = await res.json();
                                        if (data.success) {
                                          alert(`Успешно очищено. Удалено пустых стримов: ${data.count}`);
                                          fetchStreams();
                                          fetchAdminStats();
                                        } else {
                                          alert(`Ошибка: ${data.error}`);
                                        }
                                      } catch (e) {
                                        alert('Ошибка при очистке стримов.');
                                      } finally {
                                        setCleaningStreams(false);
                                      }
                                    }}
                                  >
                                    Очистить пустые стримы
                                  </button>
                                </div>

                              </div>
                            </div>

                            {/* System Statistics Panel */}
                            <div className="panel">
                              <div className="panel-header">
                                <h3 className="panel-title">Системная статистика</h3>
                              </div>
                              
                              {loadingAdminStats || !adminStats ? (
                                <div style={{ padding: '1rem', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: '0.85rem' }}>
                                  Загрузка статистики...
                                </div>
                              ) : (
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', fontSize: '0.8rem' }}>
                                  <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '0.4rem', borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                                    <span style={{ color: 'var(--color-text-muted)' }}>Режим базы данных:</span>
                                    <strong style={{ color: 'var(--color-brand)' }}>{adminStats.dbMode.toUpperCase()}</strong>
                                  </div>
                                  {adminStats.dbMode === 'sqlite' && (
                                    <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '0.4rem', borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                                      <span style={{ color: 'var(--color-text-muted)' }}>Размер файла SQLite:</span>
                                      <strong>{adminStats.dbSizeMb} МБ</strong>
                                    </div>
                                  )}
                                  <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '0.4rem', borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                                    <span style={{ color: 'var(--color-text-muted)' }}>Всего стримов в базе:</span>
                                    <strong>{adminStats.totalStreams}</strong>
                                  </div>
                                  <div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '0.4rem', borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                                    <span style={{ color: 'var(--color-text-muted)' }}>Всего сообщений чата:</span>
                                    <strong>{adminStats.totalMessages.toLocaleString()}</strong>
                                  </div>
                                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: 'var(--color-text-muted)' }}>Всего голосовых слов:</span>
                                    <strong>{adminStats.totalVoiceWords.toLocaleString()}</strong>
                                  </div>
                                  
                                  <button 
                                    className="btn btn-secondary"
                                    style={{ width: '100%', fontSize: '0.75rem', padding: '0.4rem', marginTop: '0.5rem' }}
                                    onClick={fetchAdminStats}
                                  >
                                    Обновить статистику
                                  </button>
                                </div>
                              )}
                            </div>

                          </div>

                </div>
              </div>
            )}

            {/* MODERATOR TAB */}
            {activeTab === 'moderator' && (
              <div className="tab-content">
                {twitchConfigured && !auth.loggedIn ? (
                  <div className="login-overlay">
                    <div className="login-card">
                      <Lock size={48} style={{ color: 'var(--color-brand)', marginBottom: '1.5rem' }} />
                      <h2 className="login-title">Доступ Ограничен</h2>
                      <p className="login-description">
                        Лог действий модераторов и статистика банов/удалений доступны только стримеру и официальным модераторам канала **winx_prinx**. 
                        Пожалуйста, авторизуйтесь через Twitch для проверки прав.
                      </p>
                      <button className="btn" onClick={handleLogin}>
                        <LogIn size={16} /> Войти через Twitch
                      </button>
                    </div>
                  </div>
                ) : twitchConfigured && (auth.user?.role !== 'streamer' && auth.user?.role !== 'moderator' && auth.user?.role !== 'admin') ? (
                  <div className="status-msg">
                    <ShieldAlert size={48} className="status-msg-icon" />
                    <h2>Недостаточно прав</h2>
                    <p>Вы успешно вошли как <strong>{auth.user?.displayName}</strong>, но вы не являетесь модератором канала {TWITCH_CHANNEL}.</p>
                  </div>
                ) : (
                  <div>
                    {modProfiles.length <= 2 && (
                      <div style={{ background: 'rgba(145, 70, 255, 0.1)', border: '1px solid rgba(145, 70, 255, 0.3)', borderRadius: '8px', padding: '1rem', marginBottom: '1.5rem', display: 'flex', gap: '1rem', alignItems: 'center' }}>
                        <ShieldAlert size={24} style={{ color: 'var(--color-brand)' }} />
                        <div>
                          <h4 style={{ margin: '0 0 0.25rem 0', color: 'var(--color-text-main)', fontSize: '0.95rem' }}>Данные накапливаются</h4>
                          <p style={{ margin: 0, fontSize: '0.85rem', color: 'var(--color-text-muted)' }}>Информация о модераторах появляется по мере их активности в выбранном стриме.</p>
                        </div>
                      </div>
                    )}
                    {/* TOP 3 PODIUM */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '1.5rem', marginBottom: '2rem' }}>
                      {modProfiles.slice(0, 3).map((mod, idx) => {
                        const trophyColor = idx === 0 ? '#FFD700' : idx === 1 ? '#C0C0C0' : '#CD7F32';
                        const glowStyle = {
                          border: `1px solid ${trophyColor}40`,
                          boxShadow: `0 0 15px ${trophyColor}12`,
                          position: 'relative',
                          overflow: 'hidden'
                        };
                        return (
                          <div key={idx} className="panel" style={glowStyle}>
                            <div style={{ position: 'absolute', top: '-10px', right: '-10px', fontSize: '5rem', opacity: 0.08, color: trophyColor, fontWeight: 900 }}>
                              #{idx + 1}
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                              <div style={{ 
                                width: '44px', 
                                height: '44px', 
                                borderRadius: '50%', 
                                background: 'var(--color-bg-base)', 
                                border: `2px solid ${trophyColor}`,
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontWeight: 700,
                                fontSize: '1.1rem',
                                color: trophyColor
                              }}>
                                {idx === 0 ? '👑' : idx === 1 ? '🥈' : '🥉'}
                              </div>
                              <div>
                                <h4 style={{ margin: 0, fontSize: '1rem', fontWeight: 700 }}>{mod.moderator}</h4>
                                <span style={{ fontSize: '0.7rem', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                                  {idx === 0 ? 'Глава патруля' : idx === 1 ? 'Старший мод' : 'Защитник чата'}
                                </span>
                              </div>
                            </div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '1.25rem', fontSize: '0.8rem' }}>
                              <div>
                                <div style={{ color: 'var(--color-text-muted)' }}>Действий</div>
                                <div style={{ fontSize: '1.1rem', fontWeight: 700, color: 'var(--color-text-accent)' }}>{mod.total_actions}</div>
                              </div>
                              <div>
                                <div style={{ color: 'var(--color-text-muted)' }}>Ср. Реакция</div>
                                <div style={{ fontSize: '1.1rem', fontWeight: 700, color: '#00F5D4' }}>
                                  {mod.reaction_time_avg ? `${mod.reaction_time_avg}с` : '—'}
                                </div>
                              </div>
                              <div>
                                <div style={{ color: 'var(--color-text-muted)' }}>КПД Активности</div>
                                <div style={{ fontSize: '1.1rem', fontWeight: 700, color: '#A370F7' }}>{mod.scores.activity}%</div>
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>

                    <div className="grid-2col" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '1.5rem', alignItems: 'start' }}>
                      {/* Left: Mod List */}
                      <div className="panel">
                        <div className="panel-header">
                          <h3 className="panel-title"><ShieldAlert size={20} /> Рейтинг модераторов</h3>
                        </div>
                        {modProfiles.length === 0 ? (
                          <div className="status-msg">
                            <ShieldAlert size={40} className="status-msg-icon" />
                            <p>Модераторы еще не совершали действий в этом периоде</p>
                          </div>
                        ) : (
                          <div className="table-wrapper">
                            <table className="data-table">
                              <thead>
                                <tr>
                                  <th>Ранг</th>
                                  <th>Никнейм</th>
                                  <th>Действий</th>
                                  <th>Ср. Реакция</th>
                                </tr>
                              </thead>
                              <tbody>
                                {modProfiles.map((mod, idx) => (
                                  <tr 
                                    key={idx} 
                                    onClick={() => setSelectedMod(mod)}
                                    style={{ 
                                      cursor: 'pointer',
                                      background: selectedMod && selectedMod.moderator === mod.moderator ? 'rgba(163, 112, 247, 0.08)' : 'transparent',
                                      borderLeft: selectedMod && selectedMod.moderator === mod.moderator ? '3px solid var(--color-brand)' : 'none'
                                    }}
                                  >
                                    <td>#{idx + 1}</td>
                                    <td style={{ fontWeight: 600 }}>{mod.moderator}</td>
                                    <td>{mod.total_actions}</td>
                                    <td style={{ color: '#00F5D4', fontWeight: 600 }}>{mod.reaction_time_avg ? `${mod.reaction_time_avg}с` : '—'}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>
                        )}
                      </div>

                      {/* Right: Mod Dossier */}
                      <div className="panel">
                        <div className="panel-header">
                          <h3 className="panel-title"><UserCheck size={20} /> Личное досье модератора</h3>
                        </div>
                        
                        {!selectedMod ? (
                          <div className="status-msg">
                            <UserCheck size={40} className="status-msg-icon" />
                            <p>Выберите модератора слева для просмотра досье</p>
                          </div>
                        ) : (
                          <div>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem' }}>
                              <div>
                                <h3 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 700, color: 'var(--color-brand)' }}>{selectedMod.moderator}</h3>
                                <p style={{ margin: 0, fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>Анализ стиля модерирования и характеристик</p>
                              </div>
                            </div>

                            {/* Radar chart */}
                            <div style={{ height: '280px', display: 'flex', justifyContent: 'center', marginBottom: '1.25rem' }}>
                              <Radar 
                                data={{
                                  labels: ['Скорость', 'Активность', 'Жесткость', 'Внимательность'],
                                  datasets: [{
                                    data: [
                                      selectedMod.scores.speed,
                                      selectedMod.scores.activity,
                                      selectedMod.scores.harshness,
                                      selectedMod.scores.watchfulness
                                    ],
                                    backgroundColor: 'rgba(163, 112, 247, 0.2)',
                                    borderColor: '#A370F7',
                                    borderWidth: 2,
                                    pointBackgroundColor: '#A370F7',
                                    pointBorderColor: '#FFF',
                                    pointHoverBackgroundColor: '#FFF',
                                    pointHoverBorderColor: '#A370F7'
                                  }]
                                }}
                                options={{
                                  plugins: { legend: { display: false } },
                                  scales: {
                                    r: {
                                      angleLines: { color: '#2F2F35' },
                                      grid: { color: '#2F2F35' },
                                      pointLabels: { color: '#ADADB8', font: { size: 10, weight: 'bold' } },
                                      ticks: { display: false },
                                      min: 0,
                                      max: 100
                                    }
                                  }
                                }}
                              />
                            </div>

                            {/* Actions distribution */}
                            <div style={{ marginBottom: '1rem' }}>
                              <h4 style={{ margin: '0 0 0.5rem 0', fontSize: '0.85rem', fontWeight: 600 }}>Распределение наказаний:</h4>
                              <div style={{ height: '16px', display: 'flex', borderRadius: '4px', overflow: 'hidden', background: 'var(--color-bg-base)' }}>
                                {selectedMod.bans_count > 0 && (
                                  <div 
                                    style={{ width: `${(selectedMod.bans_count / selectedMod.total_actions) * 100}%`, background: '#FF0055', height: '100%' }} 
                                    title={`Баны: ${selectedMod.bans_count}`} 
                                  />
                                )}
                                {selectedMod.timeouts_count > 0 && (
                                  <div 
                                    style={{ width: `${(selectedMod.timeouts_count / selectedMod.total_actions) * 100}%`, background: '#FFAA00', height: '100%' }} 
                                    title={`Муты/Таймауты: ${selectedMod.timeouts_count}`} 
                                  />
                                )}
                                {selectedMod.deletions_count > 0 && (
                                  <div 
                                    style={{ width: `${(selectedMod.deletions_count / selectedMod.total_actions) * 100}%`, background: '#00AAFF', height: '100%' }} 
                                    title={`Удаления сообщений: ${selectedMod.deletions_count}`} 
                                  />
                                )}
                                {selectedMod.unbans_count > 0 && (
                                  <div 
                                    style={{ width: `${(selectedMod.unbans_count / selectedMod.total_actions) * 100}%`, background: '#00FF88', height: '100%' }} 
                                    title={`Разбаны: ${selectedMod.unbans_count}`} 
                                  />
                                )}
                              </div>
                              {/* Legend */}
                              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.75rem 1.25rem', marginTop: '0.5rem', fontSize: '0.7rem', color: 'var(--color-text-muted)' }}>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
                                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: '#FF0055' }}></span>
                                  Баны ({selectedMod.bans_count})
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
                                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: '#FFAA00' }}></span>
                                  Муты ({selectedMod.timeouts_count})
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
                                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: '#00AAFF' }}></span>
                                  Удаления ({selectedMod.deletions_count})
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
                                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: '#00FF88' }}></span>
                                  Разбаны ({selectedMod.unbans_count})
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </>
        )}
      </main>

      {/* Footer */}
      <footer style={{ backgroundColor: 'var(--color-bg-card)', borderTop: '1px solid var(--color-border)', padding: '1.5rem', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: '0.8rem' }}>
        <p>Дашборд Аналитики Twitch для канала winx_prinx © {new Date().getFullYear()}</p>
      </footer>
    </div>
  );
}