File size: 21,819 Bytes
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
<!DOCTYPE html>
<html lang="en" class="{{ 'dark' if theme.is_dark else 'light' }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Install Telegram Stremio Addon</title>

<meta name="theme-color" content="{{ theme.colors.background }}">
<link rel="icon" type="image/svg+xml" href="/pwa-icon.svg">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
:root {
    color-scheme: {{ 'dark' if theme.is_dark else 'light' }};
    --primary: {{ theme.colors.primary }};
    --on-primary: {{ theme.colors.on_primary }};
    --card-high: {{ theme.colors.card_high }};
    --ok: {{ theme.colors.ok }};
    --danger: {{ theme.colors.danger }};
    --secondary: var(--primary);
    --accent: var(--primary);
    --bg: {{ theme.colors.background }};
    --card: {{ theme.colors.card }};
    --border: {{ theme.colors.border }};
    --text: {{ theme.colors.text }};
    --text-sec: {{ theme.colors.text_secondary }};
    --surface: color-mix(in srgb, var(--text) 5%, transparent);
    --surface-2: color-mix(in srgb, var(--text) 9%, transparent);
    --hairline: var(--border);
    --hairline-strong: color-mix(in srgb, var(--text) 20%, transparent);
    --ring: color-mix(in srgb, var(--primary) 35%, transparent);
    --shadow-color: {{ '0,0,0' if theme.is_dark else '15,23,42' }};
}

* { box-sizing: border-box; margin: 0; padding: 0; }
button, input, select, textarea { font-family: inherit; }

body {
    font-family: 'Space Grotesk', system-ui, -apple-system, 'Segoe UI', sans-serif;
    -webkit-font-smoothing: antialiased;
    background-color: var(--bg);
    color: var(--text);
    min-height: 100vh;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: clamp(16px, 4vw, 40px);
}

.wrap { width: 100%; max-width: 960px; margin: auto; }
.layout { display: grid; gap: 16px; grid-template-columns: minmax(0, 1fr); align-items: start; }
.layout > * { min-width: 0; }
@media (min-width: 860px) { .layout { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } }


.card {
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: clamp(24px, 4vw, 36px);
    width: 100%;
    text-align: center;
}

.brand { display: flex; align-items: center; justify-content: center; gap: 12px; margin-bottom: 20px; }
.brand-logo {
    width: 44px; height: 44px; border-radius: 14px;
    background: var(--primary); color: var(--on-primary);
    display: flex; align-items: center; justify-content: center;
    font-size: 1rem;
}
.brand-name {
    font-size: 1.4rem; font-weight: 600; letter-spacing: -0.01em; color: var(--text);
}

h1 { font-size: 1.15rem; font-weight: 600; color: var(--text); margin-bottom: 6px; }
.sub-title { color: var(--text-sec); font-size: 0.85rem; margin-bottom: 26px; line-height: 1.5; }

.info-row {
    display: flex; justify-content: space-between; align-items: center;
    background: var(--surface); border: 1px solid var(--hairline);
    border-radius: 0.85rem; padding: 12px 16px; margin-bottom: 10px; font-size: 0.88rem;
}
.info-label { color: var(--text-sec); font-weight: 500; }
.info-val { font-weight: 600; color: var(--text); }
.status-badge {
    display: inline-flex; align-items: center; gap: 0.35rem;
    padding: 3px 12px; border-radius: 9999px; font-size: 0.78rem; font-weight: 600;
    background: color-mix(in srgb, {{ 'var(--ok)' if status_text == 'Active' else 'var(--danger)' }} 14%, transparent); color: {{ 'var(--ok)' if status_text == 'Active' else 'var(--danger)' }};
}

.btn-install {
    display: flex; align-items: center; justify-content: center; gap: 0.6rem;
    width: 100%; margin: 26px 0 12px;
    background: var(--primary);
    color: var(--on-primary); font-weight: 500; font-size: 0.98rem;
    padding: 13px 24px; border-radius: 9999px; border: none;
    cursor: pointer; text-decoration: none;
    transition: filter .2s ease, transform .12s ease;
}
.btn-install:hover { filter: brightness(1.08); }
.btn-install:active { transform: scale(.98); }

.btn-web {
    display: block; color: var(--primary); font-size: 0.82rem;
    font-weight: 600; text-decoration: none; margin-bottom: 22px;
}
.btn-web:hover { text-decoration: underline; }

