File size: 54,832 Bytes
1404692
 
 
 
 
 
 
 
 
 
 
d3a7f5b
1404692
d3a7f5b
f697c3b
d3a7f5b
 
 
 
 
 
 
 
 
1404692
 
 
 
 
 
d3a7f5b
1404692
 
 
 
d3a7f5b
 
 
 
 
 
 
1404692
 
 
 
d3a7f5b
1404692
 
 
d3a7f5b
 
1404692
 
 
d3a7f5b
 
 
1404692
 
 
d3a7f5b
 
1404692
 
 
d3a7f5b
 
1404692
 
 
 
d3a7f5b
f697c3b
d3a7f5b
 
 
f697c3b
 
 
 
 
 
 
 
 
1404692
 
d3a7f5b
 
 
 
 
 
1404692
d3a7f5b
 
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
f697c3b
 
 
 
 
d3a7f5b
f697c3b
 
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
f697c3b
 
 
 
 
d3a7f5b
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
1404692
f697c3b
 
 
d3a7f5b
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
1404692
f697c3b
1404692
 
 
 
d3a7f5b
 
 
1404692
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
 
 
1404692
 
 
 
d3a7f5b
 
1404692
f697c3b
 
 
1404692
 
d3a7f5b
f697c3b
1404692
d3a7f5b
 
 
 
1404692
d3a7f5b
 
 
 
 
 
 
1404692
 
 
 
 
d3a7f5b
 
1404692
 
 
 
d3a7f5b
 
1404692
d3a7f5b
 
 
 
 
 
 
1404692
 
 
 
 
d3a7f5b
 
1404692
 
 
 
 
 
d3a7f5b
 
1404692
d3a7f5b
 
 
 
 
 
 
1404692
 
d3a7f5b
 
1404692
 
d3a7f5b
 
 
 
f697c3b
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
 
 
 
1404692
 
 
d3a7f5b
 
 
 
f697c3b
d3a7f5b
1404692
 
 
d3a7f5b
 
1404692
 
 
d3a7f5b
1404692
d3a7f5b
 
 
 
 
 
 
 
 
 
 
1404692
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
 
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f697c3b
 
 
 
 
 
 
 
d3a7f5b
1404692
f697c3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
{% extends "base.html" %}

{% block title %}Dashboard - Telegram Stremio{% endblock %}

