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

global $wpdb;
// 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.
$project_id = intval(get_option('aysa_project_id', 0));
// 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.
$metrics_table = esc_sql($wpdb->prefix . 'aysa_keyword_metrics');
// 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.
$strategy_table = esc_sql($wpdb->prefix . 'aysa_content_strategies');
// 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.
$_planned_missing_keywords = array();

// 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.
$missing_keywords = array();
// 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.
$missing_strategies = array();

if ($project_id > 0) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
    $metrics_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $metrics_table));
    if ($metrics_exists === $metrics_table) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $missing_keywords = $wpdb->get_results($wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: interpolation is limited to escaped or allowlisted plugin-owned table identifiers and generated placeholder lists; all request-derived values are passed to prepare.
            "SELECT keyword, intent, search_volume, difficulty, source, updated_at
" .
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: the interpolated identifier is an escaped or allowlisted plugin-owned table name; request-derived values remain prepared.
            "             FROM {$metrics_table}
             WHERE project_id = %d
               AND keyword IS NOT NULL
               AND keyword <> ''
               AND (target_url IS NULL OR target_url = '')
             ORDER BY search_volume DESC, keyword ASC
             LIMIT 500",
            $project_id
        ), ARRAY_A);
    }

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
    $strategies_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $strategy_table));
    if ($strategies_exists === $strategy_table) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $missing_strategies = $wpdb->get_results($wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: interpolation is limited to escaped or allowlisted plugin-owned table identifiers and generated placeholder lists; all request-derived values are passed to prepare.
            "SELECT id, title, keywords, intent, strategy_type, status, automation_status, created_at
" .
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: the interpolated identifier is an escaped or allowlisted plugin-owned table name; request-derived values remain prepared.
            "             FROM {$strategy_table}
             WHERE project_id = %d
               AND COALESCE(associated_page, '') = ''
               AND COALESCE(automation_status, '') <> 'deleted'
             ORDER BY created_at DESC
             LIMIT 500",
            $project_id
        ), ARRAY_A);

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $planned_rows = $wpdb->get_results($wpdb->prepare(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: interpolation is limited to escaped or allowlisted plugin-owned table identifiers and generated placeholder lists; all request-derived values are passed to prepare.
            "SELECT title, keywords
" .
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: the interpolated identifier is an escaped or allowlisted plugin-owned table name; request-derived values remain prepared.
            "             FROM {$strategy_table}
             WHERE project_id = %d
               AND strategy_type = 'missing_pages'
               AND COALESCE(automation_status, '') <> 'deleted'
             LIMIT 2000",
            $project_id
        ), ARRAY_A);
        // 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.
        foreach ((array) $planned_rows as $planned_row) {
            // 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.
            $kw = '';
            // 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.
            $kw_payload = isset($planned_row['keywords']) ? json_decode((string) $planned_row['keywords'], true) : null;
            if (is_array($kw_payload) && isset($kw_payload[0]) && is_string($kw_payload[0])) {
                // 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.
                $kw = trim((string) $kw_payload[0]);
            }
            if ($kw === '') {
                $title = (string) ($planned_row['title'] ?? '');
                if (preg_match('/for\s+(.+)$/iu', $title, $m)) {
                    // 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.
                    $kw = trim((string) ($m[1] ?? ''));
                }
            }
            if ($kw !== '') {
                // 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.
                $key = function_exists('mb_strtolower') ? mb_strtolower($kw, 'UTF-8') : strtolower($kw);
                // 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.
                $_planned_missing_keywords[$key] = true;
            }
        }
    }
}

