@obitosouls/tizenbrew-netmirror 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/js/app.js ADDED
@@ -0,0 +1,3058 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ /* =====================================================================
5
+ * CONFIG — point SERVERS at your own backend.
6
+ * With SERVERS empty the app runs in DEMO mode on public test streams.
7
+ *
8
+ * Each ENDPOINTS entry:
9
+ * path — URL path appended to the active server base
10
+ * method — 'GET' (params become ?key=val) or 'POST' (form-encoded body)
11
+ * ===================================================================== */
12
+ const CONFIG = {
13
+ APP_NAME: 'NetMirror TV',
14
+ STORE_KEY: 'tvplayer.v2',
15
+ MAX_PROFILES: 5,
16
+ OSD_HIDE_MS: 5000,
17
+ SEARCH_DEBOUNCE_MS: 300,
18
+ REQUEST_TIMEOUT_MS: 15000
19
+ };
20
+
21
+ const DEFAULT_SETTINGS = {
22
+ audioLang: 'en',
23
+ subLang: 'off',
24
+ quality: 'auto', // auto | high | saver
25
+ speed: 1,
26
+ seekStep: 10,
27
+ sub: { size: 'medium', color: 'white', bg: true, bgOpacity: 0.75 }
28
+ };
29
+ const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];
30
+ const SUB_SIZES = { small: 38, medium: 50, large: 66 };
31
+ const SUB_COLORS = { white: '#ffffff', yellow: '#ffe14d', cyan: '#5ef1ff', green: '#6dff7a' };
32
+ const AVATAR_COLORS = [['#e50914', 'Red'], ['#f5a623', 'Amber'], ['#2bb673', 'Green'], ['#2d9cdb', 'Blue'], ['#9b51e0', 'Purple'], ['#00a8a0', 'Teal'], ['#eb5aa8', 'Pink']];
33
+
34
+ /* =====================================================================
35
+ * Utilities
36
+ * ===================================================================== */
37
+ const $ = id => document.getElementById(id);
38
+
39
+ function h(tag, props, kids) {
40
+ const el = document.createElement(tag);
41
+ if (props) Object.keys(props).forEach(k => {
42
+ const v = props[k];
43
+ if (v == null || v === false) return;
44
+ if (k === 'class') el.className = v;
45
+ else if (k === 'text') el.textContent = v;
46
+ else if (k === 'html') el.innerHTML = v; // static markup only
47
+ else if (k === 'style') el.style.cssText = v;
48
+ else if (k.indexOf('on') === 0) el.addEventListener(k.slice(2), v);
49
+ else el.setAttribute(k, v === true ? '' : v);
50
+ });
51
+ if (kids) kids.forEach(c => {
52
+ if (c == null || c === false) return;
53
+ el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
54
+ });
55
+ return el;
56
+ }
57
+
58
+ const ICON_PATHS = {
59
+ play: 'M8 5v14l11-7z',
60
+ pause: 'M6 19h4V5H6v14zm8-14v14h4V5h-4z',
61
+ rew: 'M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z',
62
+ fwd: 'M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z',
63
+ back: 'M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z',
64
+ check: 'M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z',
65
+ plus: 'M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z',
66
+ info: 'M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z',
67
+ edit: 'M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z',
68
+ search: 'M15.5 14h-.79l-.28-.27A6.47 6.47 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z',
69
+ bksp: 'M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 12.59L17.59 17 14 13.41 10.41 17 9 15.59 12.59 12 9 8.41 10.41 7 14 10.59 17.59 7 19 8.41 15.41 12 19 15.59z',
70
+ cc: 'M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 7H9.5v-.5h-2v3h2V13H11v1c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H18v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1z',
71
+ gear: 'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.48.48 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.48.48 0 0 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z'
72
+ };
73
+ const icon = name => '<svg viewBox="0 0 24 24"><path d="' + ICON_PATHS[name] + '"/></svg>';
74
+
75
+ const pad2 = n => (n < 10 ? '0' : '') + n;
76
+ function fmtTime(s) {
77
+ if (!isFinite(s) || s < 0) s = 0;
78
+ s = Math.floor(s);
79
+ const hh = Math.floor(s / 3600), mm = Math.floor((s % 3600) / 60), ss = s % 60;
80
+ return (hh ? hh + ':' + pad2(mm) : mm) + ':' + pad2(ss);
81
+ }
82
+ const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
83
+ const cssUrl = u => 'url("' + String(u).replace(/["\\\n\r]/g, c => encodeURIComponent(c)) + '")';
84
+ const safeColor = c => (/^#[0-9a-f]{3,8}$/i.test(c) ? c : '#555');
85
+
86
+ function debounce(fn, ms) {
87
+ let t = null;
88
+ return function () { const a = arguments; clearTimeout(t); t = setTimeout(() => fn.apply(null, a), ms); };
89
+ }
90
+ function hashHue(s) {
91
+ let x = 0;
92
+ for (let i = 0; i < s.length; i++) x = (x * 31 + s.charCodeAt(i)) % 360;
93
+ return x;
94
+ }
95
+ function fallbackGradient(item) {
96
+ const hue = hashHue(item.title || item.id || '');
97
+ return 'linear-gradient(135deg, hsl(' + hue + ',55%,30%), hsl(' + ((hue + 50) % 360) + ',60%,12%))';
98
+ }
99
+ function posterBg(item, useBackdrop) {
100
+ var src = useBackdrop ? (item.backdrop || item.image) : (item.image || item.backdrop);
101
+ return (src ? cssUrl(src) + ', ' : '') + fallbackGradient(item);
102
+ }
103
+ // First user-perceived character, keeping Indic vowel signs / virama attached.
104
+ function firstGrapheme(s) {
105
+ const m = String(s || '').trim().match(/^[\s\S][̀-ͯऀ-ःऺ-ॏঁ-ঃ়-্ஂா-்ௗఀ-ఄా-ౖಁ-ಃ಼-ೖഀ-ഃാ-്‌‍]*/);
106
+ return m ? m[0].toUpperCase() : '?';
107
+ }
108
+ function fetchWithTimeout(url, opts, ms) {
109
+ opts = opts || {};
110
+ const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
111
+ if (ctrl) opts.signal = ctrl.signal;
112
+ return new Promise((resolve, reject) => {
113
+ const t = setTimeout(() => { if (ctrl) ctrl.abort(); reject(new Error('Request timed out')); }, ms);
114
+ fetch(url, opts).then(r => { clearTimeout(t); resolve(r); }, e => { clearTimeout(t); reject(e); });
115
+ });
116
+ }
117
+
118
+ // Fit the fixed 1920×1080 stage to whatever viewport the TV gives us (720p, 1080p, 4K).
119
+ const Screen = {
120
+ scale: 1,
121
+ fit() {
122
+ const w = window.innerWidth || document.documentElement.clientWidth || 1920;
123
+ const hgt = window.innerHeight || document.documentElement.clientHeight || 1080;
124
+ const s = Math.min(w / 1920, hgt / 1080);
125
+ const st = $('app').style;
126
+ st.webkitTransform = st.transform = 'scale(' + s + ')';
127
+ st.left = Math.round((w - 1920 * s) / 2) + 'px';
128
+ st.top = Math.round((hgt - 1080 * s) / 2) + 'px';
129
+ this.scale = s;
130
+ }
131
+ };
132
+
133
+ // ES5-safe synthetic 'input' event (no Event constructor on older engines).
134
+ function fireInput(el) {
135
+ const ev = document.createEvent('Event');
136
+ ev.initEvent('input', true, true);
137
+ el.dispatchEvent(ev);
138
+ }
139
+
140
+ // hls.js is bundled in js/; fall back to the CDN only if the local copy is missing.
141
+ let hlsLoading = null;
142
+ function ensureHls() {
143
+ if (window.Hls) return Promise.resolve(window.Hls);
144
+ if (!hlsLoading) {
145
+ hlsLoading = new Promise(resolve => {
146
+ const s = document.createElement('script');
147
+ s.src = 'https://cdn.jsdelivr.net/npm/hls.js@1.5.13/dist/hls.min.js';
148
+ s.onload = s.onerror = () => resolve(window.Hls || null);
149
+ document.head.appendChild(s);
150
+ });
151
+ }
152
+ return hlsLoading;
153
+ }
154
+
155
+ const UI = {
156
+ toastTimer: null,
157
+ toast(msg, kind) {
158
+ const el = $('toast');
159
+ el.textContent = msg;
160
+ el.className = 'show' + (kind === 'error' ? ' error' : '');
161
+ clearTimeout(this.toastTimer);
162
+ this.toastTimer = setTimeout(() => { el.className = ''; }, 4200);
163
+ },
164
+ loading(on, text) {
165
+ $('loading-text').textContent = text || 'Loading…';
166
+ $('loading').classList.toggle('show', !!on);
167
+ }
168
+ };
169
+
170
+ /* =====================================================================
171
+ * Languages + fallback engine
172
+ * ===================================================================== */
173
+ const LANGS = [
174
+ ['en', 'English', ['eng']], ['ta', 'Tamil', ['tam', 'தமிழ்']], ['hi', 'Hindi', ['hin', 'हिन्दी']],
175
+ ['te', 'Telugu', ['tel']], ['ml', 'Malayalam', ['mal']], ['kn', 'Kannada', ['kan']],
176
+ ['bn', 'Bengali', ['ben', 'bangla']], ['mr', 'Marathi', ['mar']], ['es', 'Spanish', ['spa', 'español', 'espanol', 'castellano']],
177
+ ['fr', 'French', ['fra', 'fre', 'français', 'francais']], ['de', 'German', ['deu', 'ger', 'deutsch']],
178
+ ['it', 'Italian', ['ita', 'italiano']], ['pt', 'Portuguese', ['por', 'português']], ['ru', 'Russian', ['rus']],
179
+ ['ja', 'Japanese', ['jpn', '日本語']], ['ko', 'Korean', ['kor', '한국어']], ['zh', 'Chinese', ['zho', 'chi', 'mandarin', '中文']],
180
+ ['ar', 'Arabic', ['ara']]
181
+ ];
182
+
183
+ const Lang = (function () {
184
+ const alias = {};
185
+ LANGS.forEach(([code, name, al]) => {
186
+ alias[code] = code;
187
+ alias[name.toLowerCase()] = code;
188
+ al.forEach(a => { alias[a.toLowerCase()] = code; });
189
+ });
190
+ function norm(s) {
191
+ if (!s) return '';
192
+ s = String(s).trim().toLowerCase();
193
+ if (alias[s]) return alias[s];
194
+ const base = s.split(/[-_\s(]/)[0];
195
+ if (alias[base]) return alias[base];
196
+ return /^[a-z]{2,3}$/.test(base) ? base : '';
197
+ }
198
+ function fromName(n) {
199
+ if (!n) return '';
200
+ const s = String(n).toLowerCase();
201
+ for (const [code, name, al] of LANGS) {
202
+ if (s.indexOf(name.toLowerCase()) > -1) return code;
203
+ for (const a of al) if (a.length > 3 && s.indexOf(a.toLowerCase()) > -1) return code;
204
+ }
205
+ return '';
206
+ }
207
+ // Works for hls.js tracks ({lang,name}), native tracks ({language,label}) and API tracks.
208
+ function ofTrack(t) {
209
+ return norm(t.lang || t.language) || fromName(t.name || t.label) || norm(t.name || t.label);
210
+ }
211
+ function label(code) {
212
+ const l = LANGS.find(x => x[0] === code);
213
+ return l ? l[1] : (code ? code.toUpperCase() : 'Unknown');
214
+ }
215
+ /**
216
+ * Preferred ➔ English ➔ next available (manifest DEFAULT track, else first).
217
+ * tracks: [{ code, isDefault }] → { index, matched: 'preferred'|'english'|'first' }
218
+ */
219
+ function pick(tracks, preferred) {
220
+ if (!tracks.length) return { index: -1, matched: 'none' };
221
+ const order = [preferred, 'en'];
222
+ for (let k = 0; k < order.length; k++) {
223
+ if (!order[k]) continue;
224
+ const i = tracks.findIndex(t => t.code === order[k]);
225
+ if (i > -1) return { index: i, matched: k === 0 ? 'preferred' : 'english' };
226
+ }
227
+ const d = tracks.findIndex(t => t.isDefault);
228
+ return { index: d > -1 ? d : 0, matched: 'first' };
229
+ }
230
+ function chainText(code) {
231
+ if (code === 'off') return 'Off';
232
+ return (code === 'en' ? 'English' : label(code) + ' → English') + ' → first available';
233
+ }
234
+ return { norm, fromName, ofTrack, label, pick, chainText };
235
+ })();
236
+
237
+ /* =====================================================================
238
+ * Persistence: profiles + per-profile settings
239
+ * ===================================================================== */
240
+ function mergeSettings(s) {
241
+ const d = JSON.parse(JSON.stringify(DEFAULT_SETTINGS));
242
+ if (s && typeof s === 'object') {
243
+ Object.keys(d).forEach(k => {
244
+ if (k === 'sub') Object.assign(d.sub, s.sub || {});
245
+ else if (s[k] !== undefined) d[k] = s[k];
246
+ });
247
+ }
248
+ return d;
249
+ }
250
+
251
+ const Store = {
252
+ data: { profiles: [], lastProfileId: null },
253
+ profile: null,
254
+ guest: null,
255
+ load() {
256
+ try {
257
+ const raw = localStorage.getItem(CONFIG.STORE_KEY);
258
+ if (raw) {
259
+ const d = JSON.parse(raw);
260
+ if (d && Array.isArray(d.profiles)) this.data = d;
261
+ }
262
+ } catch (e) { /* storage unavailable or corrupt: start fresh */ }
263
+ this.data.profiles.forEach(p => { p.settings = mergeSettings(p.settings); p.color = safeColor(p.color); });
264
+ this.guest = mergeSettings();
265
+ },
266
+ save() { try { localStorage.setItem(CONFIG.STORE_KEY, JSON.stringify(this.data)); } catch (e) {} },
267
+ settings() { return this.profile ? this.profile.settings : this.guest; },
268
+ setActive(p) { this.profile = p; this.data.lastProfileId = p ? p.id : null; this.save(); },
269
+ addProfile(name, color) {
270
+ const p = { id: 'p' + Date.now().toString(36), name: name, color: color, settings: mergeSettings() };
271
+ this.data.profiles.push(p);
272
+ this.save();
273
+ return p;
274
+ },
275
+ removeProfile(p) {
276
+ this.data.profiles = this.data.profiles.filter(x => x !== p);
277
+ if (this.profile === p) this.profile = null;
278
+ if (this.data.lastProfileId === p.id) this.data.lastProfileId = null;
279
+ this.save();
280
+ }
281
+ };
282
+
283
+ const Settings = {
284
+ get(k) {
285
+ const s = Store.settings();
286
+ return k.indexOf('sub.') === 0 ? s.sub[k.slice(4)] : s[k];
287
+ },
288
+ set(k, v) {
289
+ const s = Store.settings();
290
+ if (k.indexOf('sub.') === 0) s.sub[k.slice(4)] = v; else s[k] = v;
291
+ Store.save();
292
+ App.onSettingsChanged(k);
293
+ },
294
+ resetSub() {
295
+ Store.settings().sub = JSON.parse(JSON.stringify(DEFAULT_SETTINGS.sub));
296
+ Store.save();
297
+ App.onSettingsChanged('sub');
298
+ }
299
+ };
300
+
301
+ // Injects a stylesheet instead of CSS variables (unsupported on older Tizen engines).
302
+ const SubStyle = {
303
+ el: null,
304
+ apply() {
305
+ const s = Store.settings().sub;
306
+ const size = SUB_SIZES[s.size] || 50;
307
+ const decl = 'color:' + (SUB_COLORS[s.color] || '#fff') + ';' +
308
+ 'background:' + (s.bg ? 'rgba(0,0,0,' + s.bgOpacity + ')' : 'transparent') + ';' +
309
+ 'text-shadow:' + (s.bg ? 'none' : '0 0 4px #000, 0 0 8px #000, 2px 2px 2px #000, -2px -2px 2px #000') + ';';
310
+ if (!this.el) { this.el = document.createElement('style'); document.head.appendChild(this.el); }
311
+ this.el.textContent =
312
+ '#subs .sub-text{font-size:' + size + 'px;' + decl + '}' +
313
+ '.sub-preview .sub-text{font-size:' + Math.round(size * 0.72) + 'px;' + decl + '}';
314
+ this.size = size;
315
+ }
316
+ };
317
+
318
+ /* =====================================================================
319
+ * Backend: NM-backed API layer
320
+ *
321
+ * Adapts NetMirror responses to the internal model used by UI layers.
322
+ * ===================================================================== */
323
+
324
+ const Api = {
325
+ parseMainResponse(data) {
326
+ var items = [];
327
+ if (!data) return items;
328
+
329
+ // Cache CDNs to persistent storage for subsequent image resolution
330
+ if (data.imgcdn_h) NM.storage.set('imgcdn_h', data.imgcdn_h);
331
+ if (data.imgcdn_v) NM.storage.set('imgcdn_v', data.imgcdn_v);
332
+ if (data.imgcdn) NM.storage.set('imgcdn', data.imgcdn);
333
+ if (data.detailsimgcdn) NM.storage.set('detailsimgcdn', data.detailsimgcdn);
334
+ if (data.img_referer) NM.storage.set('img_referer', data.img_referer);
335
+ if (data.pub_msg) NM.storage.set('pub_msg', data.pub_msg);
336
+ if (data.pub_msg_img && typeof data.pub_msg_img === 'object') {
337
+ NM.storage.set('pub_msg_img', JSON.stringify(data.pub_msg_img));
338
+ }
339
+
340
+ var ott = (NM.storage.getOtt() || 'nf').toLowerCase();
341
+ var imgcdnH = data.imgcdn_h || data.imgcdn || NM.storage.get('imgcdn_h') || '';
342
+ var imgcdnV = data.imgcdn_v || data.imgcdn || NM.storage.get('imgcdn_v') || imgcdnH;
343
+ var imgRef = data.img_referer || NM.storage.get('img_referer') || '';
344
+
345
+ // Provider-specific high-resolution CDN templates
346
+ if (ott === 'pv') {
347
+ imgcdnH = 'https://imgcdn.kim/pv/h/------------------.jpg';
348
+ imgcdnV = 'https://imgcdn.kim/pv/v/------------------.jpg';
349
+ } else if (ott === 'nf') {
350
+ imgcdnH = 'https://imgcdn.kim/poster/h/------------------.jpg';
351
+ imgcdnV = 'https://imgcdn.kim/poster/v/------------------.jpg';
352
+ } else if (ott === 'hs') {
353
+ imgcdnH = data.imgcdn_h || 'https://imgcdn.kim/hs/v/166/------------------.jpg';
354
+ imgcdnV = data.imgcdn_v || 'https://imgcdn.kim/hs/v/166/------------------.jpg';
355
+ }
356
+
357
+ // Slider banners — handle array OR dictionary/object of sliders
358
+ var sliderList = [];
359
+ if (data.slider) {
360
+ if (Array.isArray(data.slider)) sliderList = data.slider;
361
+ else if (typeof data.slider === 'object') {
362
+ Object.keys(data.slider).forEach(function (k) {
363
+ if (data.slider[k] && typeof data.slider[k] === 'object') sliderList.push(data.slider[k]);
364
+ });
365
+ }
366
+ }
367
+
368
+ sliderList.forEach(function (s) {
369
+ if (!s) return;
370
+ var sId = String(s.id || s.post_id || '');
371
+ if (!sId) return;
372
+ var sImg = normalizeImageUrl(s.img || s.image || s.poster || s.backdrop, imgcdnH, sId);
373
+ var cleanTitle = (function () {
374
+ var t = (s.title || s.name || s.title_name || '').trim();
375
+ if (!t && s.desc) {
376
+ var m = s.desc.match(/"([^"]+)"/);
377
+ if (m) t = m[1];
378
+ }
379
+ return /^#?\d+$/.test(t) ? '' : t;
380
+ })();
381
+
382
+ items.push({
383
+ id: sId,
384
+ title: cleanTitle,
385
+ namelogo: s.namelogo || '',
386
+ description: s.desc || s.description || '',
387
+ image: sImg,
388
+ backdrop: sImg,
389
+ year: s.year || '',
390
+ duration: s.runtime || s.duration || '',
391
+ rating: s.ua || s.rating || '',
392
+ genres: [],
393
+ category: 'Featured',
394
+ type: s.type === 't' ? 'series' : 'movie',
395
+ seasons: [],
396
+ _imgRef: imgRef
397
+ });
398
+ });
399
+
400
+ // Content sections:
401
+ // In NetMirror bytecode (f6639 / f6655), the sections array is called `post`!
402
+ // Also support `sections`, `data`, or key-value object
403
+ var sections = data.post || data.sections || data.data || [];
404
+ if (!Array.isArray(sections)) {
405
+ var tmp = [];
406
+ Object.keys(data).forEach(function (k) {
407
+ var v = data[k];
408
+ if (v && typeof v === 'object' && (v.cate || v.category || v.ids)) tmp.push(v);
409
+ if (Array.isArray(v) && v.length && v[0] && (v[0].cate || v[0].ids)) tmp = tmp.concat(v);
410
+ });
411
+ sections = tmp;
412
+ }
413
+
414
+ sections.forEach(function (sec) {
415
+ if (!sec) return;
416
+ var cat = sec.cate || sec.category || 'Featured';
417
+ var isHoriz = sec.row === 'h';
418
+ var cdn = isHoriz ? imgcdnH : imgcdnV;
419
+ // Auto-detect TV Series by category name (e.g. "Critically Acclaimed TV Shows", "Drama Series")
420
+ var isSeries = /(?:tv|series|shows|serial|season|episodes)/i.test(cat);
421
+
422
+ var ids = [];
423
+ if (typeof sec.ids === 'string') ids = sec.ids.split(',').filter(Boolean);
424
+ else if (Array.isArray(sec.ids)) ids = sec.ids;
425
+ else if (Array.isArray(sec.items)) ids = sec.items;
426
+ else if (Array.isArray(sec.posts)) ids = sec.posts;
427
+
428
+ ids.forEach(function (entry) {
429
+ if (!entry) return;
430
+ var id = '', title = '', img = '', desc = '';
431
+ if (typeof entry === 'object') {
432
+ id = String(entry.id || entry.post_id || '');
433
+ title = entry.title || entry.name || '';
434
+ if (/^#?\d+$/.test(title)) title = '';
435
+ desc = entry.desc || entry.description || '';
436
+ img = normalizeImageUrl(entry.img || entry.poster || entry.image, cdn, id);
437
+ } else {
438
+ id = String(entry).trim();
439
+ title = '';
440
+ img = normalizeImageUrl(id + '.jpg', cdn, id);
441
+ }
442
+ if (!id) return;
443
+
444
+ items.push({
445
+ id: id,
446
+ title: title,
447
+ description: desc,
448
+ image: img,
449
+ backdrop: img,
450
+ year: '',
451
+ duration: '',
452
+ rating: '',
453
+ genres: [],
454
+ category: cat,
455
+ type: isSeries ? 'series' : 'movie',
456
+ seasons: [],
457
+ _imgRef: imgRef
458
+ });
459
+ });
460
+ });
461
+
462
+ return items;
463
+ },
464
+
465
+ parseSearchResponse(data) {
466
+ if (!data) return [];
467
+ if (data.imgcdn) NM.storage.set('imgcdn', data.imgcdn);
468
+ if (data.detailsimgcdn) NM.storage.set('detailsimgcdn', data.detailsimgcdn);
469
+ if (data.img_referer) NM.storage.set('img_referer', data.img_referer);
470
+
471
+ var ott = (NM.storage.getOtt() || 'nf').toLowerCase();
472
+ var imgcdn = data.imgcdn || NM.storage.get('imgcdn') || '';
473
+ var detailsCdn = data.detailsimgcdn || imgcdn;
474
+
475
+ if (ott === 'pv') {
476
+ imgcdn = 'https://imgcdn.kim/pv/341/------------------.jpg';
477
+ detailsCdn = 'https://imgcdn.kim/pv/h/------------------.jpg';
478
+ } else if (ott === 'nf') {
479
+ imgcdn = 'https://imgcdn.kim/poster/341/------------------.jpg';
480
+ detailsCdn = 'https://imgcdn.kim/poster/h/------------------.jpg';
481
+ }
482
+
483
+ var imgRef = data.img_referer || '';
484
+ var results = data.searchResult || data.results || data.data || [];
485
+ if (!Array.isArray(results)) return [];
486
+
487
+ return results.map(function (x) {
488
+ if (!x) return null;
489
+ var id = String(x.id || x.post_id || '');
490
+ var rawImg = x.img || x.poster || x.image || (id ? (id + '.jpg') : '');
491
+ var img = normalizeImageUrl(rawImg, imgcdn, id);
492
+ var backdrop = normalizeImageUrl(x.backdrop || (id ? (id + '.jpg') : ''), detailsCdn, id);
493
+ return {
494
+ id: id,
495
+ title: (x.t || x.title || x.name || '').trim(),
496
+ description: x.desc || x.description || '',
497
+ image: img,
498
+ backdrop: backdrop,
499
+ year: x.year || '',
500
+ duration: x.runtime || '',
501
+ rating: x.ua || '',
502
+ genres: [],
503
+ category: 'Search Results',
504
+ type: x.type === 't' ? 'series' : 'movie',
505
+ seasons: [],
506
+ _imgRef: imgRef
507
+ };
508
+ }).filter(Boolean);
509
+ },
510
+
511
+ parsePostResponse(data) {
512
+ if (!data) return {};
513
+ if (data.imgcdn) NM.storage.set('imgcdn', data.imgcdn);
514
+ if (data.img_referer) NM.storage.set('img_referer', data.img_referer);
515
+
516
+ var ott = (data.ott || NM.storage.getOtt() || 'nf').toLowerCase();
517
+ var imgcdn = data.imgcdn || NM.storage.get('imgcdn') || '';
518
+ var detailsCdn = data.detailsimgcdn || NM.storage.get('detailsimgcdn') || imgcdn;
519
+ var imgRef = data.img_referer || '';
520
+ var mainId = String(data.main_id || data.id || '');
521
+
522
+ var rawPoster = data.main_poster || data.poster || '';
523
+ if (ott === 'pv' && (!rawPoster || rawPoster.indexOf('--') > -1)) {
524
+ rawPoster = 'https://imgcdn.kim/pv/c/------------------.jpg';
525
+ } else if (ott === 'nf' && (!rawPoster || rawPoster.indexOf('--') > -1)) {
526
+ rawPoster = 'https://imgcdn.kim/poster/h/------------------.jpg';
527
+ }
528
+ var poster = normalizeImageUrl(rawPoster, detailsCdn, mainId);
529
+ var isSeries = data.type === 't';
530
+
531
+ var item = {
532
+ id: mainId,
533
+ title: (data.title_name || data.title || '').trim(),
534
+ description: data.desc || data.description || '',
535
+ image: poster,
536
+ backdrop: poster,
537
+ year: data.year || '',
538
+ duration: data.runtime || '',
539
+ rating: data.ua || '',
540
+ genres: [],
541
+ category: '',
542
+ type: isSeries ? 'series' : 'movie',
543
+ seasons: [],
544
+ _imgRef: imgRef,
545
+ _lastEp: data.last_ep || '',
546
+ _hdsd: data.hdsd || '',
547
+ _lang: data.lang || [],
548
+ _season: data.season || null,
549
+ _ott_logo: data.ott_logo || null,
550
+ _resume_title: data.resume_title || '',
551
+ _ep_poster: data.ep_poster || '',
552
+ _morelike: data.morelike_poster || ''
553
+ };
554
+
555
+ if (Array.isArray(data.suggest) && data.suggest.length) {
556
+ var sCdn = (ott === 'pv') ? 'https://imgcdn.kim/pv/341/------------------.jpg' : 'https://imgcdn.kim/poster/341/------------------.jpg';
557
+ item._suggest = data.suggest.map(function (s) {
558
+ var sId = String(s.id || '');
559
+ return {
560
+ id: sId,
561
+ title: '',
562
+ image: normalizeImageUrl(sId + '.jpg', sCdn, sId),
563
+ backdrop: normalizeImageUrl(sId + '.jpg', detailsCdn, sId),
564
+ category: 'More Like This',
565
+ type: 'movie',
566
+ _imgRef: imgRef
567
+ };
568
+ });
569
+ }
570
+
571
+ var seasons = [];
572
+ var initialEps = [];
573
+ if (Array.isArray(data.episodes) && data.episodes.length) {
574
+ initialEps = data.episodes.filter(Boolean).map(function (e, ei) {
575
+ var epNum = e.ep || e.episode || (ei + 1);
576
+ var epTitle = e.t || e.ep_title || e.title || ('Episode ' + epNum);
577
+ var epDesc = e.ep_desc || e.desc || e.description || '';
578
+ var dur = (Array.isArray(e.info) ? e.info[2] : (e.runtime || e.duration || '')) || '';
579
+ var epImg = normalizeImageUrl(e.img || e.ep_poster || data.ep_poster, imgcdn, e.id || epNum);
580
+ return {
581
+ id: e.id != null ? String(e.id) : undefined,
582
+ season: e.s || e.season || 1,
583
+ episode: epNum,
584
+ title: epTitle,
585
+ description: epDesc,
586
+ duration: dur,
587
+ image: epImg,
588
+ url: '',
589
+ _sid: e.sid || e.id || ''
590
+ };
591
+ });
592
+ }
593
+
594
+ var selectedSeasonIdx = 0;
595
+ if (Array.isArray(data.season) && data.season.length) {
596
+ data.season.forEach(function (sObj, sIdx) {
597
+ if (!sObj) return;
598
+ var sLabel = sObj.s || ('Season ' + (sIdx + 1));
599
+ var matchNum = sLabel.match(/Season\s*(\d+)/i);
600
+ var sNum = matchNum ? parseInt(matchNum[1], 10) : (sIdx + 1);
601
+ var isSel = !!sObj.selected;
602
+ if (isSel) selectedSeasonIdx = sIdx;
603
+ seasons.push({
604
+ season: sNum,
605
+ title: sLabel,
606
+ id: String(sObj.id || ''),
607
+ selected: isSel,
608
+ episodes: isSel ? initialEps : (sIdx === 0 && !data.season.some(function (x) { return x.selected; }) ? initialEps : [])
609
+ });
610
+ });
611
+ } else if (initialEps.length) {
612
+ seasons.push({ season: 1, title: 'Season 1', id: mainId, selected: true, episodes: initialEps });
613
+ }
614
+ item.seasons = seasons;
615
+ item._initialSeasonIdx = selectedSeasonIdx;
616
+ item._nextPageShow = data.nextPageShow;
617
+
618
+ return item;
619
+ },
620
+
621
+ catalog(mode) {
622
+ var p = 'all';
623
+ if (mode === 'movie') p = 'movie';
624
+ else if (mode === 'series' || mode === 'show') p = 'show';
625
+ else if (mode) p = String(mode);
626
+ return NM.main(null, p).then(function (data) {
627
+ return Api.parseMainResponse(data);
628
+ });
629
+ },
630
+
631
+ search(q) {
632
+ return NM.search(q).then(function (data) {
633
+ return Api.parseSearchResponse(data);
634
+ });
635
+ },
636
+
637
+ detail(id) {
638
+ return NM.post(id).then(function (data) {
639
+ return Api.parsePostResponse(data);
640
+ });
641
+ },
642
+
643
+ episodes(id, page) {
644
+ return NM.episodes(id, null, page);
645
+ },
646
+
647
+ stream(item) {
648
+ return NM.player(item.id).then(function (data) {
649
+ if (!data || !data.video_link) {
650
+ if (data && data.status === 'otp') {
651
+ return NM.autoLogin().then(function (tok) {
652
+ if (tok) {
653
+ return NM.player(item.id).then(function (d2) {
654
+ if (d2 && d2.video_link) {
655
+ return {
656
+ url: d2.video_link,
657
+ type: d2.video_link.indexOf('.m3u8') !== -1 ? 'hls' : '',
658
+ headers: NM.streamHeaders(d2.referer),
659
+ subtitles: [],
660
+ audioTracks: [],
661
+ referer: d2.referer || 'https://net52.cc',
662
+ _referer: d2.referer || 'https://net52.cc'
663
+ };
664
+ }
665
+ throw new Error('Stream link not available for this title');
666
+ });
667
+ }
668
+ throw new Error('OTP verification required');
669
+ });
670
+ }
671
+ throw new Error((data && data.error) || 'Stream link not available for this title');
672
+ }
673
+ return {
674
+ url: data.video_link,
675
+ type: data.video_link.indexOf('.m3u8') !== -1 ? 'hls' : '',
676
+ headers: NM.streamHeaders(data.referer),
677
+ subtitles: [],
678
+ audioTracks: [],
679
+ referer: data.referer || 'https://net52.cc',
680
+ _referer: data.referer || 'https://net52.cc'
681
+ };
682
+ });
683
+ }
684
+ };
685
+
686
+ /* =====================================================================
687
+ * Subtitle text engine — Unicode-safe cleaning, Tamil repair, rendering
688
+ * ===================================================================== */
689
+ const SubText = (function () {
690
+ // Windows-1252 code points for bytes 0x80–0x9F (needed to undo mojibake).
691
+ const CP1252 = { 0x20AC: 0x80, 0x201A: 0x82, 0x0192: 0x83, 0x201E: 0x84, 0x2026: 0x85, 0x2020: 0x86, 0x2021: 0x87,
692
+ 0x02C6: 0x88, 0x2030: 0x89, 0x0160: 0x8A, 0x2039: 0x8B, 0x0152: 0x8C, 0x017D: 0x8E, 0x2018: 0x91, 0x2019: 0x92,
693
+ 0x201C: 0x93, 0x201D: 0x94, 0x2022: 0x95, 0x2013: 0x96, 0x2014: 0x97, 0x02DC: 0x98, 0x2122: 0x99, 0x0161: 0x9A,
694
+ 0x203A: 0x9B, 0x0153: 0x9C, 0x017E: 0x9E, 0x0178: 0x9F };
695
+ let strict = null;
696
+ try { strict = new TextDecoder('utf-8', { fatal: true }); } catch (e) {}
697
+ const MOJIBAKE = /[Â-ô][\u0080-¿Œ-™]/;
698
+
699
+ // UTF-8 bytes that were decoded as Latin-1/CP1252 (e.g. Tamil "த") → re-decode.
700
+ function fixMojibake(s) {
701
+ if (!strict || !MOJIBAKE.test(s)) return s;
702
+ const bytes = new Uint8Array(s.length);
703
+ for (let i = 0; i < s.length; i++) {
704
+ const c = s.charCodeAt(i);
705
+ if (c < 0x100) bytes[i] = c;
706
+ else if (CP1252[c]) bytes[i] = CP1252[c];
707
+ else return s;
708
+ }
709
+ try { return strict.decode(bytes); } catch (e) { return s; }
710
+ }
711
+
712
+ function stripLoneSurrogates(s) {
713
+ let out = '';
714
+ for (let i = 0; i < s.length; i++) {
715
+ const c = s.charCodeAt(i);
716
+ if (c >= 0xD800 && c <= 0xDBFF) {
717
+ const n = s.charCodeAt(i + 1);
718
+ if (n >= 0xDC00 && n <= 0xDFFF) { out += s[i] + s[i + 1]; i++; }
719
+ continue;
720
+ }
721
+ if (c >= 0xDC00 && c <= 0xDFFF) continue;
722
+ out += s[i];
723
+ }
724
+ return out;
725
+ }
726
+
727
+ // Tamil: orphaned dependent vowel signs / virama render as dotted circles.
728
+ // Re-attach signs separated by stray whitespace / ZWSP and drop duplicates.
729
+ // ZWJ / ZWNJ are intentionally preserved.
730
+ function repairTamil(s) {
731
+ if (!/[஀-௿]/.test(s)) return s;
732
+ return s
733
+ .replace(/([அ-ஹா-்])[  ​]+(?=[ா-்ௗ])/g, '$1')
734
+ .replace(/்{2,}/g, '்')
735
+ .replace(/([ா-ௌ])\1+/g, '$1');
736
+ }
737
+
738
+ function clean(s) {
739
+ s = String(s == null ? '' : s).replace(/\r\n?/g, '\n').replace(//g, '');
740
+ s = fixMojibake(s);
741
+ if (/[\uD800-\uDFFF]/.test(s)) s = stripLoneSurrogates(s);
742
+ s = s.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F￾￿]/g, '');
743
+ s = repairTamil(s);
744
+ // NFC composes split two-part vowels (e.g. U+0BC6 + U+0BBE → U+0BCA "ொ").
745
+ if (s.normalize) { try { s = s.normalize('NFC'); } catch (e) {} }
746
+ return s;
747
+ }
748
+
749
+ const ENT = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', lrm: '‎', rlm: '‏' };
750
+ function decodeEntities(s) {
751
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
752
+ if (e[0] === '#') {
753
+ const n = (e[1] === 'x' || e[1] === 'X') ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
754
+ try { return n > 0 && n <= 0x10FFFF ? String.fromCodePoint(n) : ''; } catch (x) { return ''; }
755
+ }
756
+ const v = ENT[e.toLowerCase()];
757
+ return v !== undefined ? v : m;
758
+ });
759
+ }
760
+
761
+ const SCRIPTS = [[/[஀-௿]/, 'ta'], [/[ऀ-ॿ]/, 'hi'], [/[ఀ-౿]/, 'te'], [/[ഀ-ൿ]/, 'ml'],
762
+ [/[ಀ-೿]/, 'kn'], [/[ঀ-৿]/, 'bn'], [/[؀-ۿ]/, 'ar'], [/[぀-ヿ]/, 'ja'],
763
+ [/[가-힯]/, 'ko'], [/[一-鿿]/, 'zh']];
764
+ function detectScript(s) {
765
+ for (const [re, l] of SCRIPTS) if (re.test(s)) return l;
766
+ return '';
767
+ }
768
+
769
+ // Builds DOM with textContent only (never innerHTML). Keeps <i>/<b>/<u>,
770
+ // drops other tags (<c.x>, <v Name>, <font>, <ruby>) but keeps their text.
771
+ function appendInline(parent, line) {
772
+ const stack = [parent];
773
+ const re = /<(\/?)([a-zA-Z]+)[^>]*>/g;
774
+ let last = 0, m;
775
+ const addText = t => { if (t) stack[stack.length - 1].appendChild(document.createTextNode(decodeEntities(t))); };
776
+ while ((m = re.exec(line))) {
777
+ addText(line.slice(last, m.index));
778
+ last = re.lastIndex;
779
+ const tag = m[2].toLowerCase();
780
+ if (tag === 'i' || tag === 'b' || tag === 'u') {
781
+ if (m[1]) {
782
+ if (stack.length > 1 && stack[stack.length - 1].tagName.toLowerCase() === tag) stack.pop();
783
+ } else {
784
+ const el = document.createElement(tag);
785
+ stack[stack.length - 1].appendChild(el);
786
+ stack.push(el);
787
+ }
788
+ }
789
+ }
790
+ addText(line.slice(last));
791
+ }
792
+
793
+ function renderInto(container, raw) {
794
+ const text = clean(raw).replace(/\{\\[^}]*\}/g, ''); // strip ASS override tags ({\an8})
795
+ text.split('\n').forEach(line => {
796
+ if (!line.trim()) return;
797
+ const span = h('span', { class: 'sub-text' });
798
+ appendInline(span, line);
799
+ const lineEl = h('div', { class: 'sub-line' }, [span]);
800
+ const l = detectScript(line);
801
+ if (l) lineEl.setAttribute('lang', l); // selects the right font + line-height
802
+ container.appendChild(lineEl);
803
+ });
804
+ }
805
+
806
+ return { clean, renderInto };
807
+ })();
808
+
809
+ /* ---------- External subtitle files (SRT / VTT) ---------- */
810
+ const SubParser = {
811
+ decode(buf) {
812
+ const b = new Uint8Array(buf);
813
+ const dec = (enc, data) => new TextDecoder(enc).decode(data);
814
+ if (b[0] === 0xEF && b[1] === 0xBB && b[2] === 0xBF) return dec('utf-8', b.subarray(3));
815
+ if (b[0] === 0xFF && b[1] === 0xFE) return dec('utf-16le', b.subarray(2));
816
+ if (b[0] === 0xFE && b[1] === 0xFF) return dec('utf-16be', b.subarray(2));
817
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(b); } catch (e) {}
818
+ let zeros = 0;
819
+ const n = Math.min(b.length, 4000);
820
+ for (let i = 0; i < n; i++) if (!b[i]) zeros++;
821
+ if (zeros > n * 0.2) return dec('utf-16le', b);
822
+ try { return dec('windows-1252', b); } catch (e) { return dec('utf-8', b); }
823
+ },
824
+
825
+ // Line-based state machine: tolerates missing indices, missing blank lines,
826
+ // ',' or '.' millisecond separators, optional hours and VTT cue settings.
827
+ parse(text) {
828
+ const TIME = /(?:(\d+):)?(\d{1,2}):(\d{1,2})(?:[.,:](\d{1,3}))?/;
829
+ const toSec = m => (+(m[1] || 0)) * 3600 + (+m[2]) * 60 + (+m[3]) + (m[4] ? +('0.' + (m[4] + '00').slice(0, 3)) : 0);
830
+ const lines = String(text).replace(/\r\n?/g, '\n').replace(/^/, '').split('\n');
831
+ const cues = [];
832
+ let cur = null;
833
+ lines.forEach(raw => {
834
+ const line = raw.replace(/\s+$/, '');
835
+ if (line.indexOf('-->') > -1) {
836
+ const parts = line.split('-->');
837
+ const a = TIME.exec(parts[0]), b = TIME.exec(parts[1]);
838
+ if (cur && !cur.ended && cur.lines.length && /^\d+$/.test(cur.lines[cur.lines.length - 1].trim())) cur.lines.pop();
839
+ cur = (a && b) ? { start: toSec(a), end: toSec(b), lines: [], ended: false } : null;
840
+ if (cur) cues.push(cur);
841
+ return;
842
+ }
843
+ if (!line.trim()) { if (cur) cur.ended = true; return; }
844
+ if (cur && !cur.ended) cur.lines.push(line);
845
+ });
846
+ return cues
847
+ .map(c => ({ start: c.start, end: c.end, text: SubText.clean(c.lines.join('\n')) }))
848
+ .filter(c => c.end > c.start && c.text.trim())
849
+ .sort((x, y) => x.start - y.start);
850
+ },
851
+
852
+ toVtt(cues) {
853
+ const ts = s => pad2(Math.floor(s / 3600)) + ':' + pad2(Math.floor(s % 3600 / 60)) + ':' +
854
+ pad2(Math.floor(s % 60)) + '.' + ('00' + Math.round((s % 1) * 1000)).slice(-3);
855
+ return 'WEBVTT\n\n' + cues.map(c =>
856
+ ts(c.start) + ' --> ' + ts(c.end) + '\n' + c.text.replace(/-->/g, '->').replace(/\n{2,}/g, '\n')
857
+ ).join('\n\n') + '\n';
858
+ },
859
+
860
+ load(url) {
861
+ return fetchWithTimeout(url, {}, CONFIG.REQUEST_TIMEOUT_MS)
862
+ .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.arrayBuffer(); })
863
+ .then(buf => this.parse(this.decode(buf)));
864
+ }
865
+ };
866
+
867
+ /* ---------- Custom subtitle renderer (cues from hls.js and <track>) ---------- */
868
+ const SubRenderer = {
869
+ el: null,
870
+ last: null,
871
+ bind(video) {
872
+ this.el = $('subs');
873
+ const tt = video.textTracks;
874
+ const watch = t => {
875
+ if (t.__watched) return;
876
+ t.__watched = true;
877
+ t.addEventListener('cuechange', () => this.render());
878
+ };
879
+ for (let i = 0; i < tt.length; i++) watch(tt[i]);
880
+ tt.addEventListener('addtrack', e => { watch(e.track); this.render(); });
881
+ tt.addEventListener('change', () => this.render());
882
+ },
883
+ render() {
884
+ const tt = Player.video.textTracks;
885
+ const sel = Player.subSel;
886
+ const sources = [];
887
+ for (let i = 0; i < tt.length; i++) {
888
+ const t = tt[i];
889
+ if (t.mode === 'showing') t.mode = 'hidden'; // never let the native renderer draw
890
+ if (sel && sel.type === 'hls' && t.kind === 'subtitles' && t.mode === 'hidden') sources.push(t);
891
+ }
892
+ if (sel && sel.type === 'track') sources.push(sel.track);
893
+ const texts = [];
894
+ sources.forEach(t => {
895
+ const ac = t.activeCues;
896
+ if (!ac) return;
897
+ for (let j = 0; j < ac.length; j++) texts.push(ac[j].text || '');
898
+ });
899
+ const key = texts.join('\u0001');
900
+ if (key === this.last) return;
901
+ this.last = key;
902
+ this.el.textContent = '';
903
+ texts.forEach(tx => {
904
+ const cue = h('div', { class: 'sub-cue' });
905
+ SubText.renderInto(cue, tx);
906
+ this.el.appendChild(cue);
907
+ });
908
+ },
909
+ clear() { this.last = null; if (this.el) this.el.textContent = ''; }
910
+ };
911
+
912
+ /* =====================================================================
913
+ * Focus / layer navigation (spatial D-pad navigation)
914
+ * ===================================================================== */
915
+ // Transform-based scrolling: moves a rail child with translate() instead of
916
+ // native scroll. GPU-composited, so it stays smooth on low-end TV engines
917
+ // (native smooth-scroll of large image lists is the main cause of home lag).
918
+ //
919
+ // Geometry comes from layout offsets (offsetLeft/offsetTop/scrollWidth), NOT
920
+ // getBoundingClientRect: offsets ignore the CSS transform and its in-flight
921
+ // transition, so the math stays correct even mid-animation. They are also in
922
+ // layout px, matching clientWidth/scrollWidth, so no fit-to-screen scaling.
923
+ // Requires the rail to be the offsetParent of its items (position: relative).
924
+ function railScroll(viewport, rail, el, axis, pad) {
925
+ if (!rail || !el) return;
926
+ if (axis === 'x') {
927
+ const viewW = viewport.clientWidth, railW = rail.scrollWidth;
928
+ const left = el.offsetLeft, right = left + el.offsetWidth;
929
+ let off = -(rail.__off || 0);
930
+ if (right > off + viewW - pad) off = right - (viewW - pad);
931
+ if (left < off + pad) off = left - pad;
932
+ off = Math.max(0, Math.min(off, Math.max(0, railW - viewW)));
933
+ rail.__off = -off;
934
+ rail.style.webkitTransform = rail.style.transform = 'translateX(' + (-Math.round(off)) + 'px)';
935
+ } else {
936
+ const viewH = viewport.clientHeight, railH = rail.scrollHeight;
937
+ let off = el.offsetTop - pad; // align focused row to a fixed band
938
+ off = Math.max(0, Math.min(off, Math.max(0, railH - viewH)));
939
+ rail.__off = -off;
940
+ rail.style.webkitTransform = rail.style.transform = 'translateY(' + (-Math.round(off)) + 'px)';
941
+ }
942
+ }
943
+
944
+ function ensureVisible(el) {
945
+ // Rects are in screen pixels (after the fit-to-screen scale); scroll offsets are in CSS pixels.
946
+ const k = 1 / (Screen.scale || 1);
947
+ let node = el.parentElement;
948
+ while (node && node !== document.body) {
949
+ const ds = node.dataset;
950
+ if (ds.railx !== undefined) railScroll(node, node.querySelector('.row-rail') || node.firstElementChild, el, 'x', +ds.railx || 0);
951
+ if (ds.raily !== undefined) {
952
+ const anchor = el.closest('[data-anchor]');
953
+ railScroll(node, node.firstElementChild, (anchor && node.contains(anchor) ? anchor : el), 'y', +ds.raily || 0);
954
+ }
955
+ if (ds.scrollX !== undefined) {
956
+ const cr = node.getBoundingClientRect(), r = el.getBoundingClientRect(), pad = (+ds.scrollX || 0) / k;
957
+ if (r.right > cr.right - pad) node.scrollLeft += (r.right - (cr.right - pad)) * k;
958
+ else if (r.left < cr.left + pad) node.scrollLeft -= ((cr.left + pad) - r.left) * k;
959
+ }
960
+ if (ds.scrollY !== undefined) {
961
+ const anchor = el.closest('[data-anchor]');
962
+ const a = (anchor && node.contains(anchor) ? anchor : el).getBoundingClientRect();
963
+ const cr = node.getBoundingClientRect(), pad = (+ds.scrollY || 0) / k;
964
+ if (ds.scrollMode === 'align') node.scrollTop = Math.max(0, node.scrollTop + ((a.top - cr.top) - pad) * k);
965
+ else if (a.top < cr.top + pad) node.scrollTop -= ((cr.top + pad) - a.top) * k;
966
+ else if (a.bottom > cr.bottom - pad) node.scrollTop += (a.bottom - (cr.bottom - pad)) * k;
967
+ }
968
+ if (node.classList.contains('layer')) break;
969
+ node = node.parentElement;
970
+ }
971
+ }
972
+
973
+ const Nav = {
974
+ stack: [],
975
+ focused: null,
976
+ top() { return this.stack[this.stack.length - 1]; },
977
+ has(layer) { return this.stack.indexOf(layer) > -1; },
978
+
979
+ push(layer, focusEl) {
980
+ if (this.has(layer)) { this.closeAbove(layer); if (focusEl) this.focus(focusEl); return; }
981
+ const prev = this.top();
982
+ if (prev) prev.savedFocus = this.focused;
983
+ this.stack.push(layer);
984
+ layer.el.classList.add('open');
985
+ layer.el.style.zIndex = 10 + this.stack.length;
986
+ this.updateCover();
987
+ if (layer.onOpen) layer.onOpen();
988
+ if (this.top() === layer) {
989
+ const f = focusEl && this.visible(focusEl) ? focusEl : null;
990
+ if (f || !layer.el.contains(this.focused)) this.focus(f || this.first(layer.el));
991
+ }
992
+ },
993
+
994
+ close(layer) {
995
+ const i = this.stack.indexOf(layer);
996
+ if (i < 0) return;
997
+ while (this.stack.length > i) {
998
+ const l = this.stack.pop();
999
+ l.el.classList.remove('open');
1000
+ l.el.classList.remove('covered');
1001
+ if (l.onClose) l.onClose();
1002
+ }
1003
+ this.updateCover();
1004
+ const t = this.top();
1005
+ if (t) {
1006
+ const sf = t.savedFocus;
1007
+ this.focus(sf && t.el.contains(sf) && this.visible(sf) ? sf : this.first(t.el));
1008
+ }
1009
+ },
1010
+
1011
+ closeAbove(layer) {
1012
+ const i = this.stack.indexOf(layer);
1013
+ if (i > -1 && i < this.stack.length - 1) this.close(this.stack[i + 1]);
1014
+ },
1015
+
1016
+ // Hide layers fully covered by an opaque full-screen layer (cheaper on TVs).
1017
+ updateCover() {
1018
+ let covered = false;
1019
+ for (let i = this.stack.length - 1; i >= 0; i--) {
1020
+ const l = this.stack[i];
1021
+ l.el.classList.toggle('covered', covered);
1022
+ if (l.full) covered = true;
1023
+ }
1024
+ },
1025
+
1026
+ visible(el) { return !!el && el.getClientRects().length > 0 && !el.classList.contains('disabled'); },
1027
+ focusables(root) { return Array.prototype.filter.call(root.querySelectorAll('.focusable'), el => this.visible(el)); },
1028
+ first(root) {
1029
+ const d = root.querySelector('[data-default-focus]');
1030
+ return d && this.visible(d) ? d : this.focusables(root)[0] || null;
1031
+ },
1032
+
1033
+ focus(el, opts) {
1034
+ if (!el) return;
1035
+ if (this.focused && this.focused !== el) this.focused.classList.remove('focused');
1036
+ this.focused = el;
1037
+ el.classList.add('focused');
1038
+ const g = el.closest('[data-group]');
1039
+ if (g) g._last = el;
1040
+ if (!(opts && opts.noScroll)) ensureVisible(el);
1041
+ if (this.focusHook) this.focusHook(el);
1042
+ },
1043
+ focusHook: null,
1044
+
1045
+ move(dir) {
1046
+ const layer = this.top();
1047
+ if (!layer) return;
1048
+ const cur = this.focused;
1049
+ if (!cur || !layer.el.contains(cur) || !this.visible(cur)) { this.focus(this.first(layer.el)); return; }
1050
+ const r = cur.getBoundingClientRect();
1051
+ const cx = r.left + r.width / 2, cy = r.top + r.height / 2;
1052
+ // Containers marked data-hbound keep LEFT/RIGHT inside them (e.g. the header bar).
1053
+ const hb = (dir === 'LEFT' || dir === 'RIGHT') ? cur.closest('[data-hbound]') : null;
1054
+ let best = null, bestScore = Infinity;
1055
+ this.focusables(layer.el).forEach(c => {
1056
+ if (c === cur || (hb && !hb.contains(c))) return;
1057
+ const q = c.getBoundingClientRect();
1058
+ const qx = q.left + q.width / 2, qy = q.top + q.height / 2;
1059
+ let primary, gap, orth;
1060
+ if (dir === 'RIGHT' || dir === 'LEFT') {
1061
+ if (dir === 'RIGHT' ? q.left < cx : q.right > cx) return;
1062
+ primary = dir === 'RIGHT' ? Math.max(0, q.left - r.right) : Math.max(0, r.left - q.right);
1063
+ gap = Math.max(0, Math.max(q.top, r.top) - Math.min(q.bottom, r.bottom));
1064
+ orth = Math.abs(qy - cy);
1065
+ } else {
1066
+ if (dir === 'DOWN' ? q.top < cy : q.bottom > cy) return;
1067
+ primary = dir === 'DOWN' ? Math.max(0, q.top - r.bottom) : Math.max(0, r.top - q.bottom);
1068
+ gap = Math.max(0, Math.max(q.left, r.left) - Math.min(q.right, r.right));
1069
+ // Overlapping columns: prefer left-edge alignment (wide row → its first item).
1070
+ orth = gap === 0 ? Math.abs(q.left - r.left) : Math.abs(qx - cx);
1071
+ }
1072
+ const score = primary + gap * 4 + orth * 0.25;
1073
+ if (score < bestScore) { bestScore = score; best = c; }
1074
+ });
1075
+ if (!best) return;
1076
+ // Entering a remembered group (row, keyboard, grid) restores its last focus.
1077
+ const g = best.closest('[data-group]');
1078
+ if (g && g !== cur.closest('[data-group]') && g._last && g.contains(g._last) && this.visible(g._last)) best = g._last;
1079
+ this.focus(best);
1080
+ }
1081
+ };
1082
+
1083
+ /* ---------- Reusable components ---------- */
1084
+ function Cycler(label, options, get, set) {
1085
+ const val = h('span', { class: 'cv-text' });
1086
+ const el = h('div', { class: 'cycler focusable' }, [
1087
+ h('span', { text: label }),
1088
+ h('span', { class: 'cv' }, [h('span', { class: 'arrow', text: '‹' }), val, h('span', { class: 'arrow', text: '›' })])
1089
+ ]);
1090
+ const sync = () => {
1091
+ const cur = get();
1092
+ const o = options.find(x => x.v === cur) || options[0];
1093
+ val.textContent = o.l;
1094
+ };
1095
+ el._cycle = d => {
1096
+ let i = options.findIndex(x => x.v === get());
1097
+ i = (i + d + options.length) % options.length;
1098
+ set(options[i].v);
1099
+ sync();
1100
+ };
1101
+ el.addEventListener('click', () => el._cycle(1));
1102
+ sync();
1103
+ return el;
1104
+ }
1105
+
1106
+ function ActionRow(label, value, onSelect) {
1107
+ return h('div', { class: 'cycler focusable', onclick: onSelect }, [
1108
+ h('span', { text: label }),
1109
+ h('span', { class: 'cv' }, [value ? h('span', { text: value }) : null, h('span', { class: 'arrow', text: '›', style: 'opacity:1' })])
1110
+ ]);
1111
+ }
1112
+
1113
+ function Keyboard(input) {
1114
+ const wrap = h('div', { class: 'osk', 'data-group': '' });
1115
+ const fire = () => fireInput(input);
1116
+ const max = () => (input.maxLength > 0 ? input.maxLength : 60);
1117
+ const chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
1118
+ for (let r = 0; r < 6; r++) {
1119
+ const row = h('div', { class: 'osk-row' });
1120
+ for (let c = 0; c < 6; c++) {
1121
+ const ch = chars[r * 6 + c];
1122
+ row.appendChild(h('div', {
1123
+ class: 'key focusable', text: ch, 'data-default-focus': r === 0 && c === 0,
1124
+ onclick: () => { if (input.value.length < max()) { input.value += ch; fire(); } }
1125
+ }));
1126
+ }
1127
+ wrap.appendChild(row);
1128
+ }
1129
+ wrap.appendChild(h('div', { class: 'osk-row' }, [
1130
+ h('div', { class: 'key wide focusable', text: 'Space', onclick: () => { if (input.value.length < max()) { input.value += ' '; fire(); } } }),
1131
+ h('div', { class: 'key wide focusable', html: icon('bksp'), onclick: () => { input.value = input.value.slice(0, -1); fire(); } }),
1132
+ h('div', { class: 'key wide focusable', text: 'Clear', onclick: () => { input.value = ''; fire(); } })
1133
+ ]));
1134
+ return wrap;
1135
+ }
1136
+
1137
+
1138
+ // Normalizes poster/thumbnail URLs handling placeholders ('---'), missing protocols,
1139
+ // double protocols, relative paths, and CDN prefixes.
1140
+ function normalizeImageUrl(rawUrl, fallbackCdn, id) {
1141
+ if (!rawUrl || typeof rawUrl !== 'string') return '';
1142
+ var url = rawUrl.trim();
1143
+ if (!url) return '';
1144
+
1145
+ var cleanId = '';
1146
+ if (id) {
1147
+ cleanId = String(id).replace(/\.(?:jpg|png|webp|jpeg)$/i, '').replace(/^\/+/, '').trim();
1148
+ } else if (url.indexOf('--') === -1 && !/^(?:https?:)?\/\//i.test(url)) {
1149
+ cleanId = String(url).replace(/\.(?:jpg|png|webp|jpeg)$/i, '').replace(/^\/+/, '').trim();
1150
+ }
1151
+
1152
+ // Detect provider by ID pattern:
1153
+ // Prime Video IDs are 20-30 char alphanumeric strings starting with 0 or containing letters (e.g. 0M0MP41XNWVO29LL977I63Z58J)
1154
+ // Netflix IDs are pure numeric strings (e.g. 82813021)
1155
+ var isPvId = cleanId && (cleanId.length > 15 || (cleanId.charAt(0) === '0' && /[A-Z]/i.test(cleanId)));
1156
+ var isNfId = cleanId && /^\d+$/.test(cleanId);
1157
+
1158
+ if (/^(?:https?:)?\/\//i.test(url) || url.startsWith('data:') || url.startsWith('blob:')) {
1159
+ if (url.indexOf('--') > -1) {
1160
+ if (cleanId) {
1161
+ url = url.replace(/--+/, cleanId);
1162
+ } else {
1163
+ return '';
1164
+ }
1165
+ }
1166
+ } else {
1167
+ var cdn = (fallbackCdn || NM.storage.get('imgcdn_h') || NM.storage.get('imgcdn_v') || NM.storage.get('imgcdn') || '').trim();
1168
+ if (cdn && cdn.indexOf('--') > -1) {
1169
+ url = cdn.replace(/--+/, cleanId || 'thumb');
1170
+ } else if (cdn) {
1171
+ url = cdn.replace(/\/+$/, '') + '/' + url.replace(/^\/+/, '');
1172
+ }
1173
+ }
1174
+
1175
+ // Provider CDN path correction:
1176
+ // Upstream NetMirror returns buggy "poster/v/" CDN for Prime Video!
1177
+ // If the ID is a Prime Video ID, redirect from /poster/ to /pv/
1178
+ if (isPvId) {
1179
+ url = url.replace(/\/poster\//g, '/pv/');
1180
+ } else if (isNfId) {
1181
+ url = url.replace(/\/pv\//g, '/poster/');
1182
+ }
1183
+
1184
+ url = url.replace(/^http:\/\//i, 'https://');
1185
+ url = url.replace(/([^:])\/\/+/g, '$1/');
1186
+ return url;
1187
+ }
1188
+
1189
+ function makeCard(item, onClick) {
1190
+ var title = (item.title || '').trim();
1191
+ var isNumeric = !title || /^#?\d+$/.test(title);
1192
+ var cardKids = [];
1193
+ if (item.type === 'series') {
1194
+ cardKids.push(h('div', { class: 'card-badge', text: 'SERIES' }));
1195
+ }
1196
+ // Only render title overlay if title is a real name (not a raw numeric ID)
1197
+ if (!isNumeric) {
1198
+ cardKids.push(h('div', { class: 'card-title', text: title }));
1199
+ }
1200
+ const c = h('div', { class: 'card focusable' }, cardKids);
1201
+ c.style.backgroundImage = posterBg(item, false);
1202
+ c._item = item;
1203
+ c.addEventListener('click', onClick || (() => Detail.open(item)));
1204
+ return c;
1205
+ }
1206
+
1207
+ function seasonsLabel(item) {
1208
+ const n = (item.seasons || []).length;
1209
+ return n ? n + (n === 1 ? ' Season' : ' Seasons') : '';
1210
+ }
1211
+
1212
+ function fillMeta(el, item) {
1213
+ el.textContent = '';
1214
+ if (item.year) el.appendChild(h('span', { text: String(item.year) }));
1215
+ if (item.rating) el.appendChild(h('span', { class: 'badge', text: String(item.rating) }));
1216
+ if (item.type === 'series') { const s = seasonsLabel(item); if (s) el.appendChild(h('span', { text: s })); }
1217
+ else if (item.duration) el.appendChild(h('span', { text: String(item.duration) }));
1218
+ el.appendChild(h('span', { class: 'badge', text: 'HD' }));
1219
+ if (item.genres && item.genres.length) el.appendChild(h('span', { text: item.genres.join(' • ') }));
1220
+ }
1221
+
1222
+ // Build a playable object from a series + one episode (used by Player/Api.stream).
1223
+ function episodePlayable(series, ep) {
1224
+ return {
1225
+ id: ep.id || (series.id + '-s' + ep.season + 'e' + ep.episode),
1226
+ title: series.title + ' — S' + ep.season + ':E' + ep.episode + (ep.title ? ' · ' + ep.title : ''),
1227
+ year: series.year, duration: ep.duration || '',
1228
+ url: ep.url, demoSubs: ep.demoSubs, headers: ep.headers,
1229
+ _series: series.id, _season: ep.season, _episode: ep.episode
1230
+ };
1231
+ }
1232
+ function seasonEpisodes(series, seasonIdx) {
1233
+ const s = (series.seasons || [])[seasonIdx];
1234
+ if (!s) return [];
1235
+ return (s.episodes || []).map(e => Object.assign({ season: s.season || (seasonIdx + 1) }, e));
1236
+ }
1237
+ function firstEpisode(series, seasonIdx) {
1238
+ const eps = seasonEpisodes(series, seasonIdx || 0);
1239
+ return eps.length ? episodePlayable(series, eps[0]) : series;
1240
+ }
1241
+
1242
+ /* =====================================================================
1243
+ * Screens & layers
1244
+ * ===================================================================== */
1245
+ const NAV_TABS = [
1246
+ { id: 'nav-home', label: 'Home', mode: 'all' },
1247
+ { id: 'nav-movies', label: 'Movies', mode: 'movie' },
1248
+ { id: 'nav-series', label: 'TV Series', mode: 'series' }
1249
+ ];
1250
+
1251
+ const Home = {
1252
+ el: $('home'), full: true, items: [], hero: null, filterMode: 'all', bgT: null,
1253
+ init() {
1254
+ $('logo').textContent = CONFIG.APP_NAME;
1255
+ $('nav-search').innerHTML = icon('search') + 'Search';
1256
+ $('hdr-settings').innerHTML = icon('gear');
1257
+ $('hero-play').innerHTML = icon('play') + 'Play';
1258
+ $('hero-info').innerHTML = icon('info') + 'More Info';
1259
+ NAV_TABS.forEach(t => $(t.id).addEventListener('click', () => this.setFilter(t.mode)));
1260
+ $('nav-search').addEventListener('click', () => Search.open());
1261
+ $('hdr-profile').addEventListener('click', () => Profiles.open(false));
1262
+ $('hdr-settings').addEventListener('click', () => Nav.push(SettingsModal));
1263
+ $('hdr-ott').addEventListener('click', () => Nav.push(OttModal));
1264
+ $('hero-play').addEventListener('click', () => this.playHero());
1265
+ $('hero-info').addEventListener('click', () => { if (this.hero) Detail.open(this.hero); });
1266
+ // Billboard follows the focused card (debounced image swap to avoid thrash).
1267
+ Nav.focusHook = el => {
1268
+ if (Nav.top() !== this || !el) return;
1269
+ if (el.closest && el.closest('.home-header')) this.lastHeader = el;
1270
+ if (el.classList.contains('card') && el._item) this.setHero(el._item);
1271
+ };
1272
+ },
1273
+ onBack() { Confirm.open('Exit ' + CONFIG.APP_NAME + '?', 'Exit', () => App.exit()); return true; },
1274
+
1275
+ // Explicit row-based vertical navigation. Pure spatial search can send a
1276
+ // right-aligned card straight to the top bar (the behaviour reported on the
1277
+ // real TV); stepping row-by-row and remembering each row's column is the
1278
+ // standard 10-foot pattern and avoids that. LEFT/RIGHT stay spatial.
1279
+ rowTarget(rail) {
1280
+ if (!rail) return null;
1281
+ const last = rail._last;
1282
+ if (last && rail.contains(last) && Nav.visible(last)) return last;
1283
+ return rail.querySelector('.card');
1284
+ },
1285
+ onKey(key) {
1286
+ if (key !== 'UP' && key !== 'DOWN') return false;
1287
+ const f = Nav.focused;
1288
+ if (!f) return false;
1289
+ if (f.closest('.home-header')) {
1290
+ if (key === 'DOWN') Nav.focus($('hero-play'));
1291
+ return true; // UP from the top bar: stay
1292
+ }
1293
+ if (f.id === 'hero-play' || f.id === 'hero-info') {
1294
+ if (key === 'UP') Nav.focus(this.lastHeader && Nav.visible(this.lastHeader) ? this.lastHeader : $('nav-home'));
1295
+ else { const r = document.querySelector('#rows .row-rail'); if (r) Nav.focus(this.rowTarget(r)); }
1296
+ return true;
1297
+ }
1298
+ const curRow = f.closest('.row');
1299
+ if (curRow) {
1300
+ const rows = Array.prototype.slice.call(this.el.querySelectorAll('#rows .row'));
1301
+ const idx = rows.indexOf(curRow);
1302
+ if (key === 'UP') Nav.focus(idx > 0 ? this.rowTarget(rows[idx - 1].querySelector('.row-rail')) : $('hero-play'));
1303
+ else if (idx < rows.length - 1) Nav.focus(this.rowTarget(rows[idx + 1].querySelector('.row-rail')));
1304
+ return true; // DOWN on the last row: stay
1305
+ }
1306
+ return false;
1307
+ },
1308
+ playHero() {
1309
+ const it = this.hero;
1310
+ if (!it) return;
1311
+ if (it.type === 'series') Player.open(firstEpisode(it, 0)); else Player.open(it);
1312
+ },
1313
+ refreshHeader() {
1314
+ const p = Store.profile;
1315
+ $('hdr-name').textContent = p ? p.name : 'Guest';
1316
+ const av = $('hdr-avatar');
1317
+ av.textContent = p ? firstGrapheme(p.name) : '?';
1318
+ av.style.background = p ? p.color : '#555';
1319
+ },
1320
+ load() {
1321
+ UI.loading(true, 'Loading catalog…');
1322
+ this.lastError = '';
1323
+ var mode = this.filterMode || 'all';
1324
+ return Api.catalog(mode)
1325
+ .then(items => { this.items = items; this.lastError = ''; })
1326
+ .catch(e => {
1327
+ this.lastError = e ? e.message : 'Unknown error';
1328
+ if (e && e.isOtp) {
1329
+ this.lastError = 'OTP verification required';
1330
+ } else {
1331
+ UI.toast('Could not load catalog: ' + this.lastError, 'error');
1332
+ }
1333
+ this.items = [];
1334
+ if (typeof DebugDrawer !== 'undefined') DebugDrawer.show(true);
1335
+ })
1336
+ .then(() => { this.render(); UI.loading(false); });
1337
+ },
1338
+ visibleItems() {
1339
+ if (this.filterMode === 'movie') return this.items.filter(it => it.type !== 'series');
1340
+ if (this.filterMode === 'series') return this.items.filter(it => it.type === 'series');
1341
+ return this.items;
1342
+ },
1343
+ setFilter(mode) {
1344
+ if (this.filterMode !== mode) {
1345
+ this.filterMode = mode;
1346
+ this.load();
1347
+ } else if (Nav.top() === this) {
1348
+ Nav.focus($('hero-play'));
1349
+ }
1350
+ },
1351
+ // Updates the fixed billboard; title/meta/desc change instantly, image is debounced.
1352
+ setHero(item, immediate) {
1353
+ if (!item) return;
1354
+ const changed = this.hero !== item;
1355
+ this.hero = item;
1356
+ var title = (item.title || '').trim();
1357
+ var isNumeric = !title || /^#?\d+$/.test(title);
1358
+ if (item.namelogo) {
1359
+ var logoSrc = typeof NM !== 'undefined' && typeof NM.proxyMediaUrl === 'function' ? NM.proxyMediaUrl(item.namelogo) : item.namelogo;
1360
+ $('hero-title').innerHTML = '<img src="' + logoSrc + '" style="max-height:100px;max-width:550px;object-fit:contain;" alt="' + (title || '') + '">';
1361
+ } else {
1362
+ $('hero-title').textContent = isNumeric ? '' : title;
1363
+ }
1364
+
1365
+ fillMeta($('hero-meta'), item);
1366
+ $('hero-desc').textContent = item.description || '';
1367
+ $('hero-play').innerHTML = icon('play') + 'Play';
1368
+ $('hero-info').innerHTML = icon('info') + (item.type === 'series' ? 'Episodes' : 'More Info');
1369
+
1370
+ // Background metadata hydration for cards that only had IDs in main.php
1371
+ if (item.id && (!item.description || isNumeric) && !item._fetchedDetails) {
1372
+ item._fetchedDetails = true;
1373
+ var curId = item.id;
1374
+ if (typeof NM !== 'undefined' && typeof NM.post === 'function') {
1375
+ NM.post(curId).then(function (d) {
1376
+ if (!d) return;
1377
+ if (d.title && isNumeric) item.title = d.title;
1378
+ if (d.desc && !item.description) item.description = d.desc;
1379
+ if (d.year && !item.year) item.year = d.year;
1380
+ if (d.ua && !item.rating) item.rating = d.ua;
1381
+ if (d.runtime && !item.duration) item.duration = d.runtime;
1382
+ if (Home.hero && Home.hero.id === curId) {
1383
+ if (!item.namelogo && item.title) $('hero-title').textContent = item.title;
1384
+ if (item.description) $('hero-desc').textContent = item.description;
1385
+ fillMeta($('hero-meta'), item);
1386
+ }
1387
+ }).catch(function () {});
1388
+ }
1389
+ }
1390
+
1391
+ if (!changed && !immediate) return;
1392
+ clearTimeout(this.bgT);
1393
+ const paint = () => { $('hero-bg').style.backgroundImage = posterBg(item, true); };
1394
+ if (immediate) paint(); else this.bgT = setTimeout(paint, 150);
1395
+ },
1396
+ render() {
1397
+ NAV_TABS.forEach(t => $(t.id).classList.toggle('active', t.mode === this.filterMode));
1398
+ const items = this.visibleItems();
1399
+ const rows = $('rows');
1400
+ rows.textContent = '';
1401
+ rows.__off = 0;
1402
+ rows.style.webkitTransform = rows.style.transform = 'translateY(0)';
1403
+ const order = [], groups = {};
1404
+ items.forEach(it => {
1405
+ const c = it.category || 'Featured';
1406
+ if (!groups[c]) { groups[c] = []; order.push(c); }
1407
+ groups[c].push(it);
1408
+ });
1409
+ order.forEach(cat => {
1410
+ const rail = h('div', { class: 'row-rail', 'data-group': '', 'data-hbound': '' });
1411
+ groups[cat].forEach(it => rail.appendChild(makeCard(it)));
1412
+ rail.appendChild(h('div', { class: 'row-end' }));
1413
+ const track = h('div', { class: 'row-track', 'data-railx': '80' }, [rail]);
1414
+ rows.appendChild(h('div', { class: 'row', 'data-anchor': '' }, [h('div', { class: 'row-title', text: cat }), track]));
1415
+ });
1416
+ if (!items.length) {
1417
+ var emptyMsg = this.lastError ? ('Catalog notice: ' + this.lastError) : (this.filterMode === 'series' ? 'No series available.' : 'Nothing to show yet.');
1418
+ var emptyBox = h('div', { class: 'empty-box' }, [
1419
+ h('div', { class: 'empty-title', text: emptyMsg }),
1420
+ h('div', { class: 'empty-sub', text: 'Check your connection, verify OTP, switch provider, or view live server diagnostics below.' }),
1421
+ h('div', { class: 'empty-actions' }, [
1422
+ h('button', { class: 'btn primary focusable', text: 'Retry', onclick: () => Home.load() }),
1423
+ h('button', { class: 'btn focusable', text: 'Switch Provider', onclick: () => Nav.push(OttModal) }),
1424
+ h('button', { class: 'btn focusable', text: 'Enter OTP', onclick: () => OtpScreen.open() }),
1425
+ h('button', { class: 'btn focusable', text: 'Diagnostics', onclick: () => DebugDrawer.toggle() })
1426
+ ])
1427
+ ]);
1428
+ rows.appendChild(emptyBox);
1429
+
1430
+ this.setHero({
1431
+ title: CONFIG.APP_NAME,
1432
+ description: this.lastError ? ('Notice: ' + this.lastError + '. Use buttons below to retry or switch provider.') : 'Select an OTT provider or browse categories once loaded.',
1433
+ year: 'TV',
1434
+ rating: 'HD',
1435
+ category: 'Welcome',
1436
+ type: 'movie'
1437
+ }, true);
1438
+
1439
+ var firstEmptyBtn = emptyBox.querySelector('.focusable');
1440
+ var target = firstEmptyBtn || $('nav-home');
1441
+ if (Nav.top() === this) Nav.focus(target);
1442
+ else this.savedFocus = target;
1443
+ } else {
1444
+ this.setHero(items[0], true);
1445
+ const target = $('hero-play');
1446
+ if (Nav.top() === this) Nav.focus(target);
1447
+ else this.savedFocus = target;
1448
+ }
1449
+ }
1450
+ };
1451
+
1452
+ const Search = {
1453
+ el: $('search'), full: true, seq: 0,
1454
+ init() {
1455
+ $('search-logo').textContent = CONFIG.APP_NAME;
1456
+ const input = $('search-input');
1457
+ $('search-osk').appendChild(Keyboard(input));
1458
+ input.addEventListener('input', debounce(() => this.run(input.value), CONFIG.SEARCH_DEBOUNCE_MS));
1459
+ input._onSubmit = () => this.run(input.value);
1460
+ },
1461
+ open() { Nav.push(this); this.run($('search-input').value); },
1462
+ run(q) {
1463
+ q = (q || '').trim();
1464
+ const seq = ++this.seq;
1465
+ if (!q) { this.show(Home.items.slice(0, 24), 'Popular titles'); return; }
1466
+ $('search-title').textContent = 'Searching…';
1467
+ Api.search(q)
1468
+ .then(items => { if (seq === this.seq) this.show(items, items.length ? 'Results for "' + q + '"' : 'No results for "' + q + '"'); })
1469
+ .catch(e => { if (seq === this.seq) $('search-title').textContent = 'Search failed: ' + e.message; });
1470
+ },
1471
+ show(items, title) {
1472
+ $('search-title').textContent = title;
1473
+ const box = $('search-results');
1474
+ const hadFocus = Nav.focused && box.contains(Nav.focused);
1475
+ box.textContent = '';
1476
+ box._last = null;
1477
+ items.forEach(it => box.appendChild(makeCard(it)));
1478
+ $('search-scroll').scrollTop = 0;
1479
+ if (hadFocus && Nav.top() === this) Nav.focus(box.firstChild || Nav.first(this.el));
1480
+ }
1481
+ };
1482
+
1483
+ const Detail = {
1484
+ el: $('detail'), full: true, item: null, season: 0,
1485
+ init() {
1486
+ $('detail-lang').innerHTML = icon('cc') + 'Audio &amp; Subtitles';
1487
+ $('detail-play').addEventListener('click', () => this.play());
1488
+ $('detail-lang').addEventListener('click', () => Nav.push(SettingsModal));
1489
+ $('detail-season').addEventListener('click', () => {
1490
+ if (this.item && this.item.seasons && this.item.seasons.length > 1) {
1491
+ SeasonModal.open();
1492
+ }
1493
+ });
1494
+ $('detail-watchlist').addEventListener('click', () => this.toggleWatchlist());
1495
+ },
1496
+ isSeries() { return this.item && this.item.type === 'series' && (this.item.seasons || []).length; },
1497
+ open(item) {
1498
+ this.season = item._initialSeasonIdx || 0;
1499
+ var self = this;
1500
+ var load = function (full) {
1501
+ self.item = full;
1502
+ self.season = full._initialSeasonIdx || 0;
1503
+ self.render();
1504
+ if (!Nav.has(self)) Nav.push(self, $('detail-play'));
1505
+ else { Nav.closeAbove(self); Nav.focus($('detail-play')); }
1506
+
1507
+ // Auto-paginate remaining episodes if the active season has nextPageShow
1508
+ if (full.type === 'series' && full.seasons && full.seasons[self.season]) {
1509
+ var activeS = full.seasons[self.season];
1510
+ if (full._nextPageShow && activeS.id) {
1511
+ Api.loadAllEpisodes(activeS.id).then(function (allEps) {
1512
+ if (self.item === full && Array.isArray(allEps) && allEps.length > (activeS.episodes || []).length) {
1513
+ activeS.episodes = allEps;
1514
+ self.renderSeason();
1515
+ }
1516
+ }).catch(function () {});
1517
+ }
1518
+ } else if (full.type === 'series' && !(full.seasons && full.seasons.length)) {
1519
+ Api.loadAllEpisodes(full.id).then(function (allEps) {
1520
+ if (self.item !== full) return;
1521
+ if (allEps && allEps.length) {
1522
+ full.seasons = [{ season: 1, title: 'Season 1', id: full.id, episodes: allEps }];
1523
+ self.render();
1524
+ }
1525
+ }).catch(function () {});
1526
+ }
1527
+ };
1528
+
1529
+ if (item._lastEp !== undefined) {
1530
+ load(item);
1531
+ } else {
1532
+ this.item = item;
1533
+ this.render();
1534
+ if (!Nav.has(this)) Nav.push(this, $('detail-play'));
1535
+ else { Nav.closeAbove(this); Nav.focus($('detail-play')); }
1536
+ UI.loading(true, 'Loading details…');
1537
+ Api.detail(item.id).then(function (full) {
1538
+ UI.loading(false);
1539
+ full.category = full.category || item.category;
1540
+ load(full);
1541
+ }).catch(function (e) {
1542
+ UI.loading(false);
1543
+ if (e && e.message && e.message.indexOf('OTP') > -1) return;
1544
+ load(item);
1545
+ });
1546
+ }
1547
+ },
1548
+ play() {
1549
+ if (!this.item) return;
1550
+ if (this.isSeries()) Player.open(firstEpisode(this.item, this.season));
1551
+ else Player.open(this.item);
1552
+ },
1553
+ render() {
1554
+ const it = this.item;
1555
+ $('detail-bg').style.backgroundImage = posterBg(it, true);
1556
+ $('detail-title').textContent = it.title;
1557
+ fillMeta($('detail-meta'), it);
1558
+ $('detail-desc').textContent = it.description || 'No description available.';
1559
+ $('detail-play').innerHTML = icon('play') + (this.isSeries() ? 'Play' : 'Play');
1560
+ this.updateHint();
1561
+ this.updateWatchlistBtn();
1562
+ if (this.isSeries()) this.renderSeason();
1563
+ else this.renderRelated();
1564
+ },
1565
+ renderRelated() {
1566
+ $('detail-season').classList.add('hidden');
1567
+ $('detail-more-title').textContent = 'More Like This';
1568
+ const more = $('detail-more');
1569
+ more.textContent = ''; more._last = null; more.scrollLeft = 0;
1570
+ const it = this.item;
1571
+ var list = [];
1572
+ if (it._suggest && it._suggest.length) {
1573
+ list = it._suggest;
1574
+ } else {
1575
+ const same = Home.items.filter(x => x !== it && x.category === it.category);
1576
+ const other = Home.items.filter(x => x !== it && x.category !== it.category);
1577
+ list = same.concat(other);
1578
+ }
1579
+ list.slice(0, 15).forEach(x => more.appendChild(makeCard(x)));
1580
+ more.appendChild(h('div', { class: 'row-end' }));
1581
+ },
1582
+ selectSeason(idx) {
1583
+ this.season = idx;
1584
+ var it = this.item;
1585
+ if (!it || !it.seasons || !it.seasons[idx]) return;
1586
+ var s = it.seasons[idx];
1587
+ var sb = $('detail-season');
1588
+ sb.textContent = (s.title || ('Season ' + (s.season || (idx + 1)))) + ' ▾';
1589
+
1590
+ if (s.episodes && s.episodes.length) {
1591
+ this.renderSeason();
1592
+ return;
1593
+ }
1594
+
1595
+ UI.loading(true, 'Loading ' + (s.title || 'Season') + ' episodes…');
1596
+ var self = this;
1597
+ Api.loadAllEpisodes(s.id).then(function (allEps) {
1598
+ UI.loading(false);
1599
+ s.episodes = allEps;
1600
+ if (self.item === it && self.season === idx) {
1601
+ self.renderSeason();
1602
+ }
1603
+ }).catch(function (e) {
1604
+ UI.loading(false);
1605
+ UI.toast('Failed to load episodes: ' + e.message, 'error');
1606
+ });
1607
+ },
1608
+ renderSeason() {
1609
+ const it = this.item, seasons = it.seasons || [];
1610
+ const sb = $('detail-season');
1611
+ if (seasons.length > 1) {
1612
+ sb.classList.remove('hidden');
1613
+ var sTitle = (seasons[this.season] && seasons[this.season].title) || ('Season ' + (this.season + 1));
1614
+ sb.textContent = sTitle + ' ▾';
1615
+ } else {
1616
+ sb.classList.add('hidden');
1617
+ }
1618
+ $('detail-more-title').textContent = seasons.length > 1 ? '' : 'Episodes';
1619
+ const more = $('detail-more');
1620
+ more.textContent = ''; more._last = null; more.scrollLeft = 0;
1621
+ var eps = seasonEpisodes(it, this.season);
1622
+ eps.forEach(ep => more.appendChild(this.episodeCard(it, ep)));
1623
+ more.appendChild(h('div', { class: 'row-end' }));
1624
+ if (!eps.length) {
1625
+ more.appendChild(h('div', { class: 'empty', text: 'Loading episodes…' }));
1626
+ // Fetch if empty
1627
+ var self = this;
1628
+ var curS = seasons[this.season];
1629
+ if (curS && curS.id) {
1630
+ Api.loadAllEpisodes(curS.id).then(function (allEps) {
1631
+ if (self.item === it) {
1632
+ curS.episodes = allEps;
1633
+ self.renderSeason();
1634
+ }
1635
+ }).catch(function () {});
1636
+ }
1637
+ }
1638
+ },
1639
+ episodeCard(series, ep) {
1640
+ const thumb = h('div', { class: 'ep-thumb' }, [
1641
+ h('div', { class: 'ep-num', text: 'E' + ep.episode }),
1642
+ h('div', { class: 'ep-play', html: icon('play') })
1643
+ ]);
1644
+ thumb.style.backgroundImage = posterBg({ image: ep.image, title: series.title + ep.episode }, true);
1645
+ const card = h('div', { class: 'ep-card focusable' }, [
1646
+ thumb,
1647
+ h('div', { class: 'ep-title', text: ep.episode + '. ' + (ep.title || 'Episode ' + ep.episode) }),
1648
+ h('div', { class: 'ep-sub', text: [ep.duration, ep.description].filter(Boolean).join(' · ') })
1649
+ ]);
1650
+ card.addEventListener('click', () => Player.open(episodePlayable(series, ep)));
1651
+ return card;
1652
+ },
1653
+ updateHint() {
1654
+ $('detail-hint').textContent = 'Audio: ' + Lang.chainText(Settings.get('audioLang')) +
1655
+ ' · Subtitles: ' + Lang.chainText(Settings.get('subLang'));
1656
+ },
1657
+ toggleWatchlist() {
1658
+ var it = this.item;
1659
+ if (!it || !it.id) return;
1660
+ var key = 'wl_' + it.id;
1661
+ var isInWl = !!NM.storage.get(key);
1662
+ var self = this;
1663
+ if (isInWl) {
1664
+ NM.watchlist({ videoid: it.id, deleteid: it.id, type: it.type === 'series' ? 't' : 'm' })
1665
+ .then(function (resp) {
1666
+ if (resp && resp.key) NM.storage.set(resp.key, resp.value);
1667
+ NM.storage.set(key, '');
1668
+ self.updateWatchlistBtn();
1669
+ UI.toast('Removed from Watchlist');
1670
+ })
1671
+ .catch(function (e) { UI.toast('Could not update watchlist: ' + e.message, 'error'); });
1672
+ } else {
1673
+ NM.watchlist({ videoid: it.id, type: it.type === 'series' ? 't' : 'm', sid: it._sid || it.id })
1674
+ .then(function (resp) {
1675
+ if (resp && resp.key) NM.storage.set(resp.key, resp.value);
1676
+ NM.storage.set(key, '1');
1677
+ self.updateWatchlistBtn();
1678
+ UI.toast('Added to Watchlist');
1679
+ })
1680
+ .catch(function (e) { UI.toast('Could not update watchlist: ' + e.message, 'error'); });
1681
+ }
1682
+ },
1683
+ updateWatchlistBtn() {
1684
+ var it = this.item;
1685
+ var btn = $('detail-watchlist');
1686
+ if (!btn || !it) return;
1687
+ var isInWl = !!NM.storage.get('wl_' + it.id);
1688
+ btn.innerHTML = icon(isInWl ? 'check' : 'plus') + (isInWl ? 'In Watchlist' : 'Add to Watchlist');
1689
+ btn.classList.toggle('active', isInWl);
1690
+ },
1691
+ };
1692
+
1693
+ const SettingsModal = {
1694
+ el: $('settings'),
1695
+ onOpen() { this.render(); },
1696
+ render() {
1697
+ const list = $('set-list');
1698
+ list.textContent = '';
1699
+ $('set-profile').textContent = Store.profile ? Store.profile.name : 'Guest';
1700
+ const langOpts = LANGS.map(l => ({ v: l[0], l: l[1] }));
1701
+ const hint = h('div', { class: 'set-hint' });
1702
+ const updateHint = () => {
1703
+ hint.textContent = 'Fallback — Audio: ' + Lang.chainText(Settings.get('audioLang')) +
1704
+ '. Subtitles: ' + Lang.chainText(Settings.get('subLang')) + '.';
1705
+ };
1706
+ const inPlayer = Nav.has(Player);
1707
+ [
1708
+ h('div', { class: 'set-section', text: 'Language (applies to every title)' }),
1709
+ Cycler('Preferred audio language', langOpts, () => Settings.get('audioLang'), v => { Settings.set('audioLang', v); updateHint(); }),
1710
+ Cycler('Preferred subtitle language', [{ v: 'off', l: 'Off' }].concat(langOpts), () => Settings.get('subLang'), v => { Settings.set('subLang', v); updateHint(); }),
1711
+ hint,
1712
+ h('div', { class: 'set-section', text: 'Playback' }),
1713
+ Cycler('Video quality', [{ v: 'auto', l: 'Auto (adaptive)' }, { v: 'high', l: 'Highest available' }, { v: 'saver', l: 'Data saver (≤ 480p)' }],
1714
+ () => Settings.get('quality'), v => Settings.set('quality', v)),
1715
+ Cycler('Default playback speed', SPEEDS.map(s => ({ v: s, l: s + 'x' })), () => Settings.get('speed'), v => Settings.set('speed', v)),
1716
+ Cycler('Skip interval', [10, 15, 30].map(s => ({ v: s, l: s + ' seconds' })), () => Settings.get('seekStep'), v => Settings.set('seekStep', v)),
1717
+ h('div', { class: 'set-section', text: 'Subtitles' }),
1718
+ ActionRow('Subtitle appearance', 'Size, color, background', () => Nav.push(SubDrawer)),
1719
+ h('div', { class: 'set-section', text: 'Account' }),
1720
+ inPlayer ? null : ActionRow('Switch profile', Store.profile ? Store.profile.name : 'Guest', () => Profiles.open(false)),
1721
+ h('div', { class: 'set-info' }, [h('span', { text: 'Server' }), h('span', { text: NM.storage.apiUrl() ? NM.storage.apiUrl().replace(/^https?:\/\//, '') : 'Connecting…' })]),
1722
+ h('div', { class: 'set-info' }, [h('span', { text: 'Provider' }), h('span', { text: (NM.storage.getOtt() || 'netflix').toUpperCase() })]),
1723
+ ActionRow('Done', '', () => Nav.close(this))
1724
+ ].forEach(el => { if (el) list.appendChild(el); });
1725
+ updateHint();
1726
+ $('set-scroll').scrollTop = 0;
1727
+ }
1728
+ };
1729
+
1730
+ const SubDrawer = {
1731
+ el: $('sub-drawer'),
1732
+ onOpen() { this.render(); },
1733
+ render() {
1734
+ const pv = $('sd-preview');
1735
+ pv.textContent = '';
1736
+ const cue = h('div', { class: 'sub-cue' });
1737
+ SubText.renderInto(cue, 'Subtitles will look like this.\nவசனங்கள் இப்படித் தோன்றும்.');
1738
+ pv.appendChild(cue);
1739
+ const list = $('sd-list');
1740
+ list.textContent = '';
1741
+ [
1742
+ Cycler('Font size', [{ v: 'small', l: 'Small' }, { v: 'medium', l: 'Medium' }, { v: 'large', l: 'Large' }],
1743
+ () => Settings.get('sub.size'), v => Settings.set('sub.size', v)),
1744
+ Cycler('Text color', Object.keys(SUB_COLORS).map(k => ({ v: k, l: k.charAt(0).toUpperCase() + k.slice(1) })),
1745
+ () => Settings.get('sub.color'), v => Settings.set('sub.color', v)),
1746
+ Cycler('Background', [{ v: true, l: 'On' }, { v: false, l: 'Off (outline)' }],
1747
+ () => Settings.get('sub.bg'), v => Settings.set('sub.bg', v)),
1748
+ Cycler('Background opacity', [0.25, 0.5, 0.75, 1].map(o => ({ v: o, l: Math.round(o * 100) + '%' })),
1749
+ () => Settings.get('sub.bgOpacity'), v => Settings.set('sub.bgOpacity', v)),
1750
+ ActionRow('Reset to default', '', () => { Settings.resetSub(); this.render(); Nav.focus(Nav.first(this.el)); })
1751
+ ].forEach(el => list.appendChild(el));
1752
+ }
1753
+ };
1754
+
1755
+ const Profiles = {
1756
+ el: $('profiles'), full: true, managing: false, startup: false,
1757
+ init() {
1758
+ $('prof-logo').textContent = CONFIG.APP_NAME;
1759
+ $('prof-manage').addEventListener('click', () => { this.managing = !this.managing; this.render(); });
1760
+ },
1761
+ open(startup) {
1762
+ this.startup = !!startup;
1763
+ this.managing = false;
1764
+ Nav.push(this);
1765
+ this.render();
1766
+ },
1767
+ onBack() {
1768
+ if (this.managing) { this.managing = false; this.render(); return true; }
1769
+ if (Store.profile && !this.startup) return false;
1770
+ Confirm.open('Exit ' + CONFIG.APP_NAME + '?', 'Exit', () => App.exit());
1771
+ return true;
1772
+ },
1773
+ render(focusId) {
1774
+ const box = $('prof-tiles');
1775
+ box.textContent = '';
1776
+ box._last = null;
1777
+ this.el.classList.toggle('managing', this.managing);
1778
+ $('prof-h').textContent = this.managing ? 'Manage Profiles' : "Who's watching?";
1779
+ const ps = Store.data.profiles;
1780
+ const want = focusId || (Store.profile && Store.profile.id) || Store.data.lastProfileId;
1781
+ let focusEl = null;
1782
+ ps.forEach(p => {
1783
+ const av = h('div', { class: 'prof-av', style: 'background:' + p.color }, [firstGrapheme(p.name), h('div', { class: 'prof-edit-badge', html: icon('edit') })]);
1784
+ const tile = h('div', { class: 'prof-tile focusable' }, [av, h('div', { class: 'prof-name', text: p.name })]);
1785
+ tile.addEventListener('click', () => (this.managing ? ProfileEdit.open(p) : this.select(p)));
1786
+ box.appendChild(tile);
1787
+ if (p.id === want) focusEl = tile;
1788
+ });
1789
+ if (!this.managing && ps.length < CONFIG.MAX_PROFILES) {
1790
+ const add = h('div', { class: 'prof-tile prof-add focusable' }, [h('div', { class: 'prof-av', html: icon('plus') }), h('div', { class: 'prof-name', text: 'Add Profile' })]);
1791
+ add.addEventListener('click', () => ProfileEdit.open(null));
1792
+ box.appendChild(add);
1793
+ }
1794
+ $('prof-manage').style.display = ps.length ? '' : 'none';
1795
+ $('prof-manage').textContent = this.managing ? 'Done' : 'Manage Profiles';
1796
+ if (Nav.top() === this) Nav.focus(focusEl || box.firstChild);
1797
+ },
1798
+ select(p) {
1799
+ Store.setActive(p);
1800
+ this.startup = false;
1801
+ App.onProfileChanged();
1802
+ Nav.closeAbove(Home);
1803
+ }
1804
+ };
1805
+
1806
+ const ProfileEdit = {
1807
+ el: $('profile-edit'), profile: null, color: AVATAR_COLORS[0][0],
1808
+ init() {
1809
+ const input = $('pe-name');
1810
+ $('pe-osk').appendChild(Keyboard(input));
1811
+ input.addEventListener('input', () => this.updateAvatar());
1812
+ },
1813
+ open(p) {
1814
+ this.profile = p;
1815
+ this.color = p ? p.color : AVATAR_COLORS[Store.data.profiles.length % AVATAR_COLORS.length][0];
1816
+ $('pe-name').value = p ? p.name : '';
1817
+ $('pe-title').textContent = p ? 'Edit Profile' : 'Add Profile';
1818
+ const cbox = $('pe-color');
1819
+ cbox.textContent = '';
1820
+ cbox.appendChild(Cycler('Avatar color', AVATAR_COLORS.map(c => ({ v: c[0], l: c[1] })), () => this.color, v => { this.color = v; this.updateAvatar(); }));
1821
+ const act = $('pe-actions');
1822
+ act.textContent = '';
1823
+ act.appendChild(h('div', { class: 'btn primary focusable', text: 'Save', onclick: () => this.save() }));
1824
+ if (p) act.appendChild(h('div', { class: 'btn focusable', text: 'Delete', onclick: () => this.del() }));
1825
+ act.appendChild(h('div', { class: 'btn focusable', text: 'Cancel', onclick: () => Nav.close(this) }));
1826
+ this.updateAvatar();
1827
+ Nav.push(this);
1828
+ },
1829
+ updateAvatar() {
1830
+ const n = $('pe-name').value.trim();
1831
+ const av = $('pe-avatar');
1832
+ av.textContent = n ? firstGrapheme(n) : '?';
1833
+ av.style.background = this.color;
1834
+ },
1835
+ save() {
1836
+ const n = $('pe-name').value.trim().slice(0, 16);
1837
+ if (!n) { UI.toast('Please enter a profile name', 'error'); Nav.focus($('pe-name')); return; }
1838
+ let p = this.profile;
1839
+ if (p) {
1840
+ p.name = n; p.color = this.color; Store.save();
1841
+ if (Store.profile === p) Home.refreshHeader();
1842
+ } else {
1843
+ p = Store.addProfile(n, this.color);
1844
+ }
1845
+ Nav.close(this);
1846
+ Profiles.managing = false;
1847
+ Profiles.render(p.id);
1848
+ },
1849
+ del() {
1850
+ const p = this.profile;
1851
+ Confirm.open('Delete profile "' + p.name + '"? Its settings will be lost.', 'Delete', () => {
1852
+ Store.removeProfile(p);
1853
+ Nav.close(this);
1854
+ Profiles.render();
1855
+ Home.refreshHeader();
1856
+ });
1857
+ }
1858
+ };
1859
+
1860
+ const Confirm = {
1861
+ el: $('confirm'), cb: null,
1862
+ init() {
1863
+ $('confirm-yes').addEventListener('click', () => { const cb = this.cb; Nav.close(this); if (cb) cb(); });
1864
+ $('confirm-no').addEventListener('click', () => Nav.close(this));
1865
+ },
1866
+ open(msg, yesLabel, cb) {
1867
+ $('confirm-msg').textContent = msg;
1868
+ $('confirm-yes').textContent = yesLabel || 'OK';
1869
+ this.cb = cb;
1870
+ Nav.push(this, $('confirm-no'));
1871
+ }
1872
+ };
1873
+
1874
+ /* =====================================================================
1875
+ * Player
1876
+ * ===================================================================== */
1877
+ const SeekInd = {
1878
+ acc: 0, dir: 0, at: 0, timer: null,
1879
+ show(delta) {
1880
+ const el = $('seek-ind');
1881
+ const dir = delta < 0 ? -1 : 1, now = Date.now();
1882
+ this.acc = (dir === this.dir && now - this.at < 1200) ? this.acc + Math.abs(delta) : Math.abs(delta);
1883
+ this.dir = dir;
1884
+ this.at = now;
1885
+ const side = dir < 0 ? 'left' : 'right';
1886
+ $('seek-ind-icon').innerHTML = icon(dir < 0 ? 'rew' : 'fwd');
1887
+ $('seek-ind-text').textContent = (dir < 0 ? '-' : '+') + this.acc + 's';
1888
+ el.className = side + ' show';
1889
+ clearTimeout(this.timer);
1890
+ this.timer = setTimeout(() => { el.className = side; }, 900);
1891
+ }
1892
+ };
1893
+
1894
+ const Player = {
1895
+ el: $('player'), full: true, video: null, hls: null, item: null, stream: null,
1896
+ ext: [], subSel: null, speed: 1, session: 0, closing: false,
1897
+ userPicked: { audio: false, sub: false }, fb: { audio: '', sub: '' }, fbTimer: null, lastFbToast: '',
1898
+ osdVisible: false, osdTimer: null,
1899
+ scrubPos: null, scrubTimer: null, scrubAt: 0, scrubRep: 0,
1900
+ netErr: 0, mediaErr: 0, loadTimeout: null,
1901
+
1902
+ init() {
1903
+ const v = this.video = $('video');
1904
+ $('pl-back').innerHTML = icon('back');
1905
+ $('pl-rew').innerHTML = icon('rew') + '<span class="ctrl-n">10</span>';
1906
+ $('pl-fwd').innerHTML = icon('fwd') + '<span class="ctrl-n">10</span>';
1907
+ $('pl-cc').innerHTML = icon('cc');
1908
+ $('pl-settings').innerHTML = icon('gear');
1909
+ $('pause-icon').innerHTML = icon('pause');
1910
+ this.setPaused(false);
1911
+
1912
+ v.addEventListener('timeupdate', () => {
1913
+ clearTimeout(this.loadTimeout);
1914
+ this.spin(false);
1915
+ this.updateTime();
1916
+ this.saveProgress();
1917
+ });
1918
+ v.addEventListener('progress', () => this.updateTime());
1919
+ v.addEventListener('play', () => {
1920
+ clearTimeout(this.loadTimeout);
1921
+ this.spin(false);
1922
+ this.setPaused(false);
1923
+ });
1924
+ v.addEventListener('pause', () => { if (this.item && !this.closing && !v.ended) this.setPaused(true); });
1925
+ v.addEventListener('waiting', () => this.spin(true));
1926
+ ['playing', 'canplay', 'seeked'].forEach(ev => v.addEventListener(ev, () => {
1927
+ clearTimeout(this.loadTimeout);
1928
+ this.spin(false);
1929
+ }));
1930
+ v.addEventListener('ended', () => { if (Nav.has(this)) Nav.close(this); });
1931
+ v.addEventListener('error', () => {
1932
+ if (this.item && !this.closing) {
1933
+ clearTimeout(this.loadTimeout);
1934
+ this.spin(false);
1935
+ const err = v.error;
1936
+ let desc = 'Playback error';
1937
+ if (err) {
1938
+ if (err.code === 1) desc = 'Playback aborted';
1939
+ else if (err.code === 2) desc = 'Network connection failed while streaming';
1940
+ else if (err.code === 3) desc = 'Media decoding failed';
1941
+ else if (err.code === 4) desc = 'Video format not supported or stream link expired';
1942
+ }
1943
+ this.fail(desc);
1944
+ }
1945
+ });
1946
+ v.addEventListener('loadedmetadata', () => {
1947
+ clearTimeout(this.loadTimeout);
1948
+ this.spin(false);
1949
+ if (!this.hls) { this.applyAudioPref(); this.applySubPref(); }
1950
+ this.applySpeed();
1951
+ this.refreshStatus();
1952
+ });
1953
+ if (v.audioTracks && v.audioTracks.addEventListener) v.audioTracks.addEventListener('change', () => this.refreshStatus());
1954
+ SubRenderer.bind(v);
1955
+
1956
+ $('pl-back').addEventListener('click', () => Nav.close(this));
1957
+ $('pl-play').addEventListener('click', () => this.toggle());
1958
+ $('pl-rew').addEventListener('click', () => this.seekBy(-Settings.get('seekStep')));
1959
+ $('pl-fwd').addEventListener('click', () => this.seekBy(Settings.get('seekStep')));
1960
+ $('pl-cc').addEventListener('click', () => this.toggleSubs());
1961
+ $('pl-settings').addEventListener('click', () => Nav.push(PlayerMenu));
1962
+ $('seekbar').addEventListener('click', e => {
1963
+ if (!e.detail || !isFinite(v.duration)) return;
1964
+ const r = $('seekbar').querySelector('.seek-track').getBoundingClientRect();
1965
+ v.currentTime = clamp((e.clientX - r.left) / r.width, 0, 1) * v.duration;
1966
+ });
1967
+ this.el.addEventListener('mousemove', () => { if (Nav.top() === this) this.showOsd(); });
1968
+ },
1969
+
1970
+ /* ----- lifecycle ----- */
1971
+ open(item) {
1972
+ const sess = ++this.session;
1973
+ this.closing = false;
1974
+ clearTimeout(this.loadTimeout);
1975
+ UI.loading(true, 'Preparing stream…');
1976
+
1977
+ Api.stream(item)
1978
+ .then(stream => {
1979
+ UI.loading(false);
1980
+ if (sess !== this.session) return;
1981
+ if (!stream || !stream.url) {
1982
+ this.spin(false);
1983
+ throw new Error('No stream URL available');
1984
+ }
1985
+ this.item = item;
1986
+ this.stream = stream;
1987
+ this.userPicked = { audio: false, sub: false };
1988
+ this.fb = { audio: '', sub: '' };
1989
+ this.lastFbToast = '';
1990
+ this.subSel = null;
1991
+ this.netErr = this.mediaErr = 0;
1992
+ this.scrubPos = null;
1993
+ this.speed = Settings.get('speed');
1994
+ $('osd-title').textContent = item.title;
1995
+ $('pause-title').textContent = item.title;
1996
+ $('osd-sub').textContent = [item.year, item.duration].filter(Boolean).join(' · ');
1997
+ $('pl-rew').querySelector('.ctrl-n').textContent = Settings.get('seekStep');
1998
+ $('pl-fwd').querySelector('.ctrl-n').textContent = Settings.get('seekStep');
1999
+ this.setPaused(false);
2000
+ Nav.push(this, $('pl-play'));
2001
+ this.showOsd();
2002
+
2003
+ // Restore saved progress
2004
+ var saved = NM.storage.getProgress(item.id);
2005
+ this.attach(stream);
2006
+ if (saved > 2) {
2007
+ var v = this.video;
2008
+ var once = function () { v.currentTime = saved; v.removeEventListener('loadedmetadata', once); };
2009
+ v.addEventListener('loadedmetadata', once);
2010
+ }
2011
+
2012
+ // Background recentplay update
2013
+ if (item.id) {
2014
+ NM.recentplay({
2015
+ videoid: item.id,
2016
+ type: item.type === 'series' ? 't' : 'm',
2017
+ sid: item._sid || item.id
2018
+ }).catch(function () {});
2019
+ }
2020
+
2021
+ this.loadExternalSubs(stream.subtitles || [], sess);
2022
+ })
2023
+ .catch(e => {
2024
+ UI.loading(false);
2025
+ this.spin(false);
2026
+ if (e && e.message && e.message.indexOf('OTP') > -1) return;
2027
+ UI.toast('Could not start playback: ' + (e ? e.message : 'Unknown error'), 'error');
2028
+ if (Nav.has(this)) Nav.close(this);
2029
+ });
2030
+ },
2031
+
2032
+ attach(stream) {
2033
+ const v = this.video;
2034
+ var referer = stream.referer || stream._referer || 'https://net52.cc';
2035
+ var streamUrl = stream.url;
2036
+ if (typeof NM !== 'undefined' && typeof NM.proxyMediaUrl === 'function') {
2037
+ streamUrl = NM.proxyMediaUrl(stream.url, referer);
2038
+ }
2039
+ const isHls = stream.type === 'hls' ||
2040
+ (stream.url && stream.url.indexOf('.m3u8') !== -1) ||
2041
+ (streamUrl && streamUrl.indexOf('.m3u8') !== -1);
2042
+ const headers = stream.headers || {};
2043
+ this.spin(true);
2044
+
2045
+ // Watchdog timer: stop spinning if playback does not start within 20s
2046
+ clearTimeout(this.loadTimeout);
2047
+ const sess = this.session;
2048
+ this.loadTimeout = setTimeout(() => {
2049
+ if (this.session === sess && this.item && (!v.currentTime || v.paused)) {
2050
+ this.spin(false);
2051
+ this.fail('Stream connection timed out. Server or stream may be unavailable.');
2052
+ }
2053
+ }, 20000);
2054
+
2055
+ if (isHls && !window.Hls && !stream.hlsTried) {
2056
+ stream.hlsTried = true;
2057
+ ensureHls().then(() => { if (sess === this.session) this.attach(stream); });
2058
+ return;
2059
+ }
2060
+ v.defaultPlaybackRate = v.playbackRate = this.speed;
2061
+
2062
+ if (isHls && window.Hls && Hls.isSupported()) {
2063
+ const hls = this.hls = new Hls({
2064
+ enableWorker: false, // Avoid WebKit Worker crashes with MSE on Smart TVs
2065
+ lowLatencyMode: false,
2066
+ backBufferLength: 60,
2067
+ maxBufferLength: 60,
2068
+ maxMaxBufferLength: 120,
2069
+ maxBufferSize: 60 * 1000 * 1000,
2070
+ maxBufferHole: 1.5,
2071
+ highBufferWatchdogPeriod: 2,
2072
+ nudgeOffset: 0.2,
2073
+ nudgeMaxRetry: 10,
2074
+ startFragPrefetch: true,
2075
+ renderTextTracksNatively: true,
2076
+ xhrSetup: xhr => Object.keys(headers).forEach(k => { try { xhr.setRequestHeader(k, headers[k]); } catch (e) {} })
2077
+ });
2078
+ hls.subtitleDisplay = false;
2079
+ const E = Hls.Events;
2080
+ hls.on(E.MANIFEST_PARSED, () => {
2081
+ this.applyQualityPref();
2082
+ this.applyAudioPref();
2083
+ this.applySubPref();
2084
+ v.play().catch(() => {});
2085
+ });
2086
+ hls.on(E.AUDIO_TRACKS_UPDATED, () => this.applyAudioPref());
2087
+ hls.on(E.SUBTITLE_TRACKS_UPDATED, () => this.applySubPref());
2088
+ hls.on(E.LEVEL_SWITCHED, () => this.refreshStatus());
2089
+ hls.on(E.AUDIO_TRACK_SWITCHED, () => this.refreshStatus());
2090
+ hls.on(E.SUBTITLE_TRACK_SWITCH, () => { SubRenderer.render(); this.refreshStatus(); });
2091
+ hls.on(E.FRAG_LOADED, () => {
2092
+ clearTimeout(this.loadTimeout);
2093
+ this.spin(false);
2094
+ this.netErr = 0;
2095
+ });
2096
+ hls.on(E.ERROR, (ev, d) => this.onHlsError(d));
2097
+ hls.loadSource(streamUrl);
2098
+ hls.attachMedia(v);
2099
+ } else {
2100
+ v.src = streamUrl;
2101
+ v.play().catch(() => {});
2102
+ }
2103
+ },
2104
+
2105
+ onHlsError(d) {
2106
+ if (!d.fatal) return;
2107
+ if (d.type === Hls.ErrorTypes.NETWORK_ERROR && ++this.netErr <= 3) {
2108
+ this.hls.startLoad();
2109
+ return;
2110
+ }
2111
+ if (d.type === Hls.ErrorTypes.MEDIA_ERROR) {
2112
+ this.mediaErr++;
2113
+ if (this.mediaErr === 1) { this.hls.recoverMediaError(); return; }
2114
+ if (this.mediaErr === 2) { this.hls.swapAudioCodec(); this.hls.recoverMediaError(); return; }
2115
+ if (this.mediaErr === 3) {
2116
+ this.fail('Stream decoding failed after multiple recoveries: ' + (d.details || 'Media error'));
2117
+ return;
2118
+ }
2119
+ }
2120
+ clearTimeout(this.loadTimeout);
2121
+ this.spin(false);
2122
+ this.fail('Playback failed: ' + (d.details || 'HLS stream error'));
2123
+ },
2124
+
2125
+ fail(msg) {
2126
+ clearTimeout(this.loadTimeout);
2127
+ this.spin(false);
2128
+ UI.toast(msg, 'error');
2129
+ if (Nav.has(this)) Nav.close(this);
2130
+ },
2131
+
2132
+ onBack() { return false; }, // default → Nav.close(Player) → onClose()
2133
+
2134
+ onClose() {
2135
+ this.closing = true;
2136
+ this.session++;
2137
+ clearTimeout(this.osdTimer);
2138
+ clearTimeout(this.fbTimer);
2139
+ clearTimeout(this.scrubTimer);
2140
+ clearTimeout(this.loadTimeout);
2141
+ this.spin(false);
2142
+ this.saveProgress(true);
2143
+ this.item = null;
2144
+ this.stream = null;
2145
+ const v = this.video;
2146
+ if (this.hls) {
2147
+ this.hls.destroy();
2148
+ this.hls = null;
2149
+ const tt = v.textTracks; // tracks made via addTextTrack can't be removed: retire them
2150
+ for (let i = 0; i < tt.length; i++) {
2151
+ if (tt[i].kind === 'subtitles' || tt[i].kind === 'captions') { tt[i].mode = 'disabled'; tt[i].__stale = true; }
2152
+ }
2153
+ }
2154
+ this.ext.forEach(e => {
2155
+ e.track.mode = 'disabled';
2156
+ if (e.el.parentNode) e.el.parentNode.removeChild(e.el);
2157
+ URL.revokeObjectURL(e.url);
2158
+ });
2159
+ this.ext = [];
2160
+ this.subSel = null;
2161
+ v.pause();
2162
+ v.removeAttribute('src');
2163
+ v.load();
2164
+ SubRenderer.clear();
2165
+ this.scrubPos = null;
2166
+ $('seekbar').classList.remove('scrubbing');
2167
+ $('pl-cc').classList.remove('on');
2168
+ this.setPaused(false);
2169
+ this.hideOsd();
2170
+ this.spin(false);
2171
+ this.closing = false;
2172
+ },
2173
+
2174
+ /* ----- remote control ----- */
2175
+ onKey(key) {
2176
+ const step = Settings.get('seekStep');
2177
+ switch (key) {
2178
+ case 'PLAY': this.video.play().catch(() => {}); return true;
2179
+ case 'PAUSE': this.video.pause(); return true;
2180
+ case 'PLAYPAUSE': this.toggle(); return true;
2181
+ case 'STOP': Nav.close(this); return true;
2182
+ case 'FF': this.seekBy(step); return true;
2183
+ case 'RW': this.seekBy(-step); return true;
2184
+ }
2185
+ if (!this.osdVisible) {
2186
+ if (key === 'LEFT' || key === 'RIGHT') { this.seekBy(key === 'LEFT' ? -step : step); return true; }
2187
+ if (key === 'ENTER') { this.toggle(); return true; }
2188
+ if (key === 'UP' || key === 'DOWN') { this.showOsd($('seekbar')); return true; }
2189
+ return false; // BACK → exit player
2190
+ }
2191
+ this.armHide();
2192
+ if (Nav.focused === $('seekbar')) {
2193
+ if (key === 'LEFT' || key === 'RIGHT') { this.scrub(key === 'LEFT' ? -1 : 1); return true; }
2194
+ if (key === 'ENTER') { if (this.scrubPos !== null) this.commitScrub(); else this.toggle(); return true; }
2195
+ }
2196
+ if (key === 'BACK') {
2197
+ if (this.scrubPos !== null) this.cancelScrub(); else this.hideOsd();
2198
+ return true;
2199
+ }
2200
+ return false; // arrows/ENTER → spatial nav over OSD controls
2201
+ },
2202
+
2203
+ /* ----- OSD ----- */
2204
+ showOsd(focusEl) {
2205
+ if (!this.osdVisible) {
2206
+ this.osdVisible = true;
2207
+ this.el.classList.add('osd-on');
2208
+ if (!focusEl && !(Nav.focused && this.el.contains(Nav.focused))) focusEl = $('pl-play');
2209
+ }
2210
+ if (focusEl && Nav.top() === this) Nav.focus(focusEl);
2211
+ this.armHide();
2212
+ },
2213
+ hideOsd() {
2214
+ this.osdVisible = false;
2215
+ this.el.classList.remove('osd-on');
2216
+ clearTimeout(this.osdTimer);
2217
+ },
2218
+ armHide() {
2219
+ clearTimeout(this.osdTimer);
2220
+ this.osdTimer = setTimeout(() => {
2221
+ if (this.scrubPos !== null || Nav.top() !== this) { this.armHide(); return; }
2222
+ this.hideOsd();
2223
+ }, CONFIG.OSD_HIDE_MS);
2224
+ },
2225
+ spin(on) { this.el.classList.toggle('buffering', !!on); },
2226
+ setPaused(p) {
2227
+ this.el.classList.toggle('paused', !!p);
2228
+ $('pl-play').innerHTML = icon(p ? 'play' : 'pause');
2229
+ },
2230
+
2231
+ updateTime() {
2232
+ const v = this.video;
2233
+ const dur = v.duration;
2234
+ const live = !isFinite(dur) || !dur;
2235
+ const pos = this.scrubPos !== null ? this.scrubPos : v.currentTime;
2236
+ const pct = live ? 0 : clamp(pos / dur, 0, 1) * 100;
2237
+ $('seek-fill').style.width = pct + '%';
2238
+ $('seek-thumb').style.left = pct + '%';
2239
+ $('pl-time').textContent = live ? 'LIVE' : fmtTime(pos) + ' / ' + fmtTime(dur);
2240
+ if (this.scrubPos !== null) {
2241
+ const pv = $('seek-preview');
2242
+ pv.style.left = pct + '%';
2243
+ pv.textContent = fmtTime(pos);
2244
+ }
2245
+ let buf = 0;
2246
+ for (let i = 0; i < v.buffered.length; i++) {
2247
+ if (v.buffered.start(i) <= v.currentTime + 0.5 && v.buffered.end(i) >= v.currentTime) buf = v.buffered.end(i);
2248
+ }
2249
+ $('seek-buf').style.width = live ? '0%' : clamp(buf / dur, 0, 1) * 100 + '%';
2250
+ },
2251
+
2252
+ /* ----- transport ----- */
2253
+ toggle() {
2254
+ const v = this.video;
2255
+ if (v.paused) v.play().catch(() => {}); else v.pause();
2256
+ },
2257
+ seekRange() {
2258
+ const v = this.video;
2259
+ if (isFinite(v.duration) && v.duration > 0) return { start: 0, end: v.duration };
2260
+ if (v.seekable && v.seekable.length) return { start: v.seekable.start(0), end: v.seekable.end(v.seekable.length - 1) };
2261
+ return null;
2262
+ },
2263
+ seekBy(delta) {
2264
+ const r = this.seekRange();
2265
+ if (!r) return;
2266
+ const v = this.video;
2267
+ v.currentTime = clamp(v.currentTime + delta, r.start, Math.max(r.start, r.end - 0.5));
2268
+ SeekInd.show(delta);
2269
+ this.updateTime();
2270
+ },
2271
+ scrub(dir) {
2272
+ const v = this.video;
2273
+ if (!isFinite(v.duration) || !v.duration) return;
2274
+ const now = Date.now();
2275
+ this.scrubRep = now - this.scrubAt < 350 ? this.scrubRep + 1 : 0; // accelerate on held key
2276
+ this.scrubAt = now;
2277
+ const base = Settings.get('seekStep');
2278
+ const step = this.scrubRep > 16 ? base * 6 : this.scrubRep > 6 ? base * 3 : base;
2279
+ if (this.scrubPos === null) this.scrubPos = v.currentTime;
2280
+ this.scrubPos = clamp(this.scrubPos + dir * step, 0, v.duration - 0.5);
2281
+ $('seekbar').classList.add('scrubbing');
2282
+ this.updateTime();
2283
+ clearTimeout(this.scrubTimer);
2284
+ this.scrubTimer = setTimeout(() => this.commitScrub(), 800);
2285
+ },
2286
+ commitScrub() {
2287
+ clearTimeout(this.scrubTimer);
2288
+ if (this.scrubPos === null) return;
2289
+ this.video.currentTime = this.scrubPos;
2290
+ this.scrubPos = null;
2291
+ $('seekbar').classList.remove('scrubbing');
2292
+ this.updateTime();
2293
+ },
2294
+ cancelScrub() {
2295
+ clearTimeout(this.scrubTimer);
2296
+ this.scrubPos = null;
2297
+ $('seekbar').classList.remove('scrubbing');
2298
+ this.updateTime();
2299
+ },
2300
+ applySpeed() { this.video.defaultPlaybackRate = this.video.playbackRate = this.speed; },
2301
+ setSpeed(r) { this.speed = r; this.applySpeed(); this.refreshStatus(); },
2302
+
2303
+ /* ----- tracks: audio ----- */
2304
+ trackLabel(t, i, code) {
2305
+ let name = String(t.name || t.label || '').replace(/^ext:/, '').trim();
2306
+ if (!name || /^(sub(title)?s?|audio|track|cc)?\s*\d*$/i.test(name)) name = code ? Lang.label(code) : 'Track ' + (i + 1);
2307
+ return name;
2308
+ },
2309
+ audioTracks() {
2310
+ if (this.hls) {
2311
+ return (this.hls.audioTracks || []).map((t, i) => {
2312
+ const code = Lang.ofTrack(t);
2313
+ return { index: i, code: code, label: this.trackLabel(t, i, code), isDefault: !!t.default };
2314
+ });
2315
+ }
2316
+ const at = this.video.audioTracks;
2317
+ if (!at || !at.length) return [];
2318
+ const out = [];
2319
+ for (let i = 0; i < at.length; i++) {
2320
+ const code = Lang.ofTrack({ language: at[i].language, label: at[i].label });
2321
+ out.push({ index: i, code: code, label: this.trackLabel(at[i], i, code), isDefault: at[i].kind === 'main' });
2322
+ }
2323
+ return out;
2324
+ },
2325
+ currentAudio() {
2326
+ if (this.hls) return this.hls.audioTrack;
2327
+ const at = this.video.audioTracks;
2328
+ if (at) for (let i = 0; i < at.length; i++) if (at[i].enabled) return i;
2329
+ return -1;
2330
+ },
2331
+ setAudio(i) {
2332
+ if (this.hls) { this.hls.audioTrack = i; return; }
2333
+ const at = this.video.audioTracks;
2334
+ if (at) for (let j = 0; j < at.length; j++) at[j].enabled = j === i;
2335
+ },
2336
+ audioLabel() {
2337
+ const t = this.audioTracks().find(x => x.index === this.currentAudio());
2338
+ return t ? t.label : 'Default';
2339
+ },
2340
+
2341
+ /* ----- tracks: subtitles ----- */
2342
+ subTracks() {
2343
+ const list = [];
2344
+ if (this.hls) {
2345
+ (this.hls.subtitleTracks || []).forEach((t, i) => {
2346
+ const code = Lang.ofTrack(t);
2347
+ list.push({ type: 'hls', index: i, code: code, label: this.trackLabel(t, i, code), isDefault: !!t.default });
2348
+ });
2349
+ } else {
2350
+ const tt = this.video.textTracks;
2351
+ for (let i = 0; i < tt.length; i++) {
2352
+ const t = tt[i];
2353
+ if ((t.kind === 'subtitles' || t.kind === 'captions') && !t.__stale) {
2354
+ const code = Lang.ofTrack({ language: t.language, label: t.label });
2355
+ list.push({ type: 'track', track: t, code: code, label: this.trackLabel(t, i, code), isDefault: false });
2356
+ }
2357
+ }
2358
+ }
2359
+ return list.concat(this.ext);
2360
+ },
2361
+ sameSub(a, b) {
2362
+ if (!a || !b) return a === b;
2363
+ return a.type === b.type && (a.type === 'hls' ? a.index === b.index : a.track === b.track);
2364
+ },
2365
+ setSub(entry) {
2366
+ this.subSel = entry || null;
2367
+ this.ext.forEach(e => { e.track.mode = this.sameSub(entry, e) ? 'hidden' : 'disabled'; });
2368
+ if (this.hls) {
2369
+ const idx = entry && entry.type === 'hls' ? entry.index : -1;
2370
+ if (this.hls.subtitleTrack !== idx) this.hls.subtitleTrack = idx;
2371
+ } else {
2372
+ const tt = this.video.textTracks;
2373
+ for (let i = 0; i < tt.length; i++) {
2374
+ const t = tt[i];
2375
+ if (t.kind === 'subtitles' || t.kind === 'captions') t.mode = entry && entry.track === t ? 'hidden' : 'disabled';
2376
+ }
2377
+ }
2378
+ $('pl-cc').classList.toggle('on', !!entry);
2379
+ SubRenderer.render();
2380
+ this.refreshStatus();
2381
+ },
2382
+ subLabel() { return this.subSel ? this.subSel.label : 'Off'; },
2383
+ toggleSubs() {
2384
+ this.userPicked.sub = true;
2385
+ if (this.subSel) { this.setSub(null); UI.toast('Subtitles off'); return; }
2386
+ const list = this.subTracks();
2387
+ if (!list.length) { UI.toast('No subtitles available for this title'); return; }
2388
+ const pref = Settings.get('subLang');
2389
+ const r = Lang.pick(list, pref === 'off' ? Settings.get('audioLang') : pref);
2390
+ this.setSub(list[r.index]);
2391
+ UI.toast('Subtitles: ' + list[r.index].label);
2392
+ },
2393
+
2394
+ loadExternalSubs(list, sess) {
2395
+ list.forEach(s => {
2396
+ SubParser.load(s.url)
2397
+ .then(cues => {
2398
+ if (sess !== this.session || !cues.length) return;
2399
+ const code = Lang.norm(s.lang) || Lang.fromName(s.label);
2400
+ const label = s.label || Lang.label(code);
2401
+ const url = URL.createObjectURL(new Blob([SubParser.toVtt(cues)], { type: 'text/vtt' }));
2402
+ // kind=metadata keeps hls.js's subtitle controller from toggling our tracks.
2403
+ const el = h('track', { kind: 'metadata', label: 'ext:' + label, srclang: code || 'und', src: url });
2404
+ this.video.appendChild(el);
2405
+ el.track.mode = 'disabled';
2406
+ this.ext.push({ type: 'track', track: el.track, el: el, url: url, code: code, label: label, isDefault: false });
2407
+ this.applySubPref();
2408
+ })
2409
+ .catch(e => console.warn('[subs] ' + s.url + ': ' + e.message));
2410
+ });
2411
+ },
2412
+
2413
+ /* ----- language fallback engine ----- */
2414
+ noteFallback(kind, msg) {
2415
+ this.fb[kind] = msg;
2416
+ clearTimeout(this.fbTimer);
2417
+ this.fbTimer = setTimeout(() => {
2418
+ const m = [this.fb.audio, this.fb.sub].filter(Boolean).join(' · ');
2419
+ if (m && m !== this.lastFbToast) { this.lastFbToast = m; UI.toast(m); }
2420
+ }, 1500);
2421
+ },
2422
+ applyAudioPref() {
2423
+ if (this.userPicked.audio || !this.item) return;
2424
+ const tracks = this.audioTracks();
2425
+ if (!tracks.length) return;
2426
+ const pref = Settings.get('audioLang');
2427
+ const r = Lang.pick(tracks, pref);
2428
+ const t = tracks[r.index];
2429
+ if (this.currentAudio() !== t.index) this.setAudio(t.index);
2430
+ const tagged = tracks.some(x => x.code);
2431
+ this.noteFallback('audio', r.matched === 'preferred' || !tagged ? '' : Lang.label(pref) + ' audio not available — playing ' + t.label);
2432
+ this.refreshStatus();
2433
+ },
2434
+ applySubPref() {
2435
+ if (this.userPicked.sub || !this.item) return;
2436
+ const pref = Settings.get('subLang');
2437
+ const list = this.subTracks();
2438
+ if (pref === 'off' || !list.length) {
2439
+ if (this.subSel || this.hls) this.setSub(null);
2440
+ this.noteFallback('sub', '');
2441
+ return;
2442
+ }
2443
+ const r = Lang.pick(list, pref);
2444
+ const t = list[r.index];
2445
+ if (!this.sameSub(this.subSel, t)) this.setSub(t);
2446
+ this.noteFallback('sub', r.matched === 'preferred' ? '' : Lang.label(pref) + ' subtitles not available — showing ' + t.label);
2447
+ },
2448
+
2449
+ /* ----- quality ----- */
2450
+ qualityOptions() {
2451
+ const hls = this.hls;
2452
+ if (!hls || !hls.levels || !hls.levels.length) return [];
2453
+ const auto = hls.autoLevelEnabled, cur = hls.currentLevel;
2454
+ const lv = hls.levels.map((l, i) => ({ index: i, h: l.height || 0, b: l.bitrate || 0 })).sort((a, b) => b.h - a.h || b.b - a.b);
2455
+ const count = {};
2456
+ lv.forEach(l => { count[l.h] = (count[l.h] || 0) + 1; });
2457
+ const curL = hls.levels[cur];
2458
+ const opts = [{ index: -1, label: 'Auto' + (auto && curL && curL.height ? ' (now ' + curL.height + 'p)' : ''), checked: auto }];
2459
+ lv.forEach(l => opts.push({
2460
+ index: l.index,
2461
+ label: (l.h ? l.h + 'p' : 'Level ' + (l.index + 1)) + (count[l.h] > 1 || !l.h ? ' · ' + (l.b / 1e6).toFixed(1) + ' Mbps' : ''),
2462
+ checked: !auto && cur === l.index
2463
+ }));
2464
+ return opts;
2465
+ },
2466
+ setQuality(i) {
2467
+ if (!this.hls) return;
2468
+ if (i >= 0) this.hls.autoLevelCapping = -1;
2469
+ this.hls.currentLevel = i;
2470
+ this.refreshStatus();
2471
+ },
2472
+ applyQualityPref() {
2473
+ const hls = this.hls;
2474
+ if (!hls || !hls.levels || !hls.levels.length) return;
2475
+ const q = Settings.get('quality');
2476
+ const lv = hls.levels.map((l, i) => ({ i: i, h: l.height || 0, b: l.bitrate || 0 }));
2477
+ const byBest = (a, b) => b.h - a.h || b.b - a.b;
2478
+ if (q === 'high') {
2479
+ hls.autoLevelCapping = -1;
2480
+ hls.currentLevel = lv.slice().sort(byBest)[0].i;
2481
+ } else if (q === 'saver') {
2482
+ const ok = lv.filter(l => l.h && l.h <= 480).sort(byBest);
2483
+ hls.currentLevel = -1;
2484
+ hls.autoLevelCapping = ok.length ? ok[0].i : lv.slice().sort((a, b) => a.b - b.b)[0].i;
2485
+ } else {
2486
+ hls.autoLevelCapping = -1;
2487
+ hls.currentLevel = -1;
2488
+ }
2489
+ this.refreshStatus();
2490
+ },
2491
+ qualityLabel() {
2492
+ const hls = this.hls;
2493
+ if (!hls) return this.video.videoHeight ? this.video.videoHeight + 'p' : 'Original';
2494
+ const l = hls.levels && hls.levels[hls.currentLevel];
2495
+ if (hls.autoLevelEnabled) return 'Auto' + (l && l.height ? ' (' + l.height + 'p)' : '');
2496
+ return l && l.height ? l.height + 'p' : 'Manual';
2497
+ },
2498
+
2499
+ refreshStatus() {
2500
+ if (!this.item) { $('pl-status').textContent = ''; return; }
2501
+ const parts = [this.qualityLabel()];
2502
+ if (this.audioTracks().length) parts.push(this.audioLabel());
2503
+ if (this.subSel) parts.push('CC ' + this.subSel.label);
2504
+ if (this.speed !== 1) parts.push(this.speed + 'x');
2505
+ $('pl-status').textContent = parts.join(' · ');
2506
+ },
2507
+
2508
+ onSettingsChanged(k) {
2509
+ if (!this.item) return;
2510
+ if (k === 'audioLang') { this.userPicked.audio = false; this.applyAudioPref(); }
2511
+ else if (k === 'subLang') { this.userPicked.sub = false; this.applySubPref(); }
2512
+ else if (k === 'quality') this.applyQualityPref();
2513
+ else if (k === 'speed') this.setSpeed(Settings.get('speed'));
2514
+ else if (k === 'seekStep') {
2515
+ $('pl-rew').querySelector('.ctrl-n').textContent = Settings.get('seekStep');
2516
+ $('pl-fwd').querySelector('.ctrl-n').textContent = Settings.get('seekStep');
2517
+ }
2518
+ },
2519
+ _lastSave: 0,
2520
+ saveProgress(force) {
2521
+ if (!this.item || !this.item.id) return;
2522
+ var v = this.video;
2523
+ if (!v) return;
2524
+ var pos = v.currentTime;
2525
+ if (!isFinite(pos) || pos < 1) return;
2526
+ var now = Date.now();
2527
+ if (!force && now - this._lastSave < 5000) return;
2528
+ this._lastSave = now;
2529
+ NM.storage.setProgress(this.item.id, pos);
2530
+ }
2531
+ };
2532
+
2533
+ /* ---------- In-player settings menu ---------- */
2534
+ const PlayerMenu = {
2535
+ el: $('player-menu'), page: 'root',
2536
+ onOpen() { this.render('root'); },
2537
+ onBack() {
2538
+ if (this.page !== 'root') { this.render('root', this.page); return true; }
2539
+ return false;
2540
+ },
2541
+ onClose() { if (Nav.has(Player)) Player.armHide(); },
2542
+ render(page, focusKey) {
2543
+ this.page = page;
2544
+ let title = 'Playback Settings', items = [];
2545
+ const back = key => this.render('root', key);
2546
+ if (page === 'root') {
2547
+ items = [
2548
+ { key: 'quality', label: 'Video Quality', val: Player.qualityLabel() },
2549
+ { key: 'audio', label: 'Audio', val: Player.audioLabel() },
2550
+ { key: 'subs', label: 'Subtitles', val: Player.subLabel() },
2551
+ { key: 'speed', label: 'Playback Speed', val: Player.speed + 'x' },
2552
+ { key: 'style', label: 'Subtitle Style', val: '›' },
2553
+ { key: 'app', label: 'App Settings', val: '›' }
2554
+ ];
2555
+ items.forEach(it => {
2556
+ it.onSelect = () => {
2557
+ if (it.key === 'style') Nav.push(SubDrawer);
2558
+ else if (it.key === 'app') Nav.push(SettingsModal);
2559
+ else this.render(it.key);
2560
+ };
2561
+ });
2562
+ } else if (page === 'quality') {
2563
+ title = 'Video Quality';
2564
+ items = Player.qualityOptions().map(o => ({ label: o.label, checked: o.checked, onSelect: () => { Player.setQuality(o.index); back('quality'); } }));
2565
+ } else if (page === 'audio') {
2566
+ title = 'Audio';
2567
+ const cur = Player.currentAudio();
2568
+ items = Player.audioTracks().map(t => ({
2569
+ label: t.label, checked: t.index === cur,
2570
+ onSelect: () => { Player.userPicked.audio = true; Player.setAudio(t.index); Player.refreshStatus(); back('audio'); }
2571
+ }));
2572
+ } else if (page === 'subs') {
2573
+ title = 'Subtitles';
2574
+ items = [{ label: 'Off', checked: !Player.subSel, onSelect: () => { Player.userPicked.sub = true; Player.setSub(null); back('subs'); } }]
2575
+ .concat(Player.subTracks().map(t => ({
2576
+ label: t.label, checked: Player.sameSub(Player.subSel, t),
2577
+ onSelect: () => { Player.userPicked.sub = true; Player.setSub(t); back('subs'); }
2578
+ })));
2579
+ } else if (page === 'speed') {
2580
+ title = 'Playback Speed';
2581
+ items = SPEEDS.map(s => ({ label: s === 1 ? '1x (Normal)' : s + 'x', checked: Player.speed === s, onSelect: () => { Player.setSpeed(s); back('speed'); } }));
2582
+ }
2583
+ if (!items.length) items = [{ label: 'Not available for this stream', disabled: true }];
2584
+
2585
+ $('pm-title').textContent = title;
2586
+ const box = $('pm-list');
2587
+ box.textContent = '';
2588
+ let focusEl = null;
2589
+ items.forEach(it => {
2590
+ const el = h('div', { class: 'menu-item' + (it.disabled ? ' disabled' : ' focusable') }, [
2591
+ h('span', { class: 'check', html: it.checked ? icon('check') : '' }),
2592
+ h('span', { text: it.label }),
2593
+ it.val != null ? h('span', { class: 'val', text: it.val }) : null
2594
+ ]);
2595
+ if (!it.disabled) el.addEventListener('click', it.onSelect);
2596
+ box.appendChild(el);
2597
+ if ((focusKey && it.key === focusKey) || (!focusKey && it.checked)) focusEl = el;
2598
+ });
2599
+ $('pm-scroll').scrollTop = 0;
2600
+ Nav.focus(focusEl || Nav.first(this.el) || box.firstChild);
2601
+ }
2602
+ };
2603
+
2604
+ /* =====================================================================
2605
+ * OTT Provider Selector Modal
2606
+ * ===================================================================== */
2607
+
2608
+ /* =====================================================================
2609
+ * Season Selection Modal
2610
+ * ===================================================================== */
2611
+ const SeasonModal = {
2612
+ el: $('season-modal'),
2613
+ open() {
2614
+ this.render();
2615
+ Nav.push(this);
2616
+ },
2617
+ render() {
2618
+ var box = $('season-list');
2619
+ box.textContent = '';
2620
+ var seasons = (Detail.item && Detail.item.seasons) || [];
2621
+ var current = Detail.season;
2622
+ seasons.forEach(function (s, idx) {
2623
+ var active = current === idx;
2624
+ var el = h('div', { class: 'season-item focusable' + (active ? ' active' : '') }, [
2625
+ h('span', { class: 'season-name', text: s.title || ('Season ' + (s.season || (idx + 1))) }),
2626
+ h('span', { class: 'season-check', html: active ? icon('check') : '' })
2627
+ ]);
2628
+ el.addEventListener('click', function () {
2629
+ Nav.close(SeasonModal);
2630
+ Detail.selectSeason(idx);
2631
+ });
2632
+ box.appendChild(el);
2633
+ });
2634
+ if (!seasons.length) {
2635
+ box.appendChild(h('div', { class: 'season-item', text: 'No seasons available' }));
2636
+ }
2637
+ Nav.focus(box.children[current] || Nav.first(this.el));
2638
+ }
2639
+ };
2640
+
2641
+ const OttModal = {
2642
+ el: $('ott-modal'), providers: [],
2643
+ onOpen() { this.load(); },
2644
+ load() {
2645
+ var self = this;
2646
+ UI.loading(true, 'Loading providers…');
2647
+ NM.ott().then(function (list) {
2648
+ UI.loading(false);
2649
+ self.providers = Array.isArray(list) && list.length ? list : NM.DEFAULT_PROVIDERS;
2650
+ // If current ott is not valid or empty, set to first provider
2651
+ var current = NM.storage.getOtt();
2652
+ var exists = self.providers.some(function (p) { return p.id === current; });
2653
+ if (!exists && self.providers.length) {
2654
+ NM.storage.setOtt(self.providers[0].id);
2655
+ }
2656
+ self.render();
2657
+ }).catch(function (e) {
2658
+ UI.loading(false);
2659
+ self.providers = NM.DEFAULT_PROVIDERS;
2660
+ self.render();
2661
+ UI.toast('Using default providers: ' + e.message);
2662
+ });
2663
+ },
2664
+ render() {
2665
+ var box = $('ott-list');
2666
+ box.textContent = '';
2667
+ var current = NM.storage.getOtt();
2668
+ this.providers.forEach(function (p) {
2669
+ var name = p.name || p.title || p.id || '';
2670
+ var id = p.id || name.toLowerCase();
2671
+ var active = current === id;
2672
+ var el = h('div', { class: 'ott-item focusable' + (active ? ' active' : '') }, [
2673
+ p.logo ? h('img', { class: 'ott-logo', src: p.logo, alt: name }) : null,
2674
+ h('span', { class: 'ott-name', text: name }),
2675
+ h('span', { class: 'ott-check', html: active ? icon('check') : '' })
2676
+ ]);
2677
+ el.addEventListener('click', function () {
2678
+ NM.storage.setOtt(id);
2679
+ Nav.close(OttModal);
2680
+ UI.toast('Switched to ' + name);
2681
+ Home.load();
2682
+ });
2683
+ box.appendChild(el);
2684
+ });
2685
+ if (!this.providers.length) {
2686
+ box.appendChild(h('div', { class: 'ott-item', text: 'No providers available' }));
2687
+ }
2688
+ Nav.focus(Nav.first(this.el));
2689
+ }
2690
+ };
2691
+
2692
+ /* =====================================================================
2693
+ * OTP Screen — 6-digit verification (NetMirror auth flow)
2694
+ * ===================================================================== */
2695
+ const OtpScreen = {
2696
+ el: $('otp'), full: true,
2697
+ init() {
2698
+ if (!this.el) return;
2699
+ $('otp-logo').textContent = CONFIG.APP_NAME;
2700
+ var input = $('otp-input');
2701
+ $('otp-osk').appendChild(Keyboard(input));
2702
+ var btnQuick = $('otp-quick');
2703
+ if (btnQuick) {
2704
+ btnQuick.addEventListener('click', function () {
2705
+ $('otp-input').value = '111111';
2706
+ OtpScreen.verify();
2707
+ });
2708
+ }
2709
+ $('otp-verify').addEventListener('click', function () { OtpScreen.verify(); });
2710
+ $('otp-retry').addEventListener('click', function () {
2711
+ $('otp-input').value = '';
2712
+ $('otp-status').textContent = '';
2713
+ $('otp-status').className = 'otp-status';
2714
+ Nav.focus($('otp-input'));
2715
+ });
2716
+ input._onSubmit = function () { OtpScreen.verify(); };
2717
+ },
2718
+ open(data) {
2719
+ if (!this.el) return;
2720
+ UI.loading(false);
2721
+ $('otp-input').value = '';
2722
+ $('otp-status').textContent = '';
2723
+ $('otp-status').className = 'otp-status';
2724
+
2725
+ var pubBox = $('otp-pub');
2726
+ if (pubBox) {
2727
+ pubBox.textContent = '';
2728
+ var qrUrl = 'https://tv.imgcdn.kim/otp2.jpg';
2729
+ var rawImg = (data && data.pub_msg_img) || NM.storage.get('pub_msg_img');
2730
+ if (rawImg) {
2731
+ try {
2732
+ var parsedImg = typeof rawImg === 'string' ? JSON.parse(rawImg) : rawImg;
2733
+ if (parsedImg && parsedImg.img) qrUrl = parsedImg.img;
2734
+ } catch (e) {}
2735
+ }
2736
+ var proxiedQr = typeof NM !== 'undefined' && typeof NM.proxyMediaUrl === 'function' ? NM.proxyMediaUrl(qrUrl) : qrUrl;
2737
+ pubBox.appendChild(h('div', { class: 'pub-text', text: 'Scan with your phone or visit NetMirror to get your 6-digit OTP code:' }));
2738
+ pubBox.appendChild(h('img', { src: proxiedQr, alt: 'Scan QR for OTP', style: 'max-height:280px;max-width:320px;border-radius:8px;border:2px solid #555;margin-top:10px;' }));
2739
+ }
2740
+
2741
+ Nav.push(this, $('otp-input'));
2742
+ },
2743
+ onBack() {
2744
+ Nav.close(OtpScreen);
2745
+ return true;
2746
+ },
2747
+ verify() {
2748
+ var code = ($('otp-input').value || '').trim();
2749
+ if (code.length !== 6 || !/^\d{6}$/.test(code)) {
2750
+ $('otp-status').textContent = 'Please enter a 6-digit numeric code';
2751
+ $('otp-status').className = 'otp-status error';
2752
+ return;
2753
+ }
2754
+ $('otp-status').textContent = 'Verifying with server…';
2755
+ $('otp-status').className = 'otp-status';
2756
+ $('otp-verify').classList.add('disabled');
2757
+
2758
+ NM.otp(code).then(function (data) {
2759
+ $('otp-verify').classList.remove('disabled');
2760
+ if (data && data.status === 'ok') {
2761
+ $('otp-status').textContent = 'Verification Successful! Loading content…';
2762
+ $('otp-status').className = 'otp-status success';
2763
+ setTimeout(function () {
2764
+ Nav.close(OtpScreen);
2765
+ Home.load();
2766
+ }, 1200);
2767
+ } else {
2768
+ var msg = (data && data.error_msg) || 'Invalid OTP code. Please check and try again.';
2769
+ $('otp-status').textContent = msg;
2770
+ $('otp-status').className = 'otp-status error';
2771
+ if (typeof DebugDrawer !== 'undefined') DebugDrawer.show(true);
2772
+ }
2773
+ }).catch(function (e) {
2774
+ $('otp-verify').classList.remove('disabled');
2775
+ $('otp-status').textContent = 'Error: ' + e.message;
2776
+ $('otp-status').className = 'otp-status error';
2777
+ if (typeof DebugDrawer !== 'undefined') DebugDrawer.show(true);
2778
+ });
2779
+ }
2780
+ };
2781
+
2782
+
2783
+ /* =====================================================================
2784
+ * DebugDrawer — On-Screen Live Diagnostics for Samsung Tizen TV
2785
+ * ===================================================================== */
2786
+ const DebugDrawer = {
2787
+ el: null,
2788
+ visible: false,
2789
+ init() {
2790
+ this.el = $('debug-drawer');
2791
+ if (!this.el) return;
2792
+ var self = this;
2793
+ var btnCopy = $('dbg-copy');
2794
+ if (btnCopy) btnCopy.addEventListener('click', function () { self.copyDebug(); });
2795
+ var btnToggle = $('dbg-toggle');
2796
+ if (btnToggle) btnToggle.addEventListener('click', function () { self.toggleBody(); });
2797
+ var btnReload = $('dbg-reload');
2798
+ if (btnReload) btnReload.addEventListener('click', function () { location.reload(); });
2799
+ var btnClose = $('dbg-close');
2800
+ if (btnClose) btnClose.addEventListener('click', function () { self.close(); });
2801
+ var hdrDebug = $('hdr-debug');
2802
+ if (hdrDebug) hdrDebug.addEventListener('click', function () { self.toggle(); });
2803
+ NM.onDebugUpdate = function () { if (self.visible) self.render(); };
2804
+ },
2805
+ open() {
2806
+ this.visible = true;
2807
+ if (this.el) {
2808
+ this.el.classList.remove('hidden');
2809
+ this.render();
2810
+ }
2811
+ if (!Nav.has(this)) {
2812
+ Nav.push(this, $('dbg-close'));
2813
+ } else {
2814
+ Nav.focus($('dbg-close'));
2815
+ }
2816
+ },
2817
+ close() {
2818
+ this.visible = false;
2819
+ if (this.el) this.el.classList.add('hidden');
2820
+ if (Nav.has(this)) {
2821
+ Nav.close(this);
2822
+ }
2823
+ },
2824
+ show(val) {
2825
+ if (val) this.open();
2826
+ else this.close();
2827
+ },
2828
+ toggle() {
2829
+ if (this.visible) this.close();
2830
+ else this.open();
2831
+ },
2832
+ onBack() {
2833
+ this.close();
2834
+ return true; // Return/Back on TV remote closes debug drawer
2835
+ },
2836
+ onKey(key) {
2837
+ var body = $('dbg-body');
2838
+ if (!body || body.classList.contains('hidden')) return false;
2839
+
2840
+ if (key === 'DOWN') {
2841
+ body.scrollTop += 140;
2842
+ return true;
2843
+ } else if (key === 'UP') {
2844
+ if (body.scrollTop > 10) {
2845
+ body.scrollTop = Math.max(0, body.scrollTop - 140);
2846
+ return true;
2847
+ }
2848
+ return false; // let UP move focus to action buttons
2849
+ }
2850
+ return false;
2851
+ },
2852
+ copyDebug() {
2853
+ var prx = (typeof NM !== 'undefined' && NM.getProxyUrl && NM.getProxyUrl()) || 'http://127.0.0.1:8787';
2854
+ var txt = (typeof NM !== 'undefined' && NM.exportDebugLog && NM.exportDebugLog()) || '';
2855
+ if (!txt) {
2856
+ var info = (typeof NM !== 'undefined' && NM.getDebugInfo) ? NM.getDebugInfo() : {};
2857
+ txt = '=== NETMIRROR TV DIAGNOSTICS ===\n' +
2858
+ 'API: ' + (info.apiUrl || 'Unresolved') + '\n' +
2859
+ 'OTT: ' + (info.ott || 'None') + '\n' +
2860
+ 'Token: ' + (info.usertoken || 'Missing') + '\n' +
2861
+ 'Proxy: ' + (info.proxyUrl || 'Direct') + '\n';
2862
+ }
2863
+
2864
+ // 1. Copy to clipboard
2865
+ var copied = false;
2866
+ try {
2867
+ if (navigator.clipboard && navigator.clipboard.writeText) {
2868
+ navigator.clipboard.writeText(txt);
2869
+ copied = true;
2870
+ }
2871
+ } catch (e) {}
2872
+
2873
+ if (!copied) {
2874
+ try {
2875
+ var ta = document.createElement('textarea');
2876
+ ta.value = txt;
2877
+ ta.style.position = 'fixed';
2878
+ ta.style.opacity = '0';
2879
+ document.body.appendChild(ta);
2880
+ ta.select();
2881
+ copied = document.execCommand('copy');
2882
+ document.body.removeChild(ta);
2883
+ } catch (e2) {}
2884
+ }
2885
+
2886
+ // 2. Sync to proxy so PC/phone can view live
2887
+ if (typeof NM !== 'undefined' && NM.syncDebugToProxy) {
2888
+ NM.syncDebugToProxy();
2889
+ }
2890
+
2891
+ // 3. Show selectable overlay on TV screen
2892
+ this.showCopyOverlay(txt, prx);
2893
+ UI.toast('Debug copied! Also available at ' + prx + '/proxy/debug');
2894
+ },
2895
+ showCopyOverlay(txt, prx) {
2896
+ var modal = $('dbg-copy-modal');
2897
+ if (!modal) return;
2898
+ var ta = $('dbg-copy-textarea');
2899
+ if (ta) ta.value = txt;
2900
+ var hint = $('dbg-copy-hint');
2901
+ if (hint) hint.textContent = 'Copied to clipboard. You can also view/copy on PC/phone at: ' + prx + '/proxy/debug';
2902
+ modal.classList.remove('hidden');
2903
+
2904
+ var closeBtn = $('dbg-copy-close');
2905
+ if (closeBtn) {
2906
+ closeBtn.onclick = function () {
2907
+ modal.classList.add('hidden');
2908
+ if (DebugDrawer.el) Nav.focus(Nav.first(DebugDrawer.el));
2909
+ };
2910
+ Nav.focus(closeBtn);
2911
+ }
2912
+ },
2913
+ toggleBody() {
2914
+ var b = $('dbg-body');
2915
+ if (b) b.classList.toggle('hidden');
2916
+ },
2917
+ render() {
2918
+ var info = NM.getDebugInfo ? NM.getDebugInfo() : {};
2919
+ var apiEl = $('dbg-api');
2920
+ if (apiEl) apiEl.textContent = 'API: ' + (info.apiUrl || 'Unresolved');
2921
+ var ottEl = $('dbg-ott');
2922
+ if (ottEl) ottEl.textContent = 'OTT: ' + (info.ott || 'None');
2923
+ var tokEl = $('dbg-token');
2924
+ if (tokEl) tokEl.textContent = 'TOKEN: ' + (info.usertoken || 'Missing');
2925
+ var prxEl = $('dbg-proxy');
2926
+ if (prxEl) prxEl.textContent = 'PROXY: ' + (info.proxyUrl || 'Direct WebKit');
2927
+
2928
+ var logsEl = $('dbg-logs');
2929
+ if (logsEl && info.calls) {
2930
+ logsEl.textContent = info.calls.map(function (c) {
2931
+ return '[' + c.time + '] ' + c.name.toUpperCase() + ' (HTTP ' + c.status + ')' +
2932
+ (c.resStatus ? (' status="' + c.resStatus + '"') : '') +
2933
+ (c.keys && c.keys.length ? (' keys=[' + c.keys.join(',') + ']') : '') +
2934
+ (c.error ? (' ERROR: ' + c.error) : '') +
2935
+ '\n URL: ' + c.url +
2936
+ (c.snippet ? ('\n Snippet: ' + c.snippet) : '');
2937
+ }).join('\n\n');
2938
+ }
2939
+ }
2940
+ };
2941
+
2942
+ /* =====================================================================
2943
+ * App shell — keys, startup
2944
+ * ===================================================================== */
2945
+ const KEYMAP = {
2946
+ 37: 'LEFT', 38: 'UP', 39: 'RIGHT', 40: 'DOWN', 13: 'ENTER', 48: 'DEBUG', 68: 'DEBUG', 100: 'DEBUG', 10107: 'DEBUG',
2947
+ 10009: 'BACK', 8: 'BACK', 27: 'BACK', // Tizen Return; Backspace/Esc for browser testing
2948
+ 415: 'PLAY', 19: 'PAUSE', 10252: 'PLAYPAUSE', 413: 'STOP', 417: 'FF', 412: 'RW'
2949
+ };
2950
+ const IME_DONE = 65376, IME_CANCEL = 65385;
2951
+
2952
+ const App = {
2953
+ exit() {
2954
+ try { tizen.application.getCurrentApplication().exit(); }
2955
+ catch (e) { UI.toast('Exit requested (not running on a Tizen TV)'); }
2956
+ },
2957
+ registerKeys() {
2958
+ try {
2959
+ ['MediaPlay', 'MediaPause', 'MediaPlayPause', 'MediaStop', 'MediaFastForward', 'MediaRewind']
2960
+ .forEach(k => tizen.tvinputdevice.registerKey(k));
2961
+ } catch (e) { /* not on Tizen */ }
2962
+ },
2963
+ onSettingsChanged(k) {
2964
+ if (k.indexOf('sub') === 0) SubStyle.apply();
2965
+ Player.onSettingsChanged(k);
2966
+ if (Nav.has(Detail)) Detail.updateHint();
2967
+ },
2968
+ onProfileChanged() {
2969
+ Home.refreshHeader();
2970
+ SubStyle.apply();
2971
+ if (Nav.has(Detail)) Detail.updateHint();
2972
+ },
2973
+ onKeyDown(e) {
2974
+ const code = e.keyCode;
2975
+ const ae = document.activeElement;
2976
+
2977
+ // Text input with the TV's IME open: let typing through, handle exit keys.
2978
+ if (ae && ae.tagName === 'INPUT') {
2979
+ if (code === 13 || code === IME_DONE) { e.preventDefault(); ae.blur(); if (ae._onSubmit) ae._onSubmit(); return; }
2980
+ if (code === IME_CANCEL || code === 10009 || code === 27) { e.preventDefault(); ae.blur(); return; }
2981
+ if (code === 38 || code === 40) { e.preventDefault(); ae.blur(); Nav.move(KEYMAP[code]); return; }
2982
+ return;
2983
+ }
2984
+
2985
+ const key = KEYMAP[code];
2986
+ if (!key) return;
2987
+ e.preventDefault();
2988
+
2989
+ // Toggle debug with '0', 'D', or 'Guide' key
2990
+ if (key === 'DEBUG') {
2991
+ DebugDrawer.toggle();
2992
+ return;
2993
+ }
2994
+
2995
+ // Direct close of DebugDrawer on BACK
2996
+ if (DebugDrawer.visible && key === 'BACK') {
2997
+ DebugDrawer.close();
2998
+ return;
2999
+ }
3000
+
3001
+ const layer = Nav.top();
3002
+ if (!layer) return;
3003
+ if (layer.onKey && layer.onKey(key)) return;
3004
+
3005
+ const f = Nav.focused && layer.el.contains(Nav.focused) ? Nav.focused : null;
3006
+ if ((key === 'LEFT' || key === 'RIGHT') && f && f._cycle) { f._cycle(key === 'LEFT' ? -1 : 1); return; }
3007
+ switch (key) {
3008
+ case 'UP': case 'DOWN': case 'LEFT': case 'RIGHT': Nav.move(key); break;
3009
+ case 'ENTER':
3010
+ if (!f) Nav.focus(Nav.first(layer.el));
3011
+ else if (f.tagName === 'INPUT') f.focus(); // opens the on-screen IME
3012
+ else f.click();
3013
+ break;
3014
+ case 'BACK':
3015
+ if (!(layer.onBack && layer.onBack())) Nav.close(layer);
3016
+ break;
3017
+ }
3018
+ },
3019
+ start() {
3020
+ Screen.fit();
3021
+ window.addEventListener('resize', () => Screen.fit());
3022
+ Store.load();
3023
+ SubStyle.apply();
3024
+ App.registerKeys();
3025
+ [Home, Search, Detail, Player, Profiles, ProfileEdit, Confirm, OtpScreen, OttModal, DebugDrawer].forEach(l => { if (l.init) l.init(); });
3026
+ document.addEventListener('keydown', App.onKeyDown);
3027
+ document.addEventListener('mouseover', e => {
3028
+ const f = e.target.closest ? e.target.closest('.focusable') : null;
3029
+ const t = Nav.top();
3030
+ if (f && t && t.el.contains(f) && f !== Nav.focused) Nav.focus(f, { noScroll: true });
3031
+ });
3032
+ document.addEventListener('visibilitychange', () => {
3033
+ if (document.hidden && Player.item) Player.video.pause(); // app moved to background
3034
+ });
3035
+
3036
+ Home.refreshHeader();
3037
+ Nav.push(Home);
3038
+ Profiles.open(true);
3039
+
3040
+ // NetMirror domain resolution + OTP hook
3041
+ NM.onOtpRequired = function (data) { OtpScreen.open(data); };
3042
+ UI.loading(true, 'Connecting…');
3043
+ NM.detectProxy().then(function (prx) {
3044
+ if (prx) console.log('Connected to local proxy:', prx);
3045
+ return NM.resolve();
3046
+ }).then(function () {
3047
+ return Home.load();
3048
+ }).catch(function (e) {
3049
+ UI.loading(false);
3050
+ UI.toast('Connection error: ' + (e ? e.message : 'Check internet connection'), 'error');
3051
+ if (typeof DebugDrawer !== 'undefined') DebugDrawer.show(true);
3052
+ });
3053
+ }
3054
+ };
3055
+
3056
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', App.start);
3057
+ else App.start();
3058
+ })();