<?php
$page_title  = 'TMDB Layouts';
$page_active = 'tmdb_layouts';
require __DIR__ . '/includes/page_header.php';
?>

<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> / WebViews / TMDB Layouts
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-grid-four text-primary-400"></i> TMDB Layouts
    </h2>
</div>

<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
    <!-- Editor -->
    <div class="card">
        <div class="card-head"><h3>TMDB Layouts</h3>
            <span class="text-[10px] text-dark-500">Pick the layout style and tweak its presentation.</span>
        </div>
        <div class="px-5 py-4 border-b border-dark-700 bg-amber-500/5">
            <div class="flex items-start gap-3">
                <i class="ph ph-info text-primary-400 text-lg mt-0.5"></i>
                <div class="flex-1">
                    <p class="text-sm text-primary-300 font-semibold">Content filters live on TMDB Settings.</p>
                    <p class="text-xs text-dark-400 mt-0.5">API key, region, certification cap, block list — everything that controls <em>which</em> titles surface.</p>
                </div>
                <a href="tmdb_settings.php" class="btn-primary text-xs"><i class="ph ph-gear"></i> Open Settings</a>
            </div>
        </div>

        <div class="p-5 space-y-5">
            <div>
                <label class="form-label text-xs">Layout Style</label>
                <select class="form-input" id="layout-style" onchange="updatePreviewLabel()">
                    <option value="banner">Layout 1 — Banner</option>
                    <option value="grid">Layout 2 — Grid</option>
                    <option value="carousel">Layout 3 — Carousel</option>
                    <option value="hero">Layout 4 — Hero + List</option>
                </select>
            </div>
            <div>
                <label class="form-label text-xs flex items-center justify-between">Slide Interval <span class="text-primary-400" id="slide-display">5000ms</span></label>
                <input class="form-input" type="range" id="slide-interval" min="2000" max="15000" step="500" value="5000"
                       oninput="document.getElementById('slide-display').textContent=this.value+'ms'">
            </div>
            <div>
                <label class="form-label text-xs">Accent Color</label>
                <div class="flex items-center gap-2">
                    <input type="color" value="#f39c12" class="h-9 w-12 rounded border border-dark-600 bg-dark-800">
                    <input class="form-input mono" value="#f39c12">
                </div>
            </div>
            <div>
                <p class="form-label text-xs mb-2">Visibility Toggles</p>
                <div class="grid grid-cols-2 gap-2">
                    <label class="flex items-center gap-2 text-sm text-dark-200"><input type="checkbox" class="form-check" checked> Title Card</label>
                    <label class="flex items-center gap-2 text-sm text-dark-200"><input type="checkbox" class="form-check" checked> Year</label>
                    <label class="flex items-center gap-2 text-sm text-dark-200"><input type="checkbox" class="form-check"> Genre</label>
                    <label class="flex items-center gap-2 text-sm text-dark-200"><input type="checkbox" class="form-check" checked> Vote</label>
                    <label class="flex items-center gap-2 text-sm text-dark-200"><input type="checkbox" class="form-check" checked> Overview</label>
                </div>
            </div>
            <button id="save-tmdb-layout" class="btn-primary"><i class="ph ph-floppy-disk"></i> Save Layout</button>
        </div>
    </div>

    <!-- Live preview -->
    <div class="card">
        <div class="card-head"><h3><i class="ph ph-play-circle text-primary-400"></i> Live Preview</h3>
            <div class="flex items-center gap-3">
                <span class="text-[10px] text-dark-500" id="preview-label">Layout 1 — Banner</span>
                <a href="#" id="preview-fullscreen" onclick="event.preventDefault(); wvFullscreen(buildPreviewUrl())"
                   class="text-xs text-primary-400 hover:text-primary-300 flex items-center gap-1">
                    <i class="ph ph-arrows-out"></i> Fullscreen
                </a>
            </div>
        </div>
        <div class="m-5 rounded-lg overflow-hidden border border-dark-700 bg-black" style="aspect-ratio:16/9;">
            <iframe id="preview-iframe" src="" style="width:100%;height:100%;border:0;display:block;"></iframe>
        </div>
        <div class="px-5 pb-5 text-xs text-dark-500">
            The preview updates as you change settings. Click <strong>Save Layout</strong> to keep your changes.
        </div>
    </div>
</div>

<script>
function updatePreviewLabel() {
    const sel = document.getElementById('layout-style');
    document.getElementById('preview-label').textContent = sel.options[sel.selectedIndex].text;
}