if (!function_exists('aysa_missing_pages_recommendation')) {
    function aysa_missing_pages_recommendation($keyword, $intent, $source = '') {
        $kw_raw = trim((string) $keyword);
        $kw = function_exists('mb_strtolower') ? mb_strtolower($kw_raw, 'UTF-8') : strtolower($kw_raw);
        $intent = strtoupper(trim((string) $intent));
        $source = trim((string) $source);

        $has_number = (bool) preg_match('/\b\d{1,4}\b/u', $kw);
        $looks_question = (bool) preg_match('/\b(cum|ce|de ce|cand|unde|cat|care|ghid|sfaturi|trucuri|top|trenduri|intrebari)\b/u', $kw);
        $has_tx_words = (bool) preg_match('/\b(comanda|cumpara|pret|oferta|ieftin|livrare|rapid|non stop|program|contact)\b/u', $kw);
        $has_product_words = (bool) preg_match('/\b(buchet|aranjament|cutie|cos|planta|bonsai|trandafir|lalea|frezie|orhidee)\b/u', $kw);
        $has_category_words = (bool) preg_match('/\b(flori|buchete|aranjamente|trandafiri|plante|cadouri|tipuri|modele|colectie)\b/u', $kw);
        $is_brand_local = (bool) preg_match('/\b(florarie|bragadiru|bucuresti|sector)\b/u', $kw);

        if ($intent === 'I' || $looks_question) {
            return array('type' => 'Article', 'reason' => 'informational query');
        }

        if ($has_number && $has_product_words) {
            return array('type' => 'Product Page', 'reason' => 'specific SKU-like keyword');
        }

        if (($intent === 'T' && $has_product_words) || ($has_product_words && !$has_category_words)) {
            return array('type' => 'Product Page', 'reason' => 'transactional + product entity');
        }

        if (($intent === 'C' && $has_category_words) || ($has_category_words && !$has_tx_words && !$has_number)) {
            return array('type' => 'Category Page', 'reason' => 'broader commercial/category intent');
        }

        if ($has_tx_words || $is_brand_local || $intent === 'N' || $source === 'association_seed') {
            return array('type' => 'Landing Page', 'reason' => 'brand/local or conversion query');
        }

        if ($intent === 'T') {
            return array('type' => 'Product Page', 'reason' => 'transactional fallback');
        }
        if ($intent === 'C') {
            return array('type' => 'Category Page', 'reason' => 'commercial fallback');
        }

        return array('type' => 'Landing Page', 'reason' => 'default fallback');
    }
}

if (!function_exists('aysa_missing_pages_source_label')) {
    function aysa_missing_pages_source_label($source) {
        $normalized = strtolower(trim((string) $source));
        $labels = array(
            'association_seed' => 'Existing association seed',
            'related_keyword' => 'Related keyword expansion',
            'keyword_suggestion' => 'Keyword suggestion',
            'competitor_gap' => 'Competitor gap analysis',
            'local' => 'Local project data',
        );

        return $labels[$normalized] ?? ucwords(str_replace(array('_', '-'), ' ', $normalized));
    }
}

if (!function_exists('aysa_missing_pages_strategy_type_label')) {
    function aysa_missing_pages_strategy_type_label($value) {
        $normalized = strtolower(trim((string) $value));
        $labels = array(
            'missing_pages' => 'Missing page opportunity',
            'cluster_titles' => 'Cluster title plan',
            'competitor_titles' => 'Competitor-derived title',
            'intent_layering' => 'Intent-layered topic',
            'seasonal_events' => 'Seasonal content idea',
            'serp_features' => 'SERP feature opportunity',
            'evergreen_fresh_mix' => 'Evergreen + fresh mix',
            'customer_journey' => 'Customer journey topic',
            'local_seo' => 'Local SEO topic',
            'authority_building' => 'Authority-building topic',
            'persona_based' => 'Persona-based topic',
        );

        return $labels[$normalized] ?? ucwords(str_replace(array('_', '-'), ' ', $normalized));
    }
}

if (!function_exists('aysa_missing_pages_status_label')) {
    function aysa_missing_pages_status_label($value) {
        $normalized = strtolower(trim((string) $value));
        $labels = array(
            'proposed' => 'Proposed',
            'queued' => 'Queued',
            'processing' => 'Generating',
            'generated' => 'Generated',
            'published' => 'Published',
            'scheduled' => 'Scheduled',
            'blocked_no_association' => 'Blocked: no association',
            'blocked' => 'Blocked',
            'retry' => 'Retry needed',
            'failed' => 'Failed',
        );

        return $labels[$normalized] ?? ucwords(str_replace(array('_', '-'), ' ', $normalized));
    }
}
?>