{% block content %}
<div class="min-h-screen">
    <!-- Header with just status pill -->
    <header class="theme-card shadow-lg mb-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <h1 class="text-3xl font-bold text-primary">Dashboard</h1>
                </div>
                <button onclick="refreshSystemStats()"
                    class="flex items-center space-x-2 px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white transition-all shadow-md active:scale-95 group focus:outline-none"
                    title="Refresh System Stats">
                    <svg id="refresh-icon" xmlns="http://www.w3.org/2000/svg"
                        class="w-5 h-5 group-hover:rotate-180 transition-transform duration-500" fill="none"
                        viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    <span class="font-medium">Refresh Data</span>
                </button>
            </div>
        </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">
        <!-- System Status Section -->
        <div class="mb-8">
            <div class="grid lg:grid-cols-2 gap-8">
                <!-- System Status Card -->
                <div class="theme-card rounded-xl p-8 shadow-xl">
                    <div class="flex items-center mb-6">
                        <div
                            class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                                stroke="white">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z">
                                </path>
                            </svg>
                        </div>
                        <h3 class="text-2xl font-semibold">System Status</h3>
                    </div>

                    <div class="space-y-4">
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">Uptime</span>
                            <span id="sys-uptime" class="text-primary font-semibold">{{ system_stats.uptime or 'N/A'
                                }}</span>
                        </div>
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">Telegram Bot</span>
                            <span id="sys-bot-name" class="text-primary font-semibold">{{ system_stats.telegram_bot or
                                '@StreamBot'
                                }}</span>
                        </div>
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">Connected Bots</span>
                            <span id="sys-bots-count" class="text-primary font-semibold">{{
                                system_stats.connected_bots|default(0) }}</span>
                        </div>
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">Backend Version</span>
                            <span id="sys-version" class="text-primary font-semibold">v{{ system_stats.version or
                                '1.0.0' }}</span>
                        </div>
                    </div>
                </div>

                <!-- Bot Workload Section -->
                <!-- Live Streaming Status Card -->
                <div class="streams-container">
                    <div class="theme-card rounded-xl p-8 shadow-xl">
                        <div class="flex items-center mb-6">
                            <div
                                class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center mr-4 bg-opacity-20 text-primary">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                                    stroke="white">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z">
                                    </path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                            <div class="flex-1">
                                <h3 class="text-2xl font-semibold">Live Streaming Status</h3>
                            </div>
                            <span class="px-3 py-1 bg-red-500 text-white rounded-full text-sm font-semibold">
                                {{ system_stats.total_active_streams }} Active
                            </span>
                        </div>

                        <div class="space-y-4">
                            {% if system_stats.active_streams and system_stats.active_streams|length > 0 %}
                            {% for stream in system_stats.active_streams %}
                            <div
                                class="p-4 bg-gray-50 rounded-lg border-l-4 {% if stream.status == 'active' %}border-green-500{% elif stream.status == 'cancelled' %}border-yellow-500{% else %}border-red-500{% endif %}">
                                <div class="flex justify-between items-start mb-3">
                                    <div class="flex items-center gap-2 max-w-[70%]">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-primary shrink-0"
                                            fill="currentColor" viewBox="0 0 24 24">
                                            <path d="M8 5v14l11-7z" />
                                        </svg>
                                        <div class="truncate">
                                            <span class="font-semibold"
                                                title="{{ stream.meta.get('title') or stream.stream_id }}">{{
                                                stream.meta.get('title') or
                                                'Unknown Stream' }}</span>
                                            <div class="text-[10px] text-gray-500 font-mono mt-0.5"
                                                title="{{ stream.stream_id }}">
                                                ID: {{ stream.stream_id[:8] }}...
                                            </div>
                                        </div>
                                    </div>
                                    <span
                                        class="px-2 py-1 rounded text-xs font-semibold shrink-0 {% if stream.status == 'active' %}bg-green-100 text-green-800{% elif stream.status == 'cancelled' %}bg-yellow-100 text-yellow-800{% else %}bg-red-100 text-red-800{% endif %}">
                                        {{ stream.status|upper }}
                                    </span>
                                </div>

                                <div class="grid grid-cols-2 gap-3 mb-3">
                                    <div class="flex justify-between py-2 px-3 bg-white rounded">
                                        <span class="text-sm theme-text-secondary">Bot:</span>
                                        <span class="text-sm font-semibold">Bot{{ stream.client_index + 1 }} </span>
                                    </div>
                                    <div class="flex justify-between py-2 px-3 bg-white rounded">
                                        <span class="text-sm theme-text-secondary">File:</span>
                                        <span class="text-sm font-semibold">DC{{ stream.dc_id }}</span>
                                    </div>
                                    <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
                                        <span class="text-sm theme-text-secondary">Duration:</span>
                                        <span class="text-sm font-semibold">{{ stream.duration }}s</span>
                                    </div>

                                    <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
                                        <span class="text-sm theme-text-secondary">Data Transferred:</span>
                                        <span class="text-sm font-semibold">{{ "%.2f"|format(stream.total_bytes / 1024 /
                                            1024) }} MB</span>
                                    </div>
                                </div>

                                <div class="grid grid-cols-3 gap-3">
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Instant</div>
                                        <div class="text-sm font-bold text-primary">{{ stream.instant_mbps }} MB/s</div>
                                    </div>
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Average</div>
                                        <div class="text-sm font-bold text-primary">{{ stream.avg_mbps }} MB/s</div>
                                    </div>
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Peak</div>
                                        <div class="text-sm font-bold text-primary">{{ stream.peak_mbps }} MB/s</div>
                                    </div>
                                </div>

                                {% if stream.meta and (stream.meta.client_host or stream.meta.user_name) %}
                                <div class="mt-3 pt-3 border-t border-gray-200">
                                    <div class="flex flex-col gap-1">
                                        {% if stream.meta.client_host %}
                                        <div class="flex justify-between items-center text-sm">
                                            <div class="flex items-center gap-2">
                                                <svg xmlns="http://www.w3.org/2000/svg"
                                                    class="w-4 h-4 theme-text-secondary" fill="none" viewBox="0 0 24 24"
                                                    stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9">
                                                    </path>
                                                </svg>
                                                <span class="theme-text-secondary">Client IPv4:</span>
                                            </div>
                                            <span class="font-mono text-xs">{{ stream.meta.client_host }}</span>
                                        </div>
                                        {% endif %}
                                        {% if stream.meta.user_name %}
                                        <div class="flex justify-between items-center text-sm">
                                            <div class="flex items-center gap-2">
                                                <svg xmlns="http://www.w3.org/2000/svg"
                                                    class="w-4 h-4 theme-text-secondary" fill="none" viewBox="0 0 24 24"
                                                    stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z">
                                                    </path>
                                                </svg>
                                                <span class="theme-text-secondary">User:</span>
                                            </div>
                                            <span class="font-mono text-xs font-semibold">{{ stream.meta.user_name
                                                }}</span>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                                {% endif %}
                            </div>
                            {% endfor %}
                            {% else %}
                            <div class="text-center py-12">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-16 h-16 mx-auto mb-4 text-gray-300"
                                    fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z">
                                    </path>
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                                <p class="text-gray-500 font-medium mb-1">No active streams</p>
                                <p class="text-gray-400 text-sm">Streams will appear here when users start watching
                                    content</p>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Database Statistics Section -->
        <div class="mb-8 mt-4">
            <h2 class="text-2xl font-bold mb-6 text-center">Database and Commands</h2>
            <div class="grid lg:grid-cols-2 gap-6">
                {% if system_stats.databases %}
                {% for db_stat in system_stats.databases %}
                <div class="theme-card rounded-xl p-8 shadow-xl w-full flex flex-col h-full">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-xl font-semibold">{{ db_stat.db_name.replace("storage_", "Database ") }}</h3>
                        <div
                            class="w-12 h-12 theme-primary rounded-lg flex items-center justify-center bg-opacity-20 text-primary">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24"
                                stroke="white">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4">
                                </path>
                            </svg>
                        </div>
                    </div>

                    <div class="space-y-4 flex-grow">
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">Movies</span>
                            <span id="db-movies-{{ loop.index0 }}" class="text-primary font-semibold">{{
                                "{:,}".format(db_stat.movie_count) }}</span>
                        </div>
                        <div class="flex justify-between items-center py-3 px-4 bg-gray-50 rounded-lg">
                            <span class="font-medium theme-text-secondary">TV Shows</span>
                            <span id="db-tv-{{ loop.index0 }}" class="text-primary font-semibold">{{
                                "{:,}".format(db_stat.tv_count) }}</span>
                        </div>

                        <div class="py-3 px-4 bg-gray-50 rounded-lg">
                            <div class="flex justify-between items-center mb-2">
                                <span class="font-medium theme-text-secondary">Storage Used</span>
                                <span id="db-storage-{{ loop.index0 }}" class="text-primary font-semibold text-sm">{{
                                    "%.1f"|format(db_stat.storageSize /
                                    1024 / 1024) }} MB</span>
                            </div>
                            {% set storage_percent = (db_stat.storageSize / (500 * 1024 * 1024) * 100) | round %}
                            <div class="w-full bg-gray-200 rounded-full h-2.5">
                                <div class="theme-primary h-2.5 rounded-full" style="width: {{ storage_percent }}%">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
                {% else %}
                <div class="col-span-full text-center theme-text-secondary py-8">No database statistics available</div>
                {% endif %} <!-- Add this closing tag -->
            </div>
        </div>



        <!-- Media Management Section -->
        <div class="mb-8">
            <div class="grid lg:grid-cols-2 gap-6">
                <a href="/media/manage?media_type=movie"
                    class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group w-full">
                    <div class="flex items-center">
                        <div
                            class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
                                stroke="white">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2h4a1 1 0 110 2h-1v12a2 2 0 01-2-2V6H3a1 1 0 110-2h4zM9 6v10h6V6H9z">
                                </path>
                            </svg>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-2">Manage Movies</h3>
                            <p class="theme-text-secondary">Edit and organize movie collections</p>
                            <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.movies|default(0) }}
                                movies</div>
                        </div>
                    </div>
                </a>

                <a href="/media/manage?media_type=tv"
                    class="block theme-card rounded-xl p-8 shadow-xl hover:shadow-2xl transition-all group w-full">
                    <div class="flex items-center">
                        <div
                            class="w-16 h-16 theme-primary rounded-lg flex items-center justify-center mr-6 group-hover:scale-110 transition-transform bg-opacity-20 text-primary">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
                                stroke="white">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z">
                                </path>
                            </svg>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold mb-2">Manage TV Shows</h3>
                            <p class="theme-text-secondary">Edit and organize TV series</p>
                            <div class="mt-2 text-primary font-semibold text-sm">{{ system_stats.tv_shows|default(0) }}
                                shows</div>
                        </div>
                    </div>
                </a>
            </div>
        </div>

        <!-- Access Management Section -->
        <div class="theme-card rounded-xl p-8 shadow-xl mb-8">
            <div class="text-center mb-8">
                <div
                    class="w-16 h-16 theme-primary rounded-full flex items-center justify-center mx-auto mb-4 bg-opacity-20 text-primary">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24"
                        stroke="white">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11.536 16.464l-4.786 1.768a3 3 0 01-3.951-3.951l1.768-4.786L14.464 11.536A6 6 0 0121 9z">
                        </path>
                    </svg>
                </div>
                <h3 class="text-2xl font-bold mb-2">Access Management</h3>
                <p class="theme-text-secondary">Manage API tokens for Stremio addon access</p>
            </div>

            <!-- Create Token Form -->
            <div class="mb-8">
                <div id="create-btn-container">
                    <button onclick="toggleCreateForm()"
                        class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors duration-200 flex items-center shadow-md">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 mr-2" fill="none" viewBox="0 0 24 24"
                            stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        New Token
                    </button>
                </div>

                <div id="create-form-container"
                    class="hidden mt-4 bg-gray-50 p-6 rounded-xl border border-gray-200 transition-all duration-300">
                    <form onsubmit="createToken(event)" class="flex flex-col md:flex-row gap-4 items-end">
                        <div class="flex-1 w-full">
                            <label class="block text-sm font-medium theme-text-secondary mb-1">Token Name</label>
                            <input type="text" id="token-name" placeholder="E.g., Family iPad" required
                                class="w-full theme-card border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-primary">
                        </div>

                        <div class="w-full md:w-32">
                            <label class="block text-sm font-medium theme-text-secondary mb-1">Daily Limit</label>
                            <div class="relative">
                                <input type="number" id="daily-limit" placeholder="0" step="0.1" min="0"
                                    class="w-full theme-card border border-gray-300 rounded-lg pl-4 pr-12 py-3 focus:outline-none focus:border-primary">
                                <span class="absolute right-4 top-3 text-gray-400 text-sm pointer-events-none">GB</span>
                            </div>
                        </div>

                        <div class="w-full md:w-32">
                            <label class="block text-sm font-medium theme-text-secondary mb-1">Monthly Limit</label>
                            <div class="relative">
                                <input type="number" id="monthly-limit" placeholder="0" step="0.1" min="0"
                                    class="w-full theme-card border border-gray-300 rounded-lg pl-4 pr-12 py-3 focus:outline-none focus:border-primary">
                                <span class="absolute right-4 top-3 text-gray-400 text-sm pointer-events-none">GB</span>
                            </div>
                        </div>

                        <div class="flex gap-2 w-full md:w-auto">
                            <button type="button" onclick="toggleCreateForm()"
                                class="w-full md:w-auto bg-gray-200 text-gray-700 px-6 py-3 rounded-lg font-semibold hover:bg-gray-300 transition-colors duration-200">
                                Cancel
                            </button>
                            <button type="submit"
                                class="w-full md:w-auto bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-semibold transition-colors duration-200 flex items-center justify-center">
                                Create
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Token List -->
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-4 px-4 font-semibold theme-text-secondary">Name</th>
                            <th class="py-4 px-4 font-semibold theme-text-secondary">Usage (Today / Month)</th>
                            <th class="py-4 px-4 font-semibold theme-text-secondary">Limits (GB)</th>
                            <th class="py-4 px-4 font-semibold theme-text-secondary">Manifest URL</th>
                            <th class="py-4 px-4 font-semibold theme-text-secondary text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for token in api_tokens %}
                        <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                            <td class="py-4 px-4 font-medium">
                                {{ token.name }}<br>
                                <span class="text-xs theme-text-secondary">{{ token.created_at.strftime('%Y-%m-%d')
                                    }}</span>
                            </td>
                            <td class="py-4 px-4 text-sm">
                                <span class="block">Today: <span class="font-semibold text-primary"
                                        data-bytes="{{ token.usage.daily.bytes|default(0) }}"></span></span>
                                <span class="block text-gray-500">Month: <span
                                        data-bytes="{{ token.usage.monthly.bytes|default(0) }}"></span></span>
                            </td>
                            <td class="py-4 px-4 text-sm">
                                <div class="text-gray-600">
                                    <div class="flex items-center gap-1">
                                        <span class="w-4 text-gray-400">D:</span>
                                        {% if token.limits.daily_limit_gb %}
                                        <span
                                            data-bytes="{{ (token.limits.daily_limit_gb * 1024 * 1024 * 1024)|int }}"></span>
                                        {% else %}
                                        <span>∞</span>
                                        {% endif %}
                                    </div>
                                    <div class="flex items-center gap-1">
                                        <span class="w-4 text-gray-400">M:</span>
                                        {% if token.limits.monthly_limit_gb %}
                                        <span
                                            data-bytes="{{ (token.limits.monthly_limit_gb * 1024 * 1024 * 1024)|int }}"></span>
                                        {% else %}
                                        <span>∞</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </td>
                            <td class="py-4 px-4">
                                <div class="flex flex-col items-start space-y-1">
                                    <code
                                        class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded select-all border border-gray-200">
                                        API={{ token.token[:3] }}.......{{ token.token[-3:] }}
                                    </code>
                                    <button
                                        onclick="copyUrl('{{ (request.base_url|string).replace('http:', 'https:') }}stremio/{{ token.token }}/manifest.json')"
                                        class="text-primary hover:text-opacity-80 flex items-center space-x-1 text-sm font-medium"
                                        title="Copy URL">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none"
                                            viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                                d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                                        </svg>
                                        <span class="underline">Copy Link</span>
                                    </button>
                                </div>
                            </td>
                            <td class="py-4 px-4 text-right">
                                <button
                                    onclick="openEditModal('{{ token.token }}', '{{ token.limits.daily_limit_gb|default(0) }}', '{{ token.limits.monthly_limit_gb|default(0) }}')"
                                    class="text-blue-500 hover:text-blue-700 font-medium text-sm px-3 py-1 mr-2 rounded border border-blue-200 hover:bg-blue-50 transition-colors">
                                    Edit
                                </button>
                                <button onclick="revokeToken('{{ token.token }}')"
                                    class="text-red-500 hover:text-red-700 font-medium text-sm px-3 py-1 rounded border border-red-200 hover:bg-red-50 transition-colors">
                                    Revoke
                                </button>
                            </td>
                        </tr>
                        {% else %}
                        <tr>
                            <td colspan="5" class="py-8 text-center theme-text-secondary">No tokens found. Create one to
                                get started.</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Edit Limit Modal -->
        <div id="edit-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center z-50">
            <div class="bg-white rounded-lg p-6 w-full max-w-md shadow-xl transform transition-all">
                <h3 class="text-lg font-bold mb-4 theme-text-primary">Edit Token Limits</h3>
                <input type="hidden" id="edit-token-id">

                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium theme-text-secondary mb-1">Daily Limit (GB)</label>
                        <input type="number" id="edit-daily" placeholder="0 for unlimited" step="0.1" min="0"
                            class="w-full theme-card border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:border-primary">
                    </div>
                    <div>
                        <label class="block text-sm font-medium theme-text-secondary mb-1">Monthly Limit (GB)</label>
                        <input type="number" id="edit-monthly" placeholder="0 for unlimited" step="0.1" min="0"
                            class="w-full theme-card border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:border-primary">
                    </div>
                </div>

                <div class="mt-6 flex justify-end space-x-3">
                    <button onclick="closeEditModal()"
                        class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button onclick="saveTokenLimits()"
                        class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">Save
                        Changes</button>
                </div>
            </div>
        </div>


    </main>