.steps {
    background: var(--surface); border: 1px solid var(--hairline);
    border-radius: 0.85rem; padding: 14px 18px; margin: 16px 0;
    text-align: left; font-size: 0.85rem; color: var(--text-sec);
}
.steps b { color: var(--text); }
.steps ol { margin-top: 8px; margin-left: 18px; line-height: 1.9; }

.url-box {
    background: color-mix(in srgb, var(--bg) 70%, var(--card));
    border: 1px solid var(--hairline); border-radius: 0.7rem;
    padding: 10px 14px; font-family: 'JetBrains Mono', ui-monospace, monospace;
    font-size: 0.72rem; color: var(--text-sec);
    word-break: break-all; text-align: left; margin-top: 16px;
}

.btn-copy {
    margin-top: 10px; width: 100%; padding: 10px;
    background: var(--surface); border: 1px solid var(--hairline); color: var(--text-sec);
    border-radius: 9999px; cursor: pointer; font-size: 0.85rem; font-weight: 500;
    transition: background .2s ease, color .2s ease, border-color .2s ease;
}
.btn-copy:hover { background: var(--surface-2); color: var(--text); border-color: var(--hairline-strong); }
</style>
<script>
/* Clipboard API needs HTTPS; fall back to execCommand on plain-HTTP LAN access */
if (!navigator.clipboard) Object.defineProperty(navigator, 'clipboard', { value: { writeText: t => new Promise((ok, fail) => {
    const a = document.createElement('textarea');
    a.value = t; a.style.cssText = 'position:fixed;opacity:0';
    document.body.appendChild(a); a.select();
    const done = document.execCommand('copy'); a.remove();
    done ? ok() : fail(new Error('Copy failed'));
}) } });
</script>
</head>
<body>
<div class="wrap">
<div class="layout">
<div class="card">
    <div class="brand">
        <div class="brand-logo"><i class="fa-solid fa-play"></i></div>
        <span class="brand-name">TG Stremio</span>
    </div>

    <h1>Install / Update Addon</h1>
    <p class="sub-title">Add or refresh your personal Telegram library inside Stremio.</p>

    <div class="info-row">
        <span class="info-label">User</span>
        <span class="info-val">{{ user_name }}</span>
    </div>
    <div class="info-row">
        <span class="info-label">Status</span>
        <span class="status-badge">{{ status_text }}</span>
    </div>
    <div class="info-row">
        <span class="info-label">Expires</span>
        <span class="info-val">{{ expiry_str }}</span>
    </div>

    <a href="{{ web_install_url }}" class="btn-install" target="_blank">
        <i class="fa-solid fa-bolt"></i> Install / Update in Stremio
    </a>

    <div class="steps">
        <b>Prefer to do it manually?</b>
        <ol>
            <li>Open Stremio and go to the <b>Add-ons</b> tab</li>
            <li>Click the <b>Search / URL</b> field</li>
            <li>Paste the URL below and press Enter</li>
        </ol>
    </div>

    <div class="url-box" id="murl">{{ manifest_url }}</div>
    <button onclick="copyUrl()" class="btn-copy"><i class="fa-solid fa-copy"></i> Copy URL</button>
</div>

<div class="card" style="text-align:left">
    <h1 style="text-align:center"><i class="fa-solid fa-sliders"></i> Personalize</h1>
    <p class="sub-title" style="text-align:center">Tune quality and catalogs for your install. Re-install after saving.</p>

    <div class="cfg-block">
        <div class="cfg-title">Stream quality order</div>
        <div class="seg" id="cfg-sort">
            <button type="button" data-val="desc" class="seg-btn active" onclick="setSort('desc')">Highest first</button>
            <button type="button" data-val="asc" class="seg-btn" onclick="setSort('asc')">Lowest first</button>
        </div>
    </div>

    <div class="cfg-block">
        <div class="cfg-title">Show only these qualities</div>
        <div class="chips" id="cfg-quality"></div>
        <p class="cfg-hint">Leave all off to show every quality.</p>
    </div>

    <div class="cfg-block" id="cfg-via-block" style="display:none">
        <div class="cfg-title">Stream with <span class="ob-badge"><i class="fa-solid fa-cloud"></i> Cloudflare proxy enabled</span></div>
        <div class="seg" id="cfg-via">
            <button type="button" data-val="bots" class="seg-btn" onclick="setVia('bots')">My bots</button>
            <button type="button" data-val="cloudflare" class="seg-btn" onclick="setVia('cloudflare')">Cloudflare</button>
            <button type="button" data-val="both" class="seg-btn" onclick="setVia('both')">Both</button>
        </div>
    </div>

    <div class="cfg-block">
        <div class="cfg-title">Catalogs</div>
        <div id="cfg-catalogs" class="cfg-catalogs"></div>
        <p class="cfg-hint">Toggle to hide a catalog; use arrows to reorder.</p>
    </div>

    <button onclick="saveConfig()" class="btn-install" id="cfg-save" style="margin-top:8px">
        <i class="fa-solid fa-floppy-disk"></i> Save preferences
    </button>
    <p id="cfg-state" class="cfg-hint" style="text-align:center"></p>