<div class="aysa-admin aysa-missing-pages">
    <div class="aysa-page-title">
        <h1>Missing Pages</h1>
        <div class="aysa-title-right">
            <div class="mp-credits">
                <?php
                if (class_exists('Aysa_Credits_Component')) {
                    Aysa_Credits_Component::display();
                }
                ?>
            </div>
        </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>
        <div class="aysa-tab active">Missing Pages</div>
        <a href="admin.php?page=aysa-research&tab=content-strategy" class="aysa-tab">Content Strategy</a>
    </div>

    <div class="mp-header">
        <div class="mp-title-wrap">
            <h2>Keywords without matched URLs and strategy rows without associations</h2>
        </div>
        <div class="mp-head-right">
            <div class="mp-kpis">
                <span class="mp-kpi"><small>Missing keyword URLs</small><strong><?php echo intval(count($missing_keywords)); ?></strong></span>
                <span class="mp-kpi"><small>Unassociated strategies</small><strong><?php echo intval(count($missing_strategies)); ?></strong></span>
            </div>
        </div>
    </div>

    <div class="aysa-content">
        <div class="aysa-missing-card">
            <div class="aysa-missing-card-head">
                <h2>Keywords Without Matched URL</h2>
                <span class="aysa-badge"><?php echo intval(count($missing_keywords)); ?> items</span>
            </div>
            <p class="aysa-help">These keywords already exist in the local research dataset, but they do not yet have a matched page. AYSA suggests the most likely page type so your team can plan the next content move faster.</p>

            <div class="mp-toolbar">
                <input type="text" id="mp-keyword-search" placeholder="Search keyword..." />
                <select id="mp-intent-filter">
                    <option value="all">All intents</option>
                    <option value="i">Informational (I)</option>
                    <option value="c">Commercial (C)</option>
                    <option value="t">Transactional (T)</option>
                    <option value="n">Navigational (N)</option>
                </select>
                <select id="mp-rec-filter">
                    <option value="all">All recommendations</option>
                    <option value="Product Page">Product Page</option>
                    <option value="Category Page">Category Page</option>
                    <option value="Landing Page">Landing Page</option>
                    <option value="Article">Article</option>
                </select>
                <select id="mp-source-filter">
                    <option value="all">All sources</option>
                    <option value="association_seed">Existing association seed</option>
                    <option value="related_keyword">Related keyword expansion</option>
                    <option value="keyword_suggestion">Keyword suggestion</option>
                    <option value="competitor_gap">Competitor gap analysis</option>
                </select>
                <button type="button" class="button button-primary button-small" id="mp-send-visible-btn">Send visible to Content Plan</button>
            </div>

            <div class="aysa-table-wrap">
                <table class="widefat striped" id="mp-keywords-table">
                    <thead>
                        <tr>
                            <th>Keyword</th>
                            <th>Intent</th>
                            <th>Volume</th>
                            <th>KD%</th>
                            <th>Recommended Page Type</th>
                            <th>Source</th>
                            <th>Updated</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($missing_keywords)) : ?>
                            <tr><td colspan="8">No missing keywords found.</td></tr>
                        <?php else : ?>
                            <?php // 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.
                             foreach ($missing_keywords as $row) : ?>
                                <?php
                                // 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.
                                $keyword = (string) ($row['keyword'] ?? '');
                                // 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.
                                $intent = (string) ($row['intent'] ?? 'N/A');
                                // 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.
                                $volume = isset($row['search_volume']) ? (int) $row['search_volume'] : 0;
                                // 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.
                                $kd = isset($row['difficulty']) && $row['difficulty'] !== null ? (float) $row['difficulty'] : null;
                                // 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.
                                $source = (string) ($row['source'] ?? 'local');
                                // 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.
                                $updated = (string) ($row['updated_at'] ?? '-');
                                ?>
                                <tr>
                                    <td class="col-keyword"><strong><?php echo esc_html($keyword); ?></strong></td>
                                    <td>
                                        <span class="aysa-pill intent-<?php echo esc_attr(strtolower($intent)); ?>">
                                            <?php echo esc_html($intent !== '' ? $intent : 'N/A'); ?>
                                        </span>
                                    </td>
                                    <td><?php echo esc_html(number_format_i18n($volume)); ?></td>
                                    <td><?php echo esc_html($kd === null ? 'N/A' : number_format_i18n($kd, 2)); ?></td>
                                    <?php // 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.
                                     $recommendation = aysa_missing_pages_recommendation($keyword, $intent, $source); ?>
                                    <td>
                                        <span class="aysa-pill soft" title="<?php echo esc_attr((string) ($recommendation['reason'] ?? '')); ?>">
                                            <?php echo esc_html((string) ($recommendation['type'] ?? 'Landing Page')); ?>
                                        </span>
                                        <div class="mp-rec-reason"><?php echo esc_html((string) ($recommendation['reason'] ?? '')); ?></div>
                                    </td>
                                    <td><span class="aysa-pill source"><?php echo esc_html(aysa_missing_pages_source_label($source)); ?></span></td>
                                    <td class="col-date"><?php echo esc_html($updated); ?></td>
                                    <td>
                                        <?php
                                        // 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.
                                        $kw_lookup = function_exists('mb_strtolower') ? mb_strtolower($keyword, 'UTF-8') : strtolower($keyword);
                                        // 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.
                                        $already_planned = !empty($_planned_missing_keywords[$kw_lookup]);
                                        ?>
                                        <button
                                            type="button"
                                            class="button button-small <?php echo $already_planned ? 'button-secondary' : 'button-primary'; ?> mp-send-plan-btn"
                                            data-keyword="<?php echo esc_attr($keyword); ?>"
                                            data-intent="<?php echo esc_attr($intent); ?>"
                                            data-source="<?php echo esc_attr($source); ?>"
                                            data-recommended-page-type="<?php echo esc_attr((string) ($recommendation['type'] ?? 'Landing Page')); ?>"
                                            data-recommendation-reason="<?php echo esc_attr((string) ($recommendation['reason'] ?? '')); ?>"
                                            <?php echo $already_planned ? 'disabled' : ''; ?>
                                        ><?php echo $already_planned ? 'In Plan' : 'Send to Plan'; ?></button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="aysa-missing-card">
            <div class="aysa-missing-card-head">
                <h2>Content Strategy Rows Without Association</h2>
                <span class="aysa-badge"><?php echo intval(count($missing_strategies)); ?> items</span>
            </div>
            <p class="aysa-help">These strategy rows can still be planned and generated even before a final page association exists. Your team can complete associations incrementally afterwards.</p>

            <div class="mp-toolbar">
                <input type="text" id="mp-strategy-search" placeholder="Search title..." />
            </div>

            <div class="aysa-table-wrap">
                <table class="widefat striped" id="mp-strategy-table">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Intent</th>
                            <th>Strategy Type</th>
                            <th>Status</th>
                            <th>Automation</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($missing_strategies)) : ?>
                            <tr><td colspan="6">No missing strategy associations found.</td></tr>
                        <?php else : ?>
                            <?php // 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.
                             foreach ($missing_strategies as $row) : ?>
                                <tr>
                                    <td class="col-keyword"><?php echo esc_html((string) ($row['title'] ?? '')); ?></td>
                                    <td>
                                        <?php // 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.
                                         $intent = (string) ($row['intent'] ?? 'N/A'); ?>
                                        <span class="aysa-pill intent-<?php echo esc_attr(strtolower($intent)); ?>">
                                            <?php echo esc_html($intent); ?>
                                        </span>
                                    </td>
                                    <td><?php echo esc_html(aysa_missing_pages_strategy_type_label((string) ($row['strategy_type'] ?? 'unknown'))); ?></td>
                                    <td>
                                        <?php $status = (string) ($row['status'] ?? 'proposed'); ?>
                                        <span class="aysa-pill status-<?php echo esc_attr(strtolower($status)); ?>">
                                            <?php echo esc_html(aysa_missing_pages_status_label($status)); ?>
                                        </span>
                                    </td>
                                    <td><?php echo esc_html(aysa_missing_pages_status_label((string) ($row['automation_status'] ?? '-'))); ?></td>
                                    <td class="col-date"><?php echo esc_html((string) ($row['created_at'] ?? '-')); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="aysa-actions">
                <a class="button button-primary" href="admin.php?page=aysa-research&tab=content-strategy&strategy_tab=content-expansion">Open Content Strategy Plan</a>
            </div>
        </div>
    </div>
