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

$project_id = intval(get_option('aysa_project_id', 0));
?>

<div class="aysa-admin aysa-workspace-v2 aysa-workspace-v2-missing">
    <div class="aysa-page-title">
        <h1>Missing Pages</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&kdv2_tab=gsc_v2" class="aysa-tab">Google Search Console</a>
        <a href="admin.php?page=aysa-research&tab=keyword-discovery&kdv2_tab=dataforseo_v2" class="aysa-tab">Sugestii keywords</a>
        <a href="admin.php?page=aysa-research&tab=keyword-discovery&kdv2_tab=competitor_gap_v2" class="aysa-tab">Competitor Gap</a>
        <a href="admin.php?page=aysa-research&tab=keyword-discovery&kdv2_tab=keyword_mapping_v2" class="aysa-tab">Keyword Mapping</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>
        <div class="aysa-tab active">Missing Pages</div>
        <a href="admin.php?page=aysa-research&tab=content-strategy" class="aysa-tab">Content Strategy</a>
        <a href="admin.php?page=aysa-research&tab=sitemap-competition" class="aysa-tab">Sitemap Competition</a>
    </div>

    <div class="aysa-v2-shell">
        <div class="aysa-v2-head">
            <div>
                <h2>Missing Pages</h2>
                <p>Built from Keyword Mapping review + not-mapped clusters. No legacy keyword table feed.</p>
            </div>
            <div class="aysa-v2-actions">
                <button type="button" class="button button-primary" id="aysa-mp-refresh">Refresh Live</button>
            </div>
        </div>
        <div id="aysa-mp-meta" class="aysa-v2-meta">Loading workspace…</div>
        <div id="aysa-mp-summary" class="aysa-v2-summary"></div>
        <div id="aysa-mp-groups" class="aysa-v2-groups"></div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const projectId = <?php echo (int) $project_id; ?>;
    const nonce = '<?php echo esc_js(wp_create_nonce('aysa_keyword_cache_nonce')); ?>';
    const metaEl = document.getElementById('aysa-mp-meta');
    const summaryEl = document.getElementById('aysa-mp-summary');
    const groupsEl = document.getElementById('aysa-mp-groups');
    const refreshBtn = document.getElementById('aysa-mp-refresh');

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

    function renderSummary(summary) {
        const items = [
            ['Selected clusters', summary.selected_clusters || 0],
            ['Groups', summary.group_count || 0],
            ['Items', summary.total_items || 0]
        ];
        summaryEl.innerHTML = items.map(function (item) {
            return '<div class="aysa-v2-kpi"><small>' + esc(item[0]) + '</small><strong>' + esc(item[1]) + '</strong></div>';
        }).join('');
    }

    function renderGroups(groups) {
        if (!Array.isArray(groups) || !groups.length) {
            groupsEl.innerHTML = '<div class="aysa-v2-group"><div class="aysa-v2-group-head"><h3>No missing pages</h3></div><div class="aysa-v2-item">Nothing eligible from the selected clusters.</div></div>';
            return;
        }
        groupsEl.innerHTML = groups.map(function (group) {
            const items = (group.items || []).map(function (item) {
                const secondary = Array.isArray(item.secondary_keywords) && item.secondary_keywords.length
                    ? '<div class="aysa-v2-secondary"><strong>Secondary:</strong> ' + item.secondary_keywords.map(function (keyword) { return '<code>' + esc(keyword) + '</code>'; }).join(' ') + '</div>'
                    : '';
                const badges = []
                    .concat(item.sources || [])
                    .concat([item.intent || '', item.opportunity_type || '', item.page_type || '', item.selection_state || '', item.mapping_status || ''])
                    .filter(Boolean)
                    .map(function (badge) {
                        const cls = ['transactional','commercial','informational','local'].includes(String(badge).toLowerCase()) ? ' is-' + String(badge).toLowerCase() : '';
                        return '<span class="aysa-v2-badge' + cls + '">' + esc(badge) + '</span>';
                    }).join('');
                const matchConfidence = item.mapping_confidence != null ? (Number(item.mapping_confidence) * 100).toFixed(1) + '%' : '';
                const matchedPage = item.matched_page && item.matched_page.url ? String(item.matched_page.url) : '';
                return '<div class="aysa-v2-item">'
                    + '<div class="aysa-v2-item-title"><strong>' + esc(item.primary_keyword) + '</strong><div class="aysa-v2-badges">' + badges + '</div></div>'
                    + '<div class="aysa-v2-item-grid">'
                    + '<div><strong>Priority:</strong> ' + esc(item.priority_score) + '</div>'
                    + '<div><strong>Cluster:</strong> ' + esc(item.cluster_type) + '</div>'
                    + '<div><strong>Opportunity:</strong> ' + esc(item.opportunity_type || '') + '</div>'
                    + '<div><strong>Suggested page:</strong> ' + esc(item.proposed_page_title) + '</div>'
                    + (matchConfidence ? '<div><strong>Current match:</strong> ' + esc(matchConfidence) + '</div>' : '')
                    + '</div>'
                    + '<div class="aysa-v2-secondary"><strong>Why missing:</strong> ' + esc(item.missing_reason || 'No explanation available.') + '</div>'
                    + (matchedPage ? '<div class="aysa-v2-secondary aysa-v2-muted"><strong>Best current match:</strong> ' + esc(matchedPage) + '</div>' : '')
                    + secondary
                    + '</div>';
            }).join('');
            return '<section class="aysa-v2-group"><div class="aysa-v2-group-head"><h3>' + esc(group.label) + '</h3><span class="aysa-v2-count">' + esc(group.count) + '</span></div>' + items + '</section>';
        }).join('');
    }

    async function loadWorkspace(forceRefresh) {
        metaEl.textContent = forceRefresh ? 'Refreshing live data…' : 'Loading snapshot…';
        const body = new URLSearchParams({
            action: 'aysa_missing_pages_v1_workspace',
            nonce: nonce,
            project_id: String(projectId),
            force_refresh: forceRefresh ? '1' : '0'
        });
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: body.toString()
        });
        const result = await response.json();
        if (!result || !result.success || !result.data) {
            throw new Error((result && result.data) ? String(result.data) : 'Missing Pages workspace failed.');
        }
        const data = result.data;
        const cache = data.cache_meta || {};
        const flags = Array.isArray(data.quality_flags) && data.quality_flags.length ? ' | flags: ' + data.quality_flags.join(', ') : '';
        metaEl.textContent = 'Build: ' + esc(data.build || 'MPV1') + ' | source: ' + esc(cache.source || 'live_refresh') + ' @ ' + esc(cache.cached_at || '') + ' | selection: ' + esc(data.selection_mode || '') + flags;
        renderSummary(data.summary || {});
        renderGroups(data.groups || []);
    }

    refreshBtn.addEventListener('click', function () {
        loadWorkspace(true).catch(function (error) {
            metaEl.textContent = error.message || 'Missing Pages workspace failed.';
        });
    });

    loadWorkspace(false).catch(function (error) {
        metaEl.textContent = error.message || 'Missing Pages workspace failed.';
    });
});
</script>
