<?php
$page_title  = 'Framed View';
$page_active = 'frameview_settings';
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 / Framed View
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-frame-corners text-primary-400"></i> Framed View
    </h2>
</div>

<div class="card">
    <div class="card-head"><h3><i class="ph ph-square-split-horizontal text-primary-400"></i> FRAMED VIEW</h3></div>
    <div class="px-5 pt-3 text-sm text-dark-400">Combine multiple webviews into a single composite layout.</div>
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 p-5">
        <!-- Form -->
        <form id="fv-form" class="space-y-4">
            <label class="flex items-center gap-3 p-3 rounded-lg cursor-pointer" style="background:#161616;border:1px solid #1e1e1e;">
                <input type="checkbox" id="fv-use-as-backdrop" class="w-4 h-4 accent-primary-500 cursor-pointer">
                <div class="flex-1">
                    <p class="text-sm font-semibold text-white">Use this as the home backdrop</p>
                    <p class="text-[11px] text-dark-400">Replaces the TMDB backdrop on the app's home screen with this composed view. The change takes effect the next time the app calls /auth.</p>
                </div>
                <i class="ph ph-television-simple text-2xl text-primary-400"></i>
            </label>
            <div>
                <label class="form-label text-xs">Layout</label>
                <select class="form-input" id="fv-layout" onchange="updateLayoutPreview()">
                    <option value="0">Layout 0 — Fullscreen (1 slot)</option>
                    <option value="1">Layout 1 — Left + Right + Bottom</option>
                    <option value="2">Layout 2 — Left + Right (side-by-side)</option>
                    <option value="3">Layout 3 — Header + Left + Right</option>
                    <option value="4">Layout 4 — Top + Left + Right</option>
                    <option value="5">Layout 5 — 2x2 grid</option>
                </select>
            </div>
            <div id="fv-slot-left-row">
                <label class="form-label text-xs" id="fv-slot-left-label">Left panel</label>
                <select class="form-input" name="slot_left">
                    <option value="">— None —</option>
                    <option value="tmdb">TMDB Layout</option>
                    <option value="slideshow">Media Slideshow</option>
                    <option value="sports">Sports Guide</option>
                </select>
            </div>
            <div id="fv-slot-right-row">
                <label class="form-label text-xs">Right panel</label>
                <select class="form-input" name="slot_right">
                    <option value="">— None —</option>
                    <option value="tmdb">TMDB Layout</option>
                    <option value="slideshow">Media Slideshow</option>
                    <option value="sports">Sports Guide</option>
                </select>
            </div>
            <div id="fv-slot-bottom-row">
                <label class="form-label text-xs">Bottom panel</label>
                <select class="form-input" name="slot_bottom">
                    <option value="">— None —</option>
                    <option value="tmdb">TMDB Layout</option>
                    <option value="slideshow">Media Slideshow</option>
                    <option value="sports">Sports Guide</option>
                </select>
            </div>
            <div class="flex items-center gap-3 pt-2">
                <button type="submit" class="btn-primary"><i class="ph ph-floppy-disk"></i> Save</button>
                <a href="#" onclick="event.preventDefault(); openFvFullscreen()" class="text-primary-400 text-sm hover:text-primary-300 flex items-center gap-1">
                    <i class="ph ph-arrows-out"></i> View Fullscreen
                </a>
            </div>
        </form>

        <!-- Live preview -->
        <div>
            <div class="rounded-lg overflow-hidden border border-dark-600 bg-black" style="aspect-ratio:16/9;">
                <iframe id="fv-preview" src="" style="width:100%;height:100%;border:0;background:#000"></iframe>
            </div>
            <p class="text-[10px] text-dark-500 mt-2">Preview updates as you change selections. Save to apply to the app.</p>
        </div>
    </div>
</div>

<script>
// The select <option value> uses short tokens (tmdb / slideshow / sports);
// the server stores actual URLs. Map both directions.
const SLOT_TOKEN_TO_URL = {
    tmdb:      'api/webview/tmdb/autoads_0.php',
    slideshow: 'api/webview/slideshow.php',
    sports:    'api/webview/sports/sport_top.php',
};
const SLOT_URL_TO_TOKEN = Object.fromEntries(
    Object.entries(SLOT_TOKEN_TO_URL).map(([k, v]) => [v, k])
);

