<?php
if (!defined('ABSPATH')) {
    exit;
}

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$il_project_id = intval(get_option('aysa_current_project_id', 0));
if (isset($this) && method_exists($this, 'aysa_resolve_project_id_with_local_fallback')) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $il_project_id = $this->aysa_resolve_project_id_with_local_fallback($il_project_id);
}

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
$il_workspace = array(
    'summary' => array(
        'all' => 0,
        'needs_review' => 0,
        'ready_to_apply' => 0,
        'applied_by_aysa' => 0,
        'conflict' => 0,
        'manual_only' => 0,
        'invalid_target' => 0,
        'status' => 'idle',
        'current_milestone' => '',
    ),
    'filters' => array(),
    'rows' => array(),
    'pagination' => array(
        'page' => 1,
        'per_page' => 50,
        'total' => 0,
        'pages' => 1,
    ),
    'run' => array(),
);

if ($il_project_id > 0 && isset($this) && method_exists($this, 'aysa_internal_linking_workspace_service')) {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
    $service = $this->aysa_internal_linking_workspace_service();
    if ($service) {
        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template-local variable in an immediately included admin partial; it is not a public global symbol or persisted contract.
        $il_workspace = $service->build_workspace($il_project_id, array('page' => 1, 'per_page' => 50));
    }
}
?>
<div class="aysa-panel" id="aysa-internal-linking-v2-root" data-project-id="<?php echo esc_attr($il_project_id); ?>">
    <style>
        #aysa-internal-linking-v2-root .aysa-il-v2-toolbar,
        #aysa-internal-linking-v2-root .aysa-il-v2-filter-row,
        #aysa-internal-linking-v2-root .aysa-il-v2-actions {
            display:flex;
            justify-content:space-between;
            align-items:center;
            gap:12px;
            flex-wrap:wrap;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-actions,
        #aysa-internal-linking-v2-root .aysa-il-v2-filter-row {
            justify-content:flex-start;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-summary {
            display:grid;
            grid-template-columns:repeat(auto-fit,minmax(150px,1fr));
            gap:12px;
            margin:14px 0 18px;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-card,
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-card {
            background:#fff;
            border:1px solid #dcdcde;
            border-radius:10px;
            padding:14px 16px;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-card-value {
            font-size:24px;
            font-weight:700;
            margin-top:4px;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-chip {
            display:inline-flex;
            align-items:center;
            gap:6px;
            border:1px solid #c3c4c7;
            background:#fff;
            border-radius:999px;
            padding:7px 12px;
            cursor:pointer;
            font-size:13px;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-chip.is-active {
            background:#2271b1;
            border-color:#2271b1;
            color:#fff;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-chip-count {
            display:inline-flex;
            min-width:22px;
            justify-content:center;
            padding:1px 6px;
            border-radius:999px;
            background:rgba(29,35,39,.08);
            font-size:12px;
            font-weight:600;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-chip.is-active .aysa-il-v2-chip-count {
            background:rgba(255,255,255,.18);
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-table-wrap {
            border:1px solid #dcdcde;
            border-radius:10px;
            overflow:hidden;
            background:#fff;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-badge {
            display:inline-flex;
            padding:3px 8px;
            border-radius:999px;
            font-size:12px;
            font-weight:600;
        }
        #aysa-internal-linking-v2-root .aysa-tone-neutral { background:#f0f0f1; color:#1d2327; }
        #aysa-internal-linking-v2-root .aysa-tone-blue { background:#eaf3ff; color:#135e96; }
        #aysa-internal-linking-v2-root .aysa-tone-green { background:#edfaef; color:#0a7d33; }
        #aysa-internal-linking-v2-root .aysa-tone-yellow { background:#fff3cd; color:#996800; }
        #aysa-internal-linking-v2-root .aysa-tone-red { background:#fbeaea; color:#b32d2e; }
        #aysa-internal-linking-v2-root .aysa-il-v2-row { cursor:pointer; }
        #aysa-internal-linking-v2-root .aysa-il-v2-row:hover { background:#f6f7f7; }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer {
            position:fixed; inset:0; z-index:100001; display:none;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer.is-open { display:block; }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-backdrop {
            position:absolute; inset:0; background:rgba(17,24,39,.45);
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-panel {
            position:absolute; top:0; right:0; height:100%; width:min(560px,100%);
            background:#fff; box-shadow:-12px 0 40px rgba(0,0,0,.18); display:flex; flex-direction:column;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-header,
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-footer {
            padding:18px 20px; border-bottom:1px solid #dcdcde;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-footer {
            border-top:1px solid #dcdcde; border-bottom:none; margin-top:auto;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-drawer-body {
            padding:20px; overflow:auto;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-detail-grid {
            display:grid; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); gap:12px; margin:14px 0 18px;
        }
        #aysa-internal-linking-v2-root .aysa-il-v2-empty {
            padding:28px 22px; text-align:center; color:#646970;
        }
    </style>

    <div class="aysa-il-v2-toolbar">
        <div>
            <h2 class="aysa-section-title">Internal Linking</h2>
            <p class="aysa-muted-note" style="margin:4px 0 0 0;">Single workspace for inventory, opportunities, conflicts, safe apply, and worker-backed runs for Agent 8.</p>
        </div>
        <div class="aysa-il-v2-actions">
            <button type="button" class="button" id="aysa-il-v2-refresh">Refresh</button>
            <button type="button" class="button" id="aysa-il-v2-analyze">Analyze</button>
            <button type="button" class="button button-primary" id="aysa-il-v2-apply-safe">Apply Safe</button>
            <button type="button" class="button" id="aysa-il-v2-reconcile">Reconcile</button>
        </div>
    </div>

    <div id="aysa-il-v2-status" class="notice inline" style="display:none;margin:0 0 12px 0;"><p></p></div>
    <div id="aysa-il-v2-progress" style="display:none;margin:0 0 14px 0;padding:12px 14px;border:1px solid #dcdcde;border-radius:8px;background:#fff;">
        <div style="display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;">
            <div>
                <strong id="aysa-il-v2-progress-label">Internal linking idle</strong>
                <div id="aysa-il-v2-progress-meta" class="description" style="margin-top:4px;">No active worker-backed run.</div>
            </div>
            <div id="aysa-il-v2-progress-pill" class="aysa-il-v2-badge aysa-tone-neutral">Idle</div>
        </div>
    </div>

    <div id="aysa-il-v2-summary" class="aysa-il-v2-summary"></div>
    <div id="aysa-il-v2-filters" class="aysa-il-v2-filter-row" style="margin-bottom:14px;"></div>

    <div style="display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:12px;">
        <div class="description" id="aysa-il-v2-filter-description">All current internal linking opportunities and projection rows.</div>
        <div class="aysa-il-v2-actions">
            <button type="button" class="button" id="aysa-il-v2-refresh-status">Refresh Status</button>
        </div>
    </div>

    <div class="aysa-il-v2-table-wrap">
        <div class="aysa-table-responsive">
            <table class="widefat striped" id="aysa-il-v2-table">
                <thead>
                    <tr>
                        <th>Source Page</th>
                        <th>Source Type</th>
                        <th>Suggested Target</th>
                        <th>Anchor</th>
                        <th>State</th>
                        <th>Conflict / Manual</th>
                        <th>Ownership</th>
                        <th>Last Analyzed</th>
                        <th>Last Applied</th>
                        <th>Next Step</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

    <div class="aysa-il-v2-drawer" id="aysa-il-v2-drawer">
        <div class="aysa-il-v2-drawer-backdrop" data-close="1"></div>
        <div class="aysa-il-v2-drawer-panel">
            <div class="aysa-il-v2-drawer-header">
                <div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;">
                    <div>
                        <h3 style="margin:0;" id="aysa-il-v2-drawer-title">Opportunity</h3>
                        <div class="description" id="aysa-il-v2-drawer-subtitle">Source and target details.</div>
                    </div>
                    <button type="button" class="button-link" data-close="1">Close</button>
                </div>
            </div>
            <div class="aysa-il-v2-drawer-body">
                <div class="aysa-il-v2-detail-grid" id="aysa-il-v2-drawer-grid"></div>
                <div class="aysa-il-v2-drawer-card">
                    <h4 style="margin-top:0;">Open Opportunities</h4>
                    <div id="aysa-il-v2-drawer-opportunities"></div>
                </div>
            </div>
            <div class="aysa-il-v2-drawer-footer">
                <div class="aysa-il-v2-actions">
                    <button type="button" class="button" data-row-action="validate">Validate</button>
                    <button type="button" class="button" data-row-action="apply">Apply</button>
                    <button type="button" class="button" data-row-action="rewrite">Rewrite</button>
                    <button type="button" class="button" data-row-action="skip">Skip</button>
                    <button type="button" class="button" data-row-action="mark_manual_only">Mark Manual Only</button>
                </div>
            </div>
        </div>
    </div>

    <script>
    (function() {
        const root = document.getElementById('aysa-internal-linking-v2-root');
        if (!root) {
            return;
        }

        const ajaxUrl = window.ajaxurl || '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
        const nonce = (document.getElementById('aysa-internal-linking-nonce') || {}).value || '<?php echo esc_js(wp_create_nonce('aysa_internal_linking_nonce')); ?>';
        const state = {
            projectId: Number(root.dataset.projectId || 0),
            view: 'all',
            runId: 0,
            afterEventId: 0,
            polling: null,
            currentDetail: null,
        };

        const initialWorkspace = <?php echo wp_json_encode($il_workspace); ?>;
        const summaryEl = document.getElementById('aysa-il-v2-summary');
        const filtersEl = document.getElementById('aysa-il-v2-filters');
        const tbodyEl = document.querySelector('#aysa-il-v2-table tbody');
        const statusEl = document.getElementById('aysa-il-v2-status');
        const progressWrap = document.getElementById('aysa-il-v2-progress');
        const progressLabel = document.getElementById('aysa-il-v2-progress-label');
        const progressMeta = document.getElementById('aysa-il-v2-progress-meta');
        const progressPill = document.getElementById('aysa-il-v2-progress-pill');
        const drawer = document.getElementById('aysa-il-v2-drawer');
        const drawerTitle = document.getElementById('aysa-il-v2-drawer-title');
        const drawerSubtitle = document.getElementById('aysa-il-v2-drawer-subtitle');
        const drawerGrid = document.getElementById('aysa-il-v2-drawer-grid');
        const drawerOpportunities = document.getElementById('aysa-il-v2-drawer-opportunities');
        const filterDescription = document.getElementById('aysa-il-v2-filter-description');

        const filterLabels = {
            all: 'All',
            needs_review: 'Needs Review',
            ready_to_apply: 'Ready to Apply',
            applied_by_aysa: 'Applied by AYSA',
            conflict: 'Conflict',
            manual_only: 'Manual Only',
            invalid_target: 'Invalid Target',
            articles: 'Articles',
            products: 'Products',
            pages: 'Pages',
            terms: 'Terms'
        };

        function tone(stateValue) {
            switch (stateValue) {
                case 'applied_by_aysa': return 'aysa-tone-green';
                case 'ready_to_apply': return 'aysa-tone-blue';
                case 'conflict': return 'aysa-tone-red';
                case 'manual_only':
                case 'invalid_target': return 'aysa-tone-yellow';
                default: return 'aysa-tone-neutral';
            }
        }

        function showStatus(message, kind = 'info') {
            statusEl.style.display = '';
            statusEl.className = 'notice inline ' + (kind === 'error' ? 'notice-error' : kind === 'success' ? 'notice-success' : 'notice-info');
            statusEl.querySelector('p').textContent = message;
        }

        function setProgress(run) {
            if (!run || !run.status || run.status === 'idle') {
                progressWrap.style.display = 'none';
                return;
            }
            progressWrap.style.display = '';
            progressLabel.textContent = run.current_milestone || 'Internal linking run active';
            progressMeta.textContent = 'Run #' + (run.run_id || run.id || 0) + ' · ' + (run.run_type || 'internal_linking');
            progressPill.textContent = run.status;
            progressPill.className = 'aysa-il-v2-badge ' + tone(run.status === 'completed' ? 'applied_by_aysa' : run.status === 'failed' ? 'conflict' : 'ready_to_apply');
        }

        function renderSummary(summary) {
            const cards = [
                ['Inventory', summary.all || 0],
                ['Needs Review', summary.needs_review || 0],
                ['Ready to Apply', summary.ready_to_apply || 0],
                ['Applied by AYSA', summary.applied_by_aysa || 0],
                ['Conflict', summary.conflict || 0],
                ['Manual Only', summary.manual_only || 0]
            ];
            summaryEl.innerHTML = cards.map(([label, value]) => (
                '<div class="aysa-il-v2-card"><div>' + label + '</div><div class="aysa-il-v2-card-value">' + value + '</div></div>'
            )).join('');
        }

        function renderFilters(counts) {
            const order = ['all', 'needs_review', 'ready_to_apply', 'applied_by_aysa', 'conflict', 'manual_only', 'invalid_target', 'articles', 'products', 'pages', 'terms'];
            filtersEl.innerHTML = order.map((key) => (
                '<button type="button" class="aysa-il-v2-chip' + (state.view === key ? ' is-active' : '') + '" data-view="' + key + '">' +
                    '<span>' + (filterLabels[key] || key) + '</span>' +
                    '<span class="aysa-il-v2-chip-count">' + Number(counts[key] || 0) + '</span>' +
                '</button>'
            )).join('');
        }

        function renderRows(rows) {
            if (!rows.length) {
                tbodyEl.innerHTML = '<tr><td colspan="10" class="aysa-il-v2-empty">No internal linking rows match the current filter.</td></tr>';
                return;
            }
            tbodyEl.innerHTML = rows.map((row) => {
                const reason = row.conflict_reason || (row.manual_only ? 'Manual only' : '');
                return '<tr class="aysa-il-v2-row" data-entity-key="' + (row.entity_key || '') + '" data-opportunity-id="' + Number(row.opportunity_id || 0) + '">' +
                    '<td><a href="' + (row.url || '#') + '" target="_blank" rel="noreferrer noopener">' + (row.source_page || row.url || 'Untitled') + '</a></td>' +
                    '<td>' + (row.source_type || '') + '</td>' +
                    '<td>' + ((row.target_url ? '<a href="' + row.target_url + '" target="_blank" rel="noreferrer noopener">' + (row.suggested_target || row.target_url) + '</a>' : 'No target yet')) + '</td>' +
                    '<td>' + (row.anchor || '—') + '</td>' +
                    '<td><span class="aysa-il-v2-badge ' + tone(row.state || '') + '">' + (row.state || 'discovered') + '</span></td>' +
                    '<td>' + (reason || '—') + '</td>' +
                    '<td>' + (row.ownership || 'none') + '</td>' +
                    '<td>' + (row.last_analyzed || '—') + '</td>' +
                    '<td>' + (row.last_applied || '—') + '</td>' +
                    '<td>' + (row.next_step || 'Review details') + '</td>' +
                '</tr>';
            }).join('');
        }

        function applyWorkspace(workspace) {
            renderSummary(workspace.summary || {});
            renderFilters(workspace.filters || {});
            renderRows(workspace.rows || []);
            setProgress(workspace.run || {});
            const label = filterLabels[state.view] || 'All';
            filterDescription.textContent = label + ' internal linking rows from the plugin-local projection.';
        }

        async function post(action, payload = {}) {
            const body = new URLSearchParams();
            body.set('action', action);
            body.set('nonce', nonce);
            Object.entries(payload).forEach(([key, value]) => {
                if (value === undefined || value === null) {
                    return;
                }
                if (Array.isArray(value) || typeof value === 'object') {
                    body.set(key, JSON.stringify(value));
                } else {
                    body.set(key, String(value));
                }
            });
            const res = await fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: body.toString()
            });
            return res.json();
        }

        async function refreshWorkspace(refresh = false) {
            const data = await post('aysa_internal_linking_workspace', {
                project_id: state.projectId,
                filters: { view: state.view },
                refresh: refresh ? 1 : 0
            });
            if (!data.success) {
                showStatus((data.data && data.data.message) || 'Could not load internal linking workspace.', 'error');
                return;
            }
            applyWorkspace(data.data.workspace || {});
        }

        async function startRun(runType) {
            showStatus('Starting ' + runType.replace(/_/g, ' ') + ' run...', 'info');
            const data = await post('aysa_internal_linking_start_run', {
                project_id: state.projectId,
                run_type: runType,
                filters: { view: state.view }
            });
            if (!data.success) {
                showStatus((data.data && data.data.message) || 'Could not start internal linking run.', 'error');
                return;
            }
            const status = data.data.status || {};
            state.runId = Number(((status.run || {}).id) || 0);
            state.afterEventId = 0;
            applyWorkspace(data.data.workspace || initialWorkspace);
            showStatus('Run started.', 'success');
            pollRun();
        }

        async function pollRun() {
            if (!state.runId) {
                return;
            }
            clearTimeout(state.polling);
            const data = await post('aysa_internal_linking_run_status', {
                project_id: state.projectId,
                run_id: state.runId,
                after_event_id: state.afterEventId,
                filters: { view: state.view }
            });
            if (!data.success) {
                showStatus((data.data && data.data.message) || 'Could not refresh run status.', 'error');
                return;
            }
            const status = data.data.status || {};
            const events = Array.isArray(status.events) ? status.events : [];
            if (events.length) {
                state.afterEventId = Number(events[events.length - 1].id || state.afterEventId);
            }
            applyWorkspace(data.data.workspace || initialWorkspace);
            const run = status.run || {};
            if (run.status === 'queued' || run.status === 'running') {
                state.polling = setTimeout(pollRun, 2500);
            } else {
                showStatus('Run ' + (run.status || 'completed') + '.', run.status === 'completed' ? 'success' : run.status === 'failed' ? 'error' : 'info');
            }
        }

        async function openDetail(opportunityId, entityKey) {
            const data = await post('aysa_internal_linking_detail', {
                project_id: state.projectId,
                opportunity_id: opportunityId,
                entity_key: entityKey
            });
            if (!data.success) {
                showStatus((data.data && data.data.message) || 'Could not load internal linking detail.', 'error');
                return;
            }
            const detail = data.data.detail || {};
            state.currentDetail = detail;
            const inv = detail.inventory || {};
            const opps = Array.isArray(detail.opportunities) ? detail.opportunities : [];
            drawerTitle.textContent = inv.title || inv.url || 'Opportunity';
            drawerSubtitle.textContent = inv.url || 'Internal linking details';
            drawerGrid.innerHTML = [
                ['Entity type', inv.entity_type || '—'],
                ['Source kind', inv.content_source_kind || '—'],
                ['Inventory status', inv.inventory_status || '—'],
                ['Manual only reason', inv.manual_only_reason || '—'],
                ['Last scanned', inv.last_scanned_at || '—'],
                ['Last applied', inv.last_applied_at || '—']
            ].map(([label, value]) => (
                '<div class="aysa-il-v2-drawer-card"><div class="description">' + label + '</div><div style="font-weight:600;margin-top:6px;">' + value + '</div></div>'
            )).join('');
            drawerOpportunities.innerHTML = opps.length ? (
                '<ul>' + opps.map((op) => (
                    '<li><strong>' + (op.anchor_text || op.keyword || 'No anchor') + '</strong> → ' + (op.target_title || op.target_url || 'No target') + ' <span class="description">(' + (op.opportunity_status || 'discovered') + ')</span></li>'
                )).join('') + '</ul>'
            ) : '<div class="description">No opportunity rows for this source yet.</div>';
            drawer.dataset.opportunityId = String(opportunityId || (opps[0] && opps[0].id) || 0);
            drawer.classList.add('is-open');
        }

        async function rowAction(action) {
            const opportunityId = Number(drawer.dataset.opportunityId || 0);
            if (!opportunityId) {
                showStatus('No opportunity selected.', 'error');
                return;
            }
            const data = await post('aysa_internal_linking_row_action_v2', {
                project_id: state.projectId,
                opportunity_id: opportunityId,
                row_action: action,
                filters: { view: state.view }
            });
            if (!data.success) {
                showStatus((data.data && data.data.message) || 'Could not update internal linking row.', 'error');
                return;
            }
            applyWorkspace(data.data.workspace || initialWorkspace);
            showStatus('Row updated.', 'success');
            drawer.classList.remove('is-open');
        }

        root.addEventListener('click', function(event) {
            const filterButton = event.target.closest('[data-view]');
            if (filterButton) {
                state.view = filterButton.getAttribute('data-view') || 'all';
                refreshWorkspace();
                return;
            }
            const row = event.target.closest('.aysa-il-v2-row');
            if (row && !event.target.closest('a')) {
                openDetail(Number(row.dataset.opportunityId || 0), row.dataset.entityKey || '');
                return;
            }
            const close = event.target.closest('[data-close]');
            if (close) {
                drawer.classList.remove('is-open');
                return;
            }
            const rowActionButton = event.target.closest('[data-row-action]');
            if (rowActionButton) {
                rowAction(rowActionButton.getAttribute('data-row-action'));
                return;
            }
        });

        document.getElementById('aysa-il-v2-refresh').addEventListener('click', function() { refreshWorkspace(true); });
        document.getElementById('aysa-il-v2-refresh-status').addEventListener('click', function() {
            if (state.runId) {
                pollRun();
            } else {
                refreshWorkspace();
            }
        });
        document.getElementById('aysa-il-v2-analyze').addEventListener('click', function() { startRun('analyze'); });
        document.getElementById('aysa-il-v2-apply-safe').addEventListener('click', function() { startRun('apply_safe'); });
        document.getElementById('aysa-il-v2-reconcile').addEventListener('click', function() { startRun('reconcile'); });

        applyWorkspace(initialWorkspace);
    })();
    </script>
</div>
