File size: 32,635 Bytes
37d6cb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Check if bypass mode is enabled (respects user preference from landing page)
function isBypassEnabled() {
    try {
        const pref = localStorage.getItem('edurocks_bypass_mode');
        return pref !== 'normal'; // default to bypass if not set
    } catch (e) {
        return true;
    }
}

function isChromeOS() {
    // If IP is restricted or user prefers normal mode, always return false to disable bypass
    if (window.isIPRestricted || window.forceDisableBypass || !isBypassEnabled()) {
        return false;
    }
    const userAgent = navigator.userAgent.toLowerCase();
    return userAgent.includes("cros") || userAgent.includes("chromeos") || userAgent.includes("chrome os")
}

function openInCloak(url) {
    // If IP restricted or user prefers normal mode, navigate normally without bypass
    if (window.isIPRestricted || window.forceDisableBypass || !isBypassEnabled()) {
        window.open(url, "_blank");
        return;
    }
    if (isChromeOS()) {
        const newWindow = window.open("about:blank", "_blank");
        if (newWindow) {
            const fakeTitle = window.getFakeTitle ? window.getFakeTitle() : 'IXL - Dashboard';
            const faviconURL = window.location.origin.replace('/edum', '') + '/filestorage/photos/favicon.ico';
            const _d = 'docu', _m = 'ment', _w = 'write', _o = 'open', _c = 'close';
            const _h = 'ht', _ml = 'ml', _bd = 'bo', _dy = 'dy', _hd = 'hea', _d2 = 'd';
            const _if = 'ifra', _me = 'me', _sr = 'sr', _c2 = 'c';
            const _bg = '#1a0f14';
            const doc = newWindow[_d + _m];
            doc[_o]();
            const parts = [
                '<!DOCTYPE ' + _h + _ml + '>',
                '<' + _h + _ml + '>',
                '<' + _hd + _d2 + '>',
                '<title>' + fakeTitle + '</title>',
                '<link rel="icon" href="' + faviconURL + '" type="image/x-icon">',
                '<style>',
                _bd + _dy + ' { margin: 0; padding: 0; height: 100vh; overflow: hidden; background-color: ' + _bg + '; }',
                _if + _me + ' { border: none; width: 100%; height: 100%; }',
                '</style>',
                '</' + _hd + _d2 + '>',
                '<' + _bd + _dy + '>',
                '<' + _if + _me + ' ' + _sr + _c2 + '="' + url + '"></' + _if + _me + '>',
                '</' + _bd + _dy + '>',
                '</' + _h + _ml + '>'
            ];
            doc[_w](parts.join(''));
            doc[_c]();
        }
    } else {
        window.open(url, "_blank")
    }
}

var openInAboutBlank = openInCloak;

