<?php
$page_title  = 'Sports Guide';
$page_active = 'sports_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 / Sports Guide
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-soccer-ball text-primary-400"></i> Sports Guide
    </h2>
</div>

<!-- Source cards -->
<div class="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-6" id="sports-sources">
    <button type="button" data-source="top" class="sport-card sport-card-active">
        <div class="sport-card-thumb"><iframe src="api/webview/sports/sport_top.php" loading="lazy" scrolling="no" tabindex="-1"></iframe></div>
        <div class="p-3">
            <p class="text-sm font-bold text-white flex items-center gap-2">Top Sports <span class="pill pill-on text-[10px]">Live Scores</span></p>
            <p class="text-xs text-dark-400 mt-1">Display top live &amp; upcoming matches with scores, team badges, and broadcast info.</p>
        </div>
    </button>
    <button type="button" data-source="tv_today" class="sport-card">
        <div class="sport-card-thumb"><iframe src="api/webview/sports/sport_tv_today.php" loading="lazy" scrolling="no" tabindex="-1"></iframe></div>
        <div class="p-3">
            <p class="text-sm font-bold text-white flex items-center gap-2">Sport on TV Today <span class="pill pill-info text-[10px]">TV Schedule</span></p>
            <p class="text-xs text-dark-400 mt-1">Shows today's live sport TV schedule with channels and broadcast times.</p>
        </div>
    </button>
    <button type="button" data-source="league_table" class="sport-card">
        <div class="sport-card-thumb"><iframe src="api/webview/sports/sport_l_table.php" loading="lazy" scrolling="no" tabindex="-1"></iframe></div>
        <div class="p-3">
            <p class="text-sm font-bold text-white flex items-center gap-2">League Tables <span class="pill pill-info text-[10px]">Standings</span></p>
            <p class="text-xs text-dark-400 mt-1">League standings table showing team rankings, points, and match results.</p>
        </div>
    </button>
    <button type="button" data-source="dashboard" class="sport-card">
        <div class="sport-card-thumb"><iframe src="api/webview/sports/dashboard.php" loading="lazy" scrolling="no" tabindex="-1"></iframe></div>
        <div class="p-3">
            <p class="text-sm font-bold text-white flex items-center gap-2">Sports Dashboard <span class="pill pill-info text-[10px]">Leagues</span></p>
            <p class="text-xs text-dark-400 mt-1">Full sports dashboard with sidebar navigation, league fixtures, and results.</p>
        </div>
    </button>
    <button type="button" data-source="external" class="sport-card">
        <div class="sport-card-thumb" style="background:#1a1a1a;"></div>
        <div class="p-3">
            <p class="text-sm font-bold text-white flex items-center gap-2">External URL <span class="pill pill-off text-[10px]">External</span></p>
            <p class="text-xs text-dark-400 mt-1">Custom external URL — add your own sport TV guide or any web page.</p>
        </div>
    </button>
</div>

<!-- Feed provider + sync controls -->
<div class="card mb-6">
    <div class="card-head"><h3><i class="ph ph-download text-primary-400"></i> Feed Provider</h3></div>
    <div class="p-5 grid grid-cols-1 lg:grid-cols-[1fr_280px] gap-5">
        <div class="space-y-4">
            <div>
                <label class="form-label text-xs">Provider</label>
                <select class="form-input" id="provider-select">
                    <option value="free">Free sports feed (no key required)</option>
                    <option value="paid">Premium sports feed (uses the key below)</option>
                </select>
            </div>
            <div id="paid-key-row">
                <label class="form-label text-xs">Premium API Key</label>
                <input class="form-input mono" id="paid-key" placeholder="your key">
                <p class="text-[10px] text-dark-400 mt-1">Paste your premium sports feed key here.</p>
            </div>
            <div class="flex gap-2 pt-2">
                <button id="save-provider" class="btn-secondary text-xs"><i class="ph ph-floppy-disk"></i> Save provider</button>
                <button id="run-sync" class="btn-primary text-xs"><i class="ph ph-arrows-clockwise"></i> Pull now</button>
            </div>
        </div>
        <div id="sync-status" class="text-xs text-dark-400 p-4 rounded-lg border border-dark-700 bg-dark-900/40">
            Loading sync status…
        </div>
    </div>
</div>

<!-- Per-source preview panels: form on left, live iframe preview on right.
     Only the panel for the active source card is visible. -->