</div>

<div class="card ob-card" id="ob-card" style="display:none">
    <h1 style="text-align:center"><i class="fa-solid fa-robot"></i> Your own bots</h1>
    <p class="sub-title" style="text-align:center">Stream through your own bots. Files are copied to your private channel and removed a day after you last watch them.</p>

    <div class="steps">
        <b>Setup</b>
        <ol>
            <li>Create a private Telegram channel</li>
            <li>Add your bots to it as admins</li>
            <li>Add <b id="ob-helpers"></b> as admin with <b>Post</b> and <b>Delete messages</b> rights</li>
            <li>Paste the channel ID and your bot tokens below, then verify</li>
        </ol>
    </div>

    <div class="cfg-block">
        <div class="cfg-title">Channel ID</div>
        <input id="ob-channel" class="ob-input" placeholder="-100xxxxxxxxxx" spellcheck="false">
    </div>

    <div class="cfg-block">
        <div class="cfg-title">Bots</div>
        <div id="ob-bots" class="cfg-catalogs"></div>
        <div class="ob-add">
            <input id="ob-token" class="ob-input" placeholder="Bot token (1234567890:ABC…)" spellcheck="false"
                onkeydown="if(event.key==='Enter'){event.preventDefault();addBot()}">
            <button type="button" class="cfg-eye ob-plus" onclick="addBot()" aria-label="Add bot"><i class="fa-solid fa-plus"></i></button>
        </div>
        <p class="cfg-hint">Changes apply after you verify.</p>
    </div>

    <button onclick="saveBots()" class="btn-install" id="ob-save" style="margin-top:8px">
        <i class="fa-solid fa-circle-check"></i> Save &amp; verify
    </button>
    <button onclick="disableBots()" class="btn-copy" id="ob-off" style="display:none">Turn off own bots</button>
    <div id="ob-checks" class="cfg-catalogs" style="margin-top:12px"></div>
</div>
</div>
</div>

