Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2289 lines (2013 loc) · 91.3 KB
/
Copy pathscript.js
File metadata and controls
2289 lines (2013 loc) · 91.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CONFIGURATION
const TMDB_API_KEY = "0a0e2bf9fe54e6e65320d51734e258a4";
const BASE_URL = "https://api.themoviedb.org/3";
const IMAGE_URL = "https://image.tmdb.org/t/p/original";
const POSTER_URL = "https://image.tmdb.org/t/p/w342";
const TMDB_KEY = TMDB_API_KEY;
const BASE = BASE_URL;
const IMG_ORIG = IMAGE_URL;
const IMG_W300 = "https://image.tmdb.org/t/p/w300";
const IMG_W185 = "https://image.tmdb.org/t/p/w185";
const IMG_POSTER = POSTER_URL;
const AMBIENT_VIDEO_PREF_KEY = "notflix_ambient_video_enabled";
// Genre IDs
const GENRES = {
action: 28,
comedy: 35,
drama: 18,
scifi: 878,
horror: 27,
mystery: 9648,
anime: 16,
};
// Category page config: label, subtitle, TMDB fetch URL builder
const CATEGORY_CONFIG = {
action: { label: "Action", subtitle: "High-octane thrills and explosive adventure.", url: () => `${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.action}&sort_by=popularity.desc` },
comedy: { label: "Comedy", subtitle: "Laughs guaranteed — no serious business here.", url: () => `${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.comedy}&sort_by=popularity.desc` },
drama: { label: "Drama", subtitle: "Powerful stories that move you.", url: () => `${BASE_URL}/discover/tv?api_key=${TMDB_API_KEY}&with_genres=${GENRES.drama}&sort_by=popularity.desc` },
scifi: { label: "Sci-Fi", subtitle: "Explore galaxies, futures, and the unknown.", url: () => `${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.scifi}&sort_by=popularity.desc` },
horror: { label: "Horror", subtitle: "Things that go bump in the dark.", url: () => `${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.horror}&sort_by=popularity.desc` },
mystery: { label: "Mystery", subtitle: "Every clue matters. Trust no one.", url: () => `${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.mystery}&sort_by=popularity.desc` },
};
const BLOCKED_ROW_TITLES = {
"row-anime": ["overflow"], //this is a no no square for me I dont wanna fail this project
};
// Watch History Expansion State
let historyExpanded = false;
// STATE
let heroInterval = null;
let currentSlide = 0;
let topMovies = [];
let currentPage = "home"; // tracks active SPA page
let currentModalId = null; // id of the currently open modal item
let currentModalType = null; // "movie" or "tv"
let currentModalDetails = null; // hydrated TMDB details for watch history
// VALIDATION FOR API KEY
document.addEventListener("DOMContentLoaded", async () => {
initNavSearch();
applyPreferences();
initProfilePage();
initSignupPage();
if (!TMDB_API_KEY || TMDB_API_KEY === "YOUR_TMDB_API_KEY_HERE") {
alert("Please insert your TMDb API Key inside script.js!");
return;
}
const homePage = document.getElementById("page-home");
const playerPage = document.getElementById("player-layout");
if (homePage) {
setupNavSPA();
const bootParams = new URLSearchParams(window.location.search);
const requestedSearch = bootParams.get("search");
const requestedPage = bootParams.get("page") || "home";
if (requestedSearch) {
runSearch(requestedSearch);
} else {
const page = requestedPage === "home" || CATEGORY_CONFIG[requestedPage] ? requestedPage : "home";
showPage(page);
}
const modalClose = document.getElementById("modal-close");
if (modalClose) modalClose.addEventListener("click", closeModal);
const detailModal = document.getElementById("detail-modal");
if (detailModal) {
detailModal.addEventListener("click", (e) => {
if (e.target.id === "detail-modal") closeModal();
});
}
const btnStream = document.querySelector(".btn-stream");
if (btnStream) {
btnStream.addEventListener("click", () => {
if (currentModalId && currentModalType) {
removePlanningItem(currentModalId, currentModalType);
saveWatchHistoryFromDetails(currentModalDetails || { id: currentModalId, type: currentModalType });
window.location.href = `videoplayer.html?id=${currentModalId}&type=${currentModalType}`;
}
});
}
const heroWatchBtn = document.querySelector(".hero-btn-primary");
if (heroWatchBtn) {
heroWatchBtn.addEventListener("click", () => {
const item = topMovies[currentSlide];
if (!item) return;
const mediaType = item.media_type || (item.title ? "movie" : "tv");
const id = item.id;
if (!id) return;
window.location.href = `videoplayer.html?id=${id}&type=${mediaType}`;
});
}
const btnPlan = document.getElementById("modal-plan-btn");
if (btnPlan) {
btnPlan.addEventListener("click", () => {
if (!currentModalDetails) return;
savePlanningItem(currentModalDetails);
btnPlan.classList.add("is-planned");
btnPlan.setAttribute("aria-label", "Added to Planning");
renderPlanningToWatch();
});
}
}
if (playerPage) {
await initPlayerPage();
}
window.addEventListener("scroll", onScroll);
});
// SPA NAVIGATION
function setupNavSPA() {
const items = document.querySelectorAll("#nav-categories .category-item");
items.forEach(item => {
const page = item.dataset.page;
const link = item.querySelector("a");
if (link) link.href = page === "home" ? "index.html" : `index.html?page=${encodeURIComponent(page)}`;
link?.addEventListener("click", (e) => {
e.preventDefault();
if (page === currentPage && !document.getElementById("page-category")?.classList.contains("search-mode")) return;
setActiveNavItem(item);
showPage(page);
history.replaceState(null, "", page === "home" ? "index.html" : `index.html?page=${encodeURIComponent(page)}`);
});
});
const initialPage = new URLSearchParams(window.location.search).get("page") || "home";
const initialItem = Array.from(items).find(item => item.dataset.page === initialPage) || items[0];
if (initialItem) setActiveNavItem(initialItem);
}
function setActiveNavItem(targetItem) {
const items = document.querySelectorAll("#nav-categories .category-item");
items.forEach(i => i.classList.remove("active"));
targetItem.classList.add("active");
// Animate the sliding underline indicator
const indicator = document.getElementById("nav-indicator");
const link = targetItem.querySelector("a");
indicator.style.left = `${link.offsetLeft}px`;
indicator.style.width = `${link.offsetWidth}px`;
indicator.style.opacity = "1";
}
function showPage(page) {
currentPage = page;
document.getElementById("page-category")?.classList.remove("search-mode");
const homeEl = document.getElementById("page-home");
const categoryEl = document.getElementById("page-category");
if (page === "home") {
homeEl.classList.remove("page-hidden");
categoryEl.classList.add("page-hidden");
loadHomePage();
} else {
homeEl.classList.add("page-hidden");
categoryEl.classList.remove("page-hidden");
loadCategoryPage(page);
}
window.scrollTo({ top: 0, behavior: "smooth" });
}
// HOME PAGE (Action)
let homeLoaded = false;
function loadHomePage() {
if (homeLoaded) return;
homeLoaded = true;
renderContinueWatching();
renderPlanningToWatch();
initSkeletons("row-trending", 8);
initSkeletons("row-anime", 6);
initSkeletons("row-kdrama", 6);
initSkeletons("row-horror", 6);
initSkeletons("row-upcoming", 6);
fetchHeroShowcase();
fetchRow(`${BASE_URL}/trending/all/day?api_key=${TMDB_API_KEY}`, "row-trending", true);
fetchRow(`${BASE_URL}/discover/tv?api_key=${TMDB_API_KEY}&with_genres=${GENRES.anime}&with_original_language=ja`, "row-anime");
fetchRow(`${BASE_URL}/discover/tv?api_key=${TMDB_API_KEY}&with_original_language=ko`, "row-kdrama");
fetchRow(`${BASE_URL}/discover/movie?api_key=${TMDB_API_KEY}&with_genres=${GENRES.horror}`, "row-horror");
fetchRow(`${BASE_URL}/movie/upcoming?api_key=${TMDB_API_KEY}`, "row-upcoming", false, true);
}
// CATEGORY PAGE
const categoryCache = {};
async function loadCategoryPage(page) {
const config = CATEGORY_CONFIG[page];
if (!config) return;
document.getElementById("category-page-title").innerText = config.label;
document.getElementById("category-page-subtitle").innerText = config.subtitle;
const grid = document.getElementById("category-grid");
if (categoryCache[page]) {
grid.innerHTML = categoryCache[page];
grid.querySelectorAll(".movie-card").forEach(card => {
card.addEventListener("click", () => openDetailModal(card.dataset.id, card.dataset.type));
enableCardHover(card);
});
return;
}
// Skeleton placeholders for better perceived performance
grid.innerHTML = "";
for (let i = 0; i < 18; i++) {
const sk = document.createElement("div");
sk.className = "movie-card skeleton";
sk.innerHTML = `<div class="card-image-placeholder"></div>`;
grid.appendChild(sk);
}
try {
const res = await fetch(config.url());
const data = await res.json();
grid.innerHTML = "";
if (!data.results || data.results.length === 0) {
grid.innerHTML = `<p class="error-msg">No titles found for this category.</p>`;
return;
}
data.results.forEach((item) => {
if (!item.poster_path) return;
const type = item.media_type || (item.title ? "movie" : "tv");
const rating = item.vote_average ? item.vote_average.toFixed(1) : "N/A";
const card = document.createElement("div");
card.className = "movie-card";
card.dataset.id = item.id;
card.dataset.type = type;
card.innerHTML = `
<span class="rating-badge">★ ${rating}</span>
<div class="card-image-placeholder" style="background-image: url('${POSTER_URL}${item.poster_path}')"></div>
`;
card.addEventListener("click", () => openDetailModal(item.id, type));
grid.appendChild(card);
});
categoryCache[page] = grid.innerHTML;
} catch (err) {
console.error("Category fetch error:", err);
grid.innerHTML = `<p class="error-msg">Failed to load content. Please try again.</p>`;
}
}
// HERO SHOWCASE
async function fetchHeroShowcase() {
try {
const res = await fetch(`${BASE_URL}/trending/all/week?api_key=${TMDB_API_KEY}`);
const data = await res.json();
topMovies = data.results.slice(0, 8);
await renderHeroSlide();
startHeroAutoplay();
} catch (err) {
console.error("Hero showcase error:", err);
}
}
async function renderHeroSlide() {
const item = topMovies[currentSlide];
if (!item) return;
const title = item.title || item.name || item.original_name;
const year = (item.release_date || item.first_air_date || "2026").split("-")[0];
const rating = item.vote_average ? item.vote_average.toFixed(1) : "7.7";
const mediaType = item.media_type || (item.title ? "movie" : "tv");
const typeLabel = mediaType === "tv" ? "TV Series" : "Movie";
const block = document.getElementById("hero-animated-block");
const logo = document.getElementById("hero-logo");
block.style.opacity = "0";
block.style.transform = "translateY(8px)";
// Fetch logo
let logoPath = null;
try {
const imgRes = await fetch(`${BASE_URL}/${mediaType}/${item.id}/images?api_key=${TMDB_API_KEY}`);
const imgData = await imgRes.json();
if (imgData.logos && imgData.logos.length > 0) {
const en = imgData.logos.find(l => l.iso_639_1 === "en");
logoPath = en ? en.file_path : imgData.logos[0].file_path;
}
} catch {}
setTimeout(() => {
document.getElementById("hero-section").style.backgroundImage = `url('${IMAGE_URL}${item.backdrop_path}')`;
if (logoPath) {
logo.src = `${IMAGE_URL}${logoPath}`;
logo.alt = title;
logo.style.display = "block";
} else {
logo.removeAttribute("src");
logo.style.display = "none";
}
document.getElementById("hero-meta").innerHTML = `
<span class="meta-pill pill-star">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="star-icon"><path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"></path></svg>
${rating}
</span>
<span class="meta-pill">${year}</span>
<span class="meta-pill opacity-50">${typeLabel}</span>
<span class="meta-pill opacity-50">Trending Now</span>
`;
document.getElementById("hero-desc").innerText = item.overview || "No description available.";
updateIndicators(topMovies.length, currentSlide);
block.style.opacity = "1";
block.style.transform = "none";
}, 400);
}
function startHeroAutoplay() {
clearInterval(heroInterval);
heroInterval = setInterval(() => {
currentSlide = (currentSlide + 1) % topMovies.length;
renderHeroSlide();
}, 8000);
}
function updateIndicators(total, active) {
const track = document.getElementById("hero-indicators");
if (!track) return;
track.innerHTML = "";
for (let i = 0; i < total; i++) {
const btn = document.createElement("button");
btn.type = "button";
btn.setAttribute("role", "tab");
btn.setAttribute("aria-selected", i === active ? "true" : "false");
btn.setAttribute("aria-label", `Go to slide ${i + 1}`);
btn.className = "timeline-tab-trigger";
const line = document.createElement("span");
line.className = `timeline-line-fill ${i === active ? "line-active" : ""}`;
btn.appendChild(line);
btn.addEventListener("click", () => {
if (currentSlide === i) return;
currentSlide = i;
renderHeroSlide();
startHeroAutoplay();
});
track.appendChild(btn);
}
}
// ROW FETCHING (Home sliders)
function initSkeletons(rowId, count) {
const el = document.getElementById(rowId);
if (!el) return;
el.innerHTML = "";
for (let i = 0; i < count; i++) {
const sk = document.createElement("div");
sk.className = "movie-card skeleton";
sk.innerHTML = `<div class="card-image-placeholder"></div>`;
el.appendChild(sk);
}
}
async function fetchRow(url, rowId, isTop10 = false, isUpcoming = false) {
try {
const res = await fetch(url);
const data = await res.json();
const el = document.getElementById(rowId);
if (!el || !data.results || data.results.length === 0) return;
el.innerHTML = "";
data.results.forEach((item, index) => {
if (!item.poster_path) return;
if (isBlockedRowItem(rowId, item)) return;
const type = item.media_type || (rowId === "row-anime" || rowId === "row-kdrama" ? "tv" : "movie");
const card = document.createElement("div");
card.className = `movie-card ${isUpcoming ? "upcoming" : ""}`;
const top10HTML = isTop10 && index < 10 ? `<span class="top10-badge">TOP<br>${index + 1}</span>` : "";
const ratingHTML = isUpcoming ? "" : `<span class="rating-badge">★ ${item.vote_average.toFixed(1)}</span>`;
const tagHTML = index === 0 && !isUpcoming
? `<span class="tag-badge red-tag">TRENDING</span>`
: isUpcoming
? `<span class="tag-badge grey-tag">${item.release_date || "2026"}</span>`
: "";
card.innerHTML = `
${top10HTML}
${ratingHTML}
<div class="card-image-placeholder" style="background-image: url('${POSTER_URL}${item.poster_path}')"></div>
${tagHTML}
`;
card.addEventListener("click", () => openDetailModal(item.id, type));
el.appendChild(card);
});
enableDragScroll(el);
} catch (err) {
console.error(`Row fetch error [${rowId}]:`, err);
}
}
function isBlockedRowItem(rowId, item) {
const blockedTitles = BLOCKED_ROW_TITLES[rowId];
if (!blockedTitles) return false;
const title = (item.title || item.name || item.original_name || "").trim().toLowerCase();
return blockedTitles.includes(title);
}
// DRAG SCROLL
function enableDragScroll(slider) {
let isDown = false, startX, scrollLeft, hasDragged = false;
slider.addEventListener("mousedown", (e) => {
isDown = true;
hasDragged = false;
slider.classList.add("drag-active");
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});
slider.addEventListener("mouseleave", () => { isDown = false; slider.classList.remove("drag-active"); });
slider.addEventListener("mouseup", (e) => {
isDown = false;
slider.classList.remove("drag-active");
if (hasDragged) { e.stopPropagation(); e.preventDefault(); }
});
slider.addEventListener("mousemove", (e) => {
if (!isDown) return;
e.preventDefault();
const walk = (e.pageX - slider.offsetLeft - startX) * 1.5;
if (Math.abs(walk) > 6) hasDragged = true;
slider.scrollLeft = scrollLeft - walk;
});
slider.addEventListener("click", (e) => {
if (hasDragged) { e.preventDefault(); e.stopImmediatePropagation(); }
}, true);
}
// Lightweight hover enabler for category grid cards (no drag needed)
function enableCardHover(card) { /* CSS handles it */ }
// MODAL
async function openDetailModal(id, type) {
const modal = document.getElementById("detail-modal");
const wrapper = document.getElementById("modal-card-wrapper");
wrapper.classList.add("skeleton");
modal.classList.add("open");
document.body.style.overflow = "hidden";
// Track which item is open so btn-stream can navigate
currentModalId = id;
currentModalType = type;
currentModalDetails = null;
const planButton = document.getElementById("modal-plan-btn");
planButton?.classList.remove("is-planned");
planButton?.setAttribute("aria-label", "Add to Planning");
try {
const [detailsRes, creditsRes] = await Promise.all([
fetch(`${BASE_URL}/${type}/${id}?api_key=${TMDB_API_KEY}`),
fetch(`${BASE_URL}/${type}/${id}/credits?api_key=${TMDB_API_KEY}`),
]);
const details = await detailsRes.json();
const credits = await creditsRes.json();
const title = details.title || details.name || details.original_name;
const year = (details.release_date || details.first_air_date || "2026").split("-")[0];
currentModalDetails = {
id,
type,
title,
year,
posterPath: details.poster_path || "",
posterUrl: details.poster_path ? `${POSTER_URL}${details.poster_path}` : "",
backdropUrl: details.backdrop_path ? `${IMAGE_URL}${details.backdrop_path}` : "",
watchedAt: Date.now()
};
const score = (details.vote_average * 10).toFixed(0);
const backdrop = details.backdrop_path ? `${IMAGE_URL}${details.backdrop_path}` : "";
document.getElementById("modal-banner").style.backgroundImage = `url('${backdrop}')`;
document.getElementById("modal-title").innerText = title;
document.getElementById("modal-year").innerText = year;
document.getElementById("modal-type").innerText = type === "tv" ? "TV Series" : "Movie";
document.getElementById("modal-rating").innerText = `★ ${details.vote_average.toFixed(1)}`;
document.getElementById("modal-overview").innerText = details.overview || "No overview available.";
document.getElementById("modal-match").innerText = `${score > 0 ? score : "85"}% Match`;
document.getElementById("modal-genres").innerText = details.genres ? details.genres.map(g => g.name).join(", ") : "N/A";
document.getElementById("modal-cast").innerText = credits.cast ? credits.cast.slice(0, 4).map(c => c.name).join(", ") : "N/A";
document.getElementById("modal-runtime").innerText = type === "tv"
? `${details.number_of_seasons || 1} Season(s)`
: details.runtime ? `${details.runtime} mins` : "N/A";
updatePlanningButtonState();
wrapper.classList.remove("skeleton");
} catch (err) {
console.error("Modal fetch error:", err);
wrapper.classList.remove("skeleton");
}
}
function closeModal() {
document.getElementById("detail-modal").classList.remove("open");
document.body.style.overflow = "auto";
}
// SCROLL — navbar blur
function onScroll() {
document.getElementById("main-nav").classList.toggle("scrolled", window.scrollY > 10);
}
// VIDEOPLAYER PAGE LOGIC
async function initPlayerPage() {
const playerLayout = document.getElementById('player-layout');
if (!playerLayout) return;
if (!TMDB_API_KEY || TMDB_API_KEY === "YOUR_TMDB_API_KEY_HERE") {
alert("Please insert your TMDb API Key inside script.js!");
return;
}
setupTabs();
setupScrollNav();
setupAmbientVideoBackground();
setupVideoProgressTracking();
setupCompleteButton();
const params = new URLSearchParams(location.search);
const MEDIA_ID = params.get("id");
const MEDIA_TYPE = params.get("type") || "movie";
if (!MEDIA_ID) {
document.getElementById("page-loading").innerHTML = `<p style="color:rgba(255,255,255,0.4)">No active content identifier found. <a href="index.html" style="color:#e50914">Go back</a></p>`;
return;
}
try {
await loadPlayerPage(MEDIA_ID, MEDIA_TYPE);
} catch (err) {
console.error("Critical core module exception:", err);
document.getElementById("page-loading").innerHTML = `<p style="color:rgba(255,255,255,0.4)">Failed to parse streaming catalog entry. <a href="index.html" style="color:#e50914">Go back</a></p>`;
}
}
async function loadPlayerPage(id, type) {
const loadingEl = document.getElementById("page-loading");
const playerLayoutEl = document.getElementById("player-layout");
const fallbackTitle = document.getElementById("placeholder-title");
const fallbackBackdrop = document.getElementById("placeholder-backdrop");
if (!loadingEl || !playerLayoutEl || !fallbackTitle || !fallbackBackdrop) {
throw new Error("Required player page elements are missing.");
}
loadingEl.style.display = "none";
playerLayoutEl.style.display = "grid";
fallbackTitle.textContent = "Loading media...";
fallbackBackdrop.style.backgroundImage = "";
const [detailsRes, creditsRes, similarRes] = await Promise.all([
fetch(`${BASE_URL}/${type}/${id}?api_key=${TMDB_API_KEY}`),
fetch(`${BASE_URL}/${type}/${id}/credits?api_key=${TMDB_API_KEY}`),
fetch(`${BASE_URL}/${type}/${id}/similar?api_key=${TMDB_API_KEY}`),
]);
if (!detailsRes.ok || !creditsRes.ok || !similarRes.ok) {
throw new Error("One or more player data requests failed.");
}
const details = await detailsRes.json();
const credits = await creditsRes.json();
const similar = await similarRes.json();
const title = details.title || details.name || details.original_name || "Untitled";
const year = (details.release_date || details.first_air_date || "").split("-")[0] || "—";
const score = Math.round((details.vote_average || 0) * 10);
const rating = getRating(details, type);
currentPlayerMedia = {
id: String(id),
type,
title,
year,
posterPath: details.poster_path || "",
posterUrl: details.poster_path ? `${POSTER_URL}${details.poster_path}` : "",
backdropUrl: details.backdrop_path ? `${IMAGE_URL}${details.backdrop_path}` : "",
finalSeason: 0,
finalEpisode: 0,
};
document.getElementById("ov-title").innerText = title;
document.getElementById("ov-overview").innerText = details.overview || "No overview available.";
fallbackTitle.textContent = title;
if (details.backdrop_path) {
fallbackBackdrop.style.backgroundImage = `url('${IMAGE_URL}${details.backdrop_path}')`;
}
buildBadges(details, type, year, score, rating);
buildCast(credits.cast || []);
buildDetails(details, credits, type);
saveWatchHistoryFromDetails({
id,
type,
title,
year,
posterPath: details.poster_path || "",
posterUrl: details.poster_path ? `${POSTER_URL}${details.poster_path}` : "",
watchedAt: Date.now()
});
buildSimilar((similar.results || []).filter(item => item.id !== parseInt(id, 10)), type);
if (type === "tv") {
document.getElementById("tv-right-panel").style.display = "block";
document.getElementById("movie-right-panel").style.display = "none";
const params = new URLSearchParams(location.search);
const requestedSeason = parseInt(params.get("season") || "", 10);
const requestedEpisode = parseInt(params.get("episode") || "", 10);
const firstSeason = (details.seasons || []).find(s => s.season_number > 0)?.season_number;
const finalSeasonInfo = [...(details.seasons || [])].reverse().find(s => s.season_number > 0 && s.episode_count > 0);
currentPlayerMedia.finalSeason = finalSeasonInfo?.season_number || 0;
currentPlayerMedia.finalEpisode = finalSeasonInfo?.episode_count || 0;
const selectedSeason = Number.isFinite(requestedSeason) ? requestedSeason : firstSeason;
buildSeasonSelector(details, selectedSeason);
if (selectedSeason) await loadSeason(id, selectedSeason, Number.isFinite(requestedEpisode) ? requestedEpisode : 1);
} else {
document.getElementById("tv-right-panel").style.display = "none";
document.getElementById("movie-right-panel").style.display = "block";
buildMoviePanel(details, details.poster_path ? `${IMG_POSTER}${details.poster_path}` : "");
setPlayerSourceForItem({
key: getMovieProgressKey(id),
id: String(id),
type: "movie",
title,
subtitle: year,
posterPath: details.poster_path || "",
posterUrl: details.poster_path ? `${POSTER_URL}${details.poster_path}` : "",
href: `videoplayer.html?id=${id}&type=movie`,
isFinalItem: true,
}, getMovieVideoSource(id));
}
}
function buildBadges(details, type, year, score, ratingLabel) {
const el = document.getElementById("ov-badges");
const seasons = type === "tv" && details.number_of_seasons
? `<span class="meta-chip">${details.number_of_seasons} Season${details.number_of_seasons > 1 ? "s" : ""}</span>` : "";
const runtime = type === "movie" && details.runtime
? `<span class="meta-chip">${details.runtime} min</span>` : "";
const genres = (details.genres || []).slice(0, 2).map(g =>
`<span class="meta-chip">${g.name}</span>`).join("");
el.innerHTML = `
<span class="meta-chip high-match">${score > 0 ? score : "—"}% Match</span>
<span class="meta-chip">${year}</span>
${ratingLabel ? `<span class="meta-chip">${ratingLabel}</span>` : ""}
${seasons}${runtime}
<span class="meta-chip">★ ${(details.vote_average||0).toFixed(1)}</span>
${genres}
`;
}
function buildCast(cast) {
const el = document.getElementById("ov-cast");
if (!el) return;
if (!cast.length) { el.innerHTML = `<p style="color:rgba(255,255,255,0.3);font-size:0.85rem">No cast metrics available.</p>`; return; }
el.innerHTML = cast.slice(0, 12).map(actor => {
const img = actor.profile_path ? `${IMG_W185}${actor.profile_path}` : "";
const avatar = img ? `background-image:url('${img}')` : `background-color:#2a2a35`;
return `
<div class="cast-card">
<div class="cast-avatar" style="${avatar}"></div>
<div class="cast-text-overlay">
<div class="cast-name">${actor.name}</div>
<div class="cast-role">${actor.character || ""}</div>
</div>
</div>`;
}).join("");
enableDragScroll(el);
}
function buildDetails(details, credits, type) {
const el = document.getElementById("details-list");
const cast = (credits.cast || []).slice(0, 6).map(c => c.name).join(", ") || "N/A";
const crew = (credits.crew || []);
const directors = crew.filter(c => c.job === "Director").map(c => c.name).join(", ") || "N/A";
const creators = (details.created_by || []).map(c => c.name).join(", ") || directors;
const genres = (details.genres || []).map(g => g.name).join(", ") || "N/A";
const studios = (details.production_companies || []).map(c => c.name).slice(0,3).join(", ") || "N/A";
const langs = (details.spoken_languages || []).map(l => l.english_name).join(", ") || "N/A";
const status = details.status || "N/A";
const network = type === "tv" ? (details.networks || []).map(n => n.name).join(", ") || "N/A" : null;
const rows = [
["Creator / Director", creators],
["Cast Personnel", cast],
["Genres Context", genres],
["Production Status", status],
network ? ["Network Source", network] : null,
["Studio Labels", studios],
["Track Languages", langs],
].filter(Boolean);
el.innerHTML = rows.map(([k, v]) =>
`<div class="extended-row"><strong>${k}</strong><span>${v}</span></div>`
).join("");
}
function buildSimilar(results, type) {
const el = document.getElementById("suggested-grid");
if (!el) return;
const filtered = results.filter(r => r.poster_path || r.backdrop_path).slice(0, 12);
if (!filtered.length) { el.innerHTML = `<p style="color:rgba(255,255,255,0.3);font-size:0.85rem;grid-column:1/-1">No alternative matching profiles discovered.</p>`; return; }
el.innerHTML = filtered.map(item => {
const thumb = item.poster_path ? `${IMG_POSTER}${item.poster_path}` : (item.backdrop_path ? `${IMG_W300}${item.backdrop_path}` : "");
const label = item.title || item.name;
const yr = (item.release_date || item.first_air_date || "").split("-")[0];
const sc = Math.round((item.vote_average || 0) * 10);
return `<div class="suggested-card" onclick="goToPlayer(${item.id}, '${type}')">
<div class="suggested-thumb" style="background-image:url('${thumb}')"></div>
<div class="suggested-info">
<h5>${label}</h5>
<p>${sc > 0 ? sc+"% Match" : "—"} · ${yr}</p>
</div>
</div>`;
}).join("");
}
function buildSeasonSelector(details, selectedSeasonNumber) {
const wrapper = document.getElementById("season-selector");
if (!wrapper) return;
const menu = wrapper.querySelector(".psd-menu");
const label = wrapper.querySelector(".psd-label");
const trigger = wrapper.querySelector(".psd-trigger");
const seasons = (details.seasons || []).filter(s => s.season_number > 0);
const activeSeason = selectedSeasonNumber || seasons[0]?.season_number;
menu.innerHTML = seasons.map((s) =>
`<div class="psd-option${s.season_number === activeSeason ? " psd-selected" : ""}" data-value="${s.season_number}">Season ${s.season_number}</div>`
).join("");
if (activeSeason) label.textContent = `Season ${activeSeason}`;
trigger.addEventListener("click", (e) => {
e.stopPropagation();
wrapper.classList.toggle("open");
});
document.addEventListener("click", () => wrapper.classList.remove("open"));
menu.addEventListener("click", async (e) => {
const opt = e.target.closest(".psd-option");
if (!opt) return;
const val = parseInt(opt.dataset.value, 10);
menu.querySelectorAll(".psd-option").forEach(o => o.classList.remove("psd-selected"));
opt.classList.add("psd-selected");
label.textContent = opt.textContent;
wrapper.classList.remove("open");
await loadSeason(new URLSearchParams(location.search).get("id"), val, 1);
});
}
async function loadSeason(seriesId, seasonNum, selectedEpisodeNum = 1) {
const listEl = document.getElementById("episode-list");
const tabListEl = document.getElementById("episodes-tab-list");
if (!listEl || !tabListEl) return;
listEl.innerHTML = `<div style="color:rgba(255,255,255,0.3);font-size:0.85rem;padding:12px">Buffering sequence nodes...</div>`;
tabListEl.innerHTML = listEl.innerHTML;
try {
const res = await fetch(`${BASE}/tv/${seriesId}/season/${seasonNum}?api_key=${TMDB_KEY}`);
const data = await res.json();
const eps = data.episodes || [];
const makeCard = (ep, active) => {
const thumb = ep.still_path ? `${IMG_W300}${ep.still_path}` : "";
const runtime = ep.runtime ? `${ep.runtime}m` : "";
const name = ep.name || `Episode ${ep.episode_number}`;
const overview = ep.overview || "No item log synopsis available.";
return `
<div class="track-strip-item ${active ? "active-stream-track" : ""}" data-season="${seasonNum}" data-ep="${ep.episode_number}">
<div class="track-thumbnail-capsule" style="${thumb ? `background-image:url('${thumb}')` : ""}"></div>
<div class="track-description-block">
<div class="track-row-header">
<h4>${ep.episode_number}. ${name}</h4>
<span class="track-duration-stamp">${runtime}</span>
</div>
<p class="track-summary-excerpt">${overview}</p>
</div>
</div>`;
};
const selectedEpisode = eps.find(ep => ep.episode_number === selectedEpisodeNum) || eps[0];
const html = eps.map((ep) => makeCard(ep, selectedEpisode && ep.episode_number === selectedEpisode.episode_number)).join("");
listEl.innerHTML = html || `<p style="color:rgba(255,255,255,0.3);font-size:0.85rem">No runtime records found.</p>`;
tabListEl.innerHTML = html || listEl.innerHTML;
[listEl, tabListEl].forEach(container => {
container.querySelectorAll(".track-strip-item").forEach(card => {
card.addEventListener("click", () => {
document.querySelectorAll(".track-strip-item").forEach(c => c.classList.remove("active-stream-track"));
const epNum = parseInt(card.dataset.ep, 10);
const season = parseInt(card.dataset.season, 10);
document.querySelectorAll(`.track-strip-item[data-season="${season}"][data-ep="${epNum}"]`).forEach(c => c.classList.add("active-stream-track"));
const episode = eps.find(ep => ep.episode_number === epNum);
if (episode) selectEpisode(seriesId, season, episode);
});
});
});
if (selectedEpisode) selectEpisode(seriesId, seasonNum, selectedEpisode, false);
} catch (err) {
listEl.innerHTML = `<p style="color:rgba(255,255,255,0.3);font-size:0.85rem">Failed to populate episode tracking.</p>`;
}
}
function buildMoviePanel(details, poster) {
if (poster) document.getElementById("movie-poster").style.backgroundImage = `url('${poster}')`;
const facts = [
["Release", details.release_date || "—"],
["Runtime", details.runtime ? `${details.runtime} min` : "—"],
["Rating", `★ ${(details.vote_average||0).toFixed(1)} / 10`],
["Votes", details.vote_count ? details.vote_count.toLocaleString() : "—"],
["Language", details.original_language?.toUpperCase() || "—"],
["Budget", details.budget ? `$${(details.budget/1e6).toFixed(0)}M` : "—"],
["Revenue", details.revenue ? `$${(details.revenue/1e6).toFixed(0)}M` : "—"],
["Status", details.status || "—"],
];
document.getElementById("movie-facts").innerHTML = facts.map(([k, v]) =>
`<div class="fact-row"><span>${k}</span><span>${v}</span></div>`
).join("");
}
function selectEpisode(seriesId, seasonNum, episode, updateUrl = true) {
if (!episode || !currentPlayerMedia) return;
const epNum = episode.episode_number;
const title = `${currentPlayerMedia.title}: S${seasonNum} E${epNum}`;
const subtitle = episode.name || `Episode ${epNum}`;
const href = `videoplayer.html?id=${seriesId}&type=tv&season=${seasonNum}&episode=${epNum}`;
setPlayerSourceForItem({
key: getEpisodeProgressKey(seriesId, seasonNum, epNum),
id: String(seriesId),
type: "tv",
season: seasonNum,
episode: epNum,
title,
subtitle,
posterPath: currentPlayerMedia.posterPath || "",
posterUrl: currentPlayerMedia.posterUrl || "",
href,
isFinalItem: seasonNum === currentPlayerMedia.finalSeason && epNum === currentPlayerMedia.finalEpisode,
}, getEpisodeVideoSource(seriesId, seasonNum, epNum));
if (updateUrl) history.replaceState(null, "", href);
}
function getMovieProgressKey(id) {
return `movie:${id}`;
}
function getEpisodeProgressKey(seriesId, seasonNum, episodeNum) {
return `tv:${seriesId}:s${seasonNum}:e${episodeNum}`;
}
function getMovieVideoSource(id) {
return VIDEO_SOURCES.movie?.[getMovieProgressKey(id)] || "";
}
function getEpisodeVideoSource(seriesId, seasonNum, episodeNum) {
return VIDEO_SOURCES.episode?.[getEpisodeProgressKey(seriesId, seasonNum, episodeNum)] || "";
}
function setPlayerSourceForItem(item, src) {
const video = document.getElementById("theater-embedded-media");
const source = video?.querySelector("source");
const fallback = document.getElementById("player-fallback-card");
const fallbackTitle = document.getElementById("placeholder-title");
if (!video || !source) return;
activePlaybackItem = item;
activeProgressKey = item.key;
activeProgressLoaded = false;
updateCompleteButtonState();
if (fallbackTitle) fallbackTitle.textContent = src ? item.title : "No local video assigned";
if (!src) {
source.removeAttribute("src");
video.removeAttribute("src");
video.load();
setAmbientVideoSource("");
if (fallback) fallback.style.display = "flex";
return;
}
if (source.getAttribute("src") !== src) {
source.src = src;
video.load();
}
setAmbientVideoSource(src);
if (fallback) fallback.style.display = "none";
}
function setupAmbientVideoBackground() {
const main = document.getElementById("theater-embedded-media");
const glow = document.getElementById("theater-ambient-media");
const toggle = document.getElementById("ambient-toggle-btn");
if (!main || !glow || glow.dataset.ambientBound === "true") return;
glow.dataset.ambientBound = "true";
glow.muted = true;
glow.playsInline = true;
const syncGlowTime = () => {
if (!Number.isFinite(main.currentTime) || Math.abs(main.currentTime - glow.currentTime) <= 0.3) return;
try {
glow.currentTime = main.currentTime;
} catch {}
};
const alignGlow = () => {
syncGlowTime();
};
const playGlow = () => {
if (!glow.src || !isAmbientVideoEnabled()) return;
alignGlow();
glow.playbackRate = main.playbackRate;
glow.play().catch(() => {});
};
main.addEventListener("play", playGlow);
main.addEventListener("pause", () => glow.pause());
main.addEventListener("ended", () => glow.pause());
main.addEventListener("seeking", () => {
glow.pause();
alignGlow();
});
main.addEventListener("seeked", () => {
alignGlow();
if (!main.paused) playGlow();
});
main.addEventListener("ratechange", () => {
glow.playbackRate = main.playbackRate;
});
main.addEventListener("timeupdate", alignGlow);
main.addEventListener("loadedmetadata", alignGlow);
if (toggle) {
toggle.addEventListener("click", () => {
const nextEnabled = !isAmbientVideoEnabled();
localStorage.setItem(AMBIENT_VIDEO_PREF_KEY, nextEnabled ? "true" : "false");
applyAmbientVideoPreference();
if (nextEnabled && !main.paused) playGlow();
});
}
applyAmbientVideoPreference();
}
function setAmbientVideoSource(src) {
const glow = document.getElementById("theater-ambient-media");
const main = document.getElementById("theater-embedded-media");
if (!glow) return;
if (!src) {
glow.pause();
glow.removeAttribute("src");
glow.load();
applyAmbientVideoPreference();