<div id="sport-panels-host">
    <?php
    $sources = [
        'top' => [
            'label'   => 'Sports Provider',
            'iframe'  => 'api/webview/sports/sport_top.php',
            'options' => [ ['top','Top Sports'], ['tv_today','Sport on TV Today'], ['league_table','League Tables'], ['dashboard','Sports Dashboard'] ],
            'fields'  => [],
        ],
        'tv_today' => [
            'label'   => 'Sports Provider',
            'iframe'  => 'api/webview/sports/sport_tv_today.php',
            'options' => [ ['tv_today','Sport on TV Today'], ['top','Top Sports'], ['league_table','League Tables'], ['dashboard','Sports Dashboard'] ],
            'fields'  => [],
        ],
        'league_table' => [
            'label'   => 'Sports Provider',
            'iframe'  => 'api/webview/sports/sport_l_table.php',
            'options' => [ ['league_table','League Tables'], ['top','Top Sports'], ['tv_today','Sport on TV Today'], ['dashboard','Sports Dashboard'] ],
            'fields'  => [
                ['type'=>'text','name'=>'sports_api_key','label'=>'API Key','placeholder'=>'your key'],
                ['type'=>'text','name'=>'league_search','label'=>'Search','placeholder'=>'Premier League'],
            ],
        ],
        'dashboard' => [
            'label'   => 'Sports Provider',
            'iframe'  => 'api/webview/sports/dashboard.php',
            'options' => [ ['dashboard','Sports Dashboard'], ['top','Top Sports'], ['tv_today','Sport on TV Today'], ['league_table','League Tables'] ],
            'fields'  => [
                ['type'=>'text','name'=>'sports_api_key','label'=>'API Key','placeholder'=>'your key'],
                ['type'=>'text','name'=>'league_filter','label'=>'Search','placeholder'=>'Premier League'],
            ],
        ],
        'external' => [
            'label'   => 'External URL',
            'iframe'  => '',
            'options' => [ ['external','External URL'] ],
            'fields'  => [
                ['type'=>'url','name'=>'external_url','label'=>'URL','placeholder'=>'https://www.sport-tv-guide.live/'],
            ],
        ],
    ];
    foreach ($sources as $key => $src):
        $isActive = ($key === 'top');
    ?>
    <div class="sport-panel<?php echo $isActive ? ' active' : ''; ?>" data-key="<?php echo h($key); ?>"
         style="<?php echo $isActive ? '' : 'display:none;'; ?>">
        <div class="sport-panel-inner">
            <div class="sport-panel-form">
                <div class="sport-panel-label"><?php echo h($src['label']); ?></div>
                <div class="sp-field">
                    <label class="form-label text-xs">Widget</label>
                    <select class="form-input">
                        <?php foreach ($src['options'] as $opt): ?>
                            <option value="<?php echo h($opt[0]); ?>"><?php echo h($opt[1]); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php foreach ($src['fields'] as $f): ?>
                <div class="sp-field">
                    <label class="form-label text-xs"><?php echo h($f['label']); ?></label>
                    <input type="<?php echo h($f['type']); ?>" name="<?php echo h($f['name']); ?>"
                           class="form-input <?php echo $f['type'] === 'url' ? 'mono' : ''; ?>"
                           placeholder="<?php echo h($f['placeholder']); ?>">
                </div>
                <?php endforeach; ?>
                <div class="sp-actions">
                    <button type="button" onclick="saveSportPanel('<?php echo h($key); ?>', this)" class="btn-primary text-xs">
                        <i class="ph ph-floppy-disk"></i> Save
                    </button>
                    <button type="button" onclick="openSportFullscreen('<?php echo h($src['iframe']); ?>')" class="btn-outline text-xs">
                        <i class="ph ph-arrows-out"></i> View Fullscreen
                    </button>
                </div>
            </div>
            <div class="sport-panel-preview">
                <?php if ($src['iframe']): ?>
                    <iframe <?php echo $isActive ? 'src="' . h($src['iframe']) . '"' : ''; ?>
                            data-src="<?php echo h($src['iframe']); ?>"
                            scrolling="no" tabindex="-1"></iframe>
                <?php else: ?>
                    <div class="sport-panel-empty">
                        <i class="ph ph-link-simple text-3xl mb-2 opacity-40"></i>
                        <p>Enter an external URL above to preview.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<style>
