<?php
$page_title  = 'Configuration';
$page_active = 'configuration';
require __DIR__ . '/includes/page_header.php';
?>

<!-- Header band (IBO GLASS style) -->
<div class="-mx-6 -mt-6 px-6 py-5 mb-6 border-b border-dark-700" style="background:#111;">
    <p class="text-xs font-semibold text-primary-400 uppercase tracking-wider mb-1">
        <span class="text-dark-400">Master Panel</span> / IBO ULTRA / Configuration
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-sliders text-primary-400"></i> Configuration
    </h2>
</div>

<form id="cfg-form">
<div class="card" x-data="{ tab: 'themes', sub: 'login_text' }">

    <!-- ============ Top tabs ============ -->
    <div class="border-b border-dark-700 flex items-center px-4">
        <button type="button" @click="tab='themes'"   :class="tab==='themes' ? 'tab-active' : ''"   class="cfg-tab"><i class="ph ph-palette"></i> Themes &amp; Login UI</button>
        <button type="button" @click="tab='app'"      :class="tab==='app' ? 'tab-active' : ''"      class="cfg-tab"><i class="ph ph-gear"></i> App Settings</button>
    </div>

    <!-- ================ Themes & Login UI ================ -->
    <div x-show="tab==='themes'" x-cloak>
        <!-- Sub tabs -->
        <div class="border-b border-dark-700 flex items-center px-6 bg-dark-900/50">
            <button type="button" @click="sub='home'"       :class="sub==='home' ? 'tab-active' : ''"       class="cfg-subtab"><i class="ph ph-house"></i> Home Theme</button>
            <button type="button" @click="sub='login_text'" :class="sub==='login_text' ? 'tab-active' : ''" class="cfg-subtab"><i class="ph ph-text-aa"></i> Login Text</button>
        </div>

        <!-- Login Text sub-tab -->
        <div x-show="sub==='login_text'" x-cloak class="p-6">
            <p class="text-sm text-dark-400 mb-4">User-facing strings the app pulls from the panel. Sent verbatim in the 4.3 auth response.</p>
            <div class="cfg-section">
                <div class="cfg-section-head">
                    <div class="cfg-section-icon"><i class="ph ph-list-bullets text-primary-400"></i></div>
                    <div>
                        <p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Playlist Text</p>
                        <p class="text-xs text-dark-400">Heading shown above the user's playlist list.</p>
                    </div>
                </div>
                <div class="cfg-section-body">
                    <div><label class="form-label text-xs">Title</label>
                         <input class="form-input" name="noti_title" placeholder="Welcome!"></div>
                    <div><label class="form-label text-xs">Body</label>
                         <textarea class="form-input" name="noti_content" rows="3" placeholder="Best In The Biz!!"></textarea></div>
                </div>
            </div>
        </div>

        <!-- Home Theme sub-tab (visual 6-up gallery, mirrors IBO original) -->
        <div x-show="sub==='home'" x-cloak class="p-6">
            <div class="flex items-center justify-end mb-5 gap-4">
                <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-primary-500/10 border border-primary-500/30 flex-shrink-0">
                    <i class="ph ph-check-circle text-primary-400"></i>
                    <span class="text-xs uppercase tracking-wider text-dark-400">Current</span>
                    <span id="theme-current-label" class="text-sm font-bold text-primary-400">Theme 1</span>
                </div>
            </div>
            <input type="hidden" name="theme" id="theme-hidden" value="1">
            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-6 gap-4" id="theme-gallery">
                <?php for ($i = 0; $i < 6; $i++): $label = 'Theme ' . ($i + 1); ?>
                    <button type="button" data-theme="<?php echo $i + 1; ?>" class="ibo-theme-card cursor-pointer group text-left p-0 bg-transparent border-0">
                        <div class="theme-frame relative aspect-video bg-dark-800 border-2 border-dark-700 rounded-lg overflow-hidden transition-all hover:border-primary-400">
                            <img src="assets/v2_themes/theme_<?php echo $i; ?>.jpg" alt="<?php echo $label; ?>"
                                 class="w-full h-full object-cover" loading="lazy"
                                 onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
                            <div class="absolute inset-0 hidden flex-col items-center justify-center bg-dark-800">
                                <i class="ph ph-television text-3xl text-dark-500"></i>
                                <p class="mt-1 text-xs text-dark-500">missing image</p>
                            </div>
                            <div class="theme-check absolute top-1 right-1 bg-primary-500 text-white rounded-full w-5 h-5 items-center justify-center shadow-lg hidden">
                                <i class="ph ph-check text-xs"></i>
                            </div>
                        </div>
                        <p class="theme-label mt-1.5 text-xs text-center text-dark-400 group-hover:text-dark-200"><?php echo $label; ?></p>
                    </button>
                <?php endfor; ?>
            </div>
        </div>
    </div>

    <!-- ================ QR Settings ================ -->
    <div x-show="tab==='qr'" x-cloak class="p-6">
        <div class="flex items-center justify-between mb-4">
            <div class="flex items-center gap-2">
                <i class="ph ph-qr-code text-primary-400"></i>
                <p class="text-primary-400 font-bold text-sm uppercase tracking-wide">QR Login Page Editor</p>
            </div>
            <span class="badge"><i class="ph ph-lock"></i> IBO ULTRA</span>
        </div>
        <p class="text-sm text-dark-400 mb-6">Customize the mobile login page users see after scanning the QR code on their phone.</p>

        <div class="grid grid-cols-1 lg:grid-cols-[1fr_440px] gap-5">
            <!-- ============ FORM COLUMN ============ -->
            <div class="space-y-4">

                <!-- LOGO -->
                <div class="cfg-section" x-data="{ mode: 'text' }">
                    <div class="cfg-section-head"><div class="cfg-section-icon"><i class="ph ph-image-square text-primary-400"></i></div>
                        <div><p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Logo</p></div></div>
                    <div class="cfg-section-body">
                        <div class="grid grid-cols-2 gap-2 mb-3">
                            <button type="button" @click="mode='text'; document.querySelector('[name=qr_logo_mode]').value='text';"
                                    :class="mode==='text' ? 'bg-primary-500/15 border-primary-500/40 text-primary-400' : 'border-dark-700 text-dark-300'"
                                    class="border rounded-lg py-2 px-3 text-xs font-semibold inline-flex items-center justify-center gap-2">
                                <i class="ph ph-text-aa"></i> Text
                            </button>
                            <button type="button" @click="mode='image'; document.querySelector('[name=qr_logo_mode]').value='image';"
                                    :class="mode==='image' ? 'bg-primary-500/15 border-primary-500/40 text-primary-400' : 'border-dark-700 text-dark-300'"
                                    class="border rounded-lg py-2 px-3 text-xs font-semibold inline-flex items-center justify-center gap-2">
                                <i class="ph ph-image"></i> Image
                            </button>
                        </div>
                        <input type="hidden" name="qr_logo_mode" value="text">
                        <div x-show="mode==='text'">
                            <label class="form-label text-xs">Logo Text</label>
                            <input class="form-input qr-watch" name="qr_logo_text" placeholder="Your brand">
                        </div>
                        <div x-show="mode==='image'" x-cloak>
                            <label class="form-label text-xs">Logo Image URL</label>
                            <input class="form-input mono qr-watch" name="qr_logo_image_url" placeholder="https://…/logo.png">
                        </div>
                    </div>
                </div>

                <!-- COLORS -->
                <div class="cfg-section">
                    <div class="cfg-section-head"><div class="cfg-section-icon"><i class="ph ph-palette text-primary-400"></i></div>
                        <div><p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Colors</p></div></div>
                    <div class="cfg-section-body grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <?php
                        $colorFields = [
                            'qr_color_bg'           => 'Page Background',
                            'qr_color_card_bg'      => 'Card Background',
                            'qr_color_card_border'  => 'Card Border',
                            'qr_color_accent_start' => 'Accent (Button Start)',
                            'qr_color_accent_end'   => 'Accent (Button End)',
                            'qr_color_text'         => 'Text Color',
                            'qr_color_muted'        => 'Muted Text',
                            'qr_color_input_bg'     => 'Input Background',
                            'qr_color_input_border' => 'Input Border',
                        ];
                        foreach ($colorFields as $name => $label): ?>
                            <div>
                                <label class="form-label text-xs"><?php echo h($label); ?></label>
                                <div class="flex items-center gap-2">
                                    <input type="color" class="qr-color-picker h-9 w-9 rounded border border-dark-700 bg-dark-800 cursor-pointer flex-shrink-0" data-target="<?php echo h($name); ?>" value="#000000">
                                    <input class="form-input mono qr-watch" name="<?php echo h($name); ?>" placeholder="#000000">
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- SIZING -->
                <div class="cfg-section">
                    <div class="cfg-section-head"><div class="cfg-section-icon"><i class="ph ph-ruler text-primary-400"></i></div>
                        <div><p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Sizing</p></div></div>
                    <div class="cfg-section-body grid grid-cols-2 gap-4">
                        <div><label class="form-label text-xs">Card Corner Radius (px)</label>
                             <input class="form-input qr-watch" type="number" min="0" max="40" name="qr_radius_card"></div>
                        <div><label class="form-label text-xs">Button Corner Radius (px)</label>
                             <input class="form-input qr-watch" type="number" min="0" max="40" name="qr_radius_button"></div>
                    </div>
                </div>

                <!-- TEXT -->
                <div class="cfg-section">
                    <div class="cfg-section-head"><div class="cfg-section-icon"><i class="ph ph-text-aa text-primary-400"></i></div>
                        <div><p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Text</p></div></div>
                    <div class="cfg-section-body grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <div><label class="form-label text-xs">Title</label>
                             <input class="form-input qr-watch" name="qr_text_title"></div>
                        <div><label class="form-label text-xs">Subtitle</label>
                             <input class="form-input qr-watch" name="qr_text_subtitle"></div>
                        <div class="sm:col-span-2"><label class="form-label text-xs">Button Text</label>
                             <input class="form-input qr-watch" name="qr_text_button"></div>
                    </div>
                </div>

                <!-- SUCCESS SCREEN -->
                <div class="cfg-section">
                    <div class="cfg-section-head"><div class="cfg-section-icon"><i class="ph ph-check-circle text-primary-400"></i></div>
                        <div><p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Success Screen</p></div></div>
                    <div class="cfg-section-body grid grid-cols-1 gap-4">
                        <div><label class="form-label text-xs">Title</label>
                             <input class="form-input qr-watch" name="qr_success_title"></div>
                        <div><label class="form-label text-xs">Message</label>
                             <textarea class="form-input qr-watch" name="qr_success_message" rows="2"></textarea></div>
                    </div>
                </div>

                <!-- Pairing base URL (kept for backwards compat) -->
                <div class="cfg-section">
                    <div class="cfg-section-body">
                        <label class="form-label text-xs">QR Pairing Base URL</label>
                        <input class="form-input mono" name="qr_url" placeholder="https://your-server/qr/">
                    </div>
                </div>

                <div class="flex justify-end">
                    <button type="button" id="qr-save-btn" class="btn-primary"><i class="ph ph-floppy-disk"></i> Save QR Page Settings</button>
                </div>
            </div>

            <!-- ============ LIVE PREVIEW COLUMN ============ -->
            <div class="cfg-section overflow-hidden" x-data="{ pview: 'login' }">
                <div class="qr-preview-titlebar">
                    <span class="qr-traffic"></span>
                    <span class="qr-traffic"></span>
                    <span class="qr-traffic"></span>
                    <span class="text-xs text-dark-400 ml-2">Live preview</span>
                </div>
                <div class="qr-preview-tabs px-4 py-2 border-b border-dark-700 flex gap-2 text-xs">
                    <button type="button" @click="pview='login'"   :class="pview==='login'   ? 'bg-primary-500/15 text-primary-400' : 'text-dark-400'"   class="px-2 py-1 rounded">Login Form</button>
                    <button type="button" @click="pview='success'" :class="pview==='success' ? 'bg-primary-500/15 text-primary-400' : 'text-dark-400'"   class="px-2 py-1 rounded">Success</button>
                </div>
                <div id="qr-preview" class="qr-preview" x-show="pview==='login'">
                    <div class="qr-card">
                        <div class="qr-logo" id="qr-prev-logo">Your brand</div>
                        <div class="qr-title" id="qr-prev-title">Login to Your Device</div>
                        <div class="qr-subtitle" id="qr-prev-subtitle">Enter your credentials</div>
                        <div class="qr-field"><label>USERNAME</label><input value="demo_user" readonly></div>
                        <div class="qr-field"><label>PASSWORD</label><input type="password" value="••••••••" readonly></div>
                        <button type="button" class="qr-btn" id="qr-prev-button">Login to Device</button>
                    </div>
                </div>
                <div class="qr-preview" x-show="pview==='success'" x-cloak>
                    <div class="qr-card">
                        <i class="ph ph-check-circle text-5xl mb-3" style="color:var(--qr-accent-end,#05a82e)"></i>
                        <div class="qr-title" id="qr-prev-success-title">Connected!</div>
                        <div class="qr-subtitle" id="qr-prev-success-msg">Your TV will login automatically. You can close this page.</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ================ App Settings ================ -->
    <div x-show="tab==='app'" x-cloak class="p-6">
        <p class="text-sm text-dark-400 mb-4">The current app version and download link your viewers will see.</p>

        <div class="cfg-section mb-4">
            <div class="cfg-section-head">
                <div class="cfg-section-icon"><i class="ph ph-android-logo text-primary-400"></i></div>
                <div>
                    <p class="text-primary-400 font-bold text-sm uppercase tracking-wide">APK</p>
                    <p class="text-xs text-dark-400">Shown to viewers in the app's update screen.</p>
                </div>
            </div>
            <div class="cfg-section-body grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div><label class="form-label text-xs">App version</label>
                     <input class="form-input" name="app_version" placeholder="4.3"></div>
                <div><label class="form-label text-xs">APK download link</label>
                     <input class="form-input mono" name="apk_link"></div>
            </div>
        </div>

        <div class="cfg-section mb-4">
            <div class="cfg-section-head">
                <div class="cfg-section-icon"><i class="ph ph-storefront text-primary-400"></i></div>
                <div>
                    <p class="text-primary-400 font-bold text-sm uppercase tracking-wide">Branding</p>
                    <p class="text-xs text-dark-400">Shown to your end users on the activation screens.</p>
                </div>
            </div>
            <div class="cfg-section-body grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div class="lg:col-span-2"><label class="form-label text-xs">Display name</label>
                     <input class="form-input" name="display_name">
                     <p class="text-[11px] text-dark-500 mt-1">Shown in your end users' app and on the activation screen.</p></div>
            </div>
        </div>

    </div>

    <!-- ================ WebView ================ -->
    <div x-show="tab==='webview'" x-cloak class="p-6">
        <p class="text-sm text-dark-400 mb-4">Optional web pages shown inside the app — the home screen backdrop and the subtitle search.</p>
        <div class="cfg-section">
            <div class="cfg-section-head">
                <div class="cfg-section-icon"><i class="ph ph-monitor-play text-primary-400"></i></div>
                <div>
                    <p class="text-primary-400 font-bold text-sm uppercase tracking-wide">WebView URLs</p>
                </div>
            </div>
            <div class="cfg-section-body grid grid-cols-1 gap-4">
                <div><label class="form-label text-xs">home_url1 (WebView backdrop)</label>
                     <input class="form-input mono" name="home_url1"></div>
                <div><label class="form-label text-xs">subtitle_url</label>
                     <input class="form-input mono" name="subtitle_url"></div>
            </div>
        </div>
    </div>

    <!-- Save bar — hidden on the QR tab; QR has its own in-tab save button
         because QR settings go to a different endpoint (api/qr_settings.php). -->
    <div x-show="tab !== 'qr'" x-cloak class="border-t border-dark-700 flex justify-end gap-2 px-6 py-4 bg-dark-900/60">
        <button type="button" class="btn-secondary text-xs" onclick="loadCfg()"><i class="ph ph-arrow-counter-clockwise"></i> Reload</button>
        <button type="submit" class="btn-primary"><i class="ph ph-floppy-disk"></i> Save Changes</button>
    </div>
