<?php
if (!defined('WPINC')) {
    die;
}
?>

<div class="aysa-admin aysa-sitemap-competition">
    <div class="aysa-page-title">
        <h1>Sitemap Competition</h1>
        <div class="aysa-title-right">
            <?php if (class_exists('Aysa_Credits_Component')) {
                Aysa_Credits_Component::display();
            } ?>
        </div>
    </div>

    <div class="aysa-top-tabs">
        <a href="admin.php?page=aysa-research&tab=keyword-discovery" class="aysa-tab">Keyword Discovery</a>
        <a href="admin.php?page=aysa-research&tab=competitor-gap" class="aysa-tab">Competitor Keyword Gap</a>
        <a href="admin.php?page=aysa-research&tab=competitor-identification" class="aysa-tab">Competitor Identification</a>
        <a href="admin.php?page=aysa-research&tab=competitor-backlinks" class="aysa-tab">Competitor Backlink Analysis</a>
        <a href="admin.php?page=aysa-research&tab=missing-pages" class="aysa-tab">Missing Pages</a>
        <a href="admin.php?page=aysa-research&tab=content-strategy" class="aysa-tab">Content Strategy</a>
        <div class="aysa-tab active">Sitemap Competition</div>
    </div>

    <div class="aysa-content">
        <div class="aysa-sitemap-card">
            <div class="aysa-sitemap-head">
                <div>
                    <h2>Sitemap Competition</h2>
                    <p>Compile competitor content inventory from sitemap + page fetch, then generate a local article catch-up map. This module runs only when you open this tab and trigger it explicitly.</p>
                </div>
                <div class="aysa-sitemap-actions">
                    <button type="button" class="button button-primary" id="aysa-sitemap-competition-start">Refresh map</button>
                    <button type="button" class="button" id="aysa-sitemap-competition-reload">Reload</button>
                </div>
            </div>

            <div class="aysa-sitemap-status" id="aysa-sitemap-competition-status">Loading sitemap competition overview...</div>

            <div class="aysa-sitemap-grid">
                <div class="aysa-sitemap-kpi">
                    <small>Competitors</small>
                    <strong id="aysa-sitemap-kpi-competitors">0</strong>
                </div>
                <div class="aysa-sitemap-kpi">
                    <small>Inventory Items</small>
                    <strong id="aysa-sitemap-kpi-items">0</strong>
                </div>
                <div class="aysa-sitemap-kpi">
                    <small>Blog Post Gaps</small>
                    <strong id="aysa-sitemap-kpi-missing">0</strong>
                </div>
                <div class="aysa-sitemap-kpi">
                    <small>Last Update</small>
                    <strong id="aysa-sitemap-kpi-updated">-</strong>
                </div>
            </div>
        </div>

        <div class="aysa-sitemap-layout">
            <div class="aysa-sitemap-card">
                <div class="aysa-card-head">
                    <h3>Competitor Inventory</h3>
                    <p>Domains and sitemap scan status.</p>
                </div>
                <div class="aysa-table-wrap">
                    <table class="widefat striped">
                        <thead>
                            <tr>
                                <th>Competitor</th>
                                <th>Status</th>
                                <th>Sitemaps</th>
                                <th>URLs</th>
                                <th>Fetched</th>
                                <th>Articles</th>
                                <th>Products</th>
                            </tr>
                        </thead>
                        <tbody id="aysa-sitemap-competition-competitors">
                            <tr><td colspan="7">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="aysa-sitemap-card">
                <div class="aysa-card-head">
                    <h3>Content Inventory Summary</h3>
                    <p>Aggregated full inventory by content type.</p>
                </div>
                <div class="aysa-table-wrap">
                    <table class="widefat striped">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Count</th>
                            </tr>
                        </thead>
                        <tbody id="aysa-sitemap-competition-summary">
                            <tr><td colspan="2">Loading...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="aysa-sitemap-card">
            <div class="aysa-card-head">
                <h3>Full Inventory by Competitor</h3>
                <p>This is the primary output: full competitor inventory grouped by competitor and content type.</p>
            </div>
            <div class="aysa-table-wrap">
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>Competitor</th>
                            <th>Content Type</th>
                            <th>Count</th>
                        </tr>
                    </thead>
                    <tbody id="aysa-sitemap-competition-inventory">
                        <tr><td colspan="3">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="aysa-sitemap-card">
            <div class="aysa-card-head">
                <h3>Local Blog Post Catch-up Todo</h3>
                <p>`Full Inventory` is primary. This overlay maps only real blog posts to your local site.</p>
            </div>
            <div class="aysa-table-wrap">
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>Competitor</th>
                            <th>Competitor Article</th>
                            <th>Topic</th>
                            <th>Local Status</th>
                            <th>Suggested Action</th>
                            <th>Matched Local URL</th>
                        </tr>
                    </thead>
                    <tbody id="aysa-sitemap-competition-todo">
                        <tr><td colspan="6">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="aysa-sitemap-card">
            <div class="aysa-card-head">
                <h3>Scan History</h3>
                <p>Stored runs for this module only. It does not share execution with the other Research tabs.</p>
            </div>
            <div class="aysa-table-wrap">
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th>Run</th>
                            <th>Status</th>
                            <th>Competitors</th>
                            <th>Articles</th>
                            <th>Updated</th>
                        </tr>
                    </thead>
                    <tbody id="aysa-sitemap-competition-history">
                        <tr><td colspan="5">Loading...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.aysa-sitemap-competition .aysa-content { display:flex; flex-direction:column; gap:20px; }