.sport-card { background: #111; border: 1px solid #2a2a2a; border-radius: 8px;
    overflow: hidden; text-align: left; cursor: pointer; transition: border-color .15s; }
.sport-card:hover { border-color: #f39c12; }
.sport-card-active { border-color: #f39c12 !important; box-shadow: 0 0 0 1px #f39c12; }
.sport-card-thumb {
    position: relative;
    height: 130px;
    background: #0a0a0a;
    overflow: hidden;
    pointer-events: none;
}
.sport-card-thumb iframe {
    /* Render the live content at 4x the card width then scale it down so it
       looks like a thumbnail preview of the real webview output. */
    border: 0;
    position: absolute;
    top: 0; left: 0;
    width: 400%; height: 400%;
    transform: scale(0.25);
    transform-origin: 0 0;
    background: #0a0a0a;
}

/* Per-source bottom preview panels */
.sport-panel { display: none; }
.sport-panel.active { display: block; }
.sport-panel-inner {
    display: grid;
    grid-template-columns: 320px 1fr;
    gap: 24px;
    background: #111;
    border: 1px solid #2a2a2a;
    border-radius: 12px;
    overflow: hidden;
}
@media (max-width: 900px) {
    .sport-panel-inner { grid-template-columns: 1fr; }
}
.sport-panel-form { padding: 20px; border-right: 1px solid #1e1e1e; }
@media (max-width: 900px) {
    .sport-panel-form { border-right: 0; border-bottom: 1px solid #1e1e1e; }
}
.sport-panel-label {
    color: #f39c12; font-size: 13px; font-weight: 700;
    padding-bottom: 12px; margin-bottom: 14px;
    border-bottom: 1px solid #1e1e1e;
}
.sp-field { margin-bottom: 14px; }
.sp-actions { display: flex; gap: 10px; margin-top: 18px; }
.sport-panel-preview {
    background: #0a0a0a;
    min-height: 420px;
    position: relative;
}
.sport-panel-preview iframe {
    border: 0;
    width: 100%;
    height: 100%;
    min-height: 420px;
    display: block;
}
.sport-panel-empty {
    position: absolute; inset: 0;
    display: flex; flex-direction: column;
    align-items: center; justify-content: center;
    color: #555; font-size: 13px; text-align: center; padding: 24px;
}

/* Presentation-mode fullscreen for sports preview */
#sport-fs-modal {
    display: none; position: fixed; inset: 0; z-index: 9999;
    background: #000;
}
#sport-fs-modal iframe { width: 100%; height: 100%; border: 0; }
#sport-fs-close {
    position: absolute; top: 14px; right: 14px; z-index: 10000;
    width: 40px; height: 40px; border-radius: 50%; border: 0;
    background: rgba(0,0,0,.7); color: #fff;
    display: flex; align-items: center; justify-content: center;
    cursor: pointer; font-size: 18px;
    backdrop-filter: blur(4px);
}
#sport-fs-close:hover { background: rgba(239,68,68,.85); }
</style>

<script>
const cards = document.querySelectorAll('.sport-card');
function showSportPanel(key) {
    document.querySelectorAll('.sport-panel').forEach(p => {
        const active = p.dataset.key === key;
        p.classList.toggle('active', active);
        p.style.display = active ? 'block' : 'none';
        if (active) {
            const ifr = p.querySelector('iframe[data-src]');
            // Browsers auto-resolve empty src to parent URL, so we check the
            // raw attribute via getAttribute, not the resolved .src property.
            if (ifr && !ifr.getAttribute('src') && ifr.dataset.src) {
                ifr.setAttribute('src', ifr.dataset.src);
            }
        }
    });
}
cards.forEach(c => c.addEventListener('click', () => {
    cards.forEach(x => x.classList.remove('sport-card-active'));
    c.classList.add('sport-card-active');
    showSportPanel(c.dataset.source);
}));

async function saveSportPanel(key, btn) {
    const panel = btn.closest('.sport-panel');
    const widget = panel.querySelector('.sp-field select')?.value || '';
    const inputs = panel.querySelectorAll('.sp-field input');
    // Input `name=` attrs already carry their canonical key (e.g. `sports_api_key`,
    // `external_url`). Don't double-prefix — that was the save-but-never-readback bug.
    const pairs = { action: 'save', ['sports_widget_' + key]: widget };
    inputs.forEach(i => { if (i.name) pairs[i.name] = i.value; });
    try {
        await api.post('api/webview_settings.php', pairs);
        toast('Sports panel saved (' + key + ')', 'success');
    } catch (e) { toast(e.message, 'error'); }
}
function openSportFullscreen(url) {
    if (!url) { toast('No URL set yet', 'warn'); return; }
    let host = document.getElementById('sport-fs-modal');
    if (!host) {
        host = document.createElement('div');
        host.id = 'sport-fs-modal';
        host.innerHTML = '<button id="sport-fs-close" title="Close (Esc)">' +
                         '<i class="ph ph-x"></i></button>' +
                         '<iframe id="sport-fs-iframe" allow="fullscreen"></iframe>';
        document.body.appendChild(host);
        host.querySelector('#sport-fs-close').addEventListener('click', closeSportFullscreen);
        document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeSportFullscreen(); });
    }
    host.querySelector('#sport-fs-iframe').src = url;
    host.style.display = 'block';
    if (host.requestFullscreen) host.requestFullscreen().catch(() => {});
}
function closeSportFullscreen() {
    const host = document.getElementById('sport-fs-modal');
    if (!host) return;
    host.style.display = 'none';
    host.querySelector('iframe').src = '';
    if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
}