</div>

<style>
.aysa-admin.aysa-missing-pages {
    display: block !important;
    width: 100% !important;
    max-width: 100% !important;
}

.aysa-admin.aysa-missing-pages > * {
    width: 100%;
}

.aysa-missing-pages {
    max-width: 100%;
}

.aysa-missing-pages .aysa-page-title {
    padding: 15px 20px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-missing-pages .aysa-page-title h1 {
    font-size: 20px;
    font-weight: 500;
    margin: 0;
    color: #333;
}

.aysa-missing-pages .aysa-title-right {
    display: flex;
    align-items: center;
    gap: 12px;
}

.aysa-missing-pages .aysa-top-tabs {
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #e0e0e0;
    background-color: #f8f9fa;
    padding: 0;
}

.aysa-missing-pages .aysa-tab {
    padding: 10px 15px;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    white-space: nowrap;
    text-decoration: none;
}

.aysa-missing-pages .aysa-tab.active {
    color: #1a73e8;
    font-weight: 500;
    border-bottom: 3px solid #1a73e8;
}

.aysa-missing-pages .aysa-tab:hover:not(.active) {
    color: #1a73e8;
    border-bottom: 3px solid #e8f0fe;
}

.aysa-missing-pages .mp-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 16px;
    margin: 8px 0 12px;
}