<style>
.cfg-block { margin: 14px 0; }
.cfg-title { font-size: .8rem; font-weight: 600; text-transform: uppercase; letter-spacing: .05em; color: var(--text-sec); margin-bottom: 8px; }
.cfg-hint { font-size: .72rem; color: var(--text-sec); margin-top: 6px; }
.seg { display: flex; gap: 6px; background: var(--surface); border: 1px solid var(--hairline); border-radius: .8rem; padding: 4px; }
.seg-btn { flex: 1; padding: 9px; border-radius: .6rem; border: none; background: transparent; color: var(--text-sec); font-weight: 600; font-size: .82rem; cursor: pointer; }
.seg-btn.active { background: var(--primary); color: #fff; }
.chips { display: flex; flex-wrap: wrap; gap: 8px; }
.qchip { padding: 7px 14px; border-radius: 9999px; border: 1px solid var(--hairline); background: var(--surface); color: var(--text); font-weight: 600; font-size: .8rem; cursor: pointer; }
.qchip.on { background: linear-gradient(135deg, var(--primary), var(--accent)); color: #fff; border-color: transparent; }
.cfg-catalogs { display: flex; flex-direction: column; gap: 6px; }
.cfg-cat { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid var(--hairline); border-radius: .7rem; background: var(--surface); }
.cfg-cat.hidden-cat { opacity: .5; }
.cfg-cat .nm { flex: 1; min-width: 0; font-weight: 600; font-size: .85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cfg-eye, .cfg-arr { width: 30px; height: 26px; border-radius: .5rem; border: 1px solid var(--hairline); background: var(--bg); color: var(--text); cursor: pointer; font-size: .72rem; }
.cfg-arr:disabled { opacity: .35; cursor: not-allowed; }
.ob-card { text-align: left; grid-column: 1 / -1; }
.ob-input { width: 100%; padding: 10px 12px; border-radius: .7rem; border: 1px solid var(--hairline); background: var(--surface); color: var(--text); font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: .8rem; }
.ob-input:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
.ob-add { display: flex; gap: 8px; margin-top: 8px; }
.ob-plus { width: 42px; height: auto; flex-shrink: 0; }
.ob-badge { margin-left: 6px; padding: 2px 8px; border-radius: 9999px; font-size: .68rem; text-transform: none; letter-spacing: 0; color: var(--ok); background: color-mix(in srgb, var(--ok) 14%, transparent); }
.ob-check small { display: block; font-weight: 500; color: var(--text-sec); white-space: normal; }
</style>

<script>
const QUALITIES = ['480p', '720p', '1080p', '4K'];
let cfg = { quality_sort: 'desc', quality_filter: [], hidden_catalogs: [], catalog_order: [], stream_via: 'bots' };
let cfgCatalogs = [];
let ob = { bots: [] };
let obAdd = [];
const TOKEN_RE = /^\d{5,}:[\w-]{30,}$/;

function setVia(v) {
    cfg.stream_via = v;
    document.querySelectorAll('#cfg-via .seg-btn').forEach(b => b.classList.toggle('active', b.dataset.val === v));
}

function renderBots() {
    const rows = ob.bots.map((b, i) => `<div class="cfg-cat">
            <span class="nm">@${escapeCfg(b.username || b.id)}</span>
            <button class="cfg-eye" onclick="removeBot(${i})" aria-label="Remove"><i class="fa-solid fa-xmark"></i></button>
        </div>`).concat(obAdd.map((t, i) => `<div class="cfg-cat">
            <span class="nm">${escapeCfg(t.split(':')[0])} <small style="opacity:.6">· new</small></span>
            <button class="cfg-eye" onclick="removeNew(${i})" aria-label="Remove"><i class="fa-solid fa-xmark"></i></button>
        </div>`));
    document.getElementById('ob-bots').innerHTML = rows.join('') || '<p class="cfg-hint">No bots added yet.</p>';
}

function renderOwnBots(v) {
    ob = Object.assign({ bots: [] }, v);
    obAdd = [];
    document.getElementById('ob-card').style.display = ob.available ? '' : 'none';
    document.getElementById('ob-helpers').textContent = (ob.helpers || []).map(h => '@' + h).join(', ');
    document.getElementById('ob-channel').value = ob.channel || '';
    document.getElementById('ob-off').style.display = ob.enabled ? '' : 'none';
    document.getElementById('cfg-via-block').style.display = ob.enabled && ob.cloudflare ? '' : 'none';
    renderBots();
}

function renderChecks(checks, ok) {
    document.getElementById('ob-checks').innerHTML = checks.map(c => `<div class="cfg-cat ob-check">
            <i class="fa-solid ${c.ok ? 'fa-circle-check' : 'fa-circle-xmark'}" style="color:var(${c.ok ? '--ok' : '--danger'})"></i>
            <span class="nm">${escapeCfg(c.label)}${c.detail ? `<small>${escapeCfg(c.detail)}</small>` : ''}</span>
        </div>`).join('') + `<p class="cfg-hint">${ok ? 'All checks passed. Your bots are on.' : 'Fix the failed checks and verify again.'}</p>`;
}

function addBot() {
    const input = document.getElementById('ob-token');
    const t = input.value.trim();
    if (!TOKEN_RE.test(t)) { document.getElementById('ob-checks').innerHTML = '<p class="cfg-hint">That does not look like a bot token.</p>'; return; }
    const id = Number(t.split(':')[0]);
    if (!obAdd.includes(t) && !ob.bots.some(b => b.id === id)) obAdd.push(t);
    input.value = '';
    renderBots();
}

function removeBot(i) { ob.bots.splice(i, 1); renderBots(); }
function removeNew(i) { obAdd.splice(i, 1); renderBots(); }

async function saveBots() {
    const btn = document.getElementById('ob-save');
    const out = document.getElementById('ob-checks');
    btn.disabled = true;
    out.innerHTML = '<p class="cfg-hint">Verifying…</p>';
    try {
        const res = await fetch('own-bots', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ channel: document.getElementById('ob-channel').value.trim(), keep: ob.bots.map(b => b.id), add: obAdd })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Could not verify.');
        renderChecks(data.checks, data.ok);
        if (data.ok) await loadConfig();
    } catch (e) {
        out.innerHTML = `<p class="cfg-hint">${escapeCfg(e.message || 'Could not verify.')}</p>`;
    } finally {
        btn.disabled = false;
    }
}

async function disableBots() {
    if (!confirm('Turn off your own bots?')) return;
    try {
        const res = await fetch('own-bots', { method: 'DELETE' });
        if (!res.ok) throw new Error();
        document.getElementById('ob-checks').innerHTML = '';
        await loadConfig();
    } catch (e) {
        document.getElementById('ob-checks').innerHTML = '<p class="cfg-hint">Could not turn off. Please try again.</p>';
    }
}

function setSort(v) {
    cfg.quality_sort = v;
    document.querySelectorAll('#cfg-sort .seg-btn').forEach(b => b.classList.toggle('active', b.dataset.val === v));
}

function renderQuality() {
    document.getElementById('cfg-quality').innerHTML = QUALITIES.map(q =>
        `<button type="button" class="qchip ${cfg.quality_filter.includes(q) ? 'on' : ''}" onclick="toggleQuality('${q}')">${q}</button>`
    ).join('');
}

function toggleQuality(q) {
    const i = cfg.quality_filter.indexOf(q);
    if (i >= 0) cfg.quality_filter.splice(i, 1); else cfg.quality_filter.push(q);
    renderQuality();
}

function catKey(c) { return c.key || (c.id + '::' + (c.type || 'movie')); }

function renderCatalogs() {
    document.getElementById('cfg-catalogs').innerHTML = cfgCatalogs.map((c, i) => {
        const key = catKey(c);
        const hidden = cfg.hidden_catalogs.includes(key) || cfg.hidden_catalogs.includes(c.id);
        const tag = c.type === 'series' ? 'Series' : 'Movie';
        return `<div class="cfg-cat ${hidden ? 'hidden-cat' : ''}">
            <button class="cfg-eye" title="Show/hide" onclick="toggleHide(${i})"><i class="fa-solid fa-eye${hidden ? '-slash' : ''}"></i></button>
            <span class="nm">${escapeCfg(c.name)} <small style="opacity:.6">· ${tag}</small></span>
            <button class="cfg-arr" ${i === 0 ? 'disabled' : ''} onclick="moveCat(${i}, -1)" aria-label="Move up"><i class="fa-solid fa-chevron-up"></i></button>
            <button class="cfg-arr" ${i === cfgCatalogs.length - 1 ? 'disabled' : ''} onclick="moveCat(${i}, 1)" aria-label="Move down"><i class="fa-solid fa-chevron-down"></i></button>
        </div>`;
    }).join('') || '<p class="cfg-hint">No catalogs available.</p>';
}

function toggleHide(i) {
    const key = catKey(cfgCatalogs[i]);
    const at = cfg.hidden_catalogs.indexOf(key);
    if (at >= 0) cfg.hidden_catalogs.splice(at, 1); else cfg.hidden_catalogs.push(key);
    renderCatalogs();
}

function moveCat(i, dir) {
    const j = i + dir;
    if (j < 0 || j >= cfgCatalogs.length) return;
    [cfgCatalogs[i], cfgCatalogs[j]] = [cfgCatalogs[j], cfgCatalogs[i]];
    renderCatalogs();
}

function escapeCfg(s) {
    return String(s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

async function loadConfig() {
    try {
        const res = await fetch('addon-config');
        const data = await res.json();
        cfg = Object.assign(cfg, data.config || {});
        cfgCatalogs = data.catalogs || [];
        if (!Array.isArray(cfg.quality_filter)) cfg.quality_filter = [];
        if (!Array.isArray(cfg.hidden_catalogs)) cfg.hidden_catalogs = [];
        setSort(cfg.quality_sort || 'desc');
        setVia(cfg.stream_via || 'bots');
        renderQuality();
        renderCatalogs();
        renderOwnBots(data.own_bots || {});
    } catch (e) {}
}

async function saveConfig() {
    const btn = document.getElementById('cfg-save');
    const state = document.getElementById('cfg-state');
    btn.disabled = true;
    cfg.catalog_order = cfgCatalogs.map(c => catKey(c));
    try {
        const res = await fetch('addon-config', {
            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cfg)
        });
        if (!res.ok) throw new Error();
        state.textContent = 'Saved! Re-install the addon to apply changes.';
    } catch (e) {
        state.textContent = 'Could not save. Please try again.';
    } finally {
        btn.disabled = false;
    }
}

loadConfig();
</script>

<script>
function copyUrl() {
    const url = document.getElementById('murl').textContent.trim();
    navigator.clipboard.writeText(url).then(() => {
        const b = document.querySelector('.btn-copy');
        b.innerHTML = '<i class="fa-solid fa-check"></i> Copied!';
        setTimeout(() => b.innerHTML = '<i class="fa-solid fa-copy"></i> Copy URL', 2000);
    });
}
</script>
</body>
</html>