function buildFvPreviewUrl() {
    const f = document.getElementById('fv-form');
    const toUrl = t => SLOT_TOKEN_TO_URL[t] || '';
    const params = new URLSearchParams({
        preview: '1',
        layout:  document.getElementById('fv-layout').value,
        slot0:   toUrl(f.slot_left.value),
        slot1:   toUrl(f.slot_right.value),
        slot2:   toUrl(f.slot_bottom.value),
        _:       Date.now(),  // cache-bust
    });
    return 'api/webview/frameview.php?' + params.toString();
}

let _fvTimer = null;
function refreshFvPreview() {
    clearTimeout(_fvTimer);
    _fvTimer = setTimeout(() => {
        const iframe = document.getElementById('fv-preview');
        if (iframe) iframe.src = buildFvPreviewUrl();
    }, 150);
}

// Which slot-selectors are relevant for each layout. Rows for slots the
// selected layout doesn't use get hidden — keeps the form honest.
const LAYOUT_SLOTS = {
    0: ['left'],                     // fullscreen — one slot
    1: ['left', 'right', 'bottom'],
    2: ['left', 'right'],
    3: ['left', 'right', 'bottom'],  // header + 2 columns
    4: ['left', 'right', 'bottom'],
    5: ['left', 'right', 'bottom'],  // 4-cell grid; the UI only exposes 3 for now
};
function updateLayoutPreview() {
    const layout = parseInt(document.getElementById('fv-layout').value, 10);
    const used = new Set(LAYOUT_SLOTS[layout] || ['left', 'right', 'bottom']);
    ['left', 'right', 'bottom'].forEach(name => {
        const row = document.getElementById('fv-slot-' + name + '-row');
        if (row) row.style.display = used.has(name) ? '' : 'none';
    });
    // Layout 0 has one slot — relabel it as "Main content" so operators
    // understand what fills the screen.
    const leftLabel = document.getElementById('fv-slot-left-label');
    if (leftLabel) leftLabel.textContent = (layout === 0) ? 'Main content' : 'Left panel';
    refreshFvPreview();
}

['change', 'input'].forEach(evt => {
    document.querySelectorAll('#fv-form select, #fv-layout').forEach(el => {
        el.addEventListener(evt, refreshFvPreview);
    });
});

async function loadFv() {
    try {
        const r = await api.get('api/webview/frames.php?action=get');
        const f = document.getElementById('fv-form');
        document.getElementById('fv-layout').value = (r.layout !== undefined ? r.layout : 0);
        document.getElementById('fv-use-as-backdrop').checked = !!r.use_as_backdrop;
        const slotMap = { 0: 'slot_left', 1: 'slot_right', 2: 'slot_bottom' };
        if (r.slots) Object.entries(r.slots).forEach(([idx, url]) => {
            const name = slotMap[idx];
            if (!name || !f[name]) return;
            f[name].value = SLOT_URL_TO_TOKEN[url] || '';
        });
    } catch (e) { /* first load */ }
    updateLayoutPreview();
}
document.getElementById('fv-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const f = e.target;
    const toUrl = t => SLOT_TOKEN_TO_URL[t] || '';
    const layout = parseInt(document.getElementById('fv-layout').value, 10);
    // Only send slot URLs that this layout actually uses — avoids stashing
    // orphaned rows from a previous layout the operator switched away from.
    const used = new Set(LAYOUT_SLOTS[layout] || ['left', 'right', 'bottom']);
    const slots = {};
    if (used.has('left'))   slots[0] = toUrl(f.slot_left.value);
    if (used.has('right'))  slots[1] = toUrl(f.slot_right.value);
    if (used.has('bottom')) slots[2] = toUrl(f.slot_bottom.value);
    const body = {
        action: 'save',
        layout,
        slots,
        use_as_backdrop: document.getElementById('fv-use-as-backdrop').checked ? 1 : 0,
    };
    try {
        await api.post('api/webview/frames.php', body);
        toast('Framed view saved', 'success');
        refreshFvPreview();
    } catch (err) { toast(err.message, 'error'); }
});
loadFv();

function openFvFullscreen() { wvFullscreen(buildFvPreviewUrl()); }
</script>

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