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

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

{% block content %}
<div>
    <header class="page-head">
        <div>
            <h1 class="page-title">{{ 'Movies' if media_type == 'movie' else 'TV shows' }}</h1>
            <p class="page-sub" id="page-count">Your indexed library</p>
        </div>
        <div class="page-actions">
            <button type="button" onclick="openManualAdd()" class="btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> Add title</button>
        </div>
    </header>

    <section class="flex flex-col md:flex-row md:items-center gap-3 mb-6">
        <div class="flex items-center gap-2 shrink-0">
        <div class="seg shrink-0" role="tablist">
            <a href="/media/manage?media_type=movie{% if custom %}&custom=1{% endif %}" role="tab" aria-selected="{{ 'true' if media_type == 'movie' else 'false' }}"><i class="fa-solid fa-film"></i>Movies</a>
            <a href="/media/manage?media_type=tv{% if custom %}&custom=1{% endif %}" role="tab" aria-selected="{{ 'true' if media_type == 'tv' else 'false' }}"><i class="fa-solid fa-tv"></i>TV shows</a>
        </div>
        <label class="chip-toggle shrink-0">
            <input type="checkbox" class="sr-only" {% if custom %}checked{% endif %}
                   onchange="window.location.href='/media/manage?media_type={{ media_type }}' + (this.checked ? '&custom=1' : '')">
            <i class="fa-solid fa-star text-xs"></i> Custom
        </label>
        </div>
        <div class="relative flex-1 min-w-0">
            <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-text-secondary text-sm pointer-events-none"></i>
            <input type="search" id="search-input" enterkeyhint="search" autocomplete="off"
                   placeholder="Search {{ 'movies' if media_type == 'movie' else 'TV shows' }}"
                   class="field pl-11 pr-12 py-2.5">
            <button onclick="clearSearch()" title="Clear search" aria-label="Clear search"
                    class="icon-btn absolute right-1 top-1/2 -translate-y-1/2 w-9 h-9">
                <i class="fa-solid fa-xmark"></i>
            </button>
        </div>
    </section>

    <!-- Loading Indicator -->
    <div id="loading" class="hidden">
        <i class="fa-solid fa-circle-notch fa-spin text-2xl text-primary mb-3"></i>
        <p class="text-text-secondary">Loading {{ media_type }}s...</p>
    </div>

    <!-- Error Display -->
    <div id="error-display" class="hidden mb-6 sm:mb-8">
        <div class="glass-panel p-5 border-danger/30">
            <div class="flex items-start gap-3">
                <div class="w-11 h-11 rounded-2xl bg-red-500/15 flex items-center justify-center shrink-0">
                    <i class="fa-solid fa-triangle-exclamation text-red-400"></i>
                </div>
                <div class="flex-1">
                    <h3 class="text-lg font-semibold text-red-300">Error Loading Media</h3>
                    <p id="error-message" class="mt-2 text-sm text-red-200/90"></p>
                    <button onclick="retryLoad()"
                            class="mt-4 inline-flex items-center gap-2 bg-primary hover:bg-primary/90 text-on-primary px-4 py-2.5 rounded-2xl transition font-semibold">
                        <i class="fa-solid fa-rotate-right"></i>
                        Try Again
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Media Grid -->
    <div id="media-grid"
         class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-7 gap-x-3 gap-y-5 mb-8">
        <!-- Media items will be loaded here -->
    </div>

    <!-- No Results -->
    <div id="no-results" class="hidden text-center py-16">
        <div class="max-w-md mx-auto">
            <div class="mx-auto w-12 h-12 rounded-full bg-card-high grid place-items-center mb-4">
                <i class="fa-solid fa-box-open text-text-secondary"></i>
            </div>
            <h3 class="text-lg font-semibold mb-1">Nothing found</h3>
            <p class="text-sm text-text-secondary mb-6">
                {% if media_type == 'movie' %}
                No movies match your search criteria.
                {% else %}
                No TV shows match your search criteria.
                {% endif %}
            </p>
            <button onclick="clearSearch()" class="btn-ghost px-4 py-2 text-sm">
                <i class="fa-solid fa-clapperboard"></i>
                Show All {{ media_type|title }}s
            </button>
        </div>
    </div>

    <!-- Pagination -->
    <div id="pagination" class="hidden mt-6 sm:mt-8">
        <div class="overflow-x-auto"><div class="flex justify-center items-center gap-1.5 min-w-max mx-auto" id="pagination-inner"></div></div>
    </div>

    <!-- Media Info -->
    <div id="media-info" class="hidden mt-6">
        <div>
            <div class="flex flex-col sm:flex-row justify-center items-center gap-1 sm:gap-4 text-sm text-text-secondary">
                <span id="results-info"></span>
                <span id="db-info"></span>
            </div>
        </div>
    </div>
</div>

<script>
    let currentPage = 1;
    let currentSearch = '';
    let isLoading = false;
    const mediaType = '{{ media_type }}';
    const isCustom = {{ 'true' if custom else 'false' }};

    const PAGE_SIZE = 30;

    function showLoading() {
        isLoading = true;
        const grid = document.getElementById('media-grid');
        if (grid.children.length) grid.classList.add('is-busy');
        else grid.innerHTML = Array.from({ length: 12 }, () => '<div class="m-skel"><div></div><p></p><p></p></div>').join('');
        document.getElementById('no-results').classList.add('hidden');
        document.getElementById('pagination').classList.add('hidden');
        document.getElementById('media-info').classList.add('hidden');
        document.getElementById('error-display').classList.add('hidden');
    }

    function hideLoading() {
        isLoading = false;
        const grid = document.getElementById('media-grid');
        grid.classList.remove('hidden', 'is-busy');
    }

    function showError(message) {
        document.getElementById('error-message').textContent = message;
        document.getElementById('error-display').classList.remove('hidden');
        document.getElementById('loading').classList.add('hidden');
        document.getElementById('media-grid').classList.add('hidden');
        document.getElementById('no-results').classList.add('hidden');
        document.getElementById('pagination').classList.add('hidden');
        document.getElementById('media-info').classList.add('hidden');
    }

    function syncPageUrl(page, search) {
        const params = new URLSearchParams();
        params.set('media_type', mediaType);
        if (isCustom) params.set('custom', '1');
        if (page > 1) params.set('page', page);
        if (search) params.set('search', search);
        history.replaceState(null, '', `${location.pathname}?${params.toString()}`);
    }

    async function loadMedia(page = 1, search = '') {
        if (isLoading) return;

        showLoading();
        currentPage = page;
        currentSearch = search;
        syncPageUrl(page, search);

        try {
            const url = `/api/media/list?media_type=${mediaType}&page=${page}&page_size=${PAGE_SIZE}&search=${encodeURIComponent(search)}&custom=${isCustom ? 1 : 0}`;
            const response = await fetch(url, {
                method: 'GET',
                credentials: 'same-origin',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                if (response.status === 401) {
                    window.location.href = '/login';
                    return;
                }
                throw new Error(`Server responded with ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            hideLoading();

            const grid = document.getElementById('media-grid');
            const mediaKey = mediaType === 'movie' ? 'movies' : 'tv_shows';
            const mediaItems = data[mediaKey] || [];

            if (mediaItems.length === 0) {
                grid.innerHTML = '';
                document.getElementById('no-results').classList.remove('hidden');
                document.getElementById('pagination').classList.add('hidden');
                document.getElementById('media-info').classList.add('hidden');
                return;
            }

            document.getElementById('no-results').classList.add('hidden');
            grid.innerHTML = mediaItems.map((item, idx) => createMediaCard(item, idx)).join('');
            updatePagination(data.current_page || page, data.total_pages || 1);
            updateMediaInfo(data);

        } catch (error) {
            console.error('Error loading media:', error);
            hideLoading();
            showError(`Failed to load ${mediaType}s: ${error.message}`);
            showToast(`Failed to load ${mediaType}s.`, 'error', 'Load Error');
        }
    }


    function collectQualities(item) {
        const out = [];
        (item.telegram || []).forEach(q => out.push(q));
        (item.seasons || []).forEach(s => (s.episodes || []).forEach(e => (e.telegram || []).forEach(q => out.push(q))));
        return out;
    }

    function sizeToBytes(str) {
        if (!str) return 0;
        const m = String(str).trim().match(/([\d.]+)\s*([A-Za-z]+)/);
        if (!m) return 0;
        const mult = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3, TB: 1024 ** 4 };
        return parseFloat(m[1]) * (mult[m[2].toUpperCase()] || 1);
    }

    function bytesToSize(bytes) {
        if (!bytes) return '';
        const units = ['B', 'KB', 'MB', 'GB', 'TB'];
        let i = 0, v = bytes;
        while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
        return `${v.toFixed(v >= 100 || i === 0 ? 0 : 1)} ${units[i]}`;
    }

    function allQualityLabels(qualities) {
        const norm = { '2160p': '4K', '4k': '4K', '1080p': '1080p', '720p': '720p', '480p': '480p', '360p': '360p' };
        const rank = { '4K': 5, '1080p': 4, '720p': 3, '480p': 2, '360p': 1 };
        const set = new Set();
        qualities.forEach(q => { const k = String(q.quality || '').toLowerCase(); if (norm[k]) set.add(norm[k]); });
        return Array.from(set).sort((a, b) => (rank[b] || 0) - (rank[a] || 0));
    }

    function mediaBadges(item) {
        const qs = collectQualities(item);
        if (!qs.length) return '';
        const isSplit = qs.some(q => q.group_key || (q.parts && q.parts.length));
        const labels = allQualityLabels(qs);
        const pills = labels.slice(0, 2).map(l => `<span class="q-chip">${l}</span>`).join('');
        return `<div class="absolute left-2 bottom-2 flex gap-1">${pills}${isSplit ? '<span class="q-chip" title="Split file"><i class="fa-solid fa-puzzle-piece"></i></span>' : ''}</div>`;
    }

    function thumb(url) {
        return String(url)
            .replace(/(image\.tmdb\.org\/t\/p\/)(?:original|w\d+)\//, '$1w342/')
            .replace(/(images\.metahub\.space\/poster\/)(?:medium|large)\//, '$1small/');
    }

    function createMediaCard(item, idx = 0) {
        const title = escapeHtml(item.title || item.name || 'Unknown title');
        const year = escapeHtml(item.release_year || '');
        const qs = collectQualities(item);
        const size = bytesToSize(qs.reduce((sum, q) => sum + sizeToBytes(q.size), 0));
        const href = `/media/edit?tmdb_id=${encodeURIComponent(item.tmdb_id)}&db_index=${encodeURIComponent(item.db_index)}&media_type=${encodeURIComponent(mediaType)}&page=${currentPage}${currentSearch ? `&search=${encodeURIComponent(currentSearch)}` : ''}`;
        const meta = [year, size].filter(Boolean).join(' · ');
        return `
        <article class="m-card">
            <a href="${href}" class="m-poster" aria-label="Edit ${title}">
                ${item.poster ? `<img src="${escapeHtml(thumb(item.poster))}" alt="" width="185" height="278" loading="${idx < 12 ? 'eager' : 'lazy'}" ${idx < 6 ? 'fetchpriority="high"' : ''} decoding="async" onerror="this.remove()">` : ''}
                <span class="m-fallback"><i class="fa-solid ${mediaType === 'movie' ? 'fa-film' : 'fa-tv'}"></i></span>
                ${item.rating ? `<span class="m-rating">★ ${parseFloat(item.rating).toFixed(1)}</span>` : ''}
                ${Number(item.tmdb_id) < 0 ? '<span class="m-custom"><i class="fa-solid fa-star"></i> Custom</span>' : ''}
                ${mediaBadges(item)}
            </a>
            <button onclick="deleteMedia(this)" data-tmdb-id="${escapeHtml(item.tmdb_id)}" data-db-index="${escapeHtml(item.db_index ?? '')}" data-title="${title}"
                    class="m-del" aria-label="Delete ${title}" title="Delete">
                <i class="fa-solid fa-trash-can"></i>
            </button>
            <a href="${href}" class="block mt-2 min-w-0">
                <h3 class="text-sm font-medium leading-snug truncate" title="${title}">${title}</h3>
                <p class="text-xs text-text-secondary truncate">${meta}</p>
            </a>
        </article>`;
    }

    function updatePagination(currentPage, totalPages) {
        const pagination = document.getElementById('pagination');
        const paginationInner = document.getElementById('pagination-inner');

        if (totalPages <= 1) {
            pagination.classList.add('hidden');
            paginationInner.innerHTML = '';
            return;
        }

        pagination.classList.remove('hidden');
        let paginationHTML = '';

        if (currentPage > 1) {
            paginationHTML += `
                <button onclick='loadMedia(${currentPage - 1}, ${JSON.stringify(currentSearch)})'
                        class="pg-btn">
                    Previous
                </button>
            `;
        }

        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        if (startPage > 1) {
            paginationHTML += `
                <button onclick='loadMedia(1, ${JSON.stringify(currentSearch)})'
                        class="pg-btn">
                    1
                </button>
            `;
            if (startPage > 2) {
                paginationHTML += `<span class="px-2 text-text-secondary text-sm">...</span>`;
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const isActive = i === currentPage;
            paginationHTML += `
                <button onclick='loadMedia(${i}, ${JSON.stringify(currentSearch)})'
                        class="pg-btn" ${isActive ? 'aria-current="page"' : ''}>
                    ${i}
                </button>
            `;
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHTML += `<span class="px-2 text-text-secondary text-sm">...</span>`;
            }
            paginationHTML += `
                <button onclick='loadMedia(${totalPages}, ${JSON.stringify(currentSearch)})'
                        class="pg-btn">
                    ${totalPages}
                </button>
            `;
        }

        if (currentPage < totalPages) {
            paginationHTML += `
                <button onclick='loadMedia(${currentPage + 1}, ${JSON.stringify(currentSearch)})'
                        class="pg-btn">
                    Next
                </button>
            `;
        }

        paginationInner.innerHTML = paginationHTML;
    }

    function updateMediaInfo(data) {
        const mediaInfo = document.getElementById('media-info');
        const resultsInfo = document.getElementById('results-info');
        const dbInfo = document.getElementById('db-info');

        const totalCount = data.total_count || 0;
        const pageSize = PAGE_SIZE;
        const current = data.current_page || 1;
        const startItem = totalCount === 0 ? 0 : ((current - 1) * pageSize) + 1;
        const endItem = Math.min(current * pageSize, totalCount);

        resultsInfo.textContent = `Showing ${startItem}-${endItem} of ${totalCount}`;
        document.getElementById('page-count').textContent = `${totalCount} title${totalCount === 1 ? '' : 's'}${currentSearch ? ` matching “${currentSearch}”` : ''}`;

        if (data.databases_checked && data.databases_checked.length > 0) {
            dbInfo.textContent = `Databases checked: ${data.databases_checked.join(', ')}`;
        } else {
            dbInfo.textContent = '';
        }

        mediaInfo.classList.remove('hidden');
    }

    function searchMedia() {
        const searchInput = document.getElementById('search-input');
        const search = searchInput.value.trim();
        loadMedia(1, search);
    }

    function clearSearch() {
        document.getElementById('search-input').value = '';
        loadMedia(1, '');
    }

    function retryLoad() {
        loadMedia(currentPage, currentSearch);
    }

    async function deleteMedia(buttonElement) {
    const tmdbId = buttonElement.getAttribute('data-tmdb-id');
    const dbIndex = buttonElement.getAttribute('data-db-index');
    const title = buttonElement.getAttribute('data-title');

    if (!confirm(`Are you sure you want to delete "${title}"?\n\nThis action cannot be undone.`)) return;

    try {
        const response = await fetch(`/api/media/delete?tmdb_id=${encodeURIComponent(tmdbId)}&db_index=${encodeURIComponent(dbIndex)}&media_type=${encodeURIComponent(mediaType)}`, {
            method: 'DELETE',
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            showToast(`"${title}" deleted successfully`, 'success', 'Deleted');
            loadMedia(currentPage, currentSearch); // Refresh grid
        } else {
            const error = await response.json().catch(() => ({}));
            showToast(error.detail || `Error deleting "${title}"`, 'error', 'Delete Failed');
        }
    } catch (error) {
        console.error('Error deleting media:', error);
        showToast(`Error deleting "${title}": ${error.message}`, 'error', 'Network Error');
    }
}

    document.addEventListener('DOMContentLoaded', () => {
        const params = new URLSearchParams(location.search);
        const startPage = Math.max(1, parseInt(params.get('page') || '1', 10) || 1);
        const startSearch = params.get('search') || '';

        const searchInput = document.getElementById('search-input');
        if (startSearch) searchInput.value = startSearch;
        loadMedia(startPage, startSearch);

        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                searchMedia();
            }
        });

        let searchTimeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            const searchValue = e.target.value.trim();

            if (searchValue.length === 0) {
                searchTimeout = setTimeout(() => {
                    loadMedia(1, '');
                }, 250);
            }
        });
    });
</script>

<style>
    .line-clamp-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .aspect-\[2\/3\] {
        aspect-ratio: 2 / 3;
    }

    /* Better mobile scrolling for pagination */
    #pagination .overflow-x-auto {
        scrollbar-width: thin;
    }

    #pagination .overflow-x-auto::-webkit-scrollbar {
        height: 6px;
    }

    #pagination .overflow-x-auto::-webkit-scrollbar-thumb {
        border-radius: 999px;
        background: color-mix(in srgb, var(--text) 20%, transparent);
    }

    .ma-input {
        width: 100%;
        background: var(--background, var(--bg));
        border: 1px solid var(--border);
        color: var(--text);
        border-radius: 0.9rem;
        padding: 0.7rem 0.9rem;
        font-size: 0.9rem;
        outline: none;
    }
    .ma-input:focus { border-color: var(--primary); }
    .ma-label { display:block; font-size:0.72rem; font-weight: 600; text-transform:uppercase; letter-spacing:0.04em; color:var(--text-secondary,var(--text-sec)); margin-bottom:0.35rem; }
    .ma-tab { flex:1; padding:0.55rem; border-radius:0.75rem; font-weight: 600; font-size:0.85rem; border:1px solid var(--border); background:transparent; color:var(--text); cursor:pointer; }
    .ma-tab.active { background:var(--primary); color:#fff; border-color:var(--primary); }
    .ma-catalog-picker { max-height:10rem; overflow-y:auto; border:1px solid var(--border); border-radius:0.85rem; padding:.4rem; display:flex; flex-direction:column; gap:.25rem; background:var(--background, var(--bg)); }
    .ma-cat-row { display:flex; align-items:center; gap:.55rem; padding:.45rem .6rem; border-radius:.6rem; cursor:pointer; transition:background .15s ease; }
    .ma-cat-row:hover { background:color-mix(in srgb, var(--primary) 10%, transparent); }
    .ma-cat-row.disabled { opacity:.4; pointer-events:none; }
    .ma-cat-row input { width:1rem; height:1rem; accent-color:var(--primary); cursor:pointer; flex-shrink:0; }
    .ma-cat-excl { font-size:.65rem; font-weight: 600; padding:.15rem .4rem; border-radius:9999px; background:color-mix(in srgb, var(--danger) 16%, transparent); color:var(--danger); border:1px solid color-mix(in srgb, var(--danger) 30%, transparent); }
    .ma-search-results { max-height:16rem; overflow-y:auto; margin-top:.5rem; display:flex; flex-direction:column; gap:.4rem; }
    .ma-result-row { display:flex; align-items:center; gap:.7rem; padding:.5rem; border-radius:.7rem; border:1px solid var(--border); background:var(--background, var(--bg)); cursor:pointer; text-align:left; transition:border-color .15s ease; }
    .ma-result-row:hover { border-color:var(--primary); }
    .ma-result-poster { width:2.5rem; height:3.75rem; object-fit:cover; border-radius:.4rem; flex-shrink:0; background:var(--surface,#222); }
    .ma-result-meta { min-width:0; flex:1; }
    .ma-src-badge { font-size:.6rem; font-weight: 600; padding:.1rem .4rem; border-radius:9999px; background:color-mix(in srgb, var(--primary) 16%, transparent); color:var(--primary); border:1px solid color-mix(in srgb, var(--primary) 30%, transparent); text-transform:uppercase; }
    .ma-linked-chip { display:inline-flex; align-items:center; gap:.5rem; padding:.35rem .7rem; border-radius:9999px; font-size:.78rem; font-weight: 600; background:color-mix(in srgb, var(--ok) 14%, transparent); color:var(--ok); border:1px solid color-mix(in srgb, var(--ok) 30%, transparent); }
    .ma-unlink-btn { background:none; border:none; color:inherit; font-size:1.1rem; line-height:1; cursor:pointer; padding:0 .1rem; }
</style>

<!-- Manual Add modal -->
<div id="manual-add-modal" class="fixed inset-0 z-50 hidden" aria-modal="true" role="dialog">
    <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="closeManualAdd()"></div>
    <div class="absolute inset-0 flex items-start sm:items-center justify-center p-2 sm:p-4 overflow-y-auto">
        <div class="glass-panel rounded-3xl w-full max-w-2xl my-4">
            <div class="flex items-center justify-between gap-3 px-5 sm:px-6 py-4 border-b border-hairline">
                <h2 class="text-lg sm:text-xl font-semibold text-text"><i class="fa-solid fa-plus text-emerald-400"></i> Add Content Manually</h2>
                <button onclick="closeManualAdd()" class="icon-btn shrink-0" aria-label="Close"><i class="fa-solid fa-xmark"></i></button>
            </div>

            <div class="px-5 sm:px-6 py-5 space-y-5 max-h-[75vh] overflow-y-auto">
                <!-- Type -->
                <div>
                    <label class="ma-label">Type</label>
                    <div class="flex gap-2">
                        <button type="button" class="ma-tab" data-ma-type="movie" onclick="maSetType('movie')"><i class="fa-solid fa-film"></i> Movie</button>
                        <button type="button" class="ma-tab" data-ma-type="tv" onclick="maSetType('tv')"><i class="fa-solid fa-tv"></i> TV Show</button>
                    </div>
                </div>

                <!-- Search TMDB/Cinemeta to auto-fill -->
                <div>
                    <label class="ma-label">Search title (TMDB / Cinemeta) — optional</label>
                    <div class="flex flex-col sm:flex-row gap-2">
                        <input id="ma-search-query" class="ma-input" placeholder="Title, IMDb id/link or TMDB id/link">
                        <button type="button" onclick="maSearchTitles()" class="px-4 py-2.5 rounded-xl bg-primary text-on-primary font-semibold text-sm shrink-0"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
                    </div>
                    <p id="ma-search-state" class="text-xs text-text-secondary mt-1 hidden"></p>
                    <div id="ma-search-results" class="ma-search-results hidden"></div>
                    <div id="ma-linked-badge" class="hidden mt-2">
                        <span class="ma-linked-chip">
                            <i class="fa-solid fa-link"></i>
                            <span id="ma-linked-text"></span>
                            <button type="button" onclick="maUnlink()" title="Unlink and enter manually" class="ma-unlink-btn">&times;</button>
                        </span>
                    </div>
                </div>

                <!-- Title details -->
                <div class="grid grid-cols-1 sm:grid-cols-4 gap-3">
                    <div class="sm:col-span-2">
                        <label class="ma-label">Title *</label>
                        <input id="ma-m-title" class="ma-input" placeholder="Custom title">
                    </div>
                    <div>
                        <label class="ma-label">Year (optional)</label>
                        <input id="ma-m-year" type="number" class="ma-input" placeholder="Telegram upload year">
                    </div>
                    <div>
                        <label class="ma-label">Rating (optional)</label>
                        <input id="ma-m-rating" type="number" step="0.1" min="0" max="10" class="ma-input" placeholder="Random">
                    </div>
                </div>
                <div>
                    <label class="ma-label">Genres (optional, comma-separated)</label>
                    <input id="ma-m-genres" class="ma-input" placeholder="Left empty = random">
                </div>
                <div>
                    <label class="ma-label">Description (optional)</label>
                    <textarea id="ma-m-description" rows="2" class="ma-input" placeholder="Left empty = random"></textarea>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                        <label class="ma-label">Poster URL (optional)</label>
                        <input id="ma-m-poster" type="url" class="ma-input" placeholder="Left empty = generated from title">
                    </div>
                    <div>
                        <label class="ma-label">Backdrop URL (optional)</label>
                        <input id="ma-m-backdrop" type="url" class="ma-input" placeholder="Left empty = generated from title">
                    </div>
                </div>
                <p class="text-xs text-text-secondary -mt-2">Only <span class="text-text font-semibold">Title *</span>, stream link and quality are required. Empty optional fields are auto-filled &mdash; poster &amp; backdrop become a random gradient cover with the title text.</p>

                <!-- TV episode fields -->
                <div id="ma-tv-fields" class="hidden grid grid-cols-2 sm:grid-cols-4 gap-3">
                    <div>
                        <label class="ma-label">Season *</label>
                        <input id="ma-season" type="number" min="0" class="ma-input" placeholder="1">
                    </div>
                    <div>
                        <label class="ma-label">Episode *</label>
                        <input id="ma-episode" type="number" min="0" class="ma-input" placeholder="1">
                    </div>
                    <div class="col-span-2">
                        <label class="ma-label">Episode Title (optional)</label>
                        <input id="ma-episode-title" class="ma-input" placeholder="Left empty = S01E01 style">
                    </div>
                </div>

                <!-- Stream -->
                <div class="space-y-3">
                    <div class="flex items-center justify-between gap-2">
                        <label class="ma-label" style="margin-bottom:0">Stream link(s) *</label>
                        <button type="button" onclick="maAddPart()" class="text-xs font-semibold text-primary shrink-0"><i class="fa-solid fa-plus"></i> Add split part</button>
                    </div>
                    <div id="ma-parts" class="space-y-2"></div>
                    <p class="text-xs text-text-secondary">Add more parts only for a split file (they join into one stream, in order).</p>
                    <p id="ma-resolve-state" class="text-xs text-text-secondary hidden"></p>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        <div>
                            <label class="ma-label">Quality *</label>
                            <select id="ma-quality" class="ma-input">
                                <option value="">Select</option>
                                <option>480p</option><option>720p</option><option selected>1080p</option>
                                <option>2160p</option><option value="__custom">Custom…</option>
                            </select>
                        </div>
                        <div class="sm:col-span-2">
                            <label class="ma-label">File name</label>
                            <input id="ma-name" class="ma-input" placeholder="Auto-detected on resolve">
                        </div>
                    </div>
                    <input id="ma-quality-custom" class="ma-input hidden" placeholder="Custom quality label (e.g. 4K HDR)">
                </div>

                <!-- Custom Catalog selector -->
                <div>
                    <label class="ma-label">Add to Custom Catalog</label>
                    <div id="ma-catalog-list" class="ma-catalog-picker">
                        <p class="text-xs text-text-secondary">Loading catalogs...</p>
                    </div>
                    <p class="text-xs text-text-secondary mt-1">Exclusive catalogs don't allow other selections.</p>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row justify-end gap-3 px-5 sm:px-6 py-4 border-t border-hairline">
                <button onclick="closeManualAdd()" class="px-5 py-2.5 rounded-2xl glass-panel border border-hairline text-text font-semibold text-sm">Cancel</button>
                <button id="ma-submit" onclick="submitManualAdd()" class="px-5 py-2.5 rounded-2xl bg-primary text-on-primary font-semibold text-sm">Add Content</button>
            </div>
        </div>
    </div>
</div>

<script>
    let maType = mediaType;
    let maSelectedId = null;
    let maSearchList = [];

    function maEsc(s) {
        return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    async function maSearchTitles() {
        const q = document.getElementById('ma-search-query').value.trim();
        const state = document.getElementById('ma-search-state');
        const box = document.getElementById('ma-search-results');
        if (!q) { showToast('Enter a title, IMDb or TMDB id/link.', 'error', 'Error'); return; }
        state.textContent = 'Searching...';
        state.classList.remove('hidden');
        box.classList.add('hidden');
        box.innerHTML = '';
        try {
            const params = new URLSearchParams({ media_type: maType, query: q });
            const yearVal = document.getElementById('ma-m-year').value.trim();
            if (yearVal) params.set('year', yearVal);
            const res = await fetch(`/api/media/rescan/search?${params.toString()}`);
            const data = await res.json().catch(() => ({}));
            if (!res.ok) throw new Error(data.detail || 'Search failed');
            maSearchList = data.results || [];
            if (!maSearchList.length) {
                state.textContent = 'No matches found.';
                return;
            }
            state.textContent = `Found ${maSearchList.length} match${maSearchList.length > 1 ? 'es' : ''}. Pick one to auto-fill.`;
            box.innerHTML = maSearchList.map((r, i) => `
                <button type="button" class="ma-result-row" onclick="maPickResult(${i})">
                    <img class="ma-result-poster" src="${maEsc(r.poster) || '/static/placeholder.svg'}" onerror="this.src='/static/placeholder.svg'">
                    <span class="ma-result-meta">
                        <span class="flex items-center gap-2">
                            <span class="text-sm font-semibold text-text truncate">${maEsc(r.title)}</span>
                            <span class="ma-src-badge">${maEsc(r.source)}</span>
                        </span>
                        <span class="text-xs text-text-secondary block truncate">${maEsc(r.year || '—')} · IMDb: ${maEsc(r.imdb_id || 'N/A')} · TMDB: ${maEsc(r.tmdb_id || 'N/A')}</span>
                    </span>
                </button>`).join('');
            box.classList.remove('hidden');
        } catch (e) {
            state.textContent = e.message || 'Search failed.';
        }
    }

    async function maPickResult(index) {
        const item = maSearchList[index];
        if (!item) return;
        const selectedId = item.tmdb_id || item.imdb_id;
        if (!selectedId) { showToast('This result has no usable id.', 'error', 'Error'); return; }
        const state = document.getElementById('ma-search-state');
        state.textContent = 'Loading metadata...';
        state.classList.remove('hidden');
        try {
            const params = new URLSearchParams({ media_type: maType, selected_id: String(selectedId) });
            const res = await fetch(`/api/media/manual-add/resolve-meta?${params.toString()}`);
            const data = await res.json().catch(() => ({}));
            if (!res.ok) throw new Error(data.detail || 'Could not load metadata');
            const m = data.metadata || {};
            document.getElementById('ma-m-title').value = m.title || '';
            document.getElementById('ma-m-year').value = m.release_year || '';
            document.getElementById('ma-m-rating').value = m.rating || '';
            document.getElementById('ma-m-genres').value = Array.isArray(m.genres) ? m.genres.join(', ') : (m.genres || '');
            document.getElementById('ma-m-description').value = m.description || '';
            document.getElementById('ma-m-poster').value = m.poster || '';
            document.getElementById('ma-m-backdrop').value = m.backdrop || '';

            maSelectedId = String(selectedId);
            document.getElementById('ma-linked-text').textContent = `${m.title || 'Selected'} (${item.source})`;
            document.getElementById('ma-linked-badge').classList.remove('hidden');
            document.getElementById('ma-search-results').classList.add('hidden');
            state.classList.add('hidden');
        } catch (e) {
            state.textContent = e.message || 'Could not load metadata.';
        }
    }

    function maUnlink() {
        maSelectedId = null;
        document.getElementById('ma-linked-badge').classList.add('hidden');
    }

    async function loadMaCatalogs() {
        const box = document.getElementById('ma-catalog-list');
        if (!box) return;
        box.innerHTML = '<p class="text-xs text-text-secondary">Loading...</p>';
        try {
            const res = await fetch('/api/media/manual-add/catalogs');
            const data = await res.json().catch(() => ({}));
            const catalogs = data.catalogs || [];
            if (!catalogs.length) {
                box.innerHTML = '<p class="text-xs text-text-secondary">No custom catalogs found.</p>';
                return;
            }
            box.innerHTML = catalogs.map((c, i) => {
                const safe = (s) => String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
                return `<label class="ma-cat-row" data-exclusive="${c.exclusive ? '1' : '0'}">
                    <input type="checkbox" value="${safe(c._id)}" onchange="onMaCatalogCheck(this)">
                    <span class="text-sm font-semibold text-text truncate">${safe(c.name)}</span>
                    ${c.exclusive ? '<span class="ma-cat-excl">Exclusive</span>' : ''}
                </label>`;
            }).join('');
        } catch (e) {
            box.innerHTML = '<p class="text-xs text-text-secondary">Failed to load catalogs.</p>';
        }
    }

    function onMaCatalogCheck(input) {
        const box = document.getElementById('ma-catalog-list');
        const rows = box.querySelectorAll('.ma-cat-row');
        const row = input.closest('.ma-cat-row');
        const isExclusive = row?.dataset.exclusive === '1';

        if (input.checked && isExclusive) {
            rows.forEach(r => {
                if (r !== row) {
                    r.classList.add('disabled');
                    r.querySelector('input').checked = false;
                }
            });
        } else if (!input.checked && isExclusive) {
            rows.forEach(r => r.classList.remove('disabled'));
        } else if (input.checked && !isExclusive) {
            rows.forEach(r => {
                if (r.dataset.exclusive === '1') {
                    r.classList.add('disabled');
                    r.querySelector('input').checked = false;
                }
            });
        } else {
            const anyNonExclChecked = [...box.querySelectorAll('.ma-cat-row:not([data-exclusive="1"]) input:checked')].length > 0;
            if (!anyNonExclChecked) {
                rows.forEach(r => r.classList.remove('disabled'));
            }
        }
    }

    function getMaSelectedCatalogIds() {
        const box = document.getElementById('ma-catalog-list');
        if (!box) return [];
        return [...box.querySelectorAll('input:checked')].map(i => i.value);
    }

    function maResetParts() {
        document.getElementById('ma-parts').innerHTML =
            `<div class="flex flex-col sm:flex-row gap-2" data-part>
                <input class="ma-input ma-part-url" placeholder="https://t.me/c/123456/789">
                <button type="button" onclick="maResolve()" class="px-4 py-2.5 rounded-xl glass-panel border border-hairline text-text font-semibold text-sm shrink-0">Resolve</button>
             </div>`;
    }

    function maAddPart() {
        const div = document.createElement('div');
        div.className = 'flex flex-col sm:flex-row gap-2';
        div.setAttribute('data-part', '');
        div.innerHTML = `<input class="ma-input ma-part-url" placeholder="Split part link (in order)">
            <button type="button" onclick="this.closest('[data-part]').remove()" class="px-4 py-2.5 rounded-xl border border-hairline text-red-300 font-semibold text-sm shrink-0">Remove</button>`;
        document.getElementById('ma-parts').appendChild(div);
    }

    function maCollectParts() {
        return [...document.querySelectorAll('#ma-parts .ma-part-url')]
            .map(i => i.value.trim()).filter(Boolean).map(url => ({ url }));
    }

    function openManualAdd() {
        maSetType(mediaType);
        ['ma-name','ma-season','ma-episode','ma-episode-title','ma-m-title','ma-m-year','ma-m-rating','ma-m-genres','ma-m-description','ma-m-poster','ma-m-backdrop','ma-quality-custom','ma-search-query'].forEach(id => { const el = document.getElementById(id); if (el) el.value = ''; });
        maResetParts();
        document.getElementById('ma-quality').value = '1080p';
        document.getElementById('ma-quality-custom').classList.add('hidden');
        document.getElementById('ma-resolve-state').classList.add('hidden');
        document.getElementById('ma-search-state').classList.add('hidden');
        document.getElementById('ma-search-results').classList.add('hidden');
        document.getElementById('ma-search-results').innerHTML = '';
        maSelectedId = null;
        maSearchList = [];
        document.getElementById('ma-linked-badge').classList.add('hidden');
        document.getElementById('manual-add-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        loadMaCatalogs();
    }

    function closeManualAdd() {
        document.getElementById('manual-add-modal').classList.add('hidden');
        document.body.style.overflow = '';
    }

    function maSetType(type) {
        maType = type;
        document.querySelectorAll('[data-ma-type]').forEach(b => b.classList.toggle('active', b.dataset.maType === type));
        document.getElementById('ma-tv-fields').classList.toggle('hidden', type !== 'tv');
    }

    async function maResolve() {
        const first = document.querySelector('#ma-parts .ma-part-url');
        const url = first ? first.value.trim() : '';
        const state = document.getElementById('ma-resolve-state');
        if (!url) { showToast('Paste a Telegram message link first.', 'error', 'Error'); return; }
        state.textContent = 'Resolving...';
        state.classList.remove('hidden');
        try {
            const res = await fetch('/api/media/resolve-telegram', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ url })
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) throw new Error(data.detail || 'Could not resolve link');
            const d = data.data || {};
            document.getElementById('ma-name').value = d.name || '';
            if (d.quality) {
                const sel = document.getElementById('ma-quality');
                const custom = document.getElementById('ma-quality-custom');
                const opt = [...sel.options].find(o => o.value.toLowerCase() === String(d.quality).toLowerCase());
                if (opt) {
                    sel.value = opt.value;
                    custom.classList.add('hidden');
                } else {
                    sel.value = '__custom';
                    custom.value = d.quality;
                    custom.classList.remove('hidden');
                }
            }
            if (maType === 'tv') {
                if (d.season != null && !document.getElementById('ma-season').value) document.getElementById('ma-season').value = d.season;
                if (d.episode != null && !document.getElementById('ma-episode').value) document.getElementById('ma-episode').value = d.episode;
            }
            state.textContent = `Found: ${d.name || 'file'} (${d.size || '—'})`;
        } catch (e) {
            state.textContent = e.message || 'Could not resolve link.';
            showToast(e.message || 'Could not resolve link.', 'error', 'Error');
        }
    }

    function maQuality() {
        const sel = document.getElementById('ma-quality');
        if (sel.value === '__custom') return document.getElementById('ma-quality-custom').value.trim();
        return sel.value;
    }

    async function submitManualAdd() {
        const btn = document.getElementById('ma-submit');
        const parts = maCollectParts();
        const quality = maQuality();
        const title = document.getElementById('ma-m-title').value.trim();
        if (!title) { showToast('Enter a title.', 'error', 'Error'); return; }
        if (!parts.length) { showToast('Paste at least one Telegram message link.', 'error', 'Error'); return; }
        if (!quality) { showToast('Select a quality.', 'error', 'Error'); return; }

        const payload = {
            media_type: maType,
            stream: { quality, name: document.getElementById('ma-name').value.trim() || undefined, parts },
            catalog_ids: getMaSelectedCatalogIds(),
            manual_metadata: {
                title,
                year: document.getElementById('ma-m-year').value.trim(),
                rate: document.getElementById('ma-m-rating').value.trim(),
                genres: document.getElementById('ma-m-genres').value.trim(),
                description: document.getElementById('ma-m-description').value.trim(),
                poster: document.getElementById('ma-m-poster').value.trim(),
                backdrop: document.getElementById('ma-m-backdrop').value.trim(),
            }
        };

        if (maSelectedId) payload.selected_id = maSelectedId;

        if (maType === 'tv') {
            const s = document.getElementById('ma-season').value.trim();
            const e = document.getElementById('ma-episode').value.trim();
            if (s === '' || e === '') { showToast('Season and episode are required.', 'error', 'Error'); return; }
            payload.season_number = Number(s);
            payload.episode_number = Number(e);
            payload.episode_title = document.getElementById('ma-episode-title').value.trim() || undefined;
        }

        btn.disabled = true;
        try {
            const res = await fetch('/api/media/manual-add', {
                method: 'POST', headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok) throw new Error(data.detail || 'Failed to add content');
            showToast(data.message || 'Added successfully.', 'success', 'Added');
            closeManualAdd();
            if (data.media_type === mediaType) {
                loadMedia(currentPage, currentSearch);
            }
        } catch (e) {
            showToast(e.message || 'Failed to add content.', 'error', 'Error');
        } finally {
            btn.disabled = false;
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('ma-quality').addEventListener('change', (e) => {
            document.getElementById('ma-quality-custom').classList.toggle('hidden', e.target.value !== '__custom');
        });
    });
    if (new URLSearchParams(location.search).get('add') === '1') document.addEventListener('DOMContentLoaded', () => { history.replaceState(null, '', location.pathname + '?media_type=' + mediaType); openManualAdd(); });
</script>
<style>
    .m-card { position: relative; min-width: 0; contain: layout paint style; }
    #media-grid { transition: opacity .2s var(--ease); }
    #media-grid.is-busy { opacity: .45; pointer-events: none; }
    .m-skel > div { aspect-ratio: 2 / 3; border-radius: 12px; }
    .m-skel > p { height: .7rem; margin-top: .55rem; border-radius: 99px; width: 80%; }
    .m-skel > p + p { width: 50%; margin-top: .4rem; }
    .m-skel > * { background: linear-gradient(90deg, var(--card) 25%, var(--card-high) 37%, var(--card) 63%); background-size: 400% 100%; animation: m-shimmer 1.3s ease infinite; }
    @keyframes m-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
    .m-del { position: absolute; z-index: 3; top: 6px; left: 6px; width: 30px; height: 30px; display: grid; place-items: center; border-radius: 99px; border: 0; font-size: .75rem; color: #fff; background: rgba(0,0,0,.72); opacity: 0; transition: opacity .18s var(--ease), background-color .18s var(--ease); cursor: pointer; }
    .m-card:hover .m-del, .m-del:focus-visible { opacity: 1; }
    .m-del:hover { background: var(--danger); }
    @media (hover: none) { .m-del { opacity: 1; width: 26px; height: 26px; } }
    .m-poster { position: relative; display: block; aspect-ratio: 2 / 3; border-radius: 12px; overflow: hidden; background: var(--card-high); }
    .m-poster img { position: relative; z-index: 1; width: 100%; height: 100%; object-fit: cover; transition: transform .4s var(--ease); }
    @media (hover: none) { .m-poster:hover img { transform: none; } }
    .m-poster:hover img { transform: scale(1.04); }
    .m-fallback { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-sec); font-size: 1.5rem; }
    .m-rating, .m-custom, .q-chip { position: absolute; z-index: 2; padding: 2px 7px; border-radius: 99px; font-size: .72rem; line-height: 1.4; color: #fff; background: rgba(0,0,0,.72); }
    .m-rating { top: 6px; right: 6px; font-size: .66rem; padding: 1px 6px; }
    .m-custom { bottom: 6px; right: 6px; background: var(--primary); color: var(--on-primary); }
    .q-chip { position: static; font-size: .62rem; padding: 1px 6px; }
    .m-poster > div { z-index: 2; }
</style>
{% endblock %}