.aysa-missing-pages .mp-title-wrap h2 {
    margin: 0;
    font-size: 16px;
    line-height: 1.4;
    font-weight: 500;
    color: #334155;
}

.aysa-missing-pages .mp-title-wrap p {
    margin: 6px 0 0;
    color: #64748b;
    font-size: 14px;
}

.aysa-missing-pages .mp-head-right {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.aysa-missing-pages .mp-kpis {
    display: flex;
    gap: 10px;
}

.aysa-missing-pages .mp-kpi {
    min-width: 180px;
    border: 1px solid #dbe3ef;
    border-radius: 10px;
    background: #f8fafc;
    padding: 10px 12px;
    display: inline-flex;
    flex-direction: column;
    gap: 4px;
}

.aysa-missing-pages .mp-kpi small {
    color: #64748b;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.aysa-missing-pages .mp-kpi strong {
    font-size: 20px;
    color: #0f172a;
}

.aysa-missing-pages .aysa-content {
    display: grid;
    gap: 16px;
    grid-template-columns: 1fr;
}

.aysa-missing-pages .aysa-missing-card {
    background: #fff;
    border: 1px solid #dbe3ef;
    border-radius: 12px;
    padding: 16px 16px 14px;
    box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}

.aysa-missing-pages .aysa-missing-card-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.aysa-missing-pages .aysa-missing-card-head h2 {
    margin: 0;
    font-size: 18px;
}

.aysa-missing-pages .aysa-badge {
    background: #eef2ff;
    color: #1e3a8a;
    border: 1px solid #c7d2fe;
    border-radius: 999px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 600;
}

.aysa-missing-pages .aysa-help {
    margin: 0 0 12px;
    color: #475569;
    font-size: 13px;
}

.aysa-missing-pages .mp-toolbar {
    display: flex;
    gap: 8px;
    margin-bottom: 10px;
    flex-wrap: wrap;
}

.aysa-missing-pages .mp-toolbar input,
.aysa-missing-pages .mp-toolbar select {
    min-height: 34px;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    padding: 0 10px;
    background: #fff;
}

.aysa-missing-pages .mp-toolbar input {
    min-width: 260px;
}

.aysa-missing-pages .aysa-table-wrap {
    overflow: visible;
    max-height: none;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #fff;
}

.aysa-missing-pages table {
    min-width: 980px;
    border-collapse: separate;
    border-spacing: 0;
}

.aysa-missing-pages table th {
    position: sticky;
    top: 0;
    z-index: 15;
    background: #f8fafc;
    font-size: 12px;
    color: #334155;
    text-transform: uppercase;
    letter-spacing: .03em;
}

.aysa-missing-pages table td {
    vertical-align: middle;
    color: #0f172a;
}

.aysa-missing-pages table tbody tr:nth-child(even) td {
    background: #fcfdff;
}

.aysa-missing-pages table tbody tr:hover td {
    background: #eef6ff;
}

.aysa-missing-pages .col-keyword {
    min-width: 340px;
    max-width: 500px;
    word-break: break-word;
}

.aysa-missing-pages .col-date {
    white-space: nowrap;
    color: #475569;
}

.aysa-missing-pages .aysa-pill {
    display: inline-flex;
    align-items: center;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 700;
    line-height: 1.6;
    border: 1px solid #dbe3ef;
    background: #f8fafc;
}

.aysa-missing-pages .aysa-pill.soft {
    background: #eff6ff;
    border-color: #bfdbfe;
    color: #1d4ed8;
}

.aysa-missing-pages .mp-rec-reason {
    margin-top: 4px;
    font-size: 11px;
    color: #64748b;
    line-height: 1.35;
}

.aysa-missing-pages .aysa-pill.source {
    background: #f1f5f9;
    border-color: #e2e8f0;
    color: #334155;
}

.aysa-missing-pages .intent-i {
    background: #e0f2fe;
    border-color: #bae6fd;
    color: #0369a1;
}

.aysa-missing-pages .intent-c,
.aysa-missing-pages .intent-t {
    background: #dcfce7;
    border-color: #bbf7d0;
    color: #166534;
}

.aysa-missing-pages .intent-n,
.aysa-missing-pages .intent-na {
    background: #f1f5f9;
    border-color: #e2e8f0;
    color: #475569;
}

.aysa-missing-pages .status-proposed {
    background: #fef3c7;
    border-color: #fde68a;
    color: #92400e;
}

.aysa-missing-pages .status-scheduled {
    background: #dbeafe;
    border-color: #bfdbfe;
    color: #1d4ed8;
}

.aysa-missing-pages .aysa-actions {
    margin-top: 12px;
}

@media (max-width: 1280px) {
    .aysa-missing-pages .mp-header {
        flex-direction: column;
    }
    .aysa-missing-pages .mp-head-right {
        width: 100%;
        justify-content: space-between;
    }
    .aysa-missing-pages .mp-kpis {
        flex-wrap: wrap;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const mpAjaxNonce = '<?php echo esc_js(wp_create_nonce('aysa_content_strategy_nonce')); ?>';
    const mpProjectId = '<?php echo esc_js((string) $project_id); ?>';

    function text(row, selector) {
        const el = row.querySelector(selector);
        return (el ? el.textContent : row.textContent || '').toLowerCase();
    }

    function setPlanButtonState(button, added) {
        if (!button) return;
        button.disabled = true;
        button.classList.remove('button-primary');
        button.classList.add('button-secondary');
        button.textContent = added ? 'Added' : 'In Plan';
    }

    async function sendItemsToPlan(items) {
        if (!Array.isArray(items) || items.length === 0) {
            return { added: 0, existing: 0, errors: 0, total: 0 };
        }
        const params = new URLSearchParams({
            action: 'aysa_missing_pages_send_to_plan',
            nonce: mpAjaxNonce,
            project_id: mpProjectId,
            items: JSON.stringify(items)
        });
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        });
        const result = await response.json();
        if (!result || !result.success) {
            throw new Error((result && result.data) ? String(result.data) : 'Failed to send keywords to plan');
        }
        return result.data || { added: 0, existing: 0, errors: 0, total: 0 };
    }

    function filterKeywordRows() {
        const table = document.getElementById('mp-keywords-table');
        if (!table) return;
        const q = (document.getElementById('mp-keyword-search')?.value || '').trim().toLowerCase();
        const intent = (document.getElementById('mp-intent-filter')?.value || 'all').toLowerCase();
        const rec = (document.getElementById('mp-rec-filter')?.value || 'all').toLowerCase();
        const src = (document.getElementById('mp-source-filter')?.value || 'all').toLowerCase();
        table.querySelectorAll('tbody tr').forEach((row) => {
            const kw = text(row, '.col-keyword');
            const it = text(row, 'td:nth-child(2)');
            const rc = text(row, 'td:nth-child(5)');
            const sc = text(row, 'td:nth-child(6)');
            const matchQ = !q || kw.includes(q);
            const matchI = intent === 'all' || it.includes(intent);
            const matchR = rec === 'all' || rc.includes(rec);
            const matchS = src === 'all' || sc.includes(src);
            row.style.display = (matchQ && matchI && matchR && matchS) ? '' : 'none';
        });
    }

    function filterStrategyRows() {
        const table = document.getElementById('mp-strategy-table');
        if (!table) return;
        const q = (document.getElementById('mp-strategy-search')?.value || '').trim().toLowerCase();
        table.querySelectorAll('tbody tr').forEach((row) => {
            const title = text(row, '.col-keyword');
            row.style.display = (!q || title.includes(q)) ? '' : 'none';
        });
    }

    ['mp-keyword-search', 'mp-intent-filter', 'mp-rec-filter', 'mp-source-filter']
        .forEach((id) => document.getElementById(id)?.addEventListener('input', filterKeywordRows));
    document.getElementById('mp-intent-filter')?.addEventListener('change', filterKeywordRows);
    document.getElementById('mp-rec-filter')?.addEventListener('change', filterKeywordRows);
    document.getElementById('mp-source-filter')?.addEventListener('change', filterKeywordRows);
    document.getElementById('mp-strategy-search')?.addEventListener('input', filterStrategyRows);

    document.addEventListener('click', async function(e) {
        const singleBtn = e.target.closest('.mp-send-plan-btn');
        if (singleBtn) {
            e.preventDefault();
            if (singleBtn.disabled) {
                return;
            }
            singleBtn.disabled = true;
            singleBtn.textContent = 'Sending...';
            try {
                const payload = {
                    keyword: singleBtn.dataset.keyword || '',
                    intent: singleBtn.dataset.intent || 'N/A',
                    source: singleBtn.dataset.source || 'missing_pages',
                    recommended_page_type: singleBtn.dataset.recommendedPageType || 'Landing Page',
                    recommendation_reason: singleBtn.dataset.recommendationReason || ''
                };
                const summary = await sendItemsToPlan([payload]);
                setPlanButtonState(singleBtn, Number(summary.added || 0) > 0);
            } catch (err) {
                singleBtn.disabled = false;
                singleBtn.textContent = 'Send to Plan';
                alert(err && err.message ? err.message : 'Could not send to plan');
            }
            return;
        }

        const bulkBtn = e.target.closest('#mp-send-visible-btn');
        if (!bulkBtn) {
            return;
        }
        e.preventDefault();
        if (bulkBtn.disabled) {
            return;
        }
        const rows = Array.from(document.querySelectorAll('#mp-keywords-table tbody tr'));
        const visibleButtons = rows
            .filter((row) => row.style.display !== 'none')
            .map((row) => row.querySelector('.mp-send-plan-btn'))
            .filter((btn) => btn && !btn.disabled);
        if (!visibleButtons.length) {
            bulkBtn.textContent = 'Nothing to add';
            setTimeout(() => {
                bulkBtn.textContent = 'Send visible to Content Plan';
            }, 1500);
            return;
        }

        bulkBtn.disabled = true;
        const originalLabel = bulkBtn.textContent;
        bulkBtn.textContent = 'Sending...';
        try {
            const payload = visibleButtons.map((btn) => ({
                keyword: btn.dataset.keyword || '',
                intent: btn.dataset.intent || 'N/A',
                source: btn.dataset.source || 'missing_pages',
                recommended_page_type: btn.dataset.recommendedPageType || 'Landing Page',
                recommendation_reason: btn.dataset.recommendationReason || ''
            }));
            const summary = await sendItemsToPlan(payload);
            visibleButtons.forEach((btn) => setPlanButtonState(btn, true));
            bulkBtn.textContent = `Added ${Number(summary.added || 0)} (${Number(summary.existing || 0)} existing)`;
            setTimeout(() => {
                bulkBtn.textContent = originalLabel;
                bulkBtn.disabled = false;
            }, 2200);
        } catch (err) {
            bulkBtn.textContent = 'Retry';
            bulkBtn.disabled = false;
            alert(err && err.message ? err.message : 'Bulk send failed');
        }
    });
});
</script>
