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

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

<div class="aysa-admin aysa-workspace-v2 aysa-workspace-v2-content">
    <div class="aysa-page-title">
        <h1>Content Strategy</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>
        <a href="admin.php?page=aysa-research&tab=missing-pages" class="aysa-tab">Missing Pages</a>
        <div class="aysa-tab active">Content Strategy</div>
    </div>

    <div class="aysa-v2-shell">
        <div class="aysa-v2-head">
            <div>
                <h2>Content Strategy</h2>
                <p>Planul editorial real generat din research-ul finalizat, grupat după sursa strategică.</p>
            </div>
            <div class="aysa-v2-actions">
                <button type="button" class="button button-primary" id="aysa-cs-refresh">Refresh Live</button>
            </div>
        </div>
        <div id="aysa-cs-meta" class="aysa-v2-meta">Loading workspace…</div>
        <div id="aysa-cs-summary" class="aysa-v2-summary"></div>
        <div id="aysa-cs-groups" class="aysa-v2-groups"></div>
    </div>
</div>

<style>
.aysa-workspace-v2 .aysa-v2-shell{background:#fff;border:1px solid #dbe3ef;border-radius:16px;padding:18px 18px 20px;box-shadow:0 1px 2px rgba(15,23,42,.04)}
.aysa-workspace-v2 .aysa-v2-head{display:flex;justify-content:space-between;gap:16px;align-items:flex-start;margin-bottom:8px}
.aysa-workspace-v2 .aysa-v2-head h2{margin:0 0 6px;font-size:24px;line-height:1.2}
.aysa-workspace-v2 .aysa-v2-head p{margin:0;color:#64748b}
.aysa-workspace-v2 .aysa-v2-meta{font-size:13px;color:#475569;margin-bottom:16px}
.aysa-workspace-v2 .aysa-v2-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:18px}
.aysa-workspace-v2 .aysa-v2-kpi{border:1px solid #dbe3ef;border-radius:12px;padding:12px 14px;background:#f8fafc}
.aysa-workspace-v2 .aysa-v2-kpi small{display:block;font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:.04em;margin-bottom:6px}
.aysa-workspace-v2 .aysa-v2-kpi strong{font-size:24px;color:#0f172a}
.aysa-workspace-v2 .aysa-v2-groups{display:grid;gap:16px}
.aysa-workspace-v2 .aysa-v2-group{border:1px solid #dbe3ef;border-radius:14px;background:#fff;overflow:hidden}
.aysa-workspace-v2 .aysa-v2-group-head{padding:14px 16px;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;gap:12px;align-items:center;background:#f8fafc}
.aysa-workspace-v2 .aysa-v2-group-head h3{margin:0;font-size:18px}
.aysa-workspace-v2 .aysa-v2-count{display:inline-flex;align-items:center;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:700;background:#eef2ff;color:#1e3a8a}
.aysa-workspace-v2 .aysa-v2-item{padding:14px 16px;border-top:1px solid #eef2f7}
.aysa-workspace-v2 .aysa-v2-item:first-child{border-top:0}
.aysa-workspace-v2 .aysa-v2-item-title{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:8px}
.aysa-workspace-v2 .aysa-v2-item-title strong{font-size:16px;color:#0f172a}
.aysa-workspace-v2 .aysa-v2-badges{display:flex;flex-wrap:wrap;gap:6px}
.aysa-workspace-v2 .aysa-v2-badge{display:inline-flex;align-items:center;padding:2px 8px;border-radius:999px;border:1px solid #dbe3ef;background:#f8fafc;font-size:11px;font-weight:700;color:#334155}
.aysa-workspace-v2 .is-transactional,.aysa-workspace-v2 .is-commercial,.aysa-workspace-v2 .is-local{background:#dcfce7;border-color:#bbf7d0;color:#166534}
.aysa-workspace-v2 .is-informational{background:#e0f2fe;border-color:#bae6fd;color:#0369a1}
.aysa-workspace-v2 .aysa-v2-item-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;color:#475569;font-size:13px;margin-bottom:8px}
.aysa-workspace-v2 .aysa-v2-proposed{padding:10px 12px;border-radius:10px;background:#f8fafc;border:1px solid #e2e8f0;color:#0f172a}
.aysa-workspace-v2 .aysa-v2-proposed small{display:block;font-size:11px;text-transform:uppercase;color:#64748b;margin-bottom:4px}
.aysa-workspace-v2 .aysa-v2-secondary{color:#334155;font-size:13px;margin-top:8px}
.aysa-workspace-v2 .aysa-v2-secondary code{background:#f8fafc;padding:2px 6px;border-radius:6px;border:1px solid #e2e8f0}
</style>

<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-cs-meta');
    const summaryEl = document.getElementById('aysa-cs-summary');
    const groupsEl = document.getElementById('aysa-cs-groups');
    const refreshBtn = document.getElementById('aysa-cs-refresh');

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

    function renderSummary(summary) {
        const items = [
            ['Strategy sets', summary.strategy_sets || summary.group_count || 0],
            ['Items', summary.total_items || 0],
            ['Articles', summary.articles || 0],
            ['Landing pages', summary.landing_pages || 0]
        ];
        const statusRows = summary.statuses && typeof summary.statuses === 'object'
            ? Object.keys(summary.statuses).map(function (key) {
                return '<div class="aysa-v2-kpi"><small>Status</small><strong>' + esc(key) + ': ' + esc(summary.statuses[key]) + '</strong></div>';
            }).join('')
            : '';
        summaryEl.innerHTML = items.map(function (item) {
            return '<div class="aysa-v2-kpi"><small>' + esc(item[0]) + '</small><strong>' + esc(item[1]) + '</strong></div>';
        }).join('') + statusRows;
    }

    function normalizeStrategyLabel(value) {
        const normalized = String(value || '').trim();
        if (!normalized) {
            return 'general';
        }
        return normalized.replace(/[_-]+/g, ' ');
    }

    function renderDateLine(item) {
        const published = String(item.published_at || '').trim();
        const scheduled = String(item.scheduled_for || item.scheduled_for_local || '').trim();
        const generated = String(item.generated_at || '').trim();
        if (published) {
            return '<div><strong>Published:</strong> ' + esc(published) + '</div>';
        }
        if (scheduled) {
            return '<div><strong>Scheduled:</strong> ' + esc(scheduled) + '</div>';
        }
        if (generated) {
            return '<div><strong>Generated:</strong> ' + esc(generated) + '</div>';
        }
        return '<div><strong>Published:</strong> not yet</div>';
    }

    function renderGroups(groups) {
        if (!Array.isArray(groups) || !groups.length) {
            groupsEl.innerHTML = '<div class="aysa-v2-group"><div class="aysa-v2-group-head"><h3>No content strategy ideas</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 badges = []
                    .concat(item.sources || [])
                    .concat([
                        item.strategy_type || item.content_bucket || '',
                        item.intent || '',
                        item.target_page_type || item.recommended_page_type || '',
                        item.execution_stage || item.selection_state || '',
                        item.status || 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 primaryTitle = String(item.title || item.primary_keyword || '').trim() || 'Untitled';
                const primaryKeyword = String(item.primary_keyword || '').trim();
                const secondary = Array.isArray(item.secondary_keywords) && item.secondary_keywords.filter(Boolean).length
                    ? '<div class="aysa-v2-secondary"><strong>Secondary:</strong> ' + item.secondary_keywords.filter(Boolean).map(function (keyword) { return '<code>' + esc(keyword) + '</code>'; }).join(' ') + '</div>'
                    : '';
                const associatedPage = String(item.associated_page || '').trim()
                    ? '<div><strong>Associated page:</strong> ' + esc(item.associated_page) + '</div>'
                    : '<div><strong>Associated page:</strong> not linked yet</div>';
                const journeyStage = String(item.journey_stage || '').trim()
                    ? '<div><strong>Journey stage:</strong> ' + esc(item.journey_stage) + '</div>'
                    : '';
                const audience = [item.persona_key || '', item.locality_key || '', item.seasonality_key || ''].filter(Boolean).join(' · ');
                const audienceLine = audience
                    ? '<div><strong>Signals:</strong> ' + esc(audience) + '</div>'
                    : '';
                return '<div class="aysa-v2-item">'
                    + '<div class="aysa-v2-item-title"><strong>' + esc(primaryTitle) + '</strong><div class="aysa-v2-badges">' + badges + '</div></div>'
                    + '<div class="aysa-v2-item-grid">'
                    + '<div><strong>Primary keyword:</strong> ' + esc(primaryKeyword || '-') + '</div>'
                    + '<div><strong>Strategy:</strong> ' + esc(normalizeStrategyLabel(item.strategy_type || item.content_bucket || 'general')) + '</div>'
                    + associatedPage
                    + renderDateLine(item)
                    + journeyStage
                    + audienceLine
                    + '</div>'
                    + '<div class="aysa-v2-proposed"><small>Recommended title</small>' + esc(item.proposed_title || primaryTitle) + '</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_content_strategy_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) : 'Content Strategy workspace failed.');
        }
        const data = result.data;
        const cache = data.cache_meta || {};
        metaEl.textContent = 'Build: ' + esc(data.build || 'CSV') + ' | source: ' + esc(cache.source || data.source || 'live_refresh') + ' @ ' + esc(cache.cached_at || data.refreshed_at || '') + ' | selection: ' + esc(data.selection_mode || '');
        renderSummary(data.summary || {});
        renderGroups(data.groups || []);
    }

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

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