const LAYOUT_KEYS = ['tmdb_layout_style','tmdb_layout_slide_ms','tmdb_layout_accent',
                     'tmdb_layout_show_title','tmdb_layout_show_year','tmdb_layout_show_genre',
                     'tmdb_layout_show_vote','tmdb_layout_show_overview'];

// Build the iframe URL with the current form state passed as query params,
// so the preview reflects unsaved changes too.
function buildPreviewUrl() {
    const checks = document.querySelectorAll('.form-check');
    const params = new URLSearchParams({
        preview: '1',
        style:           document.getElementById('layout-style').value,
        slide_ms:        document.getElementById('slide-interval').value,
        accent:          document.querySelector('input[type="color"]')?.value || '#f39c12',
        show_title:      checks[0]?.checked ? '1' : '0',
        show_year:       checks[1]?.checked ? '1' : '0',
        show_genre:      checks[2]?.checked ? '1' : '0',
        show_vote:       checks[3]?.checked ? '1' : '0',
        show_overview:   checks[4]?.checked ? '1' : '0',
        _:               Date.now(),  // cache-bust
    });
    return 'api/webview/tmdb/autoads_0.php?' + params.toString();
}

let _previewTimer = null;
function refreshPreview() {
    clearTimeout(_previewTimer);
    _previewTimer = setTimeout(() => {
        const iframe = document.getElementById('preview-iframe');
        if (iframe) iframe.src = buildPreviewUrl();
    }, 150);
}

// Trigger preview refresh on every relevant control change
['change', 'input'].forEach(evt => {
    document.querySelectorAll('#layout-style, #slide-interval, .form-check, input[type=color], input[value^="#"]').forEach(el => {
        el.addEventListener(evt, refreshPreview);
    });
});
// Re-render preview after the visible label changes too
document.getElementById('layout-style').addEventListener('change', updatePreviewLabel);

async function loadLayout() {
    try {
        const { settings } = await api.get('api/webview_settings.php?keys=' + LAYOUT_KEYS.join(','));
        if (settings.tmdb_layout_style) {
            document.getElementById('layout-style').value = settings.tmdb_layout_style;
            updatePreviewLabel();
        }
        if (settings.tmdb_layout_slide_ms) {
            document.getElementById('slide-interval').value = settings.tmdb_layout_slide_ms;
            document.getElementById('slide-display').textContent = settings.tmdb_layout_slide_ms + 'ms';
        }
        if (settings.tmdb_layout_accent) {
            document.querySelectorAll('input[type="color"], input[value^="#"]').forEach(i => i.value = settings.tmdb_layout_accent);
        }
        const checks = document.querySelectorAll('.form-check');
        ['title','year','genre','vote','overview'].forEach((label, i) => {
            const key = 'tmdb_layout_show_' + label;
            if (settings[key] !== undefined && checks[i]) checks[i].checked = settings[key] === '1';
        });
    } catch (e) { /* first load */ }
    refreshPreview();
}

document.getElementById('save-tmdb-layout').addEventListener('click', async () => {
    const checks = document.querySelectorAll('.form-check');
    const pairs = { action: 'save',
        tmdb_layout_style: document.getElementById('layout-style').value,
        tmdb_layout_slide_ms: document.getElementById('slide-interval').value,
        tmdb_layout_accent: document.querySelector('input[type="color"]')?.value || '#f39c12',
    };
    ['title','year','genre','vote','overview'].forEach((label, i) => {
        pairs['tmdb_layout_show_' + label] = checks[i]?.checked ? '1' : '0';
    });
    try {
        await api.post('api/webview_settings.php', pairs);
        toast('Layout saved', 'success');
    } catch (e) { toast(e.message, 'error'); }
});

// Sync the color-text input → color-picker
document.querySelectorAll('input[type=color]').forEach(c => {
    c.addEventListener('input', () => {
        const tx = c.parentElement.querySelector('input[type=text].mono');
        if (tx) tx.value = c.value;
        refreshPreview();
    });
});
document.querySelectorAll('input[type=text].mono').forEach(t => {
    if (!/^#/.test(t.value)) return;
    t.addEventListener('input', () => {
        const c = t.parentElement.querySelector('input[type=color]');
        if (c && /^#[0-9a-f]{6}$/i.test(t.value)) c.value = t.value;
        refreshPreview();
    });
});

loadLayout();
</script>

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