// -- Provider + sync status --
async function refreshStatus() {
    try {
        const s = await api.get('api/sports/sync.php?action=status');
        document.getElementById('provider-select').value = s.sports_provider || 'free';
        document.getElementById('paid-key').placeholder = s.paid_key_set ? '••••••• (set)' : 'your key';
        const last = s.last;
        document.getElementById('sync-status').innerHTML =
            '<p class="text-white font-semibold mb-1">Sync status</p>' +
            '<p>Leagues: <span class="text-primary-400 font-bold">' + (s.league_count||0) + '</span></p>' +
            '<p>Events: <span class="text-primary-400 font-bold">' + (s.event_count||0) + '</span></p>' +
            (last
                ? '<p class="mt-2">Last run: ' + new Date(last.started_at*1000).toLocaleString() + '<br>' +
                  'Provider: <span class="mono">'+ (last.provider||'') +'</span> · ' +
                  'OK: ' + (last.ok ? '<span class="text-emerald-400">yes</span>' : '<span class="text-red-400">no</span>') + ' · ' +
                  '+'+ (last.leagues_upserted||0) +' leagues, +'+ (last.events_upserted||0) +' events' +
                  (last.error ? '<br><span class="text-red-400">err: '+ escapeHtml(last.error) +'</span>' : '') + '</p>'
                : '<p class="mt-2 text-dark-500">No sync run yet.</p>');
    } catch (e) {
        document.getElementById('sync-status').textContent = 'Could not load status: ' + e.message;
    }
}
document.getElementById('save-provider').addEventListener('click', async () => {
    try {
        const body = {
            action: 'set_provider',
            provider: document.getElementById('provider-select').value,
        };
        const key = document.getElementById('paid-key').value.trim();
        if (key) body.paid_sportsdb_key = key;
        await api.post('api/sports/sync.php', body);
        document.getElementById('paid-key').value = '';
        toast('Provider saved', 'success');
        refreshStatus();
    } catch (e) { toast(e.message, 'error'); }
});
document.getElementById('run-sync').addEventListener('click', async () => {
    const btn = document.getElementById('run-sync');
    btn.disabled = true; btn.innerHTML = '<i class="ph ph-arrows-clockwise"></i> Syncing…';
    try {
        const r = await api.post('api/sports/sync.php', { action: 'run' });
        if (!r.ok) {
            toast('Sync failed: ' + (r.error || 'unknown'), 'error');
        } else if (r.events > 0) {
            const tail = r.auto_enabled
                ? ` — auto-enabled ${r.auto_enabled} popular leagues on first run`
                : '';
            toast(`Synced ${r.leagues} leagues, ${r.events} events${tail}`, 'success');
        } else if (r.enabled_now === 0) {
            toast(`Loaded ${r.leagues} leagues. Enable some on the Leagues tab to pull match data.`, 'warn');
        } else {
            toast(`Loaded ${r.leagues} leagues but no fixtures came back. Check again later.`, 'warn');
        }
        refreshStatus();
    } catch (e) {
        toast(e.message, 'error');
    } finally {
        btn.disabled = false; btn.innerHTML = '<i class="ph ph-arrows-clockwise"></i> Pull now';
    }
});
refreshStatus();
</script>

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