</div>

<!-- JS for Workload Updates -->
<script>
    function toggleCreateForm() {
        const formContainer = document.getElementById('create-form-container');
        const btnContainer = document.getElementById('create-btn-container');

        if (formContainer.classList.contains('hidden')) {
            formContainer.classList.remove('hidden');
            btnContainer.classList.add('hidden');
        } else {
            formContainer.classList.add('hidden');
            btnContainer.classList.remove('hidden');
        }
    }

    let currentEditToken = null;

    function openEditModal(token, daily, monthly) {
        currentEditToken = token;
        document.getElementById('edit-token-id').value = token;
        document.getElementById('edit-daily').value = daily == 'None' ? 0 : daily;
        document.getElementById('edit-monthly').value = monthly == 'None' ? 0 : monthly;

        document.getElementById('edit-modal').classList.remove('hidden');
    }

    function closeEditModal() {
        document.getElementById('edit-modal').classList.add('hidden');
        currentEditToken = null;
    }

    async function saveTokenLimits() {
        if (!currentEditToken) return;

        const daily = document.getElementById('edit-daily').value;
        const monthly = document.getElementById('edit-monthly').value;

        try {
            const response = await fetch('/api/tokens/' + currentEditToken, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    daily_limit_gb: daily,
                    monthly_limit_gb: monthly
                })
            });

            if (response.ok) {
                closeEditModal();
                // Refresh page to show new limits (or update DOM dynamically if we want)
                window.location.reload();
            } else {
                alert("Failed to update limits");
            }
        } catch (error) {
            console.error(error);
            alert("Error updating limits");
        }
    }
</script>

<!-- System Stats Auto-Refresh -->
<script>
    async function refreshSystemStats() {
        const icon = document.getElementById('refresh-icon');
        if (icon) icon.classList.add('animate-spin'); // Add tailwind spin class

        try {
            const response = await fetch('/api/system/stats');
            if (response.ok) {
                const stats = await response.json();

                // Update Static Elements
                const elUptime = document.getElementById('sys-uptime');
                if (elUptime) elUptime.innerText = stats.uptime;

                const elBotName = document.getElementById('sys-bot-name');
                if (elBotName) elBotName.innerText = stats.telegram_bot;

                const elBotCount = document.getElementById('sys-bots-count');
                if (elBotCount) elBotCount.innerText = stats.connected_bots;

                const elVersion = document.getElementById('sys-version');
                if (elVersion) elVersion.innerText = 'v' + stats.version;

                // Update Database Stats
                if (stats.databases && Array.isArray(stats.databases)) {
                    stats.databases.forEach((db, index) => {
                        const elMovies = document.getElementById(`db-movies-${index}`);
                        if (elMovies) elMovies.innerText = db.movie_count.toLocaleString();

                        const elTv = document.getElementById(`db-tv-${index}`);
                        if (elTv) elTv.innerText = db.tv_count.toLocaleString();

                        const elStorage = document.getElementById(`db-storage-${index}`);
                        if (elStorage) {
                            const mb = db.storageSize / (1024 * 1024);
                            elStorage.innerText = mb.toFixed(1) + ' MB';
                        }
                    });
                }

                // Update API Token Usage Data
                if (stats.api_tokens && Array.isArray(stats.api_tokens)) {
                    stats.api_tokens.forEach((token, index) => {
                        // Find all elements with data-bytes attributes for this token
                        const tokenRows = document.querySelectorAll('tbody tr');

                        // Get the token's row (skip the "No tokens found" row)
                        if (tokenRows.length > index && !tokenRows[index].querySelector('[colspan]')) {
                            const row = tokenRows[index];

                            // Update daily usage
                            const dailyUsageSpan = row.querySelector('td:nth-child(2) span.font-semibold');
                            if (dailyUsageSpan && token.usage && token.usage.daily) {
                                const dailyBytes = token.usage.daily.bytes || 0;
                                dailyUsageSpan.setAttribute('data-bytes', dailyBytes);
                                dailyUsageSpan.textContent = formatBytes(dailyBytes);
                            }

                            // Update monthly usage
                            const monthlyUsageSpan = row.querySelector('td:nth-child(2) span.text-gray-500 span');
                            if (monthlyUsageSpan && token.usage && token.usage.monthly) {
                                const monthlyBytes = token.usage.monthly.bytes || 0;
                                monthlyUsageSpan.setAttribute('data-bytes', monthlyBytes);
                                monthlyUsageSpan.textContent = formatBytes(monthlyBytes);
                            }
                        }
                    });
                }

                // Update Bot Workloads
                await updateBotWorkloads();

                // Update Active Streams
                await updateActiveStreams();
            }
        } catch (error) {
            console.error("Failed to refresh system stats:", error);
        } finally {
            // Remove spin after short delay to make it visible
            setTimeout(() => {
                if (icon) icon.classList.remove('animate-spin');
            }, 500);
        }
    }

    async function updateActiveStreams() {
        try {
            const response = await fetch('/stream/stats');
            if (response.ok) {
                const data = await response.json();
                const activeStreams = data.active_streams || [];
                const container = document.getElementById('active-streams-container');

                if (container) {
                    if (activeStreams.length === 0) {
                        container.innerHTML = `<div class="p-8 text-center bg-gray-50 border border-dashed rounded-lg">
                            <i class="fas fa-video-slash text-gray-300 text-3xl mb-3"></i>
                            <p class="text-gray-500 font-medium">No active streams at the moment</p>
                            <p class="text-xs text-gray-400 mt-1">Users are not currently watching any media.</p>
                        </div>`;
                    } else {
                        const escapeHtml = (unsafe) => {
                            if (!unsafe) return '';
                            return unsafe
                                .toString()
                                .replace(/&/g, "&amp;")
                                .replace(/</g, "&lt;")
                                .replace(/>/g, "&gt;")
                                .replace(/"/g, "&quot;")
                                .replace(/'/g, "&#039;");
                        };

                        const formatBytesStr = (bytes) => {
                            if (bytes === 0) return '0 B';
                            const k = 1024;
                            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
                            const i = Math.floor(Math.log(bytes) / Math.log(k));
                            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                        };

                        container.innerHTML = activeStreams.map(stream => {
                            let statusColor = 'bg-red-100 text-red-800';
                            let statusPulse = 'hidden';
                            if (stream.status === 'active') {
                                statusColor = 'bg-green-100 text-green-800';
                                statusPulse = '';
                            } else if (stream.status === 'cancelled') {
                                statusColor = 'bg-yellow-100 text-yellow-800';
                            }

                            const streamIdStr = stream.stream_id ? stream.stream_id.substring(0, 8) + '...' : 'Unknown';
                            const titleStr = (stream.meta && stream.meta.title) ? stream.meta.title : (stream.title || 'Unknown Stream');

                            return `
                            <div class="p-4 bg-gray-50 rounded-lg border-l-4 border-green-500">
                                <div class="flex justify-between items-start mb-3">
                                    <div class="flex items-center gap-2 max-w-[70%]">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-primary shrink-0" fill="currentColor" viewBox="0 0 24 24">
                                            <path d="M8 5v14l11-7z" />
                                        </svg>
                                        <div class="truncate">
                                            <span class="font-semibold" title="${escapeHtml(stream.title || stream.stream_id)}">${escapeHtml(titleStr)}</span>
                                            <div class="text-[10px] text-gray-500 font-mono mt-0.5" title="${escapeHtml(stream.stream_id)}">
                                                ID: ${escapeHtml(streamIdStr)}
                                            </div>
                                        </div>
                                    </div>
                                    <span class="px-2 py-1 rounded text-xs font-semibold shrink-0 uppercase ${statusColor}">
                                        ${escapeHtml(stream.status)}
                                    </span>
                                </div>

                                <div class="grid grid-cols-2 gap-3 mb-3">
                                    <div class="flex justify-between py-2 px-3 bg-white rounded">
                                        <span class="text-sm theme-text-secondary">Bot:</span>
                                        <span class="text-sm font-semibold">Bot${(stream.client_index || 0) + 1} </span>
                                    </div>
                                    <div class="flex justify-between py-2 px-3 bg-white rounded">
                                        <span class="text-sm theme-text-secondary">File:</span>
                                        <span class="text-sm font-semibold">DC${stream.dc_id || '-'}</span>
                                    </div>
                                    <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
                                        <span class="text-sm theme-text-secondary">Duration:</span>
                                        <span class="text-sm font-semibold">${stream.duration || 0}s</span>
                                    </div>

                                    <div class="flex justify-between py-2 px-3 bg-white rounded col-span-2">
                                        <span class="text-sm theme-text-secondary">Data Transferred:</span>
                                        <span class="text-sm font-semibold">${formatBytesStr(stream.total_bytes)}</span>
                                    </div>
                                </div>

                                <div class="grid grid-cols-3 gap-3">
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Instant</div>
                                        <div class="text-sm font-bold text-primary">${stream.instant_mbps || 0} MB/s</div>
                                    </div>
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Average</div>
                                        <div class="text-sm font-bold text-primary">${stream.avg_mbps || 0} MB/s</div>
                                    </div>
                                    <div class="text-center py-3 bg-white rounded">
                                        <div class="text-xs theme-text-secondary mb-1">Peak</div>
                                        <div class="text-sm font-bold text-primary">${stream.peak_mbps || 0} MB/s</div>
                                    </div>
                                </div>
                                </div>

                                ${stream.meta && (stream.meta.client_host || stream.meta.user_name) ? `
                                <div class="mt-3 pt-3 border-t border-gray-200">
                                    <div class="flex flex-col gap-1">
                                        ${stream.meta.client_host ? `
                                        <div class="flex justify-between items-center text-sm">
                                            <div class="flex items-center gap-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 theme-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"></path>
                                                </svg>
                                                <span class="theme-text-secondary">Client IPv4:</span>
                                            </div>
                                            <span class="font-mono text-xs">${escapeHtml(stream.meta.client_host)}</span>
                                        </div>
                                        ` : ''}
                                        ${stream.meta.user_name ? `
                                        <div class="flex justify-between items-center text-sm">
                                            <div class="flex items-center gap-2">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 theme-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                                </svg>
                                                <span class="theme-text-secondary">User:</span>
                                            </div>
                                            <span class="font-mono text-xs font-semibold">${escapeHtml(stream.meta.user_name)}</span>
                                        </div>
                                        ` : ''}
                                    </div>
                                </div>
                                ` : ''}
                            </div>
                            `;
                        }).join('');
                    }
                }
            }
        } catch (error) {
            console.error("Failed to update active streams:", error);
        }
    }

    // Auto-refresh every 2 minutes
    const statsInterval = setInterval(refreshSystemStats, 120000);
</script>
<script>
    async function createToken(event) {
        event.preventDefault();
        const nameInput = document.getElementById('token-name');
        const dailyInput = document.getElementById('daily-limit');
        const monthlyInput = document.getElementById('monthly-limit');

        const payload = {
            name: nameInput.value,
            daily_limit_gb: dailyInput.value,
            monthly_limit_gb: monthlyInput.value
        };

        try {
            const response = await fetch('/api/tokens', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                showToast('Token created successfully!');
                setTimeout(() => window.location.reload(), 1000);
            } else {
                const data = await response.json();
                showToast('Error: ' + data.detail);
            }
        } catch (error) {
            showToast('Error creating token');
        }
    }

    async function revokeToken(token) {
        if (!confirm('Are you sure you want to revoke this token? The user will lose access immediately.')) return;

        try {
            const response = await fetch('/api/tokens/' + token, {
                method: 'DELETE'
            });

            if (response.ok) {
                showToast('Token revoked successfully!');
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showToast('Error revoking token');
            }
        } catch (error) {
            showToast('Error revoking token');
        }
    }

    function copyUrl(url) {
        navigator.clipboard.writeText(url).then(function () {
            showToast('Manifest URL copied to clipboard!');
        });
    }
</script>
</main>
</div>

<script>
    function copyToClipboard() {
        const manifestUrl = document.getElementById('manifest-url').value;
        navigator.clipboard.writeText(manifestUrl).then(function () {
            showToast('Manifest URL copied to clipboard!');
        });
    }

    function showToast(message, duration = 3000) {
        const toast = document.createElement('div');
        toast.className = 'fixed top-4 right-4 bg-blue-600 text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full';
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(() => toast.classList.remove('translate-x-full'), 100);
        setTimeout(() => {
            toast.classList.add('translate-x-full');
            setTimeout(() => document.body.removeChild(toast), 300);
        }, duration);
    }

    function toggleAccordion(id) {
        const content = document.getElementById(id);
        const icon = document.getElementById(id + '-icon');

        if (content.classList.contains('hidden')) {
            content.classList.remove('hidden');
            icon.classList.add('rotate-180');
        } else {
            content.classList.add('hidden');
            icon.classList.remove('rotate-180');
        }
    }

    function formatBytes(bytes, decimals = 2) {
        if (!+bytes) return '0 B';
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
    }

    // Auto-format bytes on load
    document.addEventListener("DOMContentLoaded", () => {
        document.querySelectorAll('[data-bytes]').forEach(el => {
            el.textContent = formatBytes(el.getAttribute('data-bytes'));
        });

        // Store the first API token in localStorage so other pages (e.g. media edit) can build stream links
        {% if api_tokens %}
        const firstToken = '{{ api_tokens[0].token }}';
        if (firstToken) {
            localStorage.setItem('api_token', firstToken);
        }
        {% endif %}
    });
</script>
{% endblock %}