</div>
</form>

<style>
.cfg-tab { padding: 14px 18px; display: inline-flex; align-items: center; gap: 8px;
    color: #999; font-size: 13px; border-bottom: 2px solid transparent; cursor: pointer;
    background: transparent; transition: color .15s, border-color .15s; }
.cfg-tab:hover { color: #ccc; }
.cfg-subtab { padding: 12px 16px; display: inline-flex; align-items: center; gap: 8px;
    color: #888; font-size: 12px; border-bottom: 2px solid transparent; cursor: pointer;
    background: transparent; }
.cfg-subtab:hover { color: #ccc; }
.tab-active { color: #f39c12 !important; border-bottom-color: #f39c12 !important; }
.cfg-section { background: #111; border: 1px solid #2a2a2a; border-radius: 8px; overflow: hidden; }
.cfg-section-head { display: flex; align-items: center; gap: 12px; padding: 16px 20px; border-bottom: 1px solid #1e1e1e; background: #161616; }
.cfg-section-icon { width: 38px; height: 38px; background: rgba(243,156,18,0.12); border-radius: 8px;
    display: flex; align-items: center; justify-content: center; }
.cfg-section-icon i { font-size: 20px; }
.cfg-section-body { padding: 20px; }
.cfg-section-body > * + * { margin-top: 16px; }
.form-check { accent-color: #f39c12; width: 18px; height: 18px; }
[x-cloak] { display: none !important; }

/* QR live preview */
.qr-preview-titlebar { display:flex; align-items:center; gap:6px; padding:8px 12px; background:#0d0d0d; border-bottom:1px solid #1e1e1e; }
.qr-traffic { width:10px; height:10px; border-radius:50%; background:#444; }
.qr-traffic:nth-child(1){background:#ef4444;}
.qr-traffic:nth-child(2){background:#f59e0b;}
.qr-traffic:nth-child(3){background:#22c55e;}
.qr-preview { background: var(--qr-bg, #282929); padding: 32px 24px; min-height: 460px; display: flex; align-items: center; justify-content: center; }
.qr-preview .qr-card {
    width: 100%;
    max-width: 320px;
    background: var(--qr-card-bg, #16161f);
    border: 1px solid var(--qr-card-border, #078850);
    border-radius: var(--qr-radius-card, 14px);
    padding: 28px 22px;
    text-align: center;
}
.qr-preview .qr-logo {
    display:inline-block; margin:0 auto 22px; padding:8px 16px;
    border:1px solid var(--qr-card-border, #078850); border-radius:8px;
    color: var(--qr-text, #09e13f); font-weight:700; font-size:15px;
}
.qr-preview .qr-logo img { max-height:48px; display:block; }
.qr-preview .qr-title { color: var(--qr-text, #09e13f); font-size: 18px; font-weight: 800; margin-bottom: 6px; }
.qr-preview .qr-subtitle { color: var(--qr-muted, #666); font-size: 12px; margin-bottom: 18px; }
.qr-preview .qr-field { text-align:left; margin-bottom:12px; }
.qr-preview .qr-field label { display:block; color: var(--qr-muted, #666); font-size:10px; font-weight:700; letter-spacing:.05em; margin-bottom:4px; }
.qr-preview .qr-field input {
    width:100%; padding:8px 10px; border-radius:6px; font-size:13px;
    background: var(--qr-input-bg, #1e1e2a);
    border: 1px solid var(--qr-input-border, #06cb48);
    color: var(--qr-text, #09e13f);
    outline:0;
}
.qr-preview .qr-btn {
    width:100%; margin-top:8px; padding:10px 14px; border:0;
    background: linear-gradient(90deg, var(--qr-accent-start, #565452), var(--qr-accent-end, #05a82e));
    color: #fff; font-weight: 700;
    border-radius: var(--qr-radius-button, 25px);
    cursor: pointer; font-size: 13px;
}
</style>

<script>
function selectTheme(v) {
    const n = parseInt(v, 10) || 1;
    document.getElementById('theme-hidden').value = n;
    document.getElementById('theme-current-label').textContent = 'Theme ' + n;
    document.querySelectorAll('#theme-gallery .ibo-theme-card').forEach(c => {
        const isActive = +c.dataset.theme === n;
        const frame = c.querySelector('.theme-frame');
        const check = c.querySelector('.theme-check');
        frame.classList.toggle('border-primary-400', isActive);
        frame.classList.toggle('border-dark-700', !isActive);
        check.classList.toggle('hidden', !isActive);
        check.classList.toggle('flex', isActive);
    });
}
document.getElementById('theme-gallery').addEventListener('click', (e) => {
    const b = e.target.closest('.ibo-theme-card');
    if (b) selectTheme(b.dataset.theme);
});

async function loadCfg() {
    try {
        const { config } = await api.get('api/config.php');
        const f = document.getElementById('cfg-form');
        Object.keys(config).forEach(k => {
            if (k === 'theme') { selectTheme(config[k]); return; }
            if (f[k] != null) {
                if (f[k].type === 'checkbox') f[k].checked = config[k] == 1;
                else f[k].value = config[k] == null ? '' : config[k];
            }
        });
    } catch (e) { toast(e.message, 'error'); }
}
document.getElementById('cfg-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const body = Object.assign({ action: 'update' }, formObject(e.target));
    try { await api.post('api/config.php', body); toast('Configuration saved', 'success'); }
    catch (err) { toast(err.message, 'error'); }
});
loadCfg();

// ---------------------------------------------------------------------------
// QR Page Editor — load + live preview + save
// ---------------------------------------------------------------------------
const QR_FIELD_TO_CSS = {
    qr_color_bg: '--qr-bg',
    qr_color_card_bg: '--qr-card-bg',
    qr_color_card_border: '--qr-card-border',
    qr_color_text: '--qr-text',
    qr_color_muted: '--qr-muted',
    qr_color_input_bg: '--qr-input-bg',
    qr_color_input_border: '--qr-input-border',
    qr_color_accent_start: '--qr-accent-start',
    qr_color_accent_end: '--qr-accent-end',
};

function applyQrPreview() {
    const f = document.getElementById('cfg-form');
    const previewEls = document.querySelectorAll('.qr-preview, .qr-preview .qr-card');
    Object.entries(QR_FIELD_TO_CSS).forEach(([name, cssVar]) => {
        const v = f[name]?.value || '';
        if (v) document.querySelectorAll('.qr-preview').forEach(el => el.style.setProperty(cssVar, v));
    });
    // Sizing radii
    const cardR = f.qr_radius_card?.value ? f.qr_radius_card.value + 'px' : '14px';
    const btnR  = f.qr_radius_button?.value ? f.qr_radius_button.value + 'px' : '25px';
    document.querySelectorAll('.qr-preview').forEach(el => {
        el.style.setProperty('--qr-radius-card', cardR);
        el.style.setProperty('--qr-radius-button', btnR);
    });
    // Logo (text vs image)
    const logoEl = document.getElementById('qr-prev-logo');
    if (f.qr_logo_mode?.value === 'image' && f.qr_logo_image_url?.value) {
        logoEl.innerHTML = '<img src="' + escapeHtml(f.qr_logo_image_url.value) + '" alt="">';
    } else {
        logoEl.textContent = f.qr_logo_text?.value || 'Your brand';
    }
    // Text strings
    if (f.qr_text_title)    document.getElementById('qr-prev-title').textContent    = f.qr_text_title.value    || 'Login to Your Device';
    if (f.qr_text_subtitle) document.getElementById('qr-prev-subtitle').textContent = f.qr_text_subtitle.value || 'Enter your credentials';
    if (f.qr_text_button)   document.getElementById('qr-prev-button').textContent   = f.qr_text_button.value   || 'Login to Device';
    if (f.qr_success_title)   document.getElementById('qr-prev-success-title').textContent   = f.qr_success_title.value   || 'Connected!';
    if (f.qr_success_message) document.getElementById('qr-prev-success-msg').textContent     = f.qr_success_message.value || 'Your TV will login automatically. You can close this page.';
}

async function loadQr() {
    try {
        const { qr } = await api.get('api/qr_settings.php');
        const f = document.getElementById('cfg-form');
        Object.entries(qr).forEach(([k, v]) => {
            if (f[k] != null) f[k].value = v;
        });
        // Sync color pickers to the text-input hex values
        document.querySelectorAll('.qr-color-picker').forEach(p => {
            const target = p.dataset.target;
            if (qr[target] && /^#[0-9a-f]{6}$/i.test(qr[target])) p.value = qr[target];
        });
        applyQrPreview();
    } catch (e) { /* defaults already applied via CSS vars */ applyQrPreview(); }
}

// Live preview: every input change re-renders + colour picker syncs to its mate.
document.querySelectorAll('.qr-watch').forEach(el => {
    el.addEventListener('input', applyQrPreview);
});
document.querySelectorAll('.qr-color-picker').forEach(p => {
    p.addEventListener('input', () => {
        const target = p.dataset.target;
        const f = document.getElementById('cfg-form');
        if (f[target]) { f[target].value = p.value; applyQrPreview(); }
    });
});

document.getElementById('qr-save-btn').addEventListener('click', async () => {
    const f = document.getElementById('cfg-form');
    const qr = {};
    [
        'qr_logo_mode','qr_logo_text','qr_logo_image_url',
        'qr_color_bg','qr_color_card_bg','qr_color_card_border','qr_color_accent_start','qr_color_accent_end',
        'qr_color_text','qr_color_muted','qr_color_input_bg','qr_color_input_border',
        'qr_radius_card','qr_radius_button',
        'qr_text_title','qr_text_subtitle','qr_text_button',
        'qr_success_title','qr_success_message',
    ].forEach(k => { if (f[k] != null) qr[k] = f[k].value; });
    try { await api.post('api/qr_settings.php', { action: 'save', qr });
          toast('QR page settings saved', 'success'); }
    catch (e) { toast(e.message, 'error'); }
});

loadQr();
</script>

<?php require __DIR__ . '/includes/page_footer.php'; ?>