.aysa-sitemap-card { background:#fff; border:1px solid #d9e1ea; border-radius:16px; padding:20px; box-shadow:0 8px 24px rgba(15,23,42,.05); }
.aysa-sitemap-head, .aysa-card-head { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:16px; }
.aysa-sitemap-head h2, .aysa-card-head h3 { margin:0 0 6px; }
.aysa-sitemap-head p, .aysa-card-head p { margin:0; color:#5b6574; }
.aysa-sitemap-actions { display:flex; gap:10px; }
.aysa-sitemap-status { margin-bottom:16px; color:#334155; font-weight:600; }
.aysa-sitemap-grid { display:grid; grid-template-columns:repeat(4, minmax(0,1fr)); gap:14px; }
.aysa-sitemap-kpi { border:1px solid #e5e7eb; border-radius:14px; padding:14px 16px; background:#f8fafc; }
.aysa-sitemap-kpi small { display:block; margin-bottom:8px; color:#64748b; text-transform:uppercase; font-size:11px; letter-spacing:.08em; }
.aysa-sitemap-kpi strong { font-size:20px; color:#0f172a; }
.aysa-sitemap-layout { display:grid; grid-template-columns:1.5fr 1fr; gap:20px; }
.aysa-table-wrap { overflow:auto; }
.aysa-sitemap-pill { display:inline-block; padding:4px 10px; border-radius:999px; background:#eef2ff; color:#3730a3; font-size:12px; font-weight:600; }
.aysa-sitemap-pill.status-failed { background:#fee2e2; color:#991b1b; }
.aysa-sitemap-pill.status-partial { background:#fef3c7; color:#92400e; }
.aysa-sitemap-pill.status-completed { background:#dcfce7; color:#166534; }
.aysa-sitemap-pill.status-running { background:#dbeafe; color:#1d4ed8; }
@media (max-width: 1200px) {
    .aysa-sitemap-grid, .aysa-sitemap-layout { grid-template-columns:1fr; }
}
</style>

<script type="text/javascript">
(function () {
    function initSitemapCompetition() {
    if (!window.location.search.includes('page=aysa-research') || !window.location.search.includes('tab=sitemap-competition')) {
        return;
    }

    const ajaxUrl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;
    const nonce = <?php echo wp_json_encode(wp_create_nonce('aysa_nonce')); ?>;
    const statusEl = document.getElementById('aysa-sitemap-competition-status');
    const btnStart = document.getElementById('aysa-sitemap-competition-start');
    const btnReload = document.getElementById('aysa-sitemap-competition-reload');
    let statusPollTimer = null;

    function post(action, extra = {}) {
        const body = new URLSearchParams({ action, nonce, ...extra });
        return fetch(ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString(),
            credentials: 'same-origin'
        }).then((response) => response.json());
    }

    function htmlEscape(value) {
        return String(value ?? '').replace(/[&<>"']/g, function (char) {
            return ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;' })[char];
        });
    }

    function renderOverview(payload) {
        const run = payload?.local?.run || payload?.run || null;
        const overview = run?.overview || {};
        const todoRows = payload?.local?.todo_rows || [];
        const inventoryRows = payload?.local?.inventory_rows || [];
        const todoSummary = payload?.local?.todo_summary || {};
        const history = payload?.local?.history || payload?.history || [];
        const competitorRows = Array.isArray(overview.competitor_summaries) ? overview.competitor_summaries : [];
        const inventory = overview.inventory_summary || {};
        const inventoryTotal = Object.values(inventory).reduce((sum, value) => {
            const numeric = Number(value || 0);
            return sum + (Number.isFinite(numeric) ? numeric : 0);
        }, 0);

        document.getElementById('aysa-sitemap-kpi-competitors').textContent = String((run?.competitors || []).length || competitorRows.length || 0);
        document.getElementById('aysa-sitemap-kpi-items').textContent = String(inventoryTotal || run?.item_count || 0);
        document.getElementById('aysa-sitemap-kpi-missing').textContent = String(todoSummary.missing || 0);
        document.getElementById('aysa-sitemap-kpi-updated').textContent = run?.updated_at || '-';
        statusEl.textContent = run ? `Latest scan status: ${run.status || 'unknown'}` : 'No sitemap competition scan stored yet.';
        const activeStatus = String(run?.status || '').toLowerCase();
        if (statusPollTimer) {
            clearTimeout(statusPollTimer);
            statusPollTimer = null;
        }
        if (activeStatus === 'queued' || activeStatus === 'running') {
            statusEl.textContent = activeStatus === 'queued'
                ? 'Sitemap competition scan is queued and waiting for worker execution...'
                : 'Sitemap competition scan is running in the background...';
            statusPollTimer = window.setTimeout(loadStatus, 5000);
        }

        const competitorBody = document.getElementById('aysa-sitemap-competition-competitors');
        competitorBody.innerHTML = competitorRows.length ? competitorRows.map((row) => `
            <tr>
                <td>${htmlEscape(row.competitor)}</td>
                <td><span class="aysa-sitemap-pill status-${htmlEscape(row.status)}">${htmlEscape(row.status)}</span></td>
                <td>${htmlEscape(row.sitemap_count || 0)}</td>
                <td>${htmlEscape(row.url_count || 0)}</td>
                <td>${htmlEscape(row.fetched_pages || 0)}</td>
                <td>${htmlEscape(row.inventory_counts?.blog_post || row.inventory_counts?.article || 0)}</td>
                <td>${htmlEscape(row.inventory_counts?.product || 0)}</td>
            </tr>
        `).join('') : '<tr><td colspan="7">No competitor scan rows yet.</td></tr>';

        const summaryBody = document.getElementById('aysa-sitemap-competition-summary');
        const summaryEntries = Object.entries(inventory);
        summaryBody.innerHTML = summaryEntries.length ? summaryEntries.map(([key, value]) => `
            <tr><td>${htmlEscape(key)}</td><td>${htmlEscape(value)}</td></tr>
        `).join('') : '<tr><td colspan="2">No inventory summary yet.</td></tr>';

        const inventoryBody = document.getElementById('aysa-sitemap-competition-inventory');
        inventoryBody.innerHTML = inventoryRows.length ? inventoryRows.map((row) => `
            <tr>
                <td>${htmlEscape(row.competitor_host)}</td>
                <td>${htmlEscape(row.content_type)}</td>
                <td>${htmlEscape(row.total)}</td>
            </tr>
        `).join('') : '<tr><td colspan="3">No full inventory rows yet.</td></tr>';

        const todoBody = document.getElementById('aysa-sitemap-competition-todo');
        todoBody.innerHTML = todoRows.length ? todoRows.slice(0, 60).map((row) => `
            <tr>
                <td>${htmlEscape(row.competitor_source)}</td>
                <td><a href="${htmlEscape(row.competitor_url)}" target="_blank" rel="noopener">${htmlEscape(row.competitor_title || row.competitor_url)}</a></td>
                <td>${htmlEscape(row.estimated_topic)}</td>
                <td><span class="aysa-sitemap-pill">${htmlEscape(row.local_status)}</span></td>
                <td>${htmlEscape(row.suggested_action)}</td>
                <td>${row.matched_url ? `<a href="${htmlEscape(row.matched_url)}" target="_blank" rel="noopener">${htmlEscape(row.matched_url)}</a>` : '—'}</td>
            </tr>
        `).join('') : '<tr><td colspan="6">No article todo rows yet.</td></tr>';

        const historyBody = document.getElementById('aysa-sitemap-competition-history');
        historyBody.innerHTML = history.length ? history.map((row) => `
            <tr>
                <td>#${htmlEscape(row.remote_run_id || row.run_id || row.local_run_id || 0)}</td>
                <td>${htmlEscape(row.status)}</td>
                <td>${htmlEscape((row.overview?.competitor_count) || (row.competitors?.length) || 0)}</td>
                <td>${htmlEscape(row.article_count || row.overview?.inventory_summary?.blog_post || row.overview?.inventory_summary?.article || 0)}</td>
                <td>${htmlEscape(row.updated_at || row.completed_at || '')}</td>
            </tr>
        `).join('') : '<tr><td colspan="5">No history yet.</td></tr>';
    }

    function loadOverview() {
        statusEl.textContent = 'Loading sitemap competition overview...';
        post('aysa_sitemap_competition_get_overview').then((response) => {
            if (!response.success) {
                statusEl.textContent = response.data || 'Failed to load sitemap competition overview.';
                return;
            }
            renderOverview(response.data || {});
        }).catch((error) => {
            statusEl.textContent = error?.message || 'Failed to load sitemap competition overview.';
        });
    }

    function loadStatus() {
        post('aysa_sitemap_competition_get_status').then((response) => {
            if (!response.success) {
                statusEl.textContent = response.data || 'Failed to load sitemap competition status.';
                return;
            }
            renderOverview(response.data || {});
        }).catch((error) => {
            statusEl.textContent = error?.message || 'Failed to load sitemap competition status.';
        });
    }

    btnStart.addEventListener('click', function () {
        btnStart.disabled = true;
        statusEl.textContent = 'Queueing sitemap competition scan...';
        post('aysa_sitemap_competition_start_scan').then((response) => {
            if (!response.success) {
                statusEl.textContent = response.data || 'Sitemap competition scan failed.';
                return;
            }
            renderOverview(response.data || {});
        }).catch((error) => {
            statusEl.textContent = error?.message || 'Sitemap competition scan failed.';
        }).finally(() => {
            btnStart.disabled = false;
        });
    });

    btnReload.addEventListener('click', loadOverview);
    loadOverview();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSitemapCompetition, { once: true });
        return;
    }

    initSitemapCompetition();
})();
</script>
