-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
923 lines (825 loc) · 44.4 KB
/
main.js
File metadata and controls
923 lines (825 loc) · 44.4 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
/**
* ============================================================
* ZenView — Open Source · Made with ❤️
* https://github.com/ItsMarwan/ZenView
* main.js — Application logic
* All user-facing text is driven by labels.json
* ============================================================
*/
let isDark = true;
let isLightsOff = false;
let isCloudEnabled = false;
let db = null;
let labels = null;
let navSuggestTimer = null;
let heroSuggestTimer = null;
let trendingNextPageToken = null;
let searchNextPageToken = null;
let lastSearchQuery = null;
const STORAGE = {
HISTORY: 'ZenView_watch_history',
SAVED: 'ZenView_saved_videos',
FIREBASE: 'ZenView_firebase_config',
THEME: 'ZenView_theme',
YT_KEY: 'ZenView_youtube_api_key',
};
window.onload = async () => {
labels = await loadLabels();
await initFirebase();
loadYouTubeKey();
setupTheme();
setupEventListeners();
setTimeout(() => {
document.getElementById('app-loader').classList.add('hidden');
const app = document.getElementById('app');
app.style.display = 'flex';
app.style.flexDirection = 'column';
handleHashChange();
}, 900);
window.addEventListener('hashchange', handleHashChange);
};
async function loadLabels() {
try {
const r = await fetch('labels.json');
const text = await r.text();
const clean = text.replace(/^\/\*[\s\S]*?\*\/\s*/m, '').trim();
return JSON.parse(clean);
} catch (e) {
return {};
}
}
async function initFirebase() {
let cfg = null;
const envCfg = window.ZENVIEW_CONFIG && window.ZENVIEW_CONFIG.firebase;
if (envCfg && envCfg.apiKey) {
cfg = envCfg;
} else {
const stored = localStorage.getItem(STORAGE.FIREBASE);
if (stored) { try { cfg = JSON.parse(stored); } catch {} }
}
if (cfg && cfg.apiKey && cfg.projectId) {
try {
firebase.initializeApp(cfg);
db = firebase.firestore();
isCloudEnabled = true;
} catch (e) {}
}
}
function loadYouTubeKey() {
const defaultKey = window.ZENVIEW_CONFIG && window.ZENVIEW_CONFIG.defaultYoutubeApiKey;
if (defaultKey && !localStorage.getItem(STORAGE.YT_KEY)) {
localStorage.setItem(STORAGE.YT_KEY, defaultKey);
}
}
function setupTheme() {
const saved = localStorage.getItem(STORAGE.THEME);
isDark = saved !== 'light';
applyTheme(isDark);
document.getElementById('mode-toggle').onclick = () => { isDark = !isDark; applyTheme(isDark); };
}
function applyTheme(dark) {
document.documentElement.classList.toggle('dark', dark);
document.documentElement.classList.toggle('light', !dark);
document.getElementById('theme-icon-moon').style.display = dark ? '' : 'none';
document.getElementById('theme-icon-sun').style.display = !dark ? '' : 'none';
localStorage.setItem(STORAGE.THEME, dark ? 'dark' : 'light');
}
function setupEventListeners() {
document.getElementById('settings-btn').onclick = openSettingsModal;
const navIn = document.getElementById('nav-search-input');
navIn.addEventListener('input', () => {
clearTimeout(navSuggestTimer);
const q = navIn.value.trim();
if (q.length < 2) { closeNavSuggestions(); return; }
navSuggestTimer = setTimeout(() => fetchSuggestions(q, 'nav'), 300);
});
navIn.addEventListener('keydown', e => {
if (e.key === 'Enter') { closeNavSuggestions(); performSearch(navIn.value.trim()); }
if (e.key === 'Escape') closeNavSuggestions();
});
document.addEventListener('click', e => {
if (!e.target.closest('#nav-search-container')) closeNavSuggestions();
});
}
window.navigate = (path) => { window.location.hash = path === '/' ? '' : path; };
function handleHashChange() {
const hash = window.location.hash.slice(1);
const navSearch = document.getElementById('nav-search-container');
if (!hash || hash === 'home') {
navSearch.style.display = 'none';
renderHome();
} else if (hash === 'saved') {
navSearch.style.display = '';
renderSaved();
} else if (hash.startsWith('watch?v=')) {
navSearch.style.display = '';
const videoId = new URLSearchParams(hash.slice(6)).get('v');
videoId ? renderWatch(videoId) : renderNotFound();
} else if (hash.startsWith('search?q=')) {
navSearch.style.display = '';
const q = decodeURIComponent(hash.slice(9));
document.getElementById('nav-search-input').value = q;
renderSearchResults(q);
} else {
navSearch.style.display = '';
renderNotFound();
}
}
async function fetchSuggestions(query, context) {
try {
const target = `https://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=${encodeURIComponent(query)}`;
const res = await fetch(`https://api.allorigins.win/raw?url=${encodeURIComponent(target)}`);
const data = await res.json();
const suggestions = Array.isArray(data[1]) ? data[1].slice(0, 8) : [];
if (context === 'nav') renderNavSuggestions(suggestions);
else renderHeroSuggestions(suggestions);
} catch {
}
}
function renderNavSuggestions(items) {
const box = document.getElementById('nav-suggestions');
if (!items.length) { box.classList.add('hidden'); return; }
box.innerHTML = items.map(s => `
<div class="suggestion-item" onclick="selectSuggestion('${escHtml(s)}','nav')">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
${escHtml(s)}
</div>`).join('');
box.classList.remove('hidden');
}
function renderHeroSuggestions(items) {
const box = document.getElementById('hero-suggestions');
if (!box || !items.length) { if (box) box.classList.add('hidden'); return; }
box.innerHTML = items.map(s => `
<div class="suggestion-item" onclick="selectSuggestion('${escHtml(s)}','hero')">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
${escHtml(s)}
</div>`).join('');
box.classList.remove('hidden');
}
window.selectSuggestion = (text, context) => {
if (context === 'nav') {
document.getElementById('nav-search-input').value = text;
closeNavSuggestions();
} else {
const inp = document.getElementById('hero-search-input');
if (inp) inp.value = text;
closeHeroSuggestions();
}
performSearch(text);
};
function closeNavSuggestions() {
const b = document.getElementById('nav-suggestions');
if (b) b.classList.add('hidden');
}
function closeHeroSuggestions() {
const b = document.getElementById('hero-suggestions');
if (b) b.classList.add('hidden');
}
function performSearch(query) {
if (!query.trim()) return;
const vid = getYtId(query);
if (vid) { navigate(`watch?v=${vid}`); return; }
navigate(`search?q=${encodeURIComponent(query.trim())}`);
}
async function renderSearchResults(query) {
lastSearchQuery = query;
searchNextPageToken = null;
const root = document.getElementById('content-root');
const apiKey = localStorage.getItem(STORAGE.YT_KEY);
root.innerHTML = `
<div class="fade-in">
<h1 style="font-size:1.5rem;font-weight:700;margin-bottom:1.5rem;color:var(--text-primary);">
Results for <span style="color:var(--text-secondary);">"${escHtml(query)}"</span>
</h1>
<div id="search-results-grid" class="video-grid">${skeletonCards(8)}</div>
<div id="search-load-more" style="text-align:center;margin-top:2rem;display:none;">
<button onclick="loadMoreSearch()" class="btn btn-ghost" style="padding:0.75rem 2rem;">Load More</button>
</div>
</div>`;
if (!apiKey) {
document.getElementById('search-results-grid').innerHTML = `
<p style="color:var(--text-muted);grid-column:1/-1;">No YouTube API key configured.
<a href="#" onclick="openSettingsModal()" style="color:var(--text-primary);text-decoration:underline;margin-left:4px;">Add one in Settings</a>.
</p>`;
return;
}
await fetchSearchPage(query, null);
}
async function fetchSearchPage(query, pageToken) {
const apiKey = localStorage.getItem(STORAGE.YT_KEY);
const grid = document.getElementById('search-results-grid');
const loadMoreBtn = document.getElementById('search-load-more');
if (!grid) return;
try {
let url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(query)}&type=video&maxResults=24&key=${apiKey}`;
if (pageToken) url += `&pageToken=${pageToken}`;
const res = await fetch(url);
const data = await res.json();
if (data.error) { showToast(data.error.message, 'error'); grid.innerHTML = `<p style="color:var(--text-muted);grid-column:1/-1;">${escHtml(data.error.message)}</p>`; return; }
searchNextPageToken = data.nextPageToken || null;
const items = data.items || [];
if (!items.length && !pageToken) {
grid.innerHTML = '<p style="color:var(--text-muted);grid-column:1/-1;">No results found.</p>';
return;
}
if (!pageToken) grid.innerHTML = '';
items.forEach(item => {
const thumb = getBestThumb(item.snippet.thumbnails);
grid.insertAdjacentHTML('beforeend', videoCard(
item.id.videoId,
item.snippet.title,
item.snippet.channelTitle,
thumb
));
});
if (loadMoreBtn) loadMoreBtn.style.display = searchNextPageToken ? 'block' : 'none';
} catch {
showToast('Search failed. Check your API key.', 'error');
}
}
window.loadMoreSearch = () => {
if (!lastSearchQuery || !searchNextPageToken) return;
const btn = document.querySelector('#search-load-more button');
if (btn) { btn.textContent = 'Loading…'; btn.disabled = true; }
fetchSearchPage(lastSearchQuery, searchNextPageToken).then(() => {
if (btn) { btn.textContent = 'Load More'; btn.disabled = false; }
});
};
async function renderHome() {
const root = document.getElementById('content-root');
const history = getHistory().slice(0, 6);
const quote = labels.quotes
? labels.quotes[Math.floor(Math.random() * labels.quotes.length)]
: 'Focus on what matters.';
root.innerHTML = `
<div class="fade-in">
<div style="display:flex;flex-direction:column;align-items:center;text-align:center;padding:3rem 0 2rem;">
<h1 style="font-size:clamp(2rem,5vw,3.5rem);font-weight:900;letter-spacing:-0.02em;color:var(--text-primary);margin-bottom:0.75rem;">Welcome to ZenView</h1>
<p style="font-size:1rem;color:var(--text-secondary);max-width:480px;margin-bottom:2.5rem;font-style:italic;">"${escHtml(quote)}"</p>
<div id="hero-search-wrap" style="position:relative;width:100%;max-width:640px;">
<svg style="position:absolute;left:1.25rem;top:50%;transform:translateY(-50%);color:var(--text-muted);pointer-events:none;z-index:1;" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<input id="hero-search-input" type="text" class="hero-search-input" placeholder="Search for a video or paste a YouTube link…" autocomplete="off">
<button class="hero-search-btn" id="hero-search-btn">Watch</button>
<div id="hero-suggestions" class="hero-suggestions suggestions-list hidden"></div>
</div>
<p style="margin-top:0.875rem;font-size:0.8125rem;color:var(--text-muted);">Tip: Paste any YouTube link or search by title</p>
<div style="display:flex;gap:0.75rem;margin-top:1.5rem;flex-wrap:wrap;justify-content:center;">
<button onclick="navigate('saved')" class="btn btn-ghost" style="font-size:0.8125rem;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/></svg>
Saved Videos
</button>
<button onclick="openDocsModal('about')" class="btn btn-ghost" style="font-size:0.8125rem;">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
About ZenView
</button>
</div>
</div>
${history.length > 0 ? `
<div style="margin-top:2.5rem;">
<div style="display:flex;justify-content:space-between;align-items:center;" class="section-heading">
<span style="display:flex;align-items:center;gap:0.5rem;">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
Watch Again
</span>
<button onclick="clearHistory()" style="font-size:0.75rem;color:var(--text-muted);background:none;border:none;cursor:pointer;padding:0.25rem 0.5rem;" onmouseover="this.style.color='var(--text-primary)'" onmouseout="this.style.color='var(--text-muted)'">
Clear History
</button>
</div>
<div class="video-grid">
${history.map(v => videoCard(v.id, v.title || 'YouTube Video', '', null, v.timestamp)).join('')}
</div>
</div>
` : ''}
<div style="margin-top:2.5rem;">
<div class="section-heading" style="display:flex;justify-content:space-between;align-items:center;">
<span style="display:flex;align-items:center;gap:0.5rem;">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>
Trending Now
</span>
<button onclick="loadTrending(true)" id="trending-refresh-btn" style="background:none;border:1px solid var(--border);border-radius:9999px;padding:0.35rem 0.75rem;font-size:0.75rem;color:var(--text-muted);cursor:pointer;display:flex;align-items:center;gap:0.4rem;" onmouseover="this.style.borderColor='var(--border-strong)';this.style.color='var(--text-primary)'" onmouseout="this.style.borderColor='var(--border)';this.style.color='var(--text-muted)'">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
Refresh
</button>
</div>
<div id="trending-grid" class="video-grid">${skeletonCards(12)}</div>
<div id="trending-load-more" style="text-align:center;margin-top:2rem;display:none;">
<button onclick="loadMoreTrending()" class="btn btn-ghost" style="padding:0.75rem 2rem;">Load More</button>
</div>
</div>
<div style="margin-top:2.5rem;">
<div class="section-heading">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/></svg>
Documentation
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:1rem;">
<button onclick="openDocsModal('youtube-api')" class="card" style="text-align:left;padding:1.25rem;cursor:pointer;background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius);transition:all 0.2s;" onmouseover="this.style.borderColor='var(--border-strong)'" onmouseout="this.style.borderColor='var(--border)'">
<p style="font-weight:700;color:var(--text-primary);margin-bottom:0.25rem;">YouTube API Setup</p>
<p style="font-size:0.8125rem;color:var(--text-muted);">Get your free API key to enable search & trending.</p>
</button>
<button onclick="openDocsModal('firebase')" class="card" style="text-align:left;padding:1.25rem;cursor:pointer;background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius);transition:all 0.2s;" onmouseover="this.style.borderColor='var(--border-strong)'" onmouseout="this.style.borderColor='var(--border)'">
<p style="font-weight:700;color:var(--text-primary);margin-bottom:0.25rem;">Firebase Setup</p>
<p style="font-size:0.8125rem;color:var(--text-muted);">Configure Firebase for cloud save features.</p>
</button>
<button onclick="openDocsModal('about')" class="card" style="text-align:left;padding:1.25rem;cursor:pointer;background:var(--bg-secondary);border:1px solid var(--border);border-radius:var(--radius);transition:all 0.2s;" onmouseover="this.style.borderColor='var(--border-strong)'" onmouseout="this.style.borderColor='var(--border)'">
<p style="font-weight:700;color:var(--text-primary);margin-bottom:0.25rem;">About ZenView</p>
<p style="font-size:0.8125rem;color:var(--text-muted);">Open source, made with love. Learn more.</p>
</button>
</div>
</div>
</div>`;
const heroIn = document.getElementById('hero-search-input');
document.getElementById('hero-search-btn').onclick = () => performSearch(heroIn.value.trim());
heroIn.addEventListener('keydown', e => {
if (e.key === 'Enter') { closeHeroSuggestions(); performSearch(heroIn.value.trim()); }
if (e.key === 'Escape') closeHeroSuggestions();
});
heroIn.addEventListener('input', () => {
clearTimeout(heroSuggestTimer);
const q = heroIn.value.trim();
if (q.length < 2) { closeHeroSuggestions(); return; }
heroSuggestTimer = setTimeout(() => fetchSuggestions(q, 'hero'), 300);
});
document.addEventListener('click', e => {
if (!e.target.closest('#hero-search-wrap')) closeHeroSuggestions();
}, { once: true });
loadTrending(false);
}
async function loadTrending(forceRefresh = false) {
trendingNextPageToken = null;
const grid = document.getElementById('trending-grid');
if (!grid) return;
const apiKey = localStorage.getItem(STORAGE.YT_KEY);
if (!apiKey) {
grid.innerHTML = `<p style="color:var(--text-muted);grid-column:1/-1;">Add a YouTube API key in <a href="#" onclick="openSettingsModal()" style="color:var(--text-primary);text-decoration:underline;">Settings</a> to see trending videos.</p>`;
return;
}
grid.innerHTML = skeletonCards(12);
await fetchTrendingPage(null);
}
async function fetchTrendingPage(pageToken) {
const apiKey = localStorage.getItem(STORAGE.YT_KEY);
const grid = document.getElementById('trending-grid');
const loadMoreBtn = document.getElementById('trending-load-more');
if (!grid) return;
try {
let url = `https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&chart=mostPopular®ionCode=US&maxResults=24&key=${apiKey}`;
if (pageToken) url += `&pageToken=${pageToken}`;
const res = await fetch(url);
const data = await res.json();
if (data.error) {
showToast(data.error.message, 'error');
grid.innerHTML = `<p style="color:var(--text-muted);grid-column:1/-1;">${escHtml(data.error.message)}</p>`;
return;
}
trendingNextPageToken = data.nextPageToken || null;
const items = data.items || [];
if (!pageToken) grid.innerHTML = '';
items.forEach(item => {
const thumb = getBestThumb(item.snippet.thumbnails);
const views = item.statistics && item.statistics.viewCount
? formatViews(Number(item.statistics.viewCount))
: '';
grid.insertAdjacentHTML('beforeend', videoCard(
item.id,
item.snippet.title,
item.snippet.channelTitle,
thumb,
null,
views
));
});
if (loadMoreBtn) loadMoreBtn.style.display = trendingNextPageToken ? 'block' : 'none';
} catch {
showToast('Could not load trending videos.', 'error');
if (grid) grid.innerHTML = '<p style="color:var(--text-muted);grid-column:1/-1;">Failed to load trending.</p>';
}
}
window.loadMoreTrending = () => {
if (!trendingNextPageToken) return;
const btn = document.querySelector('#trending-load-more button');
if (btn) { btn.textContent = 'Loading…'; btn.disabled = true; }
fetchTrendingPage(trendingNextPageToken).then(() => {
if (btn) { btn.textContent = 'Load More'; btn.disabled = false; }
});
};
function getBestThumb(thumbnails) {
if (!thumbnails) return null;
return (thumbnails.maxres || thumbnails.standard || thumbnails.high || thumbnails.medium || thumbnails.default || {}).url || null;
}
function formatViews(n) {
if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M views';
if (n >= 1_000) return Math.round(n / 1_000) + 'K views';
return n + ' views';
}
function skeletonCards(count) {
return Array.from({ length: count }, () => `
<div class="video-card" style="pointer-events:none;animation:pulse 1.5s ease-in-out infinite;">
<div class="video-thumb" style="background:var(--bg-tertiary);"></div>
<div class="video-card-body">
<div style="height:0.75rem;background:var(--bg-tertiary);border-radius:4px;margin-bottom:0.5rem;width:90%;"></div>
<div style="height:0.625rem;background:var(--bg-tertiary);border-radius:4px;width:55%;"></div>
</div>
</div>`).join('');
}
function videoCard(id, title = '', channel = '', thumb = null, timestamp = null, meta = '') {
const img = thumb || `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
const sub = channel || (timestamp ? timeAgo(timestamp) : meta);
return `
<div class="video-card" onclick="navigate('watch?v=${escHtml(id)}')">
<div class="video-thumb">
<img class="video-thumb-img" src="${escHtml(img)}" alt="${escHtml(title)}" loading="lazy"
onerror="this.onerror=null;this.src='https://i.ytimg.com/vi/${escHtml(id)}/hqdefault.jpg'">
</div>
<div class="video-card-body">
<p class="video-card-title">${escHtml(title)}</p>
<p class="video-card-meta">${escHtml(sub)}</p>
</div>
</div>`;
}
async function renderWatch(videoId) {
await addToHistory(videoId);
const saved = isSaved(videoId);
const details = await fetchVideoDetails(videoId);
const root = document.getElementById('content-root');
root.innerHTML = `
<div id="video-player-container" class="fade-in">
<div class="video-wrapper" style="max-width:1000px;margin:0 auto;">
<div class="video-container" style="border-radius:var(--radius);overflow:hidden;box-shadow:var(--shadow-lg);">
<div id="load-spinner" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:var(--bg-tertiary);z-index:5;">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="spin" style="color:var(--text-muted);"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
</div>
<iframe
src="https://www.youtube-nocookie.com/embed/${escHtml(videoId)}?autoplay=1&rel=0&modestbranding=1"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
onload="document.getElementById('load-spinner').style.display='none'"
></iframe>
</div>
<div class="card" style="margin-top:1rem;padding:1.25rem;">
<h2 style="font-size:1.25rem;font-weight:700;color:var(--text-primary);margin-bottom:0.5rem;line-height:1.4;">
${escHtml(details ? details.title : 'YouTube Video')}
</h2>
<div style="display:flex;align-items:center;gap:0.75rem;font-size:0.8125rem;color:var(--text-muted);margin-bottom:1rem;flex-wrap:wrap;">
<span>ID: ${escHtml(videoId)}</span>
${details ? `<span>•</span><span>${Number(details.views).toLocaleString()} views</span><span>•</span><span>${Number(details.likes).toLocaleString()} likes</span>` : ''}
</div>
${!details && !localStorage.getItem(STORAGE.YT_KEY) ? `
<div style="padding:0.75rem;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:0.5rem;font-size:0.8125rem;color:var(--text-secondary);margin-bottom:1rem;">
<strong>Tip:</strong> Add a YouTube API key in
<a href="#" onclick="openSettingsModal()" style="color:var(--text-primary);text-decoration:underline;">Settings</a>
to see video titles, descriptions, and like counts.
</div>
` : ''}
${details && details.description ? `
<div style="margin-bottom:1rem;">
<div id="desc-text" class="description-collapsed" style="font-size:0.875rem;color:var(--text-secondary);line-height:1.6;">
${escHtml(details.description).replace(/\n/g,'<br>')}
</div>
<button onclick="toggleDesc()" style="font-size:0.8125rem;color:var(--text-secondary);background:none;border:none;cursor:pointer;margin-top:0.375rem;padding:0;text-decoration:underline;" id="desc-btn">Show more</button>
</div>
` : ''}
<div style="display:flex;flex-wrap:wrap;gap:0.5rem;">
<button onclick="toggleSave('${escHtml(videoId)}')" class="btn btn-ghost" id="save-btn" style="${saved ? 'border-color:var(--border-strong);color:var(--text-primary);' : ''}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="${saved ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="2"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/></svg>
${saved ? 'Saved' : 'Save'}
</button>
<button onclick="toggleLights()" id="lights-btn" class="btn btn-ghost">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg>
Lights Off
</button>
<button onclick="copyLink('${escHtml(videoId)}')" class="btn btn-ghost">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
Share
</button>
</div>
</div>
</div>
</div>`;
setTimeout(() => {
const s = document.getElementById('load-spinner');
if (s) s.style.display = 'none';
}, 3000);
}
window.toggleDesc = () => {
const d = document.getElementById('desc-text');
const b = document.getElementById('desc-btn');
if (d.classList.contains('description-collapsed')) {
d.classList.remove('description-collapsed');
b.textContent = 'Show less';
} else {
d.classList.add('description-collapsed');
b.textContent = 'Show more';
}
};
window.toggleLights = () => {
isLightsOff = !isLightsOff;
document.body.classList.toggle('lights-off', isLightsOff);
const btn = document.getElementById('lights-btn');
if (btn) btn.innerHTML = isLightsOff
? `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg> Lights On`
: `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg> Lights Off`;
showToast(isLightsOff ? 'Focus mode on' : 'Focus mode off', 'info');
};
window.copyLink = (videoId) => {
const link = `${location.origin}${location.pathname}#watch?v=${videoId}`;
navigator.clipboard.writeText(link)
.then(() => showToast('Link copied!', 'success'))
.catch(() => showToast('Failed to copy link', 'error'));
};
function renderSaved() {
const root = document.getElementById('content-root');
const local = getSaved('local');
const cloud = isCloudEnabled ? getSaved('cloud') : [];
root.innerHTML = `
<div class="fade-in">
<h1 style="font-size:1.5rem;font-weight:700;margin-bottom:1.5rem;color:var(--text-primary);">Saved Videos</h1>
<div class="tab-bar">
<button class="tab-btn active" id="tab-local" onclick="switchSavedTab('local')">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
Local (${local.length})
</button>
<button class="tab-btn" id="tab-cloud" onclick="switchSavedTab('cloud')">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>
Cloud ${isCloudEnabled ? `(${cloud.length})` : '(Disabled)'}
</button>
</div>
<div id="local-tab">
${local.length > 0 ? `<div class="video-grid">${local.map(v => savedCard(v, 'local')).join('')}</div>` : `
<div style="text-align:center;padding:4rem 0;color:var(--text-muted);">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin:0 auto 1rem;display:block;"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/></svg>
No saved videos yet.
</div>`}
</div>
<div id="cloud-tab" class="hidden">
${!isCloudEnabled ? `
<div style="text-align:center;padding:4rem 0;">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="margin:0 auto 1rem;display:block;color:var(--text-muted);"><path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/></svg>
<p style="color:var(--text-muted);margin-bottom:1rem;">Cloud storage not configured.</p>
<button onclick="openSettingsModal()" class="btn btn-primary">Configure Firebase</button>
</div>` :
cloud.length > 0 ? `<div class="video-grid">${cloud.map(v => savedCard(v, 'cloud')).join('')}</div>` :
`<div style="text-align:center;padding:4rem 0;color:var(--text-muted);">No cloud saved videos yet.</div>`
}
</div>
</div>`;
}
function savedCard(v, storage) {
return `
<div class="video-card">
<div class="video-thumb" onclick="navigate('watch?v=${escHtml(v.id)}')">
<img class="video-thumb-img" src="https://i.ytimg.com/vi/${escHtml(v.id)}/hqdefault.jpg" alt="" loading="lazy"
onerror="this.onerror=null;this.src='https://i.ytimg.com/vi/${escHtml(v.id)}/mqdefault.jpg'">
</div>
<div class="video-card-body" style="display:flex;justify-content:space-between;align-items:flex-start;">
<div style="flex:1;min-width:0;">
<p class="video-card-title" onclick="navigate('watch?v=${escHtml(v.id)}')" style="cursor:pointer;">${escHtml(v.title || v.id)}</p>
<p class="video-card-meta">Saved ${timeAgo(v.timestamp)}</p>
</div>
<button onclick="removeSaved('${escHtml(v.id)}','${storage}')" style="flex-shrink:0;background:none;border:none;cursor:pointer;color:var(--text-muted);padding:0.25rem;border-radius:0.25rem;margin-left:0.5rem;" onmouseover="this.style.color='#ff6b6b'" onmouseout="this.style.color='var(--text-muted)'">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>
</button>
</div>
</div>`;
}
window.switchSavedTab = (tab) => {
document.getElementById('tab-local').classList.toggle('active', tab === 'local');
document.getElementById('tab-cloud').classList.toggle('active', tab === 'cloud');
document.getElementById('local-tab').classList.toggle('hidden', tab !== 'local');
document.getElementById('cloud-tab').classList.toggle('hidden', tab !== 'cloud');
};
function renderNotFound() {
document.getElementById('content-root').innerHTML = `
<div style="text-align:center;padding:6rem 1rem;" class="fade-in">
<p style="font-size:4rem;margin-bottom:1rem;">¯\\_(ツ)_/¯</p>
<h1 style="font-size:2rem;font-weight:900;color:var(--text-primary);margin-bottom:0.5rem;">404 — Not Found</h1>
<p style="color:var(--text-muted);margin-bottom:2rem;">The page or video you're looking for doesn't exist.</p>
<button onclick="navigate('/')" class="btn btn-primary">Go Home</button>
</div>`;
}
window.openDocsModal = (topic) => {
const modal = document.getElementById('docs-modal');
const title = document.getElementById('docs-modal-title');
const content = document.getElementById('docs-modal-content');
if (topic === 'youtube-api') {
title.textContent = 'How to Get a YouTube API Key';
content.innerHTML = buildDocsSteps([
{ n:1, t:'Go to Google Cloud Console', b:'Visit <a href="https://console.cloud.google.com/" target="_blank" style="color:var(--text-primary);text-decoration:underline;">console.cloud.google.com</a> and sign in with your Google account.' },
{ n:2, t:'Create a New Project', b:'Click the project dropdown, then "New Project". Name it something like "ZenView" and click Create.' },
{ n:3, t:'Enable YouTube Data API v3', b:'Go to "APIs & Services" → "Library". Search for "YouTube Data API v3" and click Enable.' },
{ n:4, t:'Create Credentials', b:'Go to "APIs & Services" → "Credentials". Click "+ CREATE CREDENTIALS" → "API key".' },
{ n:5, t:'Restrict Your Key (Recommended)', b:'Edit the key and under "API restrictions" select "YouTube Data API v3". Under "Application restrictions" add your website domain.' },
{ n:6, t:'Add Key to ZenView', b:'Click the Settings gear in ZenView\'s header, paste your key in the YouTube API Key field, and click Save.' }
]) + `<div style="margin-top:1.5rem;padding:1rem;background:var(--bg-tertiary);border-radius:var(--radius);font-size:0.8125rem;color:var(--text-muted);">
<strong style="color:var(--text-primary);">Free tier:</strong> The YouTube Data API v3 includes a generous free quota (10,000 units/day) — more than enough for personal use.
</div>`;
} else if (topic === 'firebase') {
title.textContent = 'Setting Up Firebase';
content.innerHTML = buildDocsSteps([
{ n:1, t:'Create a Firebase Project', b:'Go to <a href="https://console.firebase.google.com/" target="_blank" style="color:var(--text-primary);text-decoration:underline;">console.firebase.google.com</a>, sign in, and click "Add project".' },
{ n:2, t:'Add a Web App', b:'In your project dashboard, click the web icon (</>) to add a web app. Give it a nickname and click "Register app".' },
{ n:3, t:'Copy the Config Object', b:'Firebase will display a firebaseConfig object. Copy each field (apiKey, authDomain, etc.) into ZenView\'s Settings → Firebase section.' },
{ n:4, t:'Set Up Firestore', b:'In the Firebase console, go to "Build" → "Firestore Database". Click "Create database", start in test mode, and choose a region.' },
{ n:5, t:'Initialize Collections', b:'In Firestore UI, click "Start collection", enter "saves" as the Collection ID, and add a placeholder document to initialize it.' }
]);
} else if (topic === 'about') {
title.textContent = 'About ZenView';
content.innerHTML = `
<div style="margin-bottom:1.5rem;">
<div style="display:inline-flex;align-items:center;gap:0.5rem;padding:0.25rem 0.75rem;border:1px solid var(--border-strong);border-radius:9999px;font-size:0.75rem;font-weight:600;color:var(--text-secondary);margin-bottom:1rem;">
Open Source · Made with ❤️
</div>
<p style="color:var(--text-secondary);line-height:1.7;margin-bottom:1rem;">ZenView is an open-source project designed to give you a cleaner, more focused way to watch YouTube content. No recommendations engine, no autoplay, no distractions — just the video.</p>
<p style="color:var(--text-secondary);line-height:1.7;">It's built with vanilla JavaScript, Tailwind CSS, and optionally Firebase — no heavy frameworks needed.</p>
</div>
<div class="feature-grid" style="margin-bottom:1.5rem;">
${[
['🎯','Distraction-Free','No sidebar, no autoplay queue, no rabbit holes.'],
['🔍','YouTube Search','Search directly inside ZenView via the API.'],
['📈','Trending Feed','See what\'s trending, refreshed each visit.'],
['🔖','Save Videos','Save locally or to Firebase cloud.'],
['🌗','Dark & Light Mode','Full theme support, remembered per device.'],
['💻','Open Source','Fork it, modify it, deploy it freely.'],
].map(([icon,t,d]) => `
<div class="feature-item">
<p style="font-size:1.5rem;margin-bottom:0.375rem;">${icon}</p>
<p style="font-weight:700;font-size:0.875rem;color:var(--text-primary);margin-bottom:0.125rem;">${t}</p>
<p style="font-size:0.75rem;color:var(--text-muted);">${d}</p>
</div>`).join('')}
</div>
<div style="padding:1rem;background:var(--bg-tertiary);border-radius:var(--radius);">
<p style="font-weight:700;font-size:0.875rem;color:var(--text-primary);margin-bottom:0.25rem;">MIT License</p>
<p style="font-size:0.8125rem;color:var(--text-muted);">ZenView is released under the MIT License. You are free to use, modify, and distribute this software for any purpose.</p>
</div>`;
}
modal.classList.remove('hidden');
};
function buildDocsSteps(steps) {
return `<div>${steps.map(s => `
<div class="docs-step">
<div class="docs-step-num">${s.n}</div>
<div>
<p style="font-weight:700;color:var(--text-primary);margin-bottom:0.25rem;">${s.t}</p>
<p style="font-size:0.875rem;color:var(--text-secondary);line-height:1.6;">${s.b}</p>
</div>
</div>`).join('')}</div>`;
}
window.closeDocsModal = () => document.getElementById('docs-modal').classList.add('hidden');
window.openSettingsModal = () => {
const modal = document.getElementById('settings-modal');
const saved = localStorage.getItem(STORAGE.FIREBASE);
if (saved) {
try {
const c = JSON.parse(saved);
['apiKey','authDomain','projectId','storageBucket','messagingSenderId','appId']
.forEach(k => { const el = document.getElementById('fb-' + k); if (el) el.value = c[k] || ''; });
} catch {}
}
const yk = localStorage.getItem(STORAGE.YT_KEY);
if (yk) document.getElementById('yt-api-key-input').value = yk;
modal.classList.remove('hidden');
};
window.closeSettingsModal = () => document.getElementById('settings-modal').classList.add('hidden');
window.saveFirebaseConfig = () => {
const cfg = {
apiKey: document.getElementById('fb-apiKey').value.trim(),
authDomain: document.getElementById('fb-authDomain').value.trim(),
projectId: document.getElementById('fb-projectId').value.trim(),
storageBucket: document.getElementById('fb-storageBucket').value.trim(),
messagingSenderId: document.getElementById('fb-messagingSenderId').value.trim(),
appId: document.getElementById('fb-appId').value.trim(),
};
if (cfg.apiKey && cfg.projectId) {
localStorage.setItem(STORAGE.FIREBASE, JSON.stringify(cfg));
showToast('Firebase config saved! Reload to apply.', 'success');
setTimeout(closeSettingsModal, 1200);
} else {
showToast('Provide at least API Key and Project ID.', 'error');
}
};
window.clearFirebaseConfig = () => {
localStorage.removeItem(STORAGE.FIREBASE);
['apiKey','authDomain','projectId','storageBucket','messagingSenderId','appId']
.forEach(k => { const el = document.getElementById('fb-' + k); if (el) el.value = ''; });
showToast('Firebase config cleared.', 'info');
};
window.saveYouTubeKey = () => {
const key = document.getElementById('yt-api-key-input').value.trim();
if (key) {
localStorage.setItem(STORAGE.YT_KEY, key);
showToast('YouTube API key saved!', 'success');
closeSettingsModal();
handleHashChange();
} else {
localStorage.removeItem(STORAGE.YT_KEY);
showToast('YouTube API key cleared.', 'info');
}
};
window.clearAllData = () => {
if (confirm('Delete all local data? This cannot be undone.')) {
Object.values(STORAGE).forEach(k => localStorage.removeItem(k));
showToast('All data cleared. Reloading…', 'info');
setTimeout(() => location.reload(), 1200);
}
};
window.togglePwVis = (id, btn) => {
const inp = document.getElementById(id);
const isPass = inp.type === 'password';
inp.type = isPass ? 'text' : 'password';
btn.innerHTML = isPass
? `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>`
: `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>`;
};
async function fetchVideoDetails(videoId) {
const apiKey = localStorage.getItem(STORAGE.YT_KEY);
if (!apiKey) return null;
try {
const res = await fetch(
`https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics&id=${videoId}&key=${apiKey}`
);
const data = await res.json();
if (data.error) {
if (data.error.code === 403) showToast('API quota exceeded.', 'error');
else showToast('API error: ' + data.error.message, 'error');
return null;
}
const item = data.items && data.items[0];
if (!item) return null;
return {
title: item.snippet.title,
description: item.snippet.description,
views: item.statistics.viewCount || '0',
likes: item.statistics.likeCount || '0',
};
} catch { return null; }
}
async function addToHistory(videoId) {
const h = getHistory();
const idx = h.findIndex(v => v.id === videoId);
if (idx !== -1) h.splice(idx, 1);
const details = await fetchVideoDetails(videoId);
h.unshift({ id: videoId, title: details ? details.title : null, timestamp: Date.now() });
localStorage.setItem(STORAGE.HISTORY, JSON.stringify(h.slice(0, 50)));
}
function getHistory() {
try { return JSON.parse(localStorage.getItem(STORAGE.HISTORY) || '[]'); } catch { return []; }
}
window.clearHistory = () => {
localStorage.removeItem(STORAGE.HISTORY);
showToast('Watch history cleared.', 'info');
handleHashChange();
};
function getSaved(store) {
try { return JSON.parse(localStorage.getItem(store === 'cloud' ? 'ZenView_cloud_videos' : STORAGE.SAVED) || '[]'); } catch { return []; }
}
function isSaved(id) {
return getSaved('local').some(v => v.id === id) || getSaved('cloud').some(v => v.id === id);
}
window.toggleSave = (videoId) => {
const key = isCloudEnabled ? 'ZenView_cloud_videos' : STORAGE.SAVED;
let vids = getSaved(isCloudEnabled ? 'cloud' : 'local');
const idx = vids.findIndex(v => v.id === videoId);
if (idx !== -1) { vids.splice(idx,1); showToast('Removed from saved.', 'info'); }
else { vids.unshift({ id: videoId, title: null, timestamp: Date.now() }); showToast('Video saved.', 'success'); }
localStorage.setItem(key, JSON.stringify(vids));
renderWatch(videoId);
};
window.removeSaved = (videoId, store) => {
const key = store === 'cloud' ? 'ZenView_cloud_videos' : STORAGE.SAVED;
let vids = getSaved(store);
vids = vids.filter(v => v.id !== videoId);
localStorage.setItem(key, JSON.stringify(vids));
showToast('Video removed.', 'info');
renderSaved();
};
function getYtId(url) {
const parts = url.replace(/(>|<)/gi,'').split(/(\/embed\/|\/v\/|youtu\.be\/|watch\?v=|&v=|\?v=)/);
if (parts[2]) return parts[2].split(/[^0-9a-z_\-]/i)[0];
try { return new URL(url).searchParams.get('v'); } catch { return null; }
}
function escHtml(str) {
if (str == null) return '';
return String(str).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
}
function timeAgo(ts) {
const s = Math.floor((Date.now() - ts) / 1000);
if (s < 60) return 'just now';
if (s < 3600) return Math.floor(s / 60) + 'm ago';
if (s < 86400) return Math.floor(s / 3600) + 'h ago';
if (s < 604800) return Math.floor(s / 86400) + 'd ago';
return new Date(ts).toLocaleDateString();
}
function showToast(text, type = 'info') {
if (labels && labels.toasts && labels.toasts.enabled === false) return;
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast toast-${type}`;
toast.textContent = text;
container.appendChild(toast);
const duration = (labels && labels.toasts && labels.toasts.duration) || 3000;
setTimeout(() => {
toast.classList.add('out');
setTimeout(() => toast.remove(), 300);
}, duration);
}
window.showMessage = showToast;