class MediaApp {
    constructor() {
        this.config = {
            playerSources: [{
                name: "Videasy",
                url: "https://player.videasy.net",
                tmdbOnly: true
            }, {
                name: "Vidsrc.ru",
                url: "https://vidsrc-embed.ru/embed",
                preferImdb: true
            }, {
                name: "Vidsrc.su",
                url: "https://vidsrc-embed.su/embed",
                preferImdb: true
            }, {
                name: "Vidsrcme.su",
                url: "https://vidsrcme.su/embed",
                preferImdb: true
            }, {
                name: "Vsrc.su",
                url: "https://vsrc.su/embed",
                preferImdb: true
            }],
            cacheTime: 24 * 60 * 60 * 1e3
        };
        this.state = {
            currentItem: null,
            searchTimeout: null,
            isLoading: false,
            selectedPlayer: null,
            audioPref: 'sub'
        };
        this.elements = this.getElements();
        this.currentPlayerUrl = "";
        this.init()
    }
    getApiUrl() {
        if (window.eduBackendRoot) {
            return window.eduBackendRoot + '/edum/edumapi.php';
        }
        if (window.eduBackendOverride) {
            return window.eduBackendOverride.replace('userauth/api.php', 'edum/edumapi.php');
        }
        const hostname = window.location.hostname;
        const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname) || /^[0-9a-fA-F:]+$/.test(hostname);
        const isLocal = hostname === 'localhost' || hostname.endsWith('.local') || hostname === '127.0.0.1' || hostname === '::1';
        if (hostname === 'devbuild.edurocks.org' || isIP || isLocal) {
            return 'https://backendapi.learnbla.org/edum/edumapi.php';
        }
        const domain = hostname.replace(/^www\./, "");
        return `https://backendapi.${domain}/edum/edumapi.php`;
    }
    getElements() {
        return {
            searchInput: document.getElementById("searchInput"),
            searchBtn: document.getElementById("searchBtn"),
            loading: document.getElementById("loading"),
            results: document.getElementById("results"),
            recentSection: document.getElementById("recentSection"),
            recentGrid: document.getElementById("recentGrid"),
            playerModal: document.getElementById("playerModal"),
            modalTitle: document.getElementById("modalTitle"),
            modalDetails: document.getElementById("modalDetails"),
            closeModal: document.getElementById("closeModal"),
            tvControls: document.getElementById("tvControls"),
            seasonSelect: document.getElementById("seasonSelect"),
            episodeListContainer: document.getElementById("episodeListContainer"),
            playerSources: document.getElementById("playerSources"),
            playerFrame: document.getElementById("playerFrame"),
            videoIframe: document.getElementById("videoIframe"),
            openExternal: document.getElementById("openExternal"),
            tryAnother: document.getElementById("tryAnother"),
            refiningIndicator: document.getElementById("refiningIndicator"),
            audioPrefContainer: document.getElementById("audioPrefContainer")
        }
    }
    async init() {
        await new Promise(resolve => setTimeout(resolve, 500));
        await this.checkApiConnectivity();
        this.setupEventListeners();
        this.loadRecentItems();
        this.elements.searchInput.focus();
        this.setupIntersectionObserver();
        this.focusedCardIndex = -1;
        this.currentEpisodeData = []
    }
    async checkApiConnectivity() {
        try {
            const response = await fetch(`${this.getApiUrl()}?action=search&query=test`, {
                method: 'GET',
                signal: AbortSignal.timeout(5000)
            });
        } catch (error) {}
    }
    setupEventListeners() {
        this.elements.searchBtn.addEventListener("click", () => this.handleSearch());
        this.elements.searchInput.addEventListener("keypress", e => {
            if (e.key === "Enter") this.handleSearch()
        });
        this.elements.searchInput.addEventListener("input", e => {
            clearTimeout(this.state.searchTimeout);
            const query = e.target.value.trim();
            if (query.length > 2) {
                this.elements.refiningIndicator.classList.add("active");
                this.state.searchTimeout = setTimeout(() => {
                    this.search(query);
                    this.elements.refiningIndicator.classList.remove("active")
                }, 500)
            } else if (query.length === 0) {
                this.clearResults();
                this.elements.refiningIndicator.classList.remove("active")
            }
        });
        this.elements.closeModal.addEventListener("click", () => this.closeModal());
        this.elements.playerModal.addEventListener("click", e => {
            if (e.target === this.elements.playerModal) this.closeModal()
        });
        this.elements.seasonSelect.addEventListener("change", () => this.updateEpisodes());
        document.addEventListener("keydown", e => {
            if (e.key === "Escape" && !this.elements.playerModal.classList.contains("hidden")) {
                this.closeModal()
            } else if (!this.elements.playerModal.classList.contains("hidden")) {
                return
            } else if (e.key === "ArrowRight") {
                this.navigateCards(1)
            } else if (e.key === "ArrowLeft") {
                this.navigateCards(-1)
            } else if (e.key === "ArrowDown") {
                this.navigateCards(6)
            } else if (e.key === "ArrowUp") {
                this.navigateCards(-6)
            } else if (e.key === "Enter" && this.focusedCardIndex >= 0) {
                const cards = document.querySelectorAll(".media-card");
                if (cards[this.focusedCardIndex]) {
                    cards[this.focusedCardIndex].click()
                }
            }
        });
        this.elements.openExternal?.addEventListener("click", () => {
            if (this.currentPlayerUrl) {
                window.open(this.currentPlayerUrl, "_blank")
            }
        });
        this.elements.tryAnother?.addEventListener("click", () => {
            this.hidePlayer()
        })
    }
    async handleSearch() {
        const query = this.elements.searchInput.value.trim();
        if (!query) return;
        await this.search(query)
    }
    async search(query) {
        if (this.state.isLoading) return;
        try {
            this.state.isLoading = true;
            this.showSkeletons();
            const cached = this.getCache(`search_${query.toLowerCase()}`);
            if (cached) {
                this.displayResults(cached);
                return
            }
            const response = await fetch(`${this.getApiUrl()}?action=search&query=${encodeURIComponent(query)}`);
            const data = await response.json();
            if (data.error) {
                throw new Error(data.error)
            }
            this.setCache(`search_${query.toLowerCase()}`, data.results);
            this.displayResults(data.results)
        } catch (error) {
            this.showError("Search failed. Please try again.")
        } finally {
            this.state.isLoading = false
        }
    }
    displayResults(results) {
        this.elements.results.innerHTML = "";
        this.focusedCardIndex = -1;
        if (!results || results.length === 0) {
            this.showNoResults();
            return
        }
        results.forEach(item => {
            const card = this.createMediaCard(item);
            this.elements.results.appendChild(card);
            if (this.imageObserver) {
                this.imageObserver.observe(card)
            }
        })
    }
    createMediaCard(item) {
        const card = document.createElement("div");
        card.className = "media-card movie-card group relative bg-edu-dark-accent border border-edu-pink/20 rounded-xl overflow-hidden transition-all hover:bg-edu-rose hover:border-edu-pink hover:-translate-y-2 hover:shadow-2xl cursor-pointer";
        card.addEventListener("click", () => this.showPlayerModal(item));
        card.dataset.itemId = item.id;
        card.dataset.itemType = item.type;
        const posterUrl = item.poster_url || (item.poster_path ? `https://image.tmdb.org/t/p/w500${item.poster_path}` : null);
        const overview = item.overview ? item.overview.substring(0, 150) + (item.overview.length > 150 ? "..." : "") : "";
        card.innerHTML = `
            <div class="relative aspect-[2/3] overflow-hidden">
                ${posterUrl?`<img src="${posterUrl}" alt="${item.title}" loading="lazy" data-src="${posterUrl}" class="w-full h-full object-cover">`:`<div class="w-full h-full flex items-center justify-center bg-edu-dark text-6xl">🎬</div>`}
                <div class="absolute inset-0 bg-gradient-to-t from-edu-dark via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                <div class="absolute top-3 right-3 ${item.type==="movie"?"bg-gradient-to-br from-edu-pink to-edu-pink-light":"bg-gradient-to-br from-edu-rose to-edu-pink"} text-edu-text text-xs font-semibold px-3 py-1.5 rounded-lg shadow-lg">${item.type==="movie"?"Film":"TV"}</div>
            </div>
            ${overview?`<div class="absolute inset-0 bg-edu-dark/95 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center p-4">
                <div class="text-edu-text-secondary text-sm leading-relaxed">${overview}</div>
            </div>`:""}
            <div class="p-4 space-y-2">
                <div class="text-edu-text font-semibold text-lg line-clamp-2">${item.title}</div>
                <div class="flex items-center gap-3 text-sm">
                    ${item.year?`<span class="text-edu-text-secondary">${item.year}</span>`:""}
                    ${item.rating?`<span class="text-edu-pink font-medium">⭐ ${item.rating}</span>`:""}
                </div>
            </div>
        `;
        return card
    }
    async showPlayerModal(item) {
        this.state.currentItem = item;
        this.elements.modalTitle.textContent = item.title;
        this.elements.modalDetails.innerHTML = `
            <p class="text-edu-text-secondary leading-relaxed mb-4">${item.overview || "No description available."}</p>
            <div class="flex items-center gap-4 text-sm">
                ${item.rating ? `<div class="flex items-center gap-2 text-edu-text"><span class="text-edu-pink">⭐</span> ${item.rating}</div>` : ''}
                ${item.year ? `<div class="flex items-center gap-2 text-edu-text"><span class="text-edu-pink">📅</span> ${item.year}</div>` : ''}
            </div>
        `;
        if (item.type === "tv") {
            this.setSelectedPlayer(this.config.playerSources[0]);
            await this.setupTVControls(item);
            this.elements.tvControls.classList.remove("hidden");
            const progress = this.loadProgress(item.id);
            if (progress) {
                this.elements.seasonSelect.value = progress.season;
                await this.updateEpisodes()
            }
        } else {
            this.elements.tvControls.classList.add("hidden")
        }
        this.updatePlayerSources();
        this.elements.playerModal.classList.remove("hidden");
        this.addToRecent(item)
    }
    async setupTVControls(item) {
        try {
            const details = await this.getItemDetails(item);
            this.elements.seasonSelect.innerHTML = "";
            const seasonCount = details.number_of_seasons || 1;
            for (let i = 1; i <= seasonCount; i++) {
                const option = document.createElement("option");
                option.value = i;
                option.textContent = `Season ${i}`;
                this.elements.seasonSelect.appendChild(option)
            }
            await this.updateEpisodes()
        } catch (error) {
            this.elements.seasonSelect.innerHTML = '<option value="1">Season 1</option>';
            this.updateBasicEpisodes()
        }
    }
    async updateEpisodes() {
        const season = this.elements.seasonSelect.value;
        try {
            const response = await fetch(`${this.getApiUrl()}?action=seasons&id=${this.state.currentItem.id}&season=${season}`);
            const data = await response.json();
            if (data.error) throw new Error(data.error);
            this.currentEpisodeData = data.episodes || [];
            if (this.currentEpisodeData.length === 0) {
                this.renderBasicEpisodeList();
                return
            }
            this.renderEpisodeList()
        } catch (error) {
            this.renderBasicEpisodeList()
        }
    }
    updateBasicEpisodes() {
        this.currentEpisodeData = [];
        for (let i = 1; i <= 20; i++) {
            this.currentEpisodeData.push({
                episode_number: i,
                name: `Episode ${i}`,
                overview: "",
                still_path: null
            })
        }
        this.renderEpisodeList()
    }
    renderBasicEpisodeList() {
        this.currentEpisodeData = [];
        for (let i = 1; i <= 20; i++) {
            this.currentEpisodeData.push({
                episode_number: i,
                name: `Episode ${i}`,
                overview: "",
                still_path: null
            })
        }
        this.renderEpisodeList()
    }
    renderEpisodeList() {
        this.elements.episodeListContainer.innerHTML = "";
        const watchedEpisodes = this.getWatchedEpisodes(this.state.currentItem.id, this.elements.seasonSelect.value);
        this.currentEpisodeData.forEach((ep, index) => {
            const episodeItem = document.createElement("div");
            episodeItem.className = "relative bg-edu-dark-accent border border-edu-pink/20 rounded-xl p-3 cursor-pointer hover:bg-edu-rose hover:border-edu-pink transition-all flex gap-3";
            const epNum = ep.episode_number || index + 1;
            const isWatched = watchedEpisodes.includes(epNum);
            const thumbnailUrl = ep.still_path ? `https://image.tmdb.org/t/p/w300${ep.still_path}` : null;
            episodeItem.innerHTML = `
                ${thumbnailUrl?`<img src="${thumbnailUrl}" class="w-32 h-20 object-cover rounded-lg flex-shrink-0" alt="${ep.name}" loading="lazy">`:`<div class="w-32 h-20 flex items-center justify-center bg-edu-dark rounded-lg flex-shrink-0 text-3xl">📺</div>`}
                <div class="flex-1 min-w-0 flex flex-col">
                    <div class="flex items-start justify-between gap-2 mb-1">
                        <div class="text-edu-text font-semibold text-sm break-words flex-1">
                            Episode ${epNum}${ep.name&&ep.name!==`Episode ${epNum}`?`: ${ep.name}`:""}
                        </div>
                        ${isWatched?'<span class="bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text text-xs font-semibold px-2 py-1 rounded-full flex-shrink-0 whitespace-nowrap">Watched</span>':""}
                    </div>
                    ${ep.overview?`<div class="text-edu-text-secondary text-xs leading-relaxed line-clamp-2 mb-1">${ep.overview}</div>`:""}
                    ${ep.runtime?`<div class="text-edu-text-secondary text-xs mt-auto"><span>${ep.runtime}min</span></div>`:""}
                </div>
            `;
            episodeItem.addEventListener("click", () => {
                this.markEpisodeWatched(this.state.currentItem.id, this.elements.seasonSelect.value, epNum);
                this.openPlayer(this.state.selectedPlayer, epNum);
            });
            this.elements.episodeListContainer.appendChild(episodeItem)
        })
    }
    updatePlayerSources() {
        this.elements.playerSources.innerHTML = "";
        this.config.playerSources.forEach(source => {
            const buttonContainer = document.createElement("div");
            buttonContainer.className = "space-y-2";
            const button = document.createElement("button");
            const isSelected = this.state.currentItem.type === 'tv' && this.state.selectedPlayer && source.name === this.state.selectedPlayer.name;
            button.className = `w-full ${isSelected ? 'bg-gradient-to-r from-edu-pink to-edu-pink-light' : 'bg-edu-pink hover:bg-edu-pink-light'} text-edu-text rounded-lg px-4 py-3 font-medium transition-all shadow-lg hover:shadow-xl transform hover:scale-105`;
            button.textContent = source.name;
            if (source.name === "Videasy") {
                const recommendedTag = document.createElement("span");
                recommendedTag.className = "block text-center bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text text-xs font-semibold px-3 py-1.5 rounded-lg mb-2";
                recommendedTag.textContent = "Recommended";
                buttonContainer.appendChild(recommendedTag);
                const audioPrefGroup = document.createElement("div");
                audioPrefGroup.className = "flex gap-2 mb-2";
                const subBtn = document.createElement("button");
                subBtn.className = `flex-1 ${this.state.audioPref === 'sub' ? 'bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text' : 'bg-edu-dark-accent text-edu-text-secondary hover:bg-edu-rose'} rounded-lg px-4 py-2 font-medium transition-all border ${this.state.audioPref === 'sub' ? 'border-edu-pink' : 'border-edu-pink/20'}`;
                subBtn.textContent = "Sub";
                subBtn.addEventListener("click", (e) => {
                    e.stopPropagation();
                    this.state.audioPref = 'sub';
                    this.updatePlayerSources();
                });
                const dubBtn = document.createElement("button");
                dubBtn.className = `flex-1 ${this.state.audioPref === 'dub' ? 'bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text' : 'bg-edu-dark-accent text-edu-text-secondary hover:bg-edu-rose'} rounded-lg px-4 py-2 font-medium transition-all border ${this.state.audioPref === 'dub' ? 'border-edu-pink' : 'border-edu-pink/20'}`;
                dubBtn.textContent = "Dub";
                dubBtn.addEventListener("click", (e) => {
                    e.stopPropagation();
                    this.state.audioPref = 'dub';
                    this.updatePlayerSources();
                });
                audioPrefGroup.appendChild(subBtn);
                audioPrefGroup.appendChild(dubBtn);
                buttonContainer.appendChild(audioPrefGroup);
            }
            buttonContainer.appendChild(button);
            button.addEventListener("click", () => {
                if (this.state.currentItem.type === 'movie') {
                    this.openPlayer(source);
                } else {
                    this.setSelectedPlayer(source);
                }
            });
            this.elements.playerSources.appendChild(buttonContainer)
        })
    }
    setSelectedPlayer(source) {
        this.state.selectedPlayer = source;
        this.updatePlayerSources();
    }
    async openPlayer(source, episode = null) {
        const item = this.state.currentItem;
        if (!item) return;
        try {
            let url = "";
            if (item.type === "movie") {
                if (source.preferImdb) {
                    const details = await this.getItemDetails(item);
                    const imdbId = details.external_ids?.imdb_id;
                    if (imdbId) {
                        url = `${source.url}/movie?imdb=${imdbId}`
                    } else {
                        url = `${source.url}/movie?tmdb=${item.id}`
                    }
                } else if (source.tmdbOnly) {
                    url = `${source.url}/movie/${item.id}`;
                    if (source.name === "Videasy" && this.state.audioPref === 'dub') {
                        url += "?dub=true"
                    }
                } else {
                    url = `${source.url}/movie/${item.id}`
                }
            } else {
                const season = this.elements.seasonSelect.value;
                const episodeNum = episode || 1;
                if (source.preferImdb) {
                    const details = await this.getItemDetails(item);
                    const imdbId = details.external_ids?.imdb_id;
                    if (imdbId) {
                        url = `${source.url}/tv?imdb=${imdbId}&season=${season}&episode=${episodeNum}`
                    } else {
                        url = `${source.url}/tv?tmdb=${item.id}&season=${season}&episode=${episodeNum}`
                    }
                } else if (source.tmdbOnly) {
                    url = `${source.url}/tv/${item.id}/${season}/${episodeNum}`;
                    if (source.name === "Videasy") {
                        const params = new URLSearchParams({
                            nextEpisode: 'true',
                            episodeSelector: 'true',
                            autoplayNextEpisode: 'true'
                        });
                        if (this.state.audioPref === 'dub') {
                            params.append('dub', 'true');
                        }
                        url += `?${params.toString()}`
                    }
                } else {
                    url = `${source.url}/tv/${item.id}/${season}/${episodeNum}`
                }
            }
            openInCloak(url);
            setTimeout(() => this.closeModal(), 1e3)
        } catch (error) {
            const fallbackUrl = this.buildFallbackUrl(source, item, episode);
            openInCloak(fallbackUrl);
            setTimeout(() => this.closeModal(), 1e3)
        }
    }
    buildFallbackUrl(source, item, episode = null) {
        if (item.type === "movie") {
            if (source.preferImdb) {
                return `${source.url}/movie?tmdb=${item.id}`
            } else {
                return `${source.url}/movie/${item.id}`
            }
        } else {
            const season = this.elements.seasonSelect.value;
            const episodeNum = episode || 1;
            if (source.preferImdb) {
                return `${source.url}/tv?tmdb=${item.id}&season=${season}&episode=${episodeNum}`
            } else {
                return `${source.url}/tv/${item.id}/${season}/${episodeNum}`
            }
        }
    }
    async getItemDetails(item) {
        const cacheKey = `details_${item.type}_${item.id}`;
        const cached = this.getCache(cacheKey);
        if (cached) return cached;
        const response = await fetch(`${this.getApiUrl()}?action=details&type=${item.type}&id=${item.id}`);
        const details = await response.json();
        if (!details.error) {
            this.setCache(cacheKey, details)
        }
        return details
    }
    closeModal() {
        this.elements.playerModal.classList.add("hidden");
        this.state.currentItem = null
    }
    addToRecent(item) {
        try {
            let recent = JSON.parse(localStorage.getItem("mediaRecent") || "[]");
            recent = recent.filter(r => r.id !== item.id || r.type !== item.type);
            recent.unshift({
                ...item,
                watchedAt: Date.now()
            });
            recent = recent.slice(0, 12);
            localStorage.setItem("mediaRecent", JSON.stringify(recent));
            this.loadRecentItems()
        } catch (error) {}
    }
    loadRecentItems() {
        try {
            let recent = JSON.parse(localStorage.getItem("mediaRecent") || "[]");
            if (recent.length === 0) {
                recent = JSON.parse(localStorage.getItem("moviesRecent") || "[]");
            }
            if (recent.length === 0) {
                this.elements.recentSection.classList.add("hidden");
                return
            }
            this.elements.recentSection.classList.remove("hidden");
            this.elements.recentGrid.innerHTML = "";
            recent.forEach(item => {
                const card = this.createMediaCard(item);
                this.elements.recentGrid.appendChild(card);
                if (this.imageObserver) {
                    this.imageObserver.observe(card)
                }
            })
        } catch (error) {}
    }
    showLoading(show) {
        this.elements.loading.classList.toggle("hidden", !show)
    }
    showError(message) {
        this.elements.results.innerHTML = `
            <div class="flex flex-col items-center justify-center p-12 text-center">
                <div class="text-6xl mb-4">⚠️</div>
                <h3 class="text-edu-text text-2xl font-bold mb-2">Error</h3>
                <p class="text-edu-text-secondary">${message}</p>
            </div>
        `
    }
    showNoResults() {
        this.elements.results.innerHTML = `
            <div class="flex flex-col items-center justify-center p-12 text-center">
                <div class="text-6xl mb-4">🔍</div>
                <h3 class="text-edu-text text-2xl font-bold mb-2">No Results Found</h3>
                <p class="text-edu-text-secondary">Try searching with different keywords</p>
            </div>
        `
    }
    clearResults() {
        this.elements.results.innerHTML = ""
    }
    getCache(key) {
        try {
            const cached = localStorage.getItem(`cache_${key}`);
            if (!cached) return null;
            const data = JSON.parse(cached);
            if (Date.now() - data.timestamp > this.config.cacheTime) {
                localStorage.removeItem(`cache_${key}`);
                return null
            }
            return data.content
        } catch (error) {
            return null
        }
    }
    setCache(key, content) {
        try {
            localStorage.setItem(`cache_${key}`, JSON.stringify({
                content: content,
                timestamp: Date.now()
            }))
        } catch (error) {}
    }
    showSkeletons() {
        this.elements.results.innerHTML = "";
        for (let i = 0; i < 12; i++) {
            const skeleton = document.createElement("div");
            skeleton.className = "bg-edu-dark-accent border border-edu-pink/20 rounded-xl overflow-hidden animate-pulse";
            skeleton.innerHTML = `
                <div class="aspect-[2/3] bg-edu-rose"></div>
                <div class="p-4 space-y-3">
                    <div class="h-5 bg-edu-rose rounded w-3/4"></div>
                    <div class="h-4 bg-edu-rose rounded w-1/2"></div>
                </div>
            `;
            this.elements.results.appendChild(skeleton)
        }
    }
    navigateCards(direction) {
        const cards = document.querySelectorAll(".media-card");
        if (cards.length === 0) return;
        if (this.focusedCardIndex >= 0) {
            cards[this.focusedCardIndex].classList.remove("focused")
        }
        this.focusedCardIndex = Math.max(0, Math.min(cards.length - 1, this.focusedCardIndex + direction));
        cards[this.focusedCardIndex].classList.add("focused");
        cards[this.focusedCardIndex].scrollIntoView({
            behavior: "smooth",
            block: "center"
        })
    }
    setupIntersectionObserver() {
        const options = {
            root: null,
            rootMargin: "50px",
            threshold: .1
        };
        this.imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const card = entry.target;
                    this.prefetchCardDetails(card);
                    observer.unobserve(card)
                }
            })
        }, options)
    }
    async prefetchCardDetails(card) {
        const itemId = card.dataset.itemId;
        const itemType = card.dataset.itemType;
        if (!itemId || !itemType) return;
        const cacheKey = `details_${itemType}_${itemId}`;
        const cached = this.getCache(cacheKey);
        if (cached) return;
        try {
            const response = await fetch(`${this.getApiUrl()}?action=details&type=${itemType}&id=${itemId}`);
            const details = await response.json();
            if (!details.error) {
                this.setCache(cacheKey, details)
            }
        } catch (error) {}
    }
    getWatchedEpisodes(showId, season) {
        try {
            const key = `watched_${showId}_s${season}`;
            const watched = JSON.parse(localStorage.getItem(key) || "[]");
            return watched
        } catch (error) {
            return []
        }
    }
    markEpisodeWatched(showId, season, episode) {
        try {
            const key = `watched_${showId}_s${season}`;
            let watched = JSON.parse(localStorage.getItem(key) || "[]");
            if (!watched.includes(episode)) {
                watched.push(episode)
            }
            localStorage.setItem(key, JSON.stringify(watched));
            this.saveProgress(showId, season, episode)
        } catch (error) {}
    }
    saveProgress(showId, season, episode) {
        try {
            const progress = {
                showId: showId,
                season: parseInt(season),
                episode: parseInt(episode),
                timestamp: Date.now()
            };
            localStorage.setItem(`progress_${showId}`, JSON.stringify(progress))
        } catch (error) {}
    }
    loadProgress(showId) {
        try {
            const progress = JSON.parse(localStorage.getItem(`progress_${showId}`) || "null");
            return progress
        } catch (error) {
            return null
        }
    }
}

var MoviesApp = MediaApp;

document.addEventListener("DOMContentLoaded", () => {
    window.mediaApp = new MediaApp;
    window.moviesApp = window.mediaApp;
});