<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

$aysa_embedded_view = isset($_GET['embedded']) && sanitize_text_field(wp_unslash((string) $_GET['embedded'])) === '1';
$aysa_requested_project_id = isset($_GET['project_id']) ? intval(wp_unslash((string) $_GET['project_id'])) : 0;
$aysa_content_project_id = 0;
if (isset($this) && is_object($this) && method_exists($this, 'aysa_resolve_project_id_with_local_fallback')) {
    $aysa_content_project_id = intval($this->aysa_resolve_project_id_with_local_fallback($aysa_requested_project_id > 0 ? $aysa_requested_project_id : intval(get_option('aysa_project_id', 0))));
} else {
    $aysa_content_project_id = $aysa_requested_project_id > 0 ? $aysa_requested_project_id : intval(get_option('aysa_project_id', 0));
}
$aysa_content_option_project_id = intval(get_option('aysa_project_id', 0));
$aysa_content_wallet_project_id = 0;
if (class_exists('Aysa_Wallet_Manager')) {
    $aysa_content_wallet_project_id = intval(Aysa_Wallet_Manager::get_instance()->get_project_id());
}
$aysa_content_strategy_rows = 0;
$aysa_content_meta_rows = 0;
$aysa_content_snapshot_rows = 0;
$aysa_projection_applied_run_id = 0;
$aysa_projection_expected_content_rows = 0;
$aysa_projection_expected_calendar_rows = 0;
$aysa_projection_last_applied_at = '';
$aysa_materialization_inconsistent = false;
if (isset($wpdb) && $aysa_content_project_id > 0) {
    $strategy_table = $wpdb->prefix . 'aysa_content_strategies';
    $meta_table = $wpdb->prefix . 'aysa_missing_page_meta';
    $snapshot_table = $wpdb->prefix . 'aysa_keyword_v2_snapshots';
    $aysa_content_strategy_rows = intval($wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$strategy_table} WHERE project_id = %d", $aysa_content_project_id)));
    $meta_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $meta_table));
    if ($meta_exists === $meta_table) {
        $aysa_content_meta_rows = intval($wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$meta_table} WHERE project_id = %d", $aysa_content_project_id)));
    }
    $snapshot_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $snapshot_table));
    if ($snapshot_exists === $snapshot_table) {
        $aysa_content_snapshot_rows = intval($wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$snapshot_table} WHERE project_id = %d AND tab_key IN (%s, %s)",
            $aysa_content_project_id,
            'content_strategy_v2',
            'missing_pages_v2'
        )));
    }
    $aysa_projection_applied_run_id = intval(get_option('aysa_keyword_research_projection_applied_run_' . $aysa_content_project_id, 0));
    $aysa_projection_expected_content_rows = intval(get_option('aysa_keyword_research_projection_last_content_row_count_' . $aysa_content_project_id, 0));
    $aysa_projection_expected_calendar_rows = intval(get_option('aysa_keyword_research_projection_last_calendar_row_count_' . $aysa_content_project_id, 0));
    $aysa_projection_last_applied_at = (string) get_option('aysa_keyword_research_projection_last_applied_at_' . $aysa_content_project_id, '');
    $aysa_materialization_inconsistent =
        $aysa_projection_applied_run_id > 0
        && ($aysa_projection_expected_content_rows > 0 || $aysa_projection_expected_calendar_rows > 0)
        && $aysa_content_strategy_rows === 0;
}
?>

<div class="aysa-admin aysa-content-strategy">
    <!-- Page Title -->
    <div class="aysa-page-title">
        <h1>Content Strategy</h1>
        <div class="aysa-title-right">
            <?php 
            // Use the credits component
            if (class_exists('Aysa_Credits_Component')) {
                Aysa_Credits_Component::display();
            } else {
                echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
            }
            ?>
        </div>
    </div>

    <!-- Top Tabs -->
    <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=sitemap-competition" class="aysa-tab">Sitemap Competition</a>
        <div class="aysa-tab active">Content Strategy</div>
    </div>

    <!-- Main Content -->
    <div class="aysa-content">
        <div class="aysa-content-strategy-dashboard">
            
            <!-- Dashboard Header -->
            <div class="aysa-dashboard-header">
                <div class="aysa-header-left">
                    <div class="aysa-header-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M3 3V21H21V3H3ZM19 19H5V5H19V19Z" stroke="#007cba" stroke-width="2"/>
                            <path d="M7 7H9V9H7V7Z" fill="#007cba"/>
                            <path d="M11 7H13V9H11V7Z" fill="#007cba"/>
                            <path d="M15 7H17V9H15V7Z" fill="#007cba"/>
                            <path d="M7 11H9V13H7V11Z" fill="#007cba"/>
                            <path d="M11 11H13V13H11V11Z" fill="#007cba"/>
                            <path d="M15 11H17V13H15V11Z" fill="#007cba"/>
                        </svg>
                    </div>
                    <h2>Content Strategy</h2>
                </div>
                <div class="aysa-header-right">
                    <button class="aysa-plan-content-btn" type="button">
                        Plan content
                    </button>
                    <button class="aysa-associate-missing-btn" type="button">
                        Associate Missing
                    </button>
                    <button class="aysa-reset-plan-btn" type="button">
                        Reset Plan
                    </button>
                    <button class="aysa-generate-strategy-btn">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 5V19M5 12H19" stroke="white" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                        Generate Strategy
                    </button>
                    <div class="aysa-strategy-picker" id="aysa-strategy-picker" hidden>
                        <div class="aysa-strategy-picker-head">
                            <div>
                                <strong>Generate Content Strategy</strong>
                                <p>Choose the generation module and start.</p>
                            </div>
                            <button type="button" class="aysa-strategy-picker-close" aria-label="Close strategy picker">&times;</button>
                        </div>
                        <div class="aysa-strategy-picker-grid">
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="cluster">
                                <span class="title">Cluster-based</span>
                                <span class="desc">Keyword clusters</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="competitor">
                                <span class="title">Competitor Analysis</span>
                                <span class="desc">From competitor titles</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="intent">
                                <span class="title">Intent Layering</span>
                                <span class="desc">Info/Commercial/Nav/Transactional</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="seasonal">
                                <span class="title">Seasonal & Events</span>
                                <span class="desc">Time-based topics</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="serp">
                                <span class="title">SERP Features</span>
                                <span class="desc">PAA/Snippet/Media</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="evergreen">
                                <span class="title">Evergreen + Fresh</span>
                                <span class="desc">Stable + trends</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="journey">
                                <span class="title">Customer Journey</span>
                                <span class="desc">Awareness to Decision</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="local">
                                <span class="title">Local SEO</span>
                                <span class="desc">City/neighborhood focus</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="authority">
                                <span class="title">Authority Building</span>
                                <span class="desc">E-E-A-T mix</span>
                            </button>
                            <button type="button" class="aysa-strategy-type-btn" data-strategy="persona">
                                <span class="title">Persona-based</span>
                                <span class="desc">Audience-targeted angles</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="aysa-plan-status" id="aysa-plan-status">Content plan status: not started</div>
            <?php if ($aysa_materialization_inconsistent): ?>
                <div class="aysa-plan-status aysa-plan-status-debug" id="aysa-materialization-warning">
                    Content plan status: projection not materialized yet. Last applied run <?php echo intval($aysa_projection_applied_run_id); ?> expected <?php echo intval($aysa_projection_expected_content_rows); ?> content rows and <?php echo intval($aysa_projection_expected_calendar_rows); ?> calendar rows.
                </div>
            <?php endif; ?>
            <div class="aysa-plan-status aysa-plan-status-debug">
                Debug:
                resolved_project_id=<?php echo intval($aysa_content_project_id); ?> |
                option_project_id=<?php echo intval($aysa_content_option_project_id); ?> |
                wallet_project_id=<?php echo intval($aysa_content_wallet_project_id); ?> |
                strategy_rows=<?php echo intval($aysa_content_strategy_rows); ?> |
                meta_rows=<?php echo intval($aysa_content_meta_rows); ?> |
                v2_snapshots=<?php echo intval($aysa_content_snapshot_rows); ?> |
                applied_run=<?php echo intval($aysa_projection_applied_run_id); ?> |
                expected_content_rows=<?php echo intval($aysa_projection_expected_content_rows); ?> |
                expected_calendar_rows=<?php echo intval($aysa_projection_expected_calendar_rows); ?> |
                last_applied_at=<?php echo esc_html($aysa_projection_last_applied_at ?: '-'); ?>
            </div>
            <div class="aysa-generation-status" id="aysa-generation-status" hidden>
                <span class="aysa-generation-dot" aria-hidden="true"></span>
                <span class="aysa-generation-text" id="aysa-generation-text">Generating strategy titles...</span>
            </div>

            <!-- Dashboard Tabs -->
            <div class="aysa-dashboard-tabs">
                <div class="aysa-tab-item active" data-tab="dashboard">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M3 3V21H21V3H3ZM19 19H5V5H19V19Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M7 7H9V9H7V7Z" fill="currentColor"/>
                        <path d="M11 7H13V9H11V7Z" fill="currentColor"/>
                        <path d="M15 7H17V9H15V7Z" fill="currentColor"/>
                    </svg>
                    Dashboard
                </div>
                <div class="aysa-tab-item" data-tab="content-expansion">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2L4 7V17L12 22L20 17V7L12 2Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M8 12H16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M12 8V16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Missing Pages Plan
                </div>
                <div class="aysa-tab-item" data-tab="publication-calendar">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                        <line x1="16" y1="2" x2="16" y2="6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <line x1="8" y1="2" x2="8" y2="6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Publication Calendar
                </div>
                <div class="aysa-tab-item" data-tab="clusters">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Clusters
                </div>
                <div class="aysa-tab-item" data-tab="competitor-titles">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M6 9H4.5A2.5 2.5 0 0 1 2 6.5V4.5A2.5 2.5 0 0 1 4.5 2H6.5A2.5 2.5 0 0 1 9 4.5V6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M18 9H19.5A2.5 2.5 0 0 0 22 6.5V4.5A2.5 2.5 0 0 0 19.5 2H17.5A2.5 2.5 0 0 0 15 4.5V6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M6 15H4.5A2.5 2.5 0 0 0 2 17.5V19.5A2.5 2.5 0 0 0 4.5 22H6.5A2.5 2.5 0 0 0 9 19.5V18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M18 15H19.5A2.5 2.5 0 0 1 22 17.5V19.5A2.5 2.5 0 0 1 19.5 22H17.5A2.5 2.5 0 0 1 15 19.5V18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Competitor Titles
                </div>
                <div class="aysa-tab-item" data-tab="legacy-content-from-sitemaps">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M4 6H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M4 12H20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M4 18H14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Legacy Content From Sitemaps
                </div>
                <div class="aysa-tab-item" data-tab="intent-layering">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 16V8A2 2 0 0 0 19 6H5A2 2 0 0 0 3 8V16A2 2 0 0 0 5 18H19A2 2 0 0 0 21 16Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M7 12H17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Intent Layering
                </div>
                <div class="aysa-tab-item" data-tab="seasonal-events">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
                        <line x1="16" y1="2" x2="16" y2="6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <line x1="8" y1="2" x2="8" y2="6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <line x1="3" y1="10" x2="21" y2="10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Seasonal & Events
                </div>
                <div class="aysa-tab-item" data-tab="serp-features">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M21 12C21 16.97 16.97 21 12 21C7.03 21 3 16.97 3 12C3 7.03 7.03 3 12 3C16.97 3 21 7.03 21 12Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M12 8V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    SERP Features
                </div>
                <div class="aysa-tab-item" data-tab="evergreen-fresh">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Evergreen + Fresh
                </div>
                <div class="aysa-tab-item" data-tab="customer-journey">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="5" cy="12" r="2" fill="currentColor"/>
                        <circle cx="12" cy="12" r="2" fill="currentColor"/>
                        <circle cx="19" cy="12" r="2" fill="currentColor"/>
                        <path d="M7 12H10" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        <path d="M14 12H17" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Customer Journey
                </div>
                <div class="aysa-tab-item" data-tab="local-seo">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 22C16 17.5 19 14.5 19 10A7 7 0 0 0 5 10C5 14.5 8 17.5 12 22Z" stroke="currentColor" stroke-width="2"/>
                        <circle cx="12" cy="10" r="2.5" stroke="currentColor" stroke-width="2"/>
                    </svg>
                    Local SEO
                </div>
                <div class="aysa-tab-item" data-tab="authority-building">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 2L4 6V12C4 17 7.5 20.5 12 22C16.5 20.5 20 17 20 12V6L12 2Z" stroke="currentColor" stroke-width="2"/>
                        <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    Authority Building
                </div>
                <div class="aysa-tab-item" data-tab="persona-based">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <circle cx="12" cy="8" r="3" stroke="currentColor" stroke-width="2"/>
                        <path d="M5 20C5 16.5 8 14 12 14C16 14 19 16.5 19 20" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    Persona-based
                </div>
            </div>

            <!-- Tab Content -->
            <div class="aysa-tab-content">
                <!-- Dashboard Tab Content -->
                <div class="aysa-tab-panel active" id="dashboard-panel">
                    <!-- Summary Cards -->
                    <div class="aysa-summary-cards">
                <div class="aysa-summary-card">
                    <div class="aysa-card-icon blue">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2Z" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <path d="M14 2V8H20" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                    <div class="aysa-card-content">
                        <h3>Total Articles</h3>
                        <span class="aysa-card-number" id="aysa-total-articles">0</span>
                    </div>
                </div>
                
                <div class="aysa-summary-card">
                    <div class="aysa-card-icon green">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M9 12L11 14L15 10" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            <circle cx="12" cy="12" r="10" stroke="white" stroke-width="2"/>
                        </svg>
                    </div>
                    <div class="aysa-card-content">
                        <h3>Published</h3>
                        <span class="aysa-card-number" id="aysa-published-articles">0</span>
                    </div>
                </div>
                
                <div class="aysa-summary-card">
                    <div class="aysa-card-icon yellow">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <circle cx="12" cy="12" r="10" stroke="white" stroke-width="2"/>
                            <polyline points="12,6 12,12 16,14" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                    <div class="aysa-card-content">
                        <h3>Pending</h3>
                        <span class="aysa-card-number" id="aysa-pending-articles">0</span>
                    </div>
                </div>
            </div>

            <div class="aysa-research-overview">
                <h3>Research overview (all tabs)</h3>
                <div class="aysa-research-overview-grid">
                    <div class="aysa-overview-item"><span class="label">Keyword Discovery</span><span class="value" id="aysa-overview-keywords">0 keywords</span></div>
                    <div class="aysa-overview-item"><span class="label">Associations</span><span class="value" id="aysa-overview-associations">0 links</span></div>
                    <div class="aysa-overview-item"><span class="label">Competitor Identification</span><span class="value" id="aysa-overview-competitors">0 competitors</span></div>
                    <div class="aysa-overview-item"><span class="label">Competitor Gap</span><span class="value" id="aysa-overview-gap">0 gap keywords</span></div>
                    <div class="aysa-overview-item"><span class="label">Backlink Analysis</span><span class="value" id="aysa-overview-backlinks">0 domains</span></div>
                    <div class="aysa-overview-item"><span class="label">Domain Authority</span><span class="value" id="aysa-overview-authority">avg 0</span></div>
                </div>
            </div>

            <!-- All Proposals Section -->
            <div class="aysa-proposals-section">
                <div class="aysa-proposals-header">
                    <h3 id="aysa-proposals-title">All Proposals (0)</h3>
                    <div class="aysa-proposals-controls">
                        <div class="aysa-search-box">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <circle cx="11" cy="11" r="8" stroke="#9CA3AF" stroke-width="2"/>
                                <path d="M21 21L16.65 16.65" stroke="#9CA3AF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                            <input type="text" placeholder="Search articles..." />
                        </div>
                        <select class="aysa-filter-select">
                            <option value="all">All Sources</option>
                            <option value="content-expansion">Missing Pages Plan</option>
                            <option value="clusters">Clusters</option>
                            <option value="competitor-titles">Competitor Titles</option>
                            <option value="legacy-content-from-sitemaps">Legacy Content From Sitemaps</option>
                            <option value="intent-layering">Intent Layering</option>
                            <option value="seasonal-events">Seasonal & Events</option>
                            <option value="serp-features">SERP Features</option>
                            <option value="evergreen-fresh">Evergreen + Fresh</option>
                            <option value="customer-journey">Customer Journey</option>
                            <option value="local-seo">Local SEO</option>
                            <option value="authority-building">Authority Building</option>
                            <option value="persona-based">Persona-based</option>
                        </select>
                        <select class="aysa-filter-select">
                            <option>All Statuses</option>
                            <option>Draft</option>
                            <option>In Review</option>
                            <option>Approved</option>
                            <option>Scheduled</option>
                            <option>Published</option>
                            <option>Blocked</option>
                        </select>
                        <button type="button" class="aysa-btn-small" id="aysa-refactor-titles-btn">Improve Titles</button>
                    </div>
                </div>

                <!-- Proposals Table -->
                <div class="aysa-proposals-table">
                    <table>
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>KEYWORDS</th>
                                <th>INTENT</th>
                                <th>SOURCE</th>
                                <th>Associated Page(s)</th>
                                <th>Recommended Date</th>
                                <th>STATUS</th>
                                <th>ACTIONS</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Rows will be populated dynamically -->
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 40px; color: #666;">
                                    <div style="margin-bottom: 10px;">
                                        <span class="dashicons dashicons-analytics" style="font-size: 32px; width: 32px; height: 32px;"></span>
                                    </div>
                                    <em>Loading strategies...</em>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="aysa-pagination">
                    <div class="aysa-pagination-info" id="aysa-pagination-info">
                        Showing 0-0 of 0 results
                    </div>
                    <div class="aysa-pagination-controls" id="aysa-pagination-controls">
                    </div>
                    </div>
                </div>

                <!-- Publication Calendar Tab -->
                <div class="aysa-tab-panel" id="publication-calendar-panel">
                    <div class="aysa-calendar-shell">
                        <div class="aysa-calendar-toolbar">
                            <div class="aysa-calendar-nav">
                                <button type="button" class="aysa-btn-small aysa-calendar-nav-btn" data-nav="-1">Prev</button>
                                <button type="button" class="aysa-btn-small aysa-calendar-nav-btn" data-nav="0">Today</button>
                                <button type="button" class="aysa-btn-small aysa-calendar-nav-btn" data-nav="1">Next</button>
                                <strong id="aysa-calendar-title">Calendar</strong>
                            </div>
                            <div class="aysa-calendar-view-switch">
                                <button type="button" class="aysa-btn-small aysa-calendar-view-btn active" data-view="month">Month</button>
                                <button type="button" class="aysa-btn-small aysa-calendar-view-btn" data-view="week">Week</button>
                                <button type="button" class="aysa-btn-small aysa-calendar-view-btn" data-view="day">Day</button>
                            </div>
                        </div>
                        <div class="aysa-calendar-summary" id="aysa-calendar-summary">
                            Loading calendar...
                        </div>
                        <div id="aysa-publication-calendar-grid" class="aysa-calendar-grid"></div>
                    </div>
                </div>

                <!-- Missing Pages Plan Tab Content -->
                <div class="aysa-tab-panel" id="content-expansion-panel">
                    <div class="aysa-panel">
                        <h3>Missing Pages Plan</h3>
                        <p>Use this view for content opportunities sent from Missing Pages. AYSA keeps the plan honest: real opportunities, real statuses, no placeholder content.</p>
                    </div>
                </div>

                <!-- Clusters Tab Content -->
                <div class="aysa-tab-panel" id="clusters-panel">
                    <div class="aysa-panel">
                        <h3>Content Clusters</h3>
                        <p>Cluster-generated strategy ideas appear here once AYSA has real data to display.</p>
                    </div>
                </div>

                <!-- Competitor Titles Tab Content -->
                <div class="aysa-tab-panel" id="competitor-titles-panel">
                    <div class="aysa-panel">
                        <h3>Competitor Title Analysis</h3>
                        <p>Review competitor-inspired title ideas generated from your actual research data.</p>
                    </div>
                </div>

                <!-- Legacy Content From Sitemaps Tab Content -->
                <div class="aysa-tab-panel" id="legacy-content-from-sitemaps-panel">
                    <div class="aysa-panel">
                        <h3>Legacy Content From Sitemaps</h3>
                        <p>Older title ideas derived from competitor sitemap imports are kept here separately from the new worker-driven competitor analysis module.</p>
                    </div>
                </div>

                <!-- Intent Layering Tab Content -->
                <div class="aysa-tab-panel" id="intent-layering-panel">
                    <div class="aysa-panel">
                        <h3>Search Intent Layering</h3>
                        <p>See how AYSA turns one topic into informational, commercial, navigational, and transactional angles when real intent-layered items exist.</p>
                    </div>
                </div>

                <!-- Seasonal & Events Tab Content -->
                <div class="aysa-tab-panel" id="seasonal-events-panel">
                    <div class="aysa-panel">
                        <h3>Seasonal & Event Content</h3>
                        <p>Seasonal and event-driven opportunities will appear here when AYSA generates them from your market and planning context.</p>
                    </div>
                </div>

                <!-- SERP Features Tab Content -->
                <div class="aysa-tab-panel" id="serp-features-panel">
                    <div class="aysa-panel">
                        <h3>SERP Features Optimization</h3>
                        <p>Use this area to review content ideas aimed at snippets, PAA blocks, and other SERP features once real suggestions exist.</p>
                    </div>
                </div>

                <!-- Evergreen + Fresh Tab Content -->
                <div class="aysa-tab-panel" id="evergreen-fresh-panel">
                    <div class="aysa-panel">
                        <h3>Evergreen & Fresh Content</h3>
                        <p>AYSA will separate evergreen and freshness-driven opportunities here when the strategy engine has real output to show.</p>
                    </div>
                </div>
            </div>

        </div>
    </div>

</div>

<style>
.aysa-content-strategy {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: #f8fafc;
    min-height: 100vh;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Base Styles */
.aysa-admin {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    width: 100%;
    margin: 0;
    padding: 0;
    background-color: #f8fafc;
    display: flex;
    flex-direction: column;
    min-height: 100vh;
}

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

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

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

/* Top Tabs */
.aysa-top-tabs {
    display: flex;
    flex-wrap: wrap;
    border-bottom: 1px solid #e0e0e0;
    background-color: #ffffff;
    padding: 0;
}

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

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

.aysa-tab.disabled {
    color: #bbb;
    cursor: not-allowed;
}

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

/* Main Content */
.aysa-content {
    padding: 0;
    flex-grow: 1;
    width: 100%;
    overflow-x: auto;
}

.aysa-content-strategy-dashboard {
    width: 100%;
    margin: 0;
    padding: 32px;
    background: #f8fafc;
}

/* Tab Content */
.aysa-tab-content {
    margin-top: 24px;
}

.aysa-tab-panel {
    display: none;
}

.aysa-tab-panel.active {
    display: block;
}

.aysa-content-strategy.is-calendar-active #dashboard-panel > .aysa-summary-cards,
.aysa-content-strategy.is-calendar-active #dashboard-panel > .aysa-research-overview,
.aysa-content-strategy.is-calendar-active #dashboard-panel > .aysa-proposals-section > .aysa-proposals-header,
.aysa-content-strategy.is-calendar-active #dashboard-panel > .aysa-proposals-section > .aysa-proposals-table,
.aysa-content-strategy.is-calendar-active #dashboard-panel > .aysa-proposals-section > .aysa-pagination {
    display: none !important;
}

.aysa-content-strategy.is-calendar-active #publication-calendar-panel {
    display: block !important;
    margin-top: 8px;
}

.aysa-content-strategy.is-embedded-calendar {
    padding: 0 !important;
    margin: 0 !important;
}

.aysa-content-strategy.is-embedded-calendar .aysa-page-title,
.aysa-content-strategy.is-embedded-calendar .aysa-top-tabs,
.aysa-content-strategy.is-embedded-calendar .aysa-header-right,
.aysa-content-strategy.is-embedded-calendar .aysa-dashboard-tabs,
.aysa-content-strategy.is-embedded-calendar .aysa-plan-status,
.aysa-content-strategy.is-embedded-calendar .aysa-generation-status {
    display: none !important;
}

.aysa-content-strategy.is-embedded-calendar .aysa-content,
.aysa-content-strategy.is-embedded-calendar .aysa-content-strategy-dashboard,
.aysa-content-strategy.is-embedded-calendar .aysa-tab-content {
    margin: 0 !important;
    padding: 0 !important;
    background: transparent !important;
}

.aysa-content-strategy.is-embedded-calendar .aysa-dashboard-header {
    display: none !important;
}

.aysa-content-strategy.is-embedded-calendar .aysa-header-left h2 {
    margin: 0;
}

.aysa-content-strategy.is-embedded-calendar #dashboard-panel,
.aysa-content-strategy.is-embedded-calendar #content-expansion-panel,
.aysa-content-strategy.is-embedded-calendar #clusters-panel,
.aysa-content-strategy.is-embedded-calendar #competitor-titles-panel,
.aysa-content-strategy.is-embedded-calendar #intent-layering-panel,
.aysa-content-strategy.is-embedded-calendar #seasonal-events-panel,
.aysa-content-strategy.is-embedded-calendar #serp-features-panel,
.aysa-content-strategy.is-embedded-calendar #evergreen-fresh-panel,
.aysa-content-strategy.is-embedded-calendar #customer-journey-panel,
.aysa-content-strategy.is-embedded-calendar #local-seo-panel,
.aysa-content-strategy.is-embedded-calendar #authority-building-panel,
.aysa-content-strategy.is-embedded-calendar #persona-based-panel {
    display: none !important;
}

.aysa-content-strategy.is-embedded-calendar #publication-calendar-panel {
    display: block !important;
    margin-top: 0 !important;
}

.aysa-content-strategy.is-embedded-calendar .aysa-calendar-shell {
    border-radius: 0;
    border-left: 0;
    border-right: 0;
    border-bottom: 0;
}

html.aysa-embedded-calendar-page,
body.aysa-embedded-calendar-page {
    margin: 0 !important;
    padding: 0 !important;
    background: #ffffff !important;
}

body.aysa-embedded-calendar-page #wpadminbar,
body.aysa-embedded-calendar-page #adminmenumain,
body.aysa-embedded-calendar-page #screen-meta,
body.aysa-embedded-calendar-page #screen-meta-links,
body.aysa-embedded-calendar-page .notice,
body.aysa-embedded-calendar-page .update-nag,
body.aysa-embedded-calendar-page .wrap > h1,
body.aysa-embedded-calendar-page #wpfooter {
    display: none !important;
}

body.aysa-embedded-calendar-page #wpcontent,
body.aysa-embedded-calendar-page #wpbody,
body.aysa-embedded-calendar-page #wpbody-content {
    margin: 0 !important;
    padding: 0 !important;
}

body.aysa-embedded-calendar-page #wpbody-content > .wrap {
    margin: 0 !important;
    padding: 0 !important;
}

body.aysa-embedded-calendar-page #wpbody-content > .wrap > h1,
body.aysa-embedded-calendar-page #wpbody-content > h1,
body.aysa-embedded-calendar-page h1.wp-heading-inline,
body.aysa-embedded-calendar-page .wrap > h1.wp-heading-inline {
    display: none !important;
}

.aysa-calendar-shell {
    background: #ffffff;
    border: 1px solid #E5E7EB;
    border-radius: 12px;
    padding: 16px;
}

.aysa-calendar-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.aysa-calendar-nav,
.aysa-calendar-view-switch {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-calendar-summary {
    margin-top: 12px;
    margin-bottom: 12px;
    padding: 10px 12px;
    border: 1px solid #DBEAFE;
    border-left: 4px solid #2563EB;
    background: #EFF6FF;
    color: #1E3A8A;
    border-radius: 8px;
    font-size: 13px;
}

.aysa-calendar-grid {
    width: 100%;
}

.aysa-cal-head {
    display: grid;
    grid-template-columns: repeat(7, minmax(0, 1fr));
    gap: 6px;
    margin-bottom: 6px;
}

.aysa-cal-head-item {
    text-align: center;
    font-size: 12px;
    font-weight: 600;
    color: #64748B;
    padding: 8px 4px;
}

.aysa-cal-month {
    display: grid;
    grid-template-columns: repeat(7, minmax(0, 1fr));
    gap: 6px;
}

.aysa-cal-day {
    min-height: 120px;
    border: 1px solid #E5E7EB;
    border-radius: 10px;
    padding: 8px;
    background: #fff;
}

.aysa-cal-day.is-outside {
    background: #F8FAFC;
    color: #94A3B8;
}

.aysa-cal-daynum {
    font-size: 12px;
    font-weight: 700;
    color: #334155;
    margin-bottom: 6px;
}

.aysa-cal-event {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 4px;
    padding: 4px 6px;
    border-radius: 999px;
    font-size: 11px;
    line-height: 1.3;
    text-decoration: none;
    border: 1px solid transparent;
    overflow: hidden;
}

.aysa-cal-event-title {
    min-width: 0;
    flex: 1 1 auto;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.aysa-cal-event.is-scheduled {
    background: #FFF7ED;
    border-color: #FDBA74;
    color: #9A3412;
}

.aysa-cal-event.is-published {
    background: #ECFDF5;
    border-color: #86EFAC;
    color: #166534;
}

.aysa-cal-event.is-missing-landing {
    background: #EFF6FF;
    border-color: #93C5FD;
    color: #1D4ED8;
}

.aysa-cal-event.is-missing-category {
    background: #F5F3FF;
    border-color: #C4B5FD;
    color: #6D28D9;
}

.aysa-cal-event.is-missing-product {
    background: #ECFDF5;
    border-color: #86EFAC;
    color: #166534;
}

.aysa-cal-event.type-post {
    box-shadow: inset 3px 0 0 #94A3B8;
}

.aysa-cal-event.type-landing {
    box-shadow: inset 3px 0 0 #60A5FA;
}

.aysa-cal-event.type-category {
    box-shadow: inset 3px 0 0 #A78BFA;
}

.aysa-cal-event.type-product {
    box-shadow: inset 3px 0 0 #4ADE80;
}

.aysa-cal-more-btn {
    display: inline-block;
    margin: 2px 6px 0;
    font-size: 11px;
    color: #1d4ed8;
    text-decoration: underline;
    cursor: pointer;
    background: transparent;
    border: none;
    padding: 0;
}

.aysa-cal-list {
    border: 1px solid #E5E7EB;
    border-radius: 10px;
    overflow: hidden;
}

.aysa-cal-list-item {
    display: grid;
    grid-template-columns: 96px 120px 1fr auto;
    gap: 8px;
    align-items: center;
    padding: 10px 12px;
    border-bottom: 1px solid #F1F5F9;
    font-size: 13px;
}

.aysa-cal-list-item.is-missing-landing {
    background: #F8FBFF;
    border-left: 3px solid #60A5FA;
}

.aysa-cal-list-item.is-missing-category {
    background: #FAF8FF;
    border-left: 3px solid #A78BFA;
}

.aysa-cal-list-item.is-missing-product {
    background: #F4FFF7;
    border-left: 3px solid #4ADE80;
}

.aysa-cal-list-item.type-post {
    border-left: 3px solid #94A3B8;
}

.aysa-cal-list-item.type-landing {
    border-left: 3px solid #60A5FA;
}

.aysa-cal-list-item.type-category {
    border-left: 3px solid #A78BFA;
}

.aysa-cal-list-item.type-product {
    border-left: 3px solid #4ADE80;
}

.aysa-cal-list-item:last-child {
    border-bottom: none;
}

.aysa-cal-badge {
    display: inline-block;
    border-radius: 999px;
    padding: 3px 8px;
    font-size: 11px;
    font-weight: 600;
}

.aysa-cal-badge.scheduled {
    background: #FFF7ED;
    color: #9A3412;
}

.aysa-cal-badge.published {
    background: #ECFDF5;
    color: #166534;
}

.aysa-cal-type-badge {
    display: inline-block;
    border-radius: 999px;
    padding: 3px 8px;
    font-size: 11px;
    font-weight: 600;
    margin-left: 4px;
    background: #F1F5F9;
    color: #334155;
}

.aysa-cal-type-badge.type-post {
    background: #E2E8F0;
    color: #334155;
}

.aysa-cal-type-badge.type-landing {
    background: #DBEAFE;
    color: #1D4ED8;
}

.aysa-cal-type-badge.type-category {
    background: #EDE9FE;
    color: #6D28D9;
}

.aysa-cal-type-badge.type-product {
    background: #DCFCE7;
    color: #166534;
}

/* Tab Panel Styles */
.aysa-tab-panel .aysa-panel {
    background: white;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 20px;
}

.aysa-tab-panel .aysa-panel h3 {
    margin: 0 0 12px 0;
    font-size: 20px;
    font-weight: 600;
    color: #111827;
}

.aysa-tab-panel .aysa-panel p {
    margin: 0 0 20px 0;
    color: #6B7280;
    font-size: 14px;
}

/* Cluster Grid */
.aysa-cluster-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;
}

.aysa-cluster-card {
    background: #F9FAFB;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
}

.aysa-cluster-card h4 {
    margin: 0 0 8px 0;
    color: #111827;
    font-size: 16px;
    font-weight: 600;
}

.aysa-cluster-count {
    color: #6B7280;
    font-size: 14px;
}

/* Competitor Titles */
.aysa-competitor-titles-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.aysa-title-item {
    background: #F9FAFB;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-title-item h4 {
    margin: 0;
    color: #111827;
    font-size: 14px;
    font-weight: 500;
    flex: 1;
}

.aysa-competitor-source {
    color: #6B7280;
    font-size: 12px;
    margin: 0 12px;
}

.aysa-title-score {
    background: #10B981;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

/* Intent Grid */
.aysa-intent-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
}

.aysa-intent-card {
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    color: white;
}

.aysa-intent-card.informational {
    background: #10B981;
}

.aysa-intent-card.commercial {
    background: #F59E0B;
}

.aysa-intent-card.navigational {
    background: #8B5CF6;
}

.aysa-intent-card.transactional {
    background: #EF4444;
}

.aysa-intent-card h4 {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
}

.aysa-intent-count {
    font-size: 14px;
    opacity: 0.9;
}

/* Seasonal Calendar */
.aysa-seasonal-calendar {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.aysa-seasonal-item {
    background: #F9FAFB;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-seasonal-item h4 {
    margin: 0;
    color: #111827;
    font-size: 14px;
    font-weight: 500;
    flex: 1;
}

.aysa-seasonal-date {
    color: #6B7280;
    font-size: 12px;
    margin: 0 12px;
}

.aysa-seasonal-status {
    background: #3B82F6;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

/* SERP Features */
.aysa-serp-features {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
}

.aysa-feature-card {
    background: #F9FAFB;
    border: 1px solid #E5E7EB;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
}

.aysa-feature-card h4 {
    margin: 0 0 8px 0;
    color: #111827;
    font-size: 16px;
    font-weight: 600;
}

.aysa-feature-count {
    color: #007cba;
    font-size: 14px;
    font-weight: 500;
}

/* Content Balance */
.aysa-content-balance {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.aysa-balance-card {
    border-radius: 8px;
    padding: 24px;
    text-align: center;
    color: white;
}

.aysa-balance-card.evergreen {
    background: #10B981;
}

.aysa-balance-card.fresh {
    background: #3B82F6;
}

.aysa-balance-card h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
}

.aysa-balance-percentage {
    display: block;
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 8px;
}

.aysa-balance-count {
    font-size: 14px;
    opacity: 0.9;
}

/* Modal Styles */
.aysa-modal-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    background: rgba(0, 0, 0, 0.5) !important;
    display: flex !important;
    z-index: 999999 !important;
    align-items: center !important;
    justify-content: center !important;
    visibility: visible !important;
    opacity: 1 !important;
}

.aysa-modal {
    background: white !important;
    border-radius: 8px !important;
    max-width: 420px !important;
    width: 90% !important;
    max-height: 80vh !important;
    overflow-y: auto !important;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15) !important;
    position: relative !important;
    z-index: 1000000 !important;
    visibility: visible !important;
    opacity: 1 !important;
    display: block !important;
    margin: auto !important;
    transform: none !important;
}

.aysa-modal-header {
    padding: 24px 24px 16px 24px;
    border-bottom: none;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-modal-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 700;
    color: #1a202c;
    line-height: 1.2;
}

.aysa-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #64748b;
    padding: 8px;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.aysa-modal-close:hover {
    color: #374151;
    background: #f1f5f9;
}

.aysa-modal-content {
    padding: 0 24px 24px 24px;
}

.aysa-modal-content p {
    margin: 0 0 20px 0;
    color: #6B7280;
    line-height: 1.5;
}

.aysa-modal-actions {
    display: flex;
    gap: 16px;
    justify-content: flex-end;
    margin-top: 24px;
    padding-top: 0;
}

.aysa-btn {
    padding: 10px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    border: none;
    transition: all 0.2s ease;
    min-width: 70px;
    text-align: center;
}

.aysa-btn-primary {
    background: #007cba;
    color: white;
}

.aysa-btn-primary:hover {
    background: #005a87;
}

.aysa-btn-secondary {
    background: #f3f4f6;
    color: #374151;
    border: none;
}

.aysa-btn-secondary:hover {
    background: #e5e7eb;
}

.aysa-schedule-options {
    margin: 16px 0;
}

.aysa-schedule-options label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: #374151;
    cursor: pointer;
}

.aysa-schedule-options input[type="radio"] {
    margin-right: 8px;
}

/* Form Styles */
.aysa-form-group {
    margin-bottom: 24px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
}

.aysa-input-group {
    display: flex;
    gap: 12px;
}

.aysa-input-with-icon {
    position: relative;
    width: 100%;
}

.aysa-input-with-icon .aysa-input {
    padding-right: 40px;
}

.aysa-input-icon {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    color: #6b7280;
    pointer-events: none;
}

.aysa-input,
.aysa-select {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 4px;
    font-size: 14px;
    background: white;
    transition: all 0.2s ease;
    box-sizing: border-box;
}

.aysa-input:focus,
.aysa-select:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 3px rgba(0,124,186,0.1);
}

.aysa-select {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 8px center;
    background-repeat: no-repeat;
    background-size: 14px;
    padding-right: 32px;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
}

.aysa-checkbox-group {
    margin: 20px 0;
}

.aysa-checkbox-group label {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 14px;
    color: #374151;
    cursor: pointer;
    font-weight: 400;
}

.aysa-checkbox-group input[type="checkbox"] {
    margin: 0;
    width: 16px;
    height: 16px;
    accent-color: #007cba;
    cursor: pointer;
}

/* Enhanced Modal Styles */
.aysa-modal-schedule,
.aysa-modal-generate {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    border: 1px solid #e5e7eb;
}

.aysa-datetime-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.aysa-date-input,
.aysa-time-input {
    flex: 1;
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    background: #ffffff;
    transition: all 0.2s ease;
}

.aysa-date-input:focus,
.aysa-time-input:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 3px rgba(0, 124, 186, 0.1);
}

.aysa-category-select,
.aysa-author-select,
.aysa-article-type-select,
.aysa-tone-select {
    padding: 12px 16px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    background: #ffffff;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-category-select:focus,
.aysa-author-select:focus,
.aysa-article-type-select:focus,
.aysa-tone-select:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 3px rgba(0, 124, 186, 0.1);
}

.aysa-checkbox-label {
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    padding: 8px 0;
}

.aysa-checkbox {
    width: 18px;
    height: 18px;
    border: 2px solid #d1d5db;
    border-radius: 4px;
    background: #ffffff;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-checkbox:checked {
    background: #007cba;
    border-color: #007cba;
}

.aysa-checkbox-text {
    font-size: 14px;
    color: #374151;
    font-weight: 500;
}

.aysa-btn-schedule,
.aysa-btn-generate {
    background: #007cba;
    color: white;
    padding: 12px 24px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-btn-schedule:hover,
.aysa-btn-generate:hover {
    background: #005a87;
    transform: translateY(-1px);
}

.aysa-btn-cancel {
    background: #f3f4f6;
    color: #374151;
    padding: 12px 24px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    border: 1px solid #d1d5db;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-btn-cancel:hover {
    background: #e5e7eb;
}

/* Modal Header Enhancement */
.aysa-modal-header h3 {
    font-size: 20px;
    font-weight: 700;
    color: #111827;
    margin: 0;
}

.aysa-modal-header {
    padding: 24px 24px 20px 24px;
    border-bottom: 1px solid #f3f4f6;
}

.aysa-modal-content {
    padding: 24px;
}

.aysa-modal-actions {
    display: flex;
    gap: 16px;
    justify-content: flex-end;
    margin-top: 24px;
    padding-top: 20px;
    border-top: 1px solid #f3f4f6;
}

.aysa-form-group {
    margin-bottom: 24px;
}

.aysa-form-group label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 600;
    color: #374151;
}

/* Modal Close Button */
.aysa-modal-close {
    background: none;
    border: none;
    font-size: 28px;
    cursor: pointer;
    color: #9ca3af;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.aysa-modal-close:hover {
    color: #374151;
    background: #f3f4f6;
}

/* Dashboard Header */
.aysa-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
    padding: 0 0 24px 0;
    border-bottom: none;
}

.aysa-header-left {
    display: flex;
    align-items: center;
    gap: 16px;
}

.aysa-header-icon {
    width: 32px;
    height: 32px;
    background: none;
    border-radius: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-dashboard-header h2 {
    margin: 0;
    font-size: 32px;
    font-weight: 700;
    color: #1a202c;
    line-height: 1.2;
}

.aysa-header-right {
    display: flex;
    align-items: center;
    position: relative;
    gap: 12px;
}

.aysa-generate-strategy-btn {
    background: #007cba;
    color: white;
    border: none;
    padding: 14px 28px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0, 124, 186, 0.2);
}

.aysa-plan-content-btn {
    height: 44px;
    border-radius: 10px;
    border: 1px solid #1f8f4e;
    background: linear-gradient(135deg, #2ea043, #1f8f4e);
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    padding: 0 16px;
    cursor: pointer;
    margin-right: 10px;
}

.aysa-plan-content-btn:hover {
    filter: brightness(0.95);
}

.aysa-associate-missing-btn {
    height: 44px;
    border-radius: 10px;
    border: 1px solid #1d4ed8;
    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    padding: 0 16px;
    cursor: pointer;
    margin-right: 10px;
}

.aysa-associate-missing-btn:hover {
    filter: brightness(0.95);
}

.aysa-associate-missing-btn[disabled] {
    opacity: 0.75;
    cursor: wait;
}

.aysa-reset-plan-btn {
    height: 44px;
    border-radius: 10px;
    border: 1px solid #b42318;
    background: linear-gradient(135deg, #ef4444, #b42318);
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    padding: 0 16px;
    cursor: pointer;
    margin-right: 10px;
}

.aysa-reset-plan-btn:hover {
    filter: brightness(0.95);
}

.aysa-reset-plan-btn[disabled] {
    opacity: 0.75;
    cursor: wait;
}

.aysa-plan-status {
    margin: 12px 0 4px;
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    background: #f8fafc;
    color: #334155;
    font-size: 13px;
}

.aysa-generation-status {
    margin: 8px 0 12px;
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid #bfdbfe;
    background: linear-gradient(135deg, #eff6ff, #e0ecff);
    color: #1e3a8a;
    font-size: 13px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 10px;
}

.aysa-generation-status[hidden] {
    display: none !important;
}

.aysa-generation-dot {
    width: 10px;
    height: 10px;
    border-radius: 999px;
    background: #2563eb;
    box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.4);
    animation: aysaPulseDot 1.6s ease-in-out infinite;
}

@keyframes aysaPulseDot {
    0% {
        box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.4);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(37, 99, 235, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(37, 99, 235, 0);
    }
}

.aysa-generate-strategy-btn:hover {
    background: #005a87;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 124, 186, 0.3);
}

.aysa-generate-strategy-btn.is-loading {
    opacity: 0.85;
    pointer-events: none;
}

.aysa-strategy-picker {
    position: absolute;
    top: calc(100% + 12px);
    right: 0;
    width: 560px;
    max-width: min(92vw, 560px);
    background: #fff;
    border: 1px solid #dbe3ef;
    border-radius: 14px;
    box-shadow: 0 16px 44px rgba(15, 23, 42, 0.18);
    z-index: 60;
    padding: 14px;
}

.aysa-strategy-picker[hidden] {
    display: none !important;
}

.aysa-strategy-picker-head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 12px;
}

.aysa-strategy-picker-head strong {
    display: block;
    font-size: 15px;
    color: #0f172a;
}

.aysa-strategy-picker-head p {
    margin: 3px 0 0;
    color: #64748b;
    font-size: 12px;
}

.aysa-strategy-picker-close {
    border: 1px solid #d6dee9;
    background: #fff;
    color: #475569;
    width: 30px;
    height: 30px;
    line-height: 28px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;
    padding: 0;
}

.aysa-strategy-picker-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 10px;
}

.aysa-strategy-type-btn {
    border: 1px solid #d8e0ea;
    background: #fff;
    border-radius: 10px;
    padding: 10px 12px;
    text-align: left;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-strategy-type-btn .title {
    display: block;
    color: #0f172a;
    font-size: 13px;
    font-weight: 700;
}

.aysa-strategy-type-btn .desc {
    display: block;
    color: #64748b;
    font-size: 12px;
    margin-top: 3px;
}

.aysa-strategy-type-btn:hover {
    border-color: #007cba;
    background: #f0f8ff;
}

.aysa-strategy-type-btn.is-loading {
    border-color: #007cba;
    background: #ebf5fb;
}

/* Dashboard Tabs */
.aysa-dashboard-tabs {
    display: flex;
    gap: 40px;
    margin-bottom: 32px;
    padding: 0 0 16px 0;
    border-bottom: 1px solid #e2e8f0;
    overflow-x: auto;
    background: white;
    padding: 20px 0;
    border-radius: 8px;
    margin: 0 0 32px 0;
}

.aysa-tab-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 0;
    font-size: 15px;
    font-weight: 500;
    color: #64748b;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    transition: all 0.2s ease;
    white-space: nowrap;
    position: relative;
}

.aysa-tab-item.active {
    color: #007cba;
    border-bottom-color: #007cba;
    font-weight: 600;
}

.aysa-tab-item:hover {
    color: #007cba;
}

.aysa-tab-item svg {
    width: 18px;
    height: 18px;
}

/* Summary Cards */
.aysa-summary-cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
    margin-bottom: 32px;
}

.aysa-summary-card {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 32px 24px;
    display: flex;
    align-items: center;
    gap: 20px;
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-summary-card:hover {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.aysa-card-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-card-icon.blue {
    background: #3B82F6;
}

.aysa-card-icon.green {
    background: #10B981;
}

.aysa-card-icon.yellow {
    background: #F59E0B;
}

.aysa-card-content h3 {
    margin: 0 0 8px 0;
    font-size: 14px;
    font-weight: 500;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.aysa-card-number {
    font-size: 36px;
    font-weight: 700;
    color: #1a202c;
    line-height: 1;
}

.aysa-research-overview {
    margin: 0 0 24px;
    padding: 16px;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    background: #f8fafc;
}

.aysa-research-overview > h3 {
    margin: 0 0 12px;
    font-size: 15px;
    color: #0f172a;
}

.aysa-research-overview-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
}

.aysa-overview-item {
    border: 1px solid #dbe2ea;
    border-radius: 8px;
    background: #ffffff;
    padding: 10px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
}

.aysa-overview-item .label {
    color: #475569;
    font-size: 12px;
    font-weight: 600;
}

.aysa-overview-item .value {
    color: #0f172a;
    font-size: 13px;
    font-weight: 700;
}

/* Proposals Section */
.aysa-proposals-section {
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    overflow: hidden;
    width: 100%;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-proposals-header {
    padding: 24px;
    border-bottom: 1px solid #E5E7EB;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
}

.aysa-proposals-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #111827;
}

.aysa-proposals-controls {
    display: flex;
    gap: 12px;
    align-items: center;
}

.aysa-search-box {
    position: relative;
    display: flex;
    align-items: center;
}

.aysa-search-box svg {
    position: absolute;
    left: 12px;
    z-index: 1;
}

.aysa-search-box input {
    padding: 8px 12px 8px 36px;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: 14px;
    width: 200px;
}

.aysa-search-box input:focus {
    outline: none;
    border-color: #007cba;
    box-shadow: 0 0 0 3px rgba(0,124,186,0.1);
}

.aysa-filter-select {
    padding: 8px 12px;
    border: 1px solid #D1D5DB;
    border-radius: 6px;
    font-size: 14px;
    background: white;
    cursor: pointer;
}

/* Table */
.aysa-proposals-table {
    overflow-x: auto;
}

.aysa-proposals-table table {
    width: 100%;
    border-collapse: collapse;
}

.aysa-proposals-table th {
    background: #f8fafc;
    padding: 20px 16px;
    text-align: left;
    font-size: 12px;
    font-weight: 600;
    color: #475569;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 1px solid #e2e8f0;
    white-space: nowrap;
}

.aysa-proposals-table td {
    padding: 20px 16px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: top;
    font-size: 14px;
}

.aysa-title-cell strong {
    color: #111827;
    font-weight: 600;
}

.aysa-meta-inline {
    margin-top: 6px;
    font-size: 12px;
    line-height: 1.45;
    color: #334155;
    max-width: 720px;
}

.aysa-meta-inline span {
    font-weight: 700;
    color: #0f172a;
}

.aysa-meta-inline-desc {
    color: #475569;
}

.aysa-meta-warning {
    display: inline-block;
    margin-top: 6px;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 700;
    color: #92400e;
    background: #fffbeb;
    border: 1px solid #fde68a;
}

.aysa-meta-source-badge {
    display: inline-block;
    margin-top: 6px;
    margin-left: 6px;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 700;
    border: 1px solid transparent;
    letter-spacing: 0.02em;
}

.aysa-meta-source-badge.is-ai {
    color: #166534;
    background: #dcfce7;
    border-color: #86efac;
}

.aysa-meta-source-badge.is-fallback {
    color: #92400e;
    background: #fffbeb;
    border-color: #fde68a;
}

.aysa-keywords-cell {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
}

.aysa-keyword-tag {
    background: #EBF8FF;
    color: #1E40AF;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-intent-tag {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    color: white;
}

.aysa-intent-tag.informational {
    background: #10B981;
}

.aysa-intent-tag.commercial {
    background: #F59E0B;
}

.aysa-intent-tag.navigational {
    background: #8B5CF6;
}

.aysa-source-tag {
    display: inline-flex;
    align-items: center;
    padding: 4px 8px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 700;
    color: #0f172a;
    background: #e5e7eb;
    border: 1px solid #cbd5e1;
}

.aysa-source-tag.cluster {
    background: #8B5CF6;
    color: #fff;
    border-color: #7c3aed;
}

.aysa-source-tag.competitor {
    background: #EF4444;
    color: #fff;
    border-color: #dc2626;
}

.aysa-source-tag.seasonal {
    background: #F59E0B;
    color: #fff;
    border-color: #d97706;
}

.aysa-source-tag.evergreen {
    background: #10B981;
    color: #fff;
    border-color: #059669;
}

.aysa-source-tag.missing_pages,
.aysa-source-tag.content_expansion {
    background: #2563EB;
    color: #fff;
    border-color: #1d4ed8;
}

.aysa-source-tag.cluster_titles,
.aysa-source-tag.clusters {
    background: #8B5CF6;
    color: #fff;
    border-color: #7c3aed;
}

.aysa-source-tag.competitor_derived_titles,
.aysa-source-tag.competitor_titles {
    background: #EF4444;
    color: #fff;
    border-color: #dc2626;
}

.aysa-source-tag.intent_layering,
.aysa-source-tag.intent {
    background: #0ea5e9;
    color: #fff;
    border-color: #0284c7;
}

.aysa-source-tag.seasonal_event,
.aysa-source-tag.seasonal_events {
    background: #F59E0B;
    color: #fff;
    border-color: #d97706;
}

.aysa-source-tag.serp_features,
.aysa-source-tag.serp {
    background: #475569;
    color: #fff;
    border-color: #334155;
}

.aysa-source-tag.evergreen_fresh_mix,
.aysa-source-tag.evergreen_fresh {
    background: #10B981;
    color: #fff;
    border-color: #059669;
}

.aysa-source-tag.customer_journey,
.aysa-source-tag.journey {
    background: #f97316;
    color: #fff;
    border-color: #ea580c;
}

.aysa-source-tag.local_seo,
.aysa-source-tag.local {
    background: #2563eb;
    color: #fff;
    border-color: #1d4ed8;
}

.aysa-source-tag.authority_building,
.aysa-source-tag.authority {
    background: #0f766e;
    color: #fff;
    border-color: #115e59;
}

.aysa-source-tag.persona_based,
.aysa-source-tag.persona {
    background: #7c3aed;
    color: #fff;
    border-color: #6d28d9;
}

.aysa-competitor-ref {
    margin-top: 8px;
    padding: 8px 10px;
    border-radius: 8px;
    background: #fff7ed;
    border: 1px solid #fed7aa;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.aysa-competitor-ref-label {
    font-size: 11px;
    font-weight: 700;
    color: #9a3412;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}

.aysa-competitor-ref-domain {
    font-size: 12px;
    font-weight: 700;
    color: #7c2d12;
}

.aysa-competitor-ref-title {
    font-size: 12px;
    color: #9a3412;
    text-decoration: none;
    line-height: 1.4;
}

.aysa-competitor-ref-title:hover {
    text-decoration: underline;
}

.aysa-competitor-why-better {
    margin-top: 6px;
    color: #475569;
}

.aysa-pages-cell {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.aysa-pages-cell a {
    display: inline-block;
    font-size: 12px;
    color: #1D4ED8;
    word-break: break-all;
}

.aysa-pages-cell span {
    font-size: 12px;
    color: #6B7280;
    font-family: monospace;
}

.aysa-date-cell {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #6B7280;
}

.aysa-status-tag {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
    color: white;
}

.aysa-status-tag.draft {
    background: #F59E0B;
}

.aysa-status-tag.in-review {
    background: #3B82F6;
}

.aysa-status-tag.approved {
    background: #10B981;
}

.aysa-status-tag.scheduled {
    background: #8B5CF6;
}

.aysa-status-tag.published {
    background: #059669;
}

.aysa-actions-cell {
    display: flex;
    gap: 8px;
    align-items: center;
}

.aysa-action-btn {
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    border: 1px solid;
    transition: all 0.2s ease;
    margin-right: 8px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.aysa-action-btn.primary {
    background: #007cba;
    color: white;
    border-color: #007cba;
}

.aysa-action-btn.primary:hover {
    background: #005a87;
    transform: translateY(-1px);
}

.aysa-action-btn.secondary {
    background: white;
    color: #64748b;
    border-color: #e2e8f0;
}

.aysa-action-btn.secondary:hover {
    background: #f8fafc;
    border-color: #cbd5e1;
}

.aysa-more-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: background 0.2s ease;
}

.aysa-more-btn:hover {
    background: #F3F4F6;
}

/* Pagination */
.aysa-pagination {
    padding: 24px 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #e2e8f0;
    background: #f8fafc;
}

.aysa-pagination-info {
    font-size: 14px;
    color: #6B7280;
}

.aysa-pagination-controls {
    display: flex;
    gap: 4px;
    align-items: center;
}

.aysa-pagination-btn {
    padding: 10px 14px;
    border: 1px solid #d1d5db;
    background: white;
    color: #475569;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    min-width: 40px;
    text-align: center;
}

.aysa-pagination-btn:hover {
    background: #F3F4F6;
}

.aysa-pagination-btn.active {
    background: #007cba;
    color: white;
    border-color: #007cba;
    font-weight: 600;
}

.aysa-pagination-dots {
    padding: 0 8px;
    color: #6B7280;
}

/* Responsive */
@media (max-width: 1200px) {
    .aysa-content-strategy-dashboard {
        padding: 24px;
    }
    
    .aysa-summary-cards {
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
    }
    
    .aysa-summary-card {
        padding: 24px 20px;
    }
    
    .aysa-card-number {
        font-size: 28px;
    }

    .aysa-strategy-picker {
        width: 500px;
    }
}

@media (max-width: 768px) {
    .aysa-content-strategy-dashboard {
        padding: 16px;
    }
    
    .aysa-dashboard-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }

    .aysa-header-right {
        width: 100%;
        flex-wrap: wrap;
    }
    
    .aysa-dashboard-header h2 {
        font-size: 24px;
    }
    
    .aysa-dashboard-tabs {
        gap: 20px;
        overflow-x: auto;
        padding: 16px 0;
    }
    
    .aysa-summary-cards {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .aysa-research-overview-grid {
        grid-template-columns: 1fr;
    }
    
    .aysa-proposals-header {
        flex-direction: column;
        align-items: flex-start;
    }
    
    .aysa-proposals-controls {
        flex-direction: column;
        width: 100%;
    }
    
    .aysa-search-box input {
        width: 100%;
    }
    
    .aysa-proposals-table {
        font-size: 12px;
    }
    
    .aysa-proposals-table th,
    .aysa-proposals-table td {
        padding: 12px 8px;
    }
    
    .aysa-action-btn {
        padding: 6px 12px;
        font-size: 12px;
    }
    
    .aysa-pagination {
        flex-direction: column;
        gap: 16px;
    }

    .aysa-strategy-picker {
        left: 0;
        right: auto;
        width: 100%;
        max-width: 100%;
    }

    .aysa-strategy-picker-grid {
        grid-template-columns: 1fr;
    }
}

.aysa-meta-preview-card {
    position: fixed;
    right: 24px;
    bottom: 24px;
    width: min(560px, calc(100vw - 32px));
    max-height: min(72vh, 700px);
    overflow: auto;
    border: 1px solid #dbe3ef;
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 20px 40px rgba(15, 23, 42, 0.16);
    z-index: 99999;
    padding: 14px 14px 12px;
}

.aysa-meta-preview-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.aysa-meta-preview-close {
    border: 0;
    background: transparent;
    font-size: 24px;
    line-height: 1;
    cursor: pointer;
    color: #475569;
}

.aysa-meta-preview-row {
    display: flex;
    gap: 10px;
    align-items: center;
    margin: 6px 0;
    font-size: 12px;
    color: #475569;
}

.aysa-meta-preview-row code {
    background: #f1f5f9;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 2px 8px;
    color: #0f172a;
}

.aysa-meta-preview-field {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    background: #f8fafc;
}

.aysa-meta-preview-field label {
    display: block;
    font-size: 11px;
    color: #475569;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 6px;
    font-weight: 700;
}

.aysa-meta-preview-field p {
    margin: 0;
    font-size: 14px;
    line-height: 1.45;
    color: #0f172a;
}

.aysa-meta-preview-warning {
    margin-top: 10px;
    font-size: 12px;
    color: #92400e;
    background: #fffbeb;
    border: 1px solid #fde68a;
    border-radius: 8px;
    padding: 8px 10px;
}
</style>

<script>
const AYSA_CONTENT_DEBUG = window.AYSA_DEBUG === true;
function aysaContentDebugLog() {
    if (!AYSA_CONTENT_DEBUG) {
        return;
    }
    console.log.apply(console, arguments);
}

if (typeof jQuery !== 'undefined') {
    jQuery(document).ready(function($) {
        initializeContentStrategy();
    });
} else {
    document.addEventListener('DOMContentLoaded', function() {
        initializeContentStrategy();
    });
}

function initializeContentStrategy() {
    const generateStrategyBtn = document.querySelector('.aysa-generate-strategy-btn');
    const planContentBtn = document.querySelector('.aysa-plan-content-btn');
    const associateMissingBtn = document.querySelector('.aysa-associate-missing-btn');
    const resetPlanBtn = document.querySelector('.aysa-reset-plan-btn');
    aysaContentDebugLog('Content Strategy initialized', {
        generateStrategyBtn: !!generateStrategyBtn,
        planContentBtn: !!planContentBtn,
        associateMissingBtn: !!associateMissingBtn,
        resetPlanBtn: !!resetPlanBtn
    });
    
    // Dashboard Tab switching
    document.addEventListener('click', function(e) {
        if (e.target.closest('.aysa-tab-item')) {
            const tabItem = e.target.closest('.aysa-tab-item');
            const tabName = tabItem.getAttribute('data-tab');
            
            // Keep tab state in header, but always render results in dashboard panel/table.
            document.querySelectorAll('.aysa-tab-item').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.aysa-tab-panel').forEach(panel => panel.classList.remove('active'));
            
            tabItem.classList.add('active');
            activatePanelForTab(tabName || 'dashboard');
            filterStrategiesByTab(tabName || 'dashboard');
        }

        const strategyPanel = document.getElementById('aysa-strategy-picker');
        if (
            strategyPanel &&
            !strategyPanel.hidden &&
            !e.target.closest('#aysa-strategy-picker') &&
            !e.target.closest('.aysa-generate-strategy-btn')
        ) {
            strategyPanel.hidden = true;
        }
        
        // Generate Strategy button
        if (e.target.closest('.aysa-generate-strategy-btn')) {
            if (typeof showStrategySelectionModal === 'function') {
                showStrategySelectionModal();
            } else {
                showNotification('Strategy selector is unavailable. Please reload this page.', 'error');
            }
        }

        if (e.target.closest('.aysa-plan-content-btn')) {
            triggerContentPlanning();
        }

        if (e.target.closest('.aysa-associate-missing-btn')) {
            triggerAssociateMissing();
        }

        if (e.target.closest('.aysa-reset-plan-btn')) {
            triggerResetContentPlan();
        }

        if (e.target.closest('#aysa-refactor-titles-btn')) {
            triggerRefactorMissingPageTitles();
        }
        
        // Generate Article button
        if (e.target.closest('.aysa-action-btn.primary')) {
            const row = e.target.closest('tr');
            const titleElement = row.querySelector('.aysa-title-cell strong');
            const title = titleElement ? titleElement.textContent : 'Untitled Article';
            showGenerateArticleModal(title);
        }
        
        // Schedule Auto button
        if (e.target.closest('.aysa-action-btn.secondary')) {
            const row = e.target.closest('tr');
            const titleElement = row.querySelector('.aysa-title-cell strong');
            const title = titleElement ? titleElement.textContent : 'Untitled Article';
            showScheduleAutoModal(title);
        }
    });

    // Initial load
    if (aysaForceEmptyContentStrategyBoot) {
        forceEmptyContentStrategyUi();
    }
    loadResearchOverview();
    loadStoredStrategies();
    loadContentPlanStatus();
    loadContentCalendarData();
    if (window.location.search.indexOf('embedded=1') !== -1) {
        window.setTimeout(applyRequestedStrategyTabFromUrl, 0);
        window.setTimeout(loadContentCalendarData, 250);
    }
    window.setInterval(loadContentPlanStatus, 15000);
    window.setInterval(loadContentCalendarData, 60000);
}

// Global storage for strategies
let allStrategies = [];
let currentTabKey = 'dashboard';
let currentPage = 1;
const pageSize = 10;
let currentSearchTerm = '';
let currentSourceFilter = 'all';
let currentStatusFilter = 'All Statuses';
let currentFilteredStrategies = [];
const aysaForceEmptyContentStrategyBoot = <?php echo wp_json_encode(
    ($aysa_content_strategy_rows === 0 && $aysa_content_meta_rows === 0 && $aysa_content_snapshot_rows === 0)
); ?>;
const aysaTabLabels = {
    'dashboard': 'Content Strategy',
    'content-expansion': 'Missing Pages Plan',
    'publication-calendar': 'Publication Calendar',
    'clusters': 'Clusters',
    'competitor-titles': 'Competitor titles',
    'legacy-content-from-sitemaps': 'Legacy content from sitemaps',
    'intent-layering': 'Intent layering',
    'seasonal-events': 'Seasonal & events',
    'serp-features': 'SERP features',
    'evergreen-fresh': 'Evergreen + fresh',
    'customer-journey': 'Customer journey',
    'local-seo': 'Local SEO',
    'authority-building': 'Authority building',
    'persona-based': 'Persona-based'
};
window.aysaContentStrategyIntegrityState = {
    inconsistent: <?php echo $aysa_materialization_inconsistent ? 'true' : 'false'; ?>,
    appliedRunId: <?php echo intval($aysa_projection_applied_run_id); ?>,
    expectedContentRows: <?php echo intval($aysa_projection_expected_content_rows); ?>,
    expectedCalendarRows: <?php echo intval($aysa_projection_expected_calendar_rows); ?>
};
let calendarViewMode = 'month';
let calendarAnchorDate = new Date();
let calendarEvents = [];
let calendarTodayInfo = null;
const AYSA_UI_LOCALE = 'en-US';
let calendarAutoFocusEnabled = true;
let activeStrategyRunId = 0;
const STRATEGY_RUN_WATCHDOG_MS = 130000;

function activatePanelForTab(tabName) {
    document.querySelectorAll('.aysa-tab-panel').forEach(panel => panel.classList.remove('active'));
    const pageRoot = document.querySelector('.aysa-content-strategy');
    if (pageRoot) {
        pageRoot.classList.remove('is-calendar-active');
    }
    const dashboardPanel = document.getElementById('dashboard-panel');
    if (dashboardPanel) {
        dashboardPanel.classList.add('active');
    }
    if (tabName === 'publication-calendar') {
        if (pageRoot) {
            pageRoot.classList.add('is-calendar-active');
        }
        const calendarPanel = document.getElementById('publication-calendar-panel');
        if (calendarPanel) {
            calendarPanel.classList.add('active');
        }
        calendarAutoFocusEnabled = true;
        loadStoredStrategies(true).finally(() => loadContentCalendarData());
    }
}

function normalizeStrategyTypeKey(value) {
    return String(value || '')
        .toLowerCase()
        .trim()
        .replace(/\s+/g, '_')
        .replace(/-/g, '_');
}

function getTabKeyForStrategyType(strategyType) {
    const key = normalizeStrategyTypeKey(strategyType);
    const map = {
        cluster: 'clusters',
        clusters: 'clusters',
        cluster_based: 'clusters',
        missing_pages: 'content-expansion',
        content_expansion: 'content-expansion',
        missing_page: 'content-expansion',
        cluster_titles: 'clusters',
        competitor: 'competitor-titles',
        competitor_analysis: 'competitor-titles',
        competitor_titles: 'competitor-titles',
        competitor_derived_titles: 'competitor-titles',
        competitor_sitemap: 'legacy-content-from-sitemaps',
        intent: 'intent-layering',
        intent_layering: 'intent-layering',
        seasonal: 'seasonal-events',
        seasonal_event: 'seasonal-events',
        seasonal_events: 'seasonal-events',
        serp: 'serp-features',
        serp_features: 'serp-features',
        evergreen: 'evergreen-fresh',
        evergreen_fresh: 'evergreen-fresh',
        evergreen_fresh_mix: 'evergreen-fresh',
        journey: 'customer-journey',
        customer_journey: 'customer-journey',
        local: 'local-seo',
        local_seo: 'local-seo',
        authority: 'authority-building',
        authority_building: 'authority-building',
        persona: 'persona-based',
        persona_based: 'persona-based'
    };
    return map[key] || null;
}

function getStrategiesForTab(tabKey) {
    const rows = Array.isArray(allStrategies) ? allStrategies : [];
    if (!tabKey || tabKey === 'dashboard' || tabKey === 'publication-calendar') {
        return rows;
    }
    return rows.filter((item) => {
        const raw = item.strategy_type || item.strategyType || '';
        const mappedTab = getTabKeyForStrategyType(raw);
        return mappedTab === tabKey;
    });
}

function getStrategySourceKey(strategyType) {
    const mappedTab = getTabKeyForStrategyType(strategyType);
    return mappedTab || normalizeStrategyTypeKey(strategyType);
}

function getStrategyTypeLabel(strategyType) {
    const key = normalizeStrategyTypeKey(strategyType);
    const labels = {
        missing_pages: 'Missing pages plan',
        content_expansion: 'Missing pages plan',
        cluster_based: 'Cluster-based',
        cluster_titles: 'Cluster-based',
        competitor_analysis: 'Competitor analysis',
        competitor_titles: 'Competitor analysis',
        competitor_derived_titles: 'Competitor analysis',
        competitor_sitemap: 'Legacy content from sitemaps',
        intent_layering: 'Intent layering',
        seasonal_event: 'Seasonal and events',
        seasonal_events: 'Seasonal and events',
        serp_features: 'SERP features',
        evergreen_fresh: 'Evergreen and fresh',
        evergreen_fresh_mix: 'Evergreen and fresh',
        customer_journey: 'Customer journey',
        local_seo: 'Local SEO',
        authority_building: 'Authority building',
        persona_based: 'Persona-based'
    };

    return labels[key] || String(strategyType || 'Uncategorized')
        .replace(/[_-]+/g, ' ')
        .replace(/\b\w/g, (char) => char.toUpperCase());
}

function getStrategyStatusLabel(rawStatus, rawAutomationStatus) {
    const normalized = String(rawAutomationStatus || rawStatus || '').toLowerCase().trim();
    const labels = {
        proposed: 'Proposed',
        queued: 'Queued',
        processing: 'Generating',
        retry: 'Retry needed',
        generated: 'Generated',
        published: 'Published',
        scheduled: 'Scheduled',
        blocked_no_association: 'Blocked: no association',
        blocked: 'Blocked',
        failed: 'Failed'
    };

    return labels[normalized] || String(rawAutomationStatus || rawStatus || 'Unknown')
        .replace(/[_-]+/g, ' ')
        .replace(/\b\w/g, (char) => char.toUpperCase());
}

function renderDashboardTable(pageData, titleLabel, totalFilteredCount) {
    const tbody = document.querySelector('.aysa-proposals-table tbody');
    if (tbody) {
        tbody.innerHTML = '';
        if (pageData.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; padding: 20px;">No strategy items are available for this view yet.</td></tr>';
        } else {
            addTitlesToTable(pageData, 'stored');
        }
    }

    const proposalsTitle = document.querySelector('#aysa-proposals-title');
    if (proposalsTitle) {
        proposalsTitle.textContent = `${titleLabel} (${totalFilteredCount})`;
    }
}

function renderStrategyPanel(tabKey, filteredData) {
    const panel = document.getElementById(tabKey + '-panel');
    if (!panel) {
        return;
    }

    const panelBody = panel.querySelector('.aysa-panel');
    if (!panelBody) {
        return;
    }

    let container = panel.querySelector('.aysa-strategy-results');
    if (!container) {
        container = document.createElement('div');
        container.className = 'aysa-strategy-results';
        panelBody.appendChild(container);
    }

    if (!filteredData.length) {
        container.innerHTML = '<div style="margin-top:16px;padding:16px;border:1px dashed #CBD5E1;border-radius:10px;color:#475569;">No saved results for this tab yet.</div>';
        return;
    }

    const rows = filteredData.slice(0, 50).map((item) => {
        const title = item.title || item.Title || '-';
        const intent = item.intent || item.Intent || '-';
        const status = getStrategyStatusLabel(item.status || 'proposed', item.automation_status || '');
        const keywords = Array.isArray(item.targetKeywords || item.TargetKeywords || item.target_keywords)
            ? (item.targetKeywords || item.TargetKeywords || item.target_keywords).slice(0, 4).join(', ')
            : '-';
        return `
            <tr>
                <td style="padding:10px;border-bottom:1px solid #E5E7EB;"><strong>${escapeHtml(title)}</strong></td>
                <td style="padding:10px;border-bottom:1px solid #E5E7EB;">${escapeHtml(String(keywords || '-'))}</td>
                <td style="padding:10px;border-bottom:1px solid #E5E7EB;">${escapeHtml(String(intent))}</td>
                <td style="padding:10px;border-bottom:1px solid #E5E7EB;">${escapeHtml(String(status))}</td>
            </tr>
        `;
    }).join('');

    container.innerHTML = `
        <div style="margin-top:16px;background:#fff;border:1px solid #E5E7EB;border-radius:10px;overflow:hidden;">
            <table style="width:100%;border-collapse:collapse;">
                <thead>
                    <tr style="background:#F8FAFC;">
                        <th style="text-align:left;padding:10px;font-size:12px;text-transform:uppercase;color:#475569;">Title</th>
                        <th style="text-align:left;padding:10px;font-size:12px;text-transform:uppercase;color:#475569;">Keywords</th>
                        <th style="text-align:left;padding:10px;font-size:12px;text-transform:uppercase;color:#475569;">Intent</th>
                        <th style="text-align:left;padding:10px;font-size:12px;text-transform:uppercase;color:#475569;">Status</th>
                    </tr>
                </thead>
                <tbody>${rows}</tbody>
            </table>
        </div>
    `;
}

function applyTabData(tabKey) {
    currentTabKey = tabKey || 'dashboard';
    const label = aysaTabLabels[currentTabKey] || 'Content Strategy';
    const countHeader = document.querySelector('.aysa-dashboard-header h2');
    if (countHeader) {
        countHeader.textContent = label;
    }
    refreshCurrentView();
}

// Filter strategies based on active tab
function filterStrategiesByTab(tabKey) {
    aysaContentDebugLog('[AYSA] Filtering by dashboard tab:', tabKey);
    currentPage = 1;
    applyTabData(tabKey);
}

function applyClientFilters(baseRows) {
    return baseRows.filter((row) => {
        const rowTitle = String(row.title || row.Title || '').toLowerCase();
        const rowKeywords = (Array.isArray(row.targetKeywords || row.TargetKeywords || row.target_keywords)
            ? (row.targetKeywords || row.TargetKeywords || row.target_keywords).join(' ')
            : String(row.targetKeywords || row.TargetKeywords || row.target_keywords || '')
        ).toLowerCase();
        const rowStatusRaw = String(row.status || '').toLowerCase();
        const rowAutomationStatus = String(row.automation_status || '').toLowerCase();
        const rowStatus = rowAutomationStatus === 'blocked_no_association'
            ? 'blocked'
            : (rowStatusRaw === 'proposed' ? 'draft' : rowStatusRaw);
        const rowSource = getStrategySourceKey(row.strategy_type || row.strategyType || '');

        if (currentSearchTerm && !(rowTitle.includes(currentSearchTerm) || rowKeywords.includes(currentSearchTerm))) {
            return false;
        }
        if (currentSourceFilter !== 'all' && rowSource !== String(currentSourceFilter || '').toLowerCase()) {
            return false;
        }
        if (currentStatusFilter !== 'All Statuses' && rowStatus !== currentStatusFilter.toLowerCase()) {
            return false;
        }
        return true;
    });
}

function renderPagination(totalCount) {
    const info = document.querySelector('#aysa-pagination-info');
    const controls = document.querySelector('#aysa-pagination-controls');
    if (!info || !controls) {
        return;
    }

    if (!totalCount) {
        info.textContent = 'Showing 0-0 of 0 results';
        controls.innerHTML = '';
        return;
    }

    const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
    if (currentPage > totalPages) {
        currentPage = totalPages;
    }
    const start = (currentPage - 1) * pageSize + 1;
    const end = Math.min(totalCount, currentPage * pageSize);
    info.textContent = `Showing ${start}-${end} of ${totalCount} results`;

    const buttons = [];
    buttons.push(`<button class="aysa-pagination-btn" data-page="${Math.max(1, currentPage - 1)}" ${currentPage === 1 ? 'disabled' : ''}>‹</button>`);

    const windowStart = Math.max(1, currentPage - 2);
    const windowEnd = Math.min(totalPages, currentPage + 2);
    if (windowStart > 1) {
        buttons.push('<button class="aysa-pagination-btn" data-page="1">1</button>');
        if (windowStart > 2) {
            buttons.push('<span class="aysa-pagination-dots">...</span>');
        }
    }
    for (let p = windowStart; p <= windowEnd; p++) {
        buttons.push(`<button class="aysa-pagination-btn ${p === currentPage ? 'active' : ''}" data-page="${p}">${p}</button>`);
    }
    if (windowEnd < totalPages) {
        if (windowEnd < totalPages - 1) {
            buttons.push('<span class="aysa-pagination-dots">...</span>');
        }
        buttons.push(`<button class="aysa-pagination-btn" data-page="${totalPages}">${totalPages}</button>`);
    }

    buttons.push(`<button class="aysa-pagination-btn" data-page="${Math.min(totalPages, currentPage + 1)}" ${currentPage === totalPages ? 'disabled' : ''}>›</button>`);
    controls.innerHTML = buttons.join('');
}

function refreshCurrentView() {
    if (currentTabKey === 'publication-calendar') {
        renderPublicationCalendar();
        return;
    }
    const baseRows = getStrategiesForTab(currentTabKey);
    currentFilteredStrategies = applyClientFilters(baseRows);
    const totalFilteredCount = currentFilteredStrategies.length;
    const pageStart = (currentPage - 1) * pageSize;
    const pageRows = currentFilteredStrategies.slice(pageStart, pageStart + pageSize);
    const label = aysaTabLabels[currentTabKey] || 'Content Strategy';
    renderDashboardTable(pageRows, `${label} proposals`, totalFilteredCount);
    renderPagination(totalFilteredCount);
    updateSummaryCards(totalFilteredCount);
}

function forceEmptyContentStrategyUi() {
    allStrategies = [];
    calendarEvents = [];
    calendarTodayInfo = null;
    currentFilteredStrategies = [];
    currentPage = 1;
    const tbody = document.querySelector('.aysa-proposals-table tbody');
    if (tbody) {
        tbody.innerHTML = '<tr><td colspan="8" style="text-align:center; padding: 20px;">No strategy items are available for this view yet.</td></tr>';
    }
    renderPagination(0);
    updateSummaryCards(0);
    const proposalsTitle = document.querySelector('#aysa-proposals-title');
    if (proposalsTitle) {
        proposalsTitle.textContent = 'All Proposals (0)';
    }
    const statusNode = document.getElementById('aysa-plan-status');
    if (statusNode) {
        if (window.aysaContentStrategyIntegrityState && window.aysaContentStrategyIntegrityState.inconsistent) {
            statusNode.textContent = 'Content plan status: projection not materialized yet';
        } else {
            statusNode.textContent = 'Content plan status: not started';
        }
    }
}

function setActiveDashboardTab(tabKey) {
    const key = String(tabKey || '').trim();
    if (!key) {
        return false;
    }
    const tabs = Array.from(document.querySelectorAll('.aysa-dashboard-tabs .aysa-tab-item'));
    const target = tabs.find((node) => String(node.getAttribute('data-tab') || '') === key);
    if (!target) {
        return false;
    }
    tabs.forEach((node) => node.classList.remove('active'));
    document.querySelectorAll('.aysa-tab-panel').forEach((panel) => panel.classList.remove('active'));
    target.classList.add('active');
    activatePanelForTab(key);
    filterStrategiesByTab(key);
    return true;
}

function syncStrategyTabInUrl(tabKey) {
    try {
        const url = new URL(window.location.href);
        if (!tabKey || tabKey === 'dashboard') {
            url.searchParams.delete('strategy_tab');
        } else {
            url.searchParams.set('strategy_tab', tabKey);
        }
        window.history.replaceState({}, '', url.toString());
    } catch (error) {
        // noop
    }
}

// Function to load stored strategies from DB
async function loadStoredStrategies(returnOnly = false) {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    
    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_strategies',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: projectId
            })
        });
        
        const result = await response.json();
        if (result.success) {
            aysaContentDebugLog('[AYSA] Loaded stored strategies:', result.data.length);
            
            // Update global store
            allStrategies = Array.isArray(result.data) ? result.data : [];

            if (!allStrategies.length) {
                forceEmptyContentStrategyUi();
            }
            
            if (returnOnly) {
                return allStrategies;
            }
            
            const activeTab = document.querySelector('.aysa-dashboard-tabs .aysa-tab-item.active');
            const activeTabKey = activeTab ? activeTab.getAttribute('data-tab') : 'dashboard';
            filterStrategiesByTab(activeTabKey);
            updateSummaryCards();
            
            return allStrategies;
        }
        return [];
    } catch (error) {
        aysaContentDebugLog('[AYSA] Failed loading strategies:', error);
        return [];
    }
}

async function loadContentCalendarData() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    if (!projectId) {
        return;
    }

    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_content_calendar',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId)
            })
        });
        const result = await response.json();
        if (!result.success || !result.data) {
            // Fallback to local strategy data if calendar endpoint fails.
            calendarEvents = buildFallbackCalendarEventsFromStrategies(allStrategies || []);
            calendarTodayInfo = buildTodaySummaryFromEvents(calendarEvents);
            renderPublicationCalendar();
            return;
        }
        calendarEvents = normalizeCalendarEvents(Array.isArray(result.data.events) ? result.data.events : []);
        if (!calendarEvents.length) {
            calendarEvents = buildFallbackCalendarEventsFromStrategies(allStrategies || []);
        }
        calendarTodayInfo = result.data.today || null;
        if (!calendarTodayInfo) {
            calendarTodayInfo = buildTodaySummaryFromEvents(calendarEvents);
        }
        if (calendarAutoFocusEnabled && calendarViewMode === 'month' && calendarEvents.length && !monthHasEvents(calendarAnchorDate, calendarEvents)) {
            calendarAnchorDate = getPreferredCalendarAnchorDate(calendarEvents, calendarAnchorDate);
            calendarAutoFocusEnabled = false;
        }
        renderPublicationCalendar();
    } catch (error) {
        aysaContentDebugLog('[AYSA] Failed loading content calendar:', error);
        calendarEvents = buildFallbackCalendarEventsFromStrategies(allStrategies || []);
        calendarTodayInfo = buildTodaySummaryFromEvents(calendarEvents);
        if (calendarAutoFocusEnabled && calendarViewMode === 'month' && calendarEvents.length && !monthHasEvents(calendarAnchorDate, calendarEvents)) {
            calendarAnchorDate = getPreferredCalendarAnchorDate(calendarEvents, calendarAnchorDate);
            calendarAutoFocusEnabled = false;
        }
        renderPublicationCalendar();
    }
}

function parseDateToTimestamp(value) {
    if (value === null || value === undefined) {
        return NaN;
    }
    if (typeof value === 'number' && Number.isFinite(value)) {
        return value > 1e12 ? value : value * 1000;
    }
    const raw = String(value).trim();
    if (!raw) {
        return NaN;
    }
    if (/^\d+$/.test(raw)) {
        const n = Number(raw);
        return Number.isFinite(n) ? (n > 1e12 ? n : n * 1000) : NaN;
    }
    let ts = new Date(raw).getTime();
    if (Number.isNaN(ts)) {
        const normalized = raw.replace(' ', 'T');
        ts = new Date(normalized).getTime();
    }
    return ts;
}

function normalizeCalendarContentType(rawType, strategyType) {
    const st = String(strategyType || '').toLowerCase();
    const ct = String(rawType || '').toLowerCase().trim();
    if (ct === 'product_page' || ct === 'product') return 'product_page';
    if (ct === 'category_page' || ct === 'category') return 'category_page';
    if (ct === 'landing_page' || ct === 'landing') return 'landing_page';
    if (ct === 'post') return 'post';
    return st === 'missing_pages' ? 'landing_page' : 'post';
}

function calendarContentTypeBadgeLabel(contentType) {
    const ct = normalizeCalendarContentType(contentType, '');
    if (ct === 'product_page') return 'PRODUCT';
    if (ct === 'category_page') return 'CATEGORY';
    if (ct === 'landing_page') return 'LANDING';
    return 'POST';
}

function calendarContentTypeBadgeClass(contentType) {
    const ct = normalizeCalendarContentType(contentType, '');
    if (ct === 'product_page') return 'type-product';
    if (ct === 'category_page') return 'type-category';
    if (ct === 'landing_page') return 'type-landing';
    return 'type-post';
}

function calendarMissingVariantClass(event) {
    const st = String((event && event.strategy_type) || '').toLowerCase();
    if (st !== 'missing_pages') {
        return '';
    }
    const ct = normalizeCalendarContentType(event && event.content_type, st);
    if (ct === 'product_page') return 'is-missing-product';
    if (ct === 'category_page') return 'is-missing-category';
    return 'is-missing-landing';
}

function normalizeCalendarEvents(events) {
    const list = Array.isArray(events) ? events : [];
    return list
        .map((event, idx) => {
            const ts = parseDateToTimestamp(event.timestamp || event.datetime || event.scheduled_for || event.scheduled_for_local);
            if (Number.isNaN(ts)) {
                return null;
            }
            return {
                ...event,
                id: event.id || `event-${idx}`,
                timestamp: ts,
                datetime: new Date(ts).toISOString(),
                type: String(event.type || '').toLowerCase() === 'published' ? 'published' : 'scheduled',
                strategy_type: String(event.strategy_type || event.strategyType || 'unknown'),
                content_type: normalizeCalendarContentType(event.content_type || event.contentType || '', event.strategy_type || event.strategyType || '')
            };
        })
        .filter(Boolean)
        .sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0));
}

function buildFallbackCalendarEventsFromStrategies(strategies) {
    const list = Array.isArray(strategies) ? strategies : [];
    const events = [];
    list.forEach((row) => {
        const ts = parseDateToTimestamp(row.scheduled_for_local || row.scheduled_for || '');
        if (Number.isNaN(ts)) {
            return;
        }
        const automationStatus = String(row.automation_status || '').toLowerCase();
        const status = String(row.status || '').toLowerCase();
        const type = (status === 'generated' || automationStatus === 'generated') ? 'published' : 'scheduled';
        const postId = row.post_id ? Number(row.post_id) : 0;
        events.push({
            id: `fallback-${row.id || Math.random().toString(36).slice(2)}`,
            strategy_id: row.id || null,
            title: row.title || row.Title || 'Untitled',
            type,
            strategy_type: row.strategy_type || row.strategyType || 'unknown',
            content_type: normalizeCalendarContentType(row.content_type || row.contentType || '', row.strategy_type || row.strategyType || ''),
            intent: row.intent || row.Intent || '-',
            status: automationStatus || status || 'scheduled',
            datetime: new Date(ts).toISOString(),
            timestamp: ts,
            post_id: postId || null,
            edit_url: postId ? `post.php?post=${encodeURIComponent(postId)}&action=edit` : '',
            public_url: ''
        });
    });
    return events.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0));
}

function buildTodaySummaryFromEvents(events) {
    const now = new Date();
    const start = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
    const end = start + (24 * 60 * 60 * 1000);
    const list = (Array.isArray(events) ? events : []).filter((e) => {
        const ts = Number(e.timestamp || 0);
        return ts >= start && ts < end;
    });
    const scheduledItems = list.filter((e) => e.type !== 'published').map((e) => ({
        title: e.title || '-',
        time: new Date(e.timestamp).toLocaleTimeString(AYSA_UI_LOCALE, { hour: '2-digit', minute: '2-digit' }),
        strategy_id: e.strategy_id || 0,
        post_id: e.post_id || 0
    }));
    const publishedItems = list.filter((e) => e.type === 'published').map((e) => ({
        title: e.title || '-',
        time: new Date(e.timestamp).toLocaleTimeString(AYSA_UI_LOCALE, { hour: '2-digit', minute: '2-digit' }),
        post_id: e.post_id || 0
    }));
    return {
        date: normalizeDateOnly(now),
        scheduled_count: scheduledItems.length,
        published_count: publishedItems.length,
        scheduled_items: scheduledItems.slice(0, 20),
        published_items: publishedItems.slice(0, 20)
    };
}

function getPreferredCalendarAnchorDate(events, currentAnchor) {
    const list = Array.isArray(events) ? events : [];
    if (!list.length) {
        return currentAnchor instanceof Date ? currentAnchor : new Date();
    }
    const now = Date.now();
    const sorted = [...list].sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0));
    const upcoming = sorted.find((e) => Number(e.timestamp || 0) >= now);
    const candidate = upcoming || sorted[0];
    const next = new Date(Number(candidate.timestamp || now));
    if (Number.isNaN(next.getTime())) {
        return currentAnchor instanceof Date ? currentAnchor : new Date();
    }
    return next;
}

function monthHasEvents(anchorDate, events) {
    const list = Array.isArray(events) ? events : [];
    const y = anchorDate.getFullYear();
    const m = anchorDate.getMonth();
    return list.some((event) => {
        const d = new Date(Number(event.timestamp || 0));
        return !Number.isNaN(d.getTime()) && d.getFullYear() === y && d.getMonth() === m;
    });
}

function normalizeDateOnly(value) {
    const d = new Date(value);
    if (Number.isNaN(d.getTime())) {
        return '';
    }
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

function getEventsForDate(dateObj) {
    const key = normalizeDateOnly(dateObj);
    return (calendarEvents || []).filter((event) => normalizeDateOnly(event.timestamp || event.datetime) === key);
}

function renderPublicationCalendar() {
    const grid = document.getElementById('aysa-publication-calendar-grid');
    const titleNode = document.getElementById('aysa-calendar-title');
    const summaryNode = document.getElementById('aysa-calendar-summary');
    if (!grid || !titleNode || !summaryNode) {
        return;
    }
    if (calendarAutoFocusEnabled && calendarViewMode === 'month' && calendarEvents.length && !monthHasEvents(calendarAnchorDate, calendarEvents)) {
        calendarAnchorDate = getPreferredCalendarAnchorDate(calendarEvents, calendarAnchorDate);
        calendarAutoFocusEnabled = false;
    }

    const today = calendarTodayInfo || {};
    const scheduledCount = Number(today.scheduled_count || 0);
    const publishedCount = Number(today.published_count || 0);
    const items = Array.isArray(today.scheduled_items) ? today.scheduled_items.slice(0, 3) : [];
    const sample = items.map((i) => `${i.time} ${i.title}`).join(' | ');
    summaryNode.textContent = scheduledCount > 0
        ? `Today: ${scheduledCount} scheduled publication(s). Already published: ${publishedCount}. ${sample}`
        : `Today: no scheduled publications. Already published: ${publishedCount}.`;

    if (calendarViewMode === 'day') {
        titleNode.textContent = calendarAnchorDate.toLocaleDateString(AYSA_UI_LOCALE, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
        renderDayList(grid, calendarAnchorDate);
        return;
    }
    if (calendarViewMode === 'week') {
        const monday = new Date(calendarAnchorDate);
        const day = monday.getDay();
        monday.setDate(monday.getDate() - ((day + 6) % 7));
        const sunday = new Date(monday);
        sunday.setDate(sunday.getDate() + 6);
        titleNode.textContent = `${monday.toLocaleDateString(AYSA_UI_LOCALE)} - ${sunday.toLocaleDateString(AYSA_UI_LOCALE)}`;
        renderWeekList(grid, monday);
        return;
    }

    titleNode.textContent = calendarAnchorDate.toLocaleDateString(AYSA_UI_LOCALE, { year: 'numeric', month: 'long' });
    renderMonthGrid(grid, calendarAnchorDate);
}

function renderMonthGrid(container, anchorDate) {
    const year = anchorDate.getFullYear();
    const month = anchorDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const start = new Date(firstDay);
    start.setDate(firstDay.getDate() - firstDay.getDay());
    const todayKey = normalizeDateOnly(new Date());
    const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    let html = '<div class="aysa-cal-head">' + dayNames.map((d) => `<div class="aysa-cal-head-item">${d}</div>`).join('') + '</div>';
    html += '<div class="aysa-cal-month">';
    for (let i = 0; i < 42; i++) {
        const cellDate = new Date(start);
        cellDate.setDate(start.getDate() + i);
        const sameMonth = cellDate.getMonth() === month;
        const key = normalizeDateOnly(cellDate);
        const isToday = key === todayKey;
        const dayEvents = getEventsForDate(cellDate);
        const publishedCount = dayEvents.filter((event) => String(event.type || '').toLowerCase() === 'published').length;
        const scheduledCount = dayEvents.length - publishedCount;
        const prioritizedEvents = [...dayEvents].sort((a, b) => {
            const aPublishedFirst = String(a.type || '').toLowerCase() === 'published' ? 0 : 1;
            const bPublishedFirst = String(b.type || '').toLowerCase() === 'published' ? 0 : 1;
            if (aPublishedFirst !== bPublishedFirst) {
                return aPublishedFirst - bPublishedFirst;
            }
            return Number(b.timestamp || 0) - Number(a.timestamp || 0);
        });
        const events = prioritizedEvents.slice(0, 3);
        const hiddenCount = Math.max(0, dayEvents.length - events.length);
        html += `<div class="aysa-cal-day ${sameMonth ? '' : 'is-outside'}" data-date="${key}" style="${isToday ? 'outline:2px solid #2563EB;' : ''}">
            <div class="aysa-cal-daynum">${cellDate.getDate()}</div>
            ${events.map((event) => {
                const eventClass = event.type === 'published' ? 'is-published' : 'is-scheduled';
                const missingVariantClass = calendarMissingVariantClass(event);
                const contentType = normalizeCalendarContentType(event.content_type || '', event.strategy_type || '');
                const typeLabel = calendarContentTypeBadgeLabel(contentType);
                const typeClass = calendarContentTypeBadgeClass(contentType);
                const href = event.public_url || event.edit_url || '#';
                return `<a class="aysa-cal-event ${eventClass} ${missingVariantClass} ${typeClass}" href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer" title="${escapeHtml(event.title || '')}"><span class="aysa-cal-event-title">${escapeHtml(event.title || '-')}</span><span class="aysa-cal-type-badge ${typeClass}">${escapeHtml(typeLabel)}</span></a>`;
            }).join('')}
            ${(publishedCount > 0 || scheduledCount > 0) ? `<div style="font-size:10px;color:#334155;padding:2px 6px;">P:${publishedCount} | S:${scheduledCount}</div>` : ''}
            ${hiddenCount > 0 ? `<button type="button" class="aysa-cal-more-btn" data-date="${key}">+${hiddenCount} more (view all)</button>` : ''}
        </div>`;
    }
    html += '</div>';
    container.innerHTML = html;
}

function renderWeekList(container, monday) {
    let html = '<div class="aysa-cal-list">';
    for (let i = 0; i < 7; i++) {
        const day = new Date(monday);
        day.setDate(monday.getDate() + i);
        const events = getEventsForDate(day);
        if (!events.length) {
            continue;
        }
        events.sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0));
        events.forEach((event) => {
            const dateText = day.toLocaleDateString(AYSA_UI_LOCALE, { weekday: 'short', day: '2-digit', month: '2-digit' });
            const timeText = new Date(event.datetime).toLocaleTimeString(AYSA_UI_LOCALE, { hour: '2-digit', minute: '2-digit' });
            const badge = event.type === 'published' ? 'published' : 'scheduled';
            const missingVariantClass = calendarMissingVariantClass(event);
            const contentType = normalizeCalendarContentType(event.content_type || '', event.strategy_type || '');
            const typeLabel = calendarContentTypeBadgeLabel(contentType);
            const typeClass = calendarContentTypeBadgeClass(contentType);
            const href = event.public_url || event.edit_url || '#';
            html += `<div class="aysa-cal-list-item ${missingVariantClass} ${typeClass}">
                <div>${dateText}</div>
                <div>${timeText}</div>
                <div><a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(event.title || '-')}</a></div>
                <div><span class="aysa-cal-badge ${badge}">${badge}</span><span class="aysa-cal-type-badge ${typeClass}">${escapeHtml(typeLabel)}</span></div>
            </div>`;
        });
    }
    html += '</div>';
    container.innerHTML = html === '<div class="aysa-cal-list"></div>' ? '<div class="aysa-calendar-summary">No events this week.</div>' : html;
}

function renderDayList(container, dayDate) {
    const events = getEventsForDate(dayDate).sort((a, b) => Number(a.timestamp || 0) - Number(b.timestamp || 0));
    if (!events.length) {
        container.innerHTML = '<div class="aysa-calendar-summary">No publications on this day.</div>';
        return;
    }
    let html = '<div class="aysa-cal-list">';
    events.forEach((event) => {
        const timeText = new Date(event.datetime).toLocaleTimeString(AYSA_UI_LOCALE, { hour: '2-digit', minute: '2-digit' });
        const badge = event.type === 'published' ? 'published' : 'scheduled';
        const missingVariantClass = calendarMissingVariantClass(event);
        const contentType = normalizeCalendarContentType(event.content_type || '', event.strategy_type || '');
        const typeLabel = calendarContentTypeBadgeLabel(contentType);
        const typeClass = calendarContentTypeBadgeClass(contentType);
        const href = event.public_url || event.edit_url || '#';
        html += `<div class="aysa-cal-list-item ${missingVariantClass} ${typeClass}">
            <div>${timeText}</div>
            <div>${escapeHtml(event.strategy_type || '-')}</div>
            <div><a href="${escapeHtml(href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(event.title || '-')}</a></div>
            <div><span class="aysa-cal-badge ${badge}">${badge}</span><span class="aysa-cal-type-badge ${typeClass}">${escapeHtml(typeLabel)}</span></div>
        </div>`;
    });
    html += '</div>';
    container.innerHTML = html;
}

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

// Search functionality
document.addEventListener('input', function(e) {
    if (e.target.closest('.aysa-search-box input')) {
        currentSearchTerm = String(e.target.value || '').toLowerCase().trim();
        currentPage = 1;
        refreshCurrentView();
    }
});

document.addEventListener('click', function(e) {
    const tabItem = e.target.closest('.aysa-dashboard-tabs .aysa-tab-item');
    if (!tabItem) {
        return;
    }

    const tabName = tabItem.getAttribute('data-tab') || 'dashboard';
    activatePanelForTab(tabName);
    filterStrategiesByTab(tabName);
    syncStrategyTabInUrl(tabName);
});

// Filter functionality
document.addEventListener('change', function(e) {
    if (e.target.closest('.aysa-filter-select')) {
        const selects = document.querySelectorAll('.aysa-filter-select');
        currentSourceFilter = selects[0] ? String(selects[0].value || 'all').toLowerCase() : 'all';
        currentStatusFilter = selects[1] ? selects[1].value : 'All Statuses';
        currentPage = 1;
        refreshCurrentView();
    }
});

function applyRequestedStrategyTabFromUrl() {
    try {
        const url = new URL(window.location.href);
        const requestedTab = String(url.searchParams.get('strategy_tab') || '').trim();
        if (requestedTab) {
            setActiveDashboardTab(requestedTab);
        }

        const embedded = String(url.searchParams.get('embedded') || '').trim() === '1';
        if (embedded) {
            const root = document.querySelector('.aysa-content-strategy');
            if (root) {
                root.classList.add('is-embedded-calendar');
            }
            document.body.classList.add('aysa-embedded-calendar-page');
            document.documentElement.classList.add('aysa-embedded-calendar-page');
            setActiveDashboardTab('publication-calendar');
        }
    } catch (error) {
        // noop
    }
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', applyRequestedStrategyTabFromUrl);
} else {
    applyRequestedStrategyTabFromUrl();
}

document.addEventListener('click', function(e) {
    const viewBtn = e.target.closest('.aysa-calendar-view-btn');
    if (viewBtn) {
        document.querySelectorAll('.aysa-calendar-view-btn').forEach((btn) => btn.classList.remove('active'));
        viewBtn.classList.add('active');
        calendarViewMode = viewBtn.getAttribute('data-view') || 'month';
        renderPublicationCalendar();
        return;
    }

    const navBtn = e.target.closest('.aysa-calendar-nav-btn');
    if (navBtn) {
        const nav = Number(navBtn.getAttribute('data-nav') || 0);
        if (nav === 0) {
            calendarAnchorDate = new Date();
            calendarAutoFocusEnabled = true;
        } else if (calendarViewMode === 'month') {
            calendarAnchorDate = new Date(calendarAnchorDate.getFullYear(), calendarAnchorDate.getMonth() + nav, 1);
            calendarAutoFocusEnabled = false;
        } else if (calendarViewMode === 'week') {
            calendarAnchorDate = new Date(calendarAnchorDate.getFullYear(), calendarAnchorDate.getMonth(), calendarAnchorDate.getDate() + (nav * 7));
            calendarAutoFocusEnabled = false;
        } else {
            calendarAnchorDate = new Date(calendarAnchorDate.getFullYear(), calendarAnchorDate.getMonth(), calendarAnchorDate.getDate() + nav);
            calendarAutoFocusEnabled = false;
        }
        renderPublicationCalendar();
        return;
    }

    const moreBtn = e.target.closest('.aysa-cal-more-btn');
    if (moreBtn) {
        const key = String(moreBtn.getAttribute('data-date') || '').trim();
        if (key) {
            const target = new Date(`${key}T12:00:00`);
            if (!Number.isNaN(target.getTime())) {
                calendarAnchorDate = target;
                calendarViewMode = 'day';
                calendarAutoFocusEnabled = false;
                document.querySelectorAll('.aysa-calendar-view-btn').forEach((btn) => btn.classList.remove('active'));
                const dayBtn = document.querySelector('.aysa-calendar-view-btn[data-view="day"]');
                if (dayBtn) {
                    dayBtn.classList.add('active');
                }
                renderPublicationCalendar();
            }
        }
        return;
    }

    const pageBtn = e.target.closest('.aysa-pagination-btn[data-page]');
    if (!pageBtn) {
        return;
    }
    if (pageBtn.hasAttribute('disabled')) {
        return;
    }
    const requestedPage = parseInt(pageBtn.getAttribute('data-page'), 10);
    if (!Number.isNaN(requestedPage) && requestedPage > 0) {
        currentPage = requestedPage;
        refreshCurrentView();
    }
});

// Modal functions
function showGenerateStrategyModal() {
    aysaContentDebugLog('Creating Generate Strategy Modal');
    const modalHTML = `
        <div class="aysa-modal-overlay">
            <div class="aysa-modal aysa-modal-schedule">
                <div class="aysa-modal-header">
                    <h3>Schedule and Generate Automatically</h3>
                    <button class="aysa-modal-close">&times;</button>
                </div>
                <div class="aysa-modal-content">
                    <div class="aysa-form-group">
                        <label>Date and Time</label>
                        <div class="aysa-input-group">
                            <div class="aysa-input-with-icon">
                                <input type="text" class="aysa-input" placeholder="mm/dd/yyyy" />
                                <svg class="aysa-input-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                                </svg>
                            </div>
                            <div class="aysa-input-with-icon">
                                <input type="text" class="aysa-input" placeholder="--:--" />
                                <svg class="aysa-input-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                        </div>
                    </div>
                    <div class="aysa-form-group">
                        <label>Category</label>
                        <select class="aysa-select aysa-category-select">
                            <option value="SEO" selected>SEO</option>
                            <option value="Content Marketing">Content Marketing</option>
                            <option value="Technical SEO">Technical SEO</option>
                        </select>
                    </div>
                    <div class="aysa-form-group">
                        <label>Author</label>
                        <select class="aysa-select aysa-author-select">
                            <option value="Admin" selected>Admin</option>
                            <option value="Writer 1">Writer 1</option>
                            <option value="Writer 2">Writer 2</option>
                        </select>
                    </div>
                    <div class="aysa-checkbox-group">
                        <label>
                            <input type="checkbox" />
                            Publish automatically after generation
                        </label>
                    </div>
                    <div class="aysa-modal-actions">
                        <button class="aysa-btn aysa-btn-primary">Schedule</button>
                        <button class="aysa-btn aysa-btn-secondary aysa-modal-close">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const modal = document.createElement('div');
    modal.innerHTML = modalHTML;
    const modalElement = modal.firstElementChild;
    
    document.body.appendChild(modalElement);
    
    // Close modal handlers
    modalElement.querySelector('.aysa-modal-close').addEventListener('click', function() {
        modalElement.remove();
    });
    
    modalElement.addEventListener('click', function(e) {
        if (e.target === modalElement) {
            modalElement.remove();
        }
    });
}

function showGenerateArticleModal(title) {
    aysaContentDebugLog('Creating Generate Article Modal for:', title);
    const modalHTML = `
        <div class="aysa-modal-overlay">
            <div class="aysa-modal aysa-modal-generate">
                <div class="aysa-modal-header">
                    <h3>Generate Article</h3>
                    <button class="aysa-modal-close">&times;</button>
                </div>
                <div class="aysa-modal-content">
                    <div class="aysa-form-group">
                        <label>Article Type</label>
                        <select class="aysa-select aysa-article-type-select">
                            <option value="Complete Guide" selected>Complete Guide</option>
                            <option value="How-to Guide">How-to Guide</option>
                            <option value="List Article">List Article</option>
                            <option value="Tutorial">Tutorial</option>
                        </select>
                    </div>
                    <div class="aysa-form-group">
                        <label>Category</label>
                        <select class="aysa-select aysa-category-select">
                            <option value="SEO" selected>SEO</option>
                            <option value="Content Marketing">Content Marketing</option>
                            <option value="Technical SEO">Technical SEO</option>
                        </select>
                    </div>
                    <div class="aysa-form-group">
                        <label>Author</label>
                        <select class="aysa-select aysa-author-select">
                            <option value="Admin" selected>Admin</option>
                            <option value="Writer 1">Writer 1</option>
                            <option value="Writer 2">Writer 2</option>
                        </select>
                    </div>
                    <div class="aysa-form-group">
                        <label>Tone</label>
                        <select class="aysa-select aysa-tone-select">
                            <option value="Professional" selected>Professional</option>
                            <option value="Casual">Casual</option>
                            <option value="Technical">Technical</option>
                            <option value="Friendly">Friendly</option>
                        </select>
                    </div>
                    <div class="aysa-modal-actions">
                        <button class="aysa-btn aysa-btn-primary">Generate</button>
                        <button class="aysa-btn aysa-btn-secondary aysa-modal-close">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const modal = document.createElement('div');
    modal.innerHTML = modalHTML;
    const modalElement = modal.firstElementChild;
    
    document.body.appendChild(modalElement);
    
    // Close modal handlers
    modalElement.querySelector('.aysa-modal-close').addEventListener('click', function() {
        modalElement.remove();
    });
    
    modalElement.addEventListener('click', function(e) {
        if (e.target === modalElement) {
            modalElement.remove();
        }
    });
}

function showScheduleAutoModal(title) {
    aysaContentDebugLog('Creating Schedule Auto Modal for:', title);
    const modalHTML = `
        <div class="aysa-modal-overlay">
            <div class="aysa-modal">
                <div class="aysa-modal-header">
                    <h3>Schedule Auto Publishing</h3>
                    <button class="aysa-modal-close">&times;</button>
                </div>
                <div class="aysa-modal-content">
                    <p style="margin-bottom: 24px; color: #374151; font-size: 14px;">Schedule automatic publishing for: <strong>${title}</strong></p>
                    <div class="aysa-form-group">
                        <label>Schedule Date</label>
                        <div class="aysa-input-with-icon">
                            <input type="text" class="aysa-input" placeholder="mm/dd/yyyy --:--" />
                            <svg class="aysa-input-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                            </svg>
                        </div>
                    </div>
                    <div class="aysa-checkbox-group">
                        <label>
                            <input type="checkbox" />
                            Publish automatically after generation
                        </label>
                    </div>
                    <div class="aysa-modal-actions">
                        <button class="aysa-btn aysa-btn-primary">Schedule</button>
                        <button class="aysa-btn aysa-btn-secondary aysa-modal-close">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const modal = document.createElement('div');
    modal.innerHTML = modalHTML;
    const modalElement = modal.firstElementChild;
    
    document.body.appendChild(modalElement);
    
    // Close modal handlers
    modalElement.querySelector('.aysa-modal-close').addEventListener('click', function() {
        modalElement.remove();
    });
    
    modalElement.addEventListener('click', function(e) {
        if (e.target === modalElement) {
            modalElement.remove();
        }
    });
}

// Filter table by search term
function filterTable(searchTerm) {
    const rows = document.querySelectorAll('.aysa-proposals-table tbody tr');
    rows.forEach(row => {
        const titleElement = row.querySelector('.aysa-title-cell strong');
        const keywordElements = row.querySelectorAll('.aysa-keyword-tag');
        
        const title = titleElement ? titleElement.textContent.toLowerCase() : '';
        const keywords = Array.from(keywordElements).map(el => el.textContent.toLowerCase()).join(' ');
        
        if (title.includes(searchTerm) || keywords.includes(searchTerm)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// Filter table by type
function filterTableByType(filterType, filterValue) {
    const rows = document.querySelectorAll('.aysa-proposals-table tbody tr');
    rows.forEach(row => {
        if (filterValue === 'All Sources' || filterValue === 'All Statuses') {
            row.style.display = '';
            return;
        }
        
        let shouldShow = false;
        
        if (filterType.includes('Sources')) {
            const sourceElement = row.querySelector('.aysa-source-tag');
            const source = sourceElement ? sourceElement.textContent : '';
            shouldShow = source === filterValue;
        } else if (filterType.includes('Statuses')) {
            const statusElement = row.querySelector('.aysa-status-tag');
            const status = statusElement ? statusElement.textContent : '';
            shouldShow = status === filterValue;
        }
        
        if (shouldShow) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// AYSA Backend Integration for Content Strategy Title Generation
// This function is called when "Generate Strategy" button is clicked
// It should show a strategy selection modal first
if (typeof showGenerateStrategyModal === 'function') {
    // Override the existing function to add backend integration
    const originalShowGenerateStrategyModal = showGenerateStrategyModal;
    showGenerateStrategyModal = function() {
        aysaContentDebugLog('[AYSA] Showing strategy selection modal');
        showStrategySelectionModal();
    };
}

function showStrategySelectionModal() {
    const panel = document.getElementById('aysa-strategy-picker');
    const trigger = document.querySelector('.aysa-generate-strategy-btn');
    if (!panel || !trigger) {
        return;
    }

    panel.hidden = !panel.hidden;

    if (panel.dataset.bound === '1') {
        return;
    }
    panel.dataset.bound = '1';

    const closeBtn = panel.querySelector('.aysa-strategy-picker-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            panel.hidden = true;
        });
    }

    panel.querySelectorAll('.aysa-strategy-type-btn').forEach((btn) => {
        btn.dataset.originalHtml = btn.innerHTML;
        btn.addEventListener('click', async function() {
            const strategy = this.getAttribute('data-strategy');
            const runId = ++activeStrategyRunId;
            const allButtons = panel.querySelectorAll('.aysa-strategy-type-btn');
            resetStrategyPickerState(panel, trigger);
            allButtons.forEach((b) => (b.disabled = true));
            this.classList.add('is-loading');
            this.innerHTML = '<span class="title"><span class="dashicons dashicons-update-alt" style="animation: spin 1s linear infinite;"></span> Generating...</span><span class="desc">Please wait</span>';
            trigger.classList.add('is-loading');
            setStrategyGenerationStatus(true, 'Generating strategy titles. Please wait (30-90 sec)...');

            const watchdogId = window.setTimeout(function() {
                if (activeStrategyRunId !== runId) {
                    return;
                }
                resetStrategyPickerState(panel, trigger);
                panel.hidden = true;
                setStrategyGenerationStatus(false);
                showNotification('Generation timed out. Please retry.', 'warning');
            }, STRATEGY_RUN_WATCHDOG_MS);

            try {
                await handleStrategyGeneration(strategy, panel);
            } catch (error) {
                showNotification('Failed to generate titles: ' + error.message, 'error');
                panel.hidden = true;
            } finally {
                window.clearTimeout(watchdogId);
                if (activeStrategyRunId === runId) {
                    resetStrategyPickerState(panel, trigger);
                    setStrategyGenerationStatus(false);
                }
            }
        });
    });
}

function resetStrategyPickerState(panel, trigger) {
    if (panel) {
        panel.querySelectorAll('.aysa-strategy-type-btn').forEach((b) => {
            b.disabled = false;
            b.classList.remove('is-loading');
            if (b.dataset.originalHtml) {
                b.innerHTML = b.dataset.originalHtml;
            }
        });
    }
    if (trigger) {
        trigger.classList.remove('is-loading');
    }
}

function setStrategyGenerationStatus(active, text) {
    const box = document.getElementById('aysa-generation-status');
    const label = document.getElementById('aysa-generation-text');
    if (!box) {
        return;
    }
    if (!active) {
        box.hidden = true;
        return;
    }
    if (label && text) {
        label.textContent = text;
    }
    box.hidden = false;
}

function showStrategyFormModal(strategy) {
    aysaContentDebugLog('[AYSA] Showing form for strategy:', strategy);
    
    let formHTML = '';
    let title = '';
    
    if (strategy === 'cluster') {
        title = 'Generate Cluster-based Titles';
        formHTML = `
            <div class="aysa-form-group">
                <label>Cluster Name</label>
                <input type="text" id="aysa-strategy-field-1" class="aysa-input" placeholder="SEO Services" required />
            </div>
            <div class="aysa-form-group">
                <label>Keywords (comma-separated)</label>
                <input type="text" id="aysa-strategy-field-2" class="aysa-input" placeholder="seo, optimization, google" required />
            </div>
            <div class="aysa-form-group">
                <label>City</label>
                <input type="text" id="aysa-strategy-field-3" class="aysa-input" placeholder="București" />
            </div>
            <div class="aysa-form-group">
                <label>Brand Name</label>
                <input type="text" id="aysa-strategy-field-4" class="aysa-input" placeholder="Your Brand" />
            </div>
            <div class="aysa-form-group">
                <label>Language</label>
                <select id="aysa-strategy-field-5" class="aysa-select">
                    <option value="ro">Romanian</option>
                    <option value="en">English</option>
                </select>
            </div>
        `;
    } else if (strategy === 'competitor') {
        title = 'Generate Competitor-based Titles';
        formHTML = `
            <div class="aysa-form-group">
                <label>Brand Name</label>
                <input type="text" id="aysa-strategy-field-1" class="aysa-input" placeholder="Your Brand" required />
            </div>
            <div class="aysa-form-group">
                <label>Competitor Titles (one per line)</label>
                <textarea id="aysa-strategy-field-2" class="aysa-input" rows="4" placeholder="Complete Guide to SEO&#10;How to Rank #1 on Google&#10;Top 10 SEO Tips" required></textarea>
            </div>
            <div class="aysa-form-group">
                <label>City</label>
                <input type="text" id="aysa-strategy-field-3" class="aysa-input" placeholder="București" />
            </div>
            <div class="aysa-form-group">
                <label>Language</label>
                <select id="aysa-strategy-field-4" class="aysa-select">
                    <option value="ro">Romanian</option>
                    <option value="en">English</option>
                </select>
            </div>
        `;
    } else if (strategy === 'intent') {
        title = 'Generate Intent Layering Titles';
        formHTML = `
            <div class="aysa-form-group">
                <label>Primary Keyword</label>
                <input type="text" id="aysa-strategy-field-1" class="aysa-input" placeholder="seo optimization" required />
            </div>
            <div class="aysa-form-group">
                <label>City</label>
                <input type="text" id="aysa-strategy-field-2" class="aysa-input" placeholder="București" />
            </div>
            <div class="aysa-form-group">
                <label>Brand Name</label>
                <input type="text" id="aysa-strategy-field-3" class="aysa-input" placeholder="Your Brand" />
            </div>
            <div class="aysa-form-group">
                <label>Language</label>
                <select id="aysa-strategy-field-4" class="aysa-select">
                    <option value="ro">Romanian</option>
                    <option value="en">English</option>
                </select>
            </div>
        `;
    } else if (strategy === 'seasonal') {
        title = 'Generate Seasonal & Event-based Titles';
        formHTML = `
            <div class="aysa-form-group">
                <label>Primary Keyword</label>
                <input type="text" id="aysa-strategy-field-1" class="aysa-input" placeholder="seo services" required />
            </div>
            <div class="aysa-form-group">
                <label>City</label>
                <input type="text" id="aysa-strategy-field-2" class="aysa-input" placeholder="București" />
            </div>
            <div class="aysa-form-group">
                <label>Brand Name</label>
                <input type="text" id="aysa-strategy-field-3" class="aysa-input" placeholder="Your Brand" />
            </div>
            <div class="aysa-form-group">
                <label>Current Month</label>
                <input type="text" id="aysa-strategy-field-4" class="aysa-input" value="<?php echo date('M Y'); ?>" />
            </div>
            <div class="aysa-form-group">
                <label>Language</label>
                <select id="aysa-strategy-field-5" class="aysa-select">
                    <option value="ro">Romanian</option>
                    <option value="en">English</option>
                </select>
            </div>
        `;
    }
    
    const modalHTML = `
        <div class="aysa-modal-overlay">
            <div class="aysa-modal">
                <div class="aysa-modal-header">
                    <h3>${title}</h3>
                    <button class="aysa-modal-close">&times;</button>
                </div>
                <div class="aysa-modal-content">
                    ${formHTML}
                    <div class="aysa-modal-actions">
                        <button class="aysa-btn aysa-btn-primary" id="aysa-generate-submit">Generate Titles</button>
                        <button class="aysa-btn aysa-btn-secondary aysa-modal-close">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    const modal = document.createElement('div');
    modal.innerHTML = modalHTML;
    const modalElement = modal.firstElementChild;
    document.body.appendChild(modalElement);
    
    // Close modal handlers
    modalElement.querySelectorAll('.aysa-modal-close').forEach(btn => {
        btn.addEventListener('click', function() {
            modalElement.remove();
        });
    });
    
    modalElement.addEventListener('click', function(e) {
        if (e.target === modalElement) {
            modalElement.remove();
        }
    });
    
    // Generate button handler
    modalElement.querySelector('#aysa-generate-submit').addEventListener('click', function() {
        handleStrategyGeneration(strategy, modalElement);
    });
}

function closeStrategySelectionUI(container) {
    if (!container) {
        return;
    }
    if (container.id === 'aysa-strategy-picker') {
        container.hidden = true;
        return;
    }
    if (typeof container.remove === 'function') {
        container.remove();
    }
}

async function handleStrategyGeneration(strategy, modalElement) {
    aysaContentDebugLog('[AYSA] Generating titles for strategy:', strategy);
    
    // Get project ID from PHP
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    
    if (!projectId) {
        showNotification('Project ID not configured. Please set it in settings.', 'error');
        throw new Error('project_id_missing');
    }
    
    aysaContentDebugLog('[AYSA] Fetching local setup/association data...');
    
    // Fetch required data from local WP data sources
    const [generalInfo, seoSettings, associations] = await Promise.all([
        fetchGeneralInformation(projectId),
        fetchSeoSettings(projectId),
        fetchAssociations(projectId)
    ]);
    
    if (!generalInfo) {
        showNotification('Failed to fetch general information', 'error');
        throw new Error('general_info_missing');
    }
    
    if (!seoSettings) {
        showNotification('Failed to fetch SEO settings', 'error');
        throw new Error('seo_settings_missing');
    }
    
    if (!associations || associations.length === 0) {
        showNotification('No keywords found. Please create associations first.', 'error');
        throw new Error('associations_missing');
    }
    
    // Select random entity groups (1 main + secondary keywords from same page)
    const entityGroups = selectRandomEntityGroups(associations, 5);
    aysaContentDebugLog('[AYSA] Selected entity groups:', entityGroups);
    
    if (entityGroups.length === 0) {
        showNotification('No valid keyword groups found. Please ensure associations have main keywords.', 'error');
        throw new Error('entity_groups_missing');
    }
    
    const brandName = generalInfo.brand_name || generalInfo.brand || generalInfo.company_name || 'Brand';
    const city = seoSettings.targeted_city || seoSettings.city || 'București';
    const language = seoSettings.primary_language || seoSettings.language || 'Romanian';
    const targetAudience = generalInfo.target_audience || 'general';
    const audienceLevel = generalInfo.audience_level || 'general';
    const publicationLocation = generalInfo.publication_location || 'online';
    const persona = generalInfo.target_persona || generalInfo.target_audience || 'general';
    const neighborhoodSeeds = [];
    if (seoSettings.targeted_region) neighborhoodSeeds.push(seoSettings.targeted_region);
    if (seoSettings.targeted_city) neighborhoodSeeds.push(seoSettings.targeted_city + ' centru');
    if (seoSettings.targeted_city) neighborhoodSeeds.push('sector 1');
    
    // ✅ For CLUSTER strategy: make 3 separate API calls with different keyword groups
    // ✅ Unified logic: Process 3 separate API calls with different keyword groups for ALL strategies
    // This ensures we get titles for 3 DIFFERENT pages/topics
    
    // Take first 3 entity groups (or all if less than 3)
    const groupsToProcess = entityGroups.slice(0, 3);
    
    aysaContentDebugLog('[AYSA] Processing', groupsToProcess.length, 'keyword groups for strategy:', strategy);
    
    // Create array of promises for parallel API calls
    const apiCalls = groupsToProcess.map((group, index) => {
        const allKeywords = [group.main, ...group.secondary];
        const normalizedGroupPages = normalizeAssociatedPages(group.associatedPages || group.associatedPage);
        const normalizedGroupPage = normalizedGroupPages[0] || '';
        let requestData = {};
        
        // Common data storage for enrichment later
        requestData._usedKeywords = allKeywords;
        requestData._associatedPage = normalizedGroupPage;
        requestData._associatedPages = normalizedGroupPages;
        
        if (strategy === 'cluster') {
            requestData = {
                ...requestData,
                cluster_id: 'cluster-' + Date.now() + '-' + index,
                cluster_name: group.main,
                cluster_intent: 'commercial',
                cluster_keywords: allKeywords,
                city: city,
                modifiers: ['rapid', 'ieftin', 'non stop', 'top', 'ghid', 'trucuri', 'în aceeași zi', 'trenduri', 'cele mai bune'],
                brand_name: brandName,
                target_audience: targetAudience,
                audience_level: audienceLevel,
                publication_location: publicationLocation,
                language: language
            };
        } else if (strategy === 'competitor') {
            requestData = {
                ...requestData,
                brand_name: brandName,
                competitor_titles: [],
                city: city,
                language: language,
                modifiers: ['modern', 'rapid', 'profesionist', 'top', 'ghid', 'în siguranță', 'cele mai bune']
            };
        } else if (strategy === 'intent') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'seasonal') {
            const currentDate = new Date();
            const currentMonth = currentDate.toLocaleString('default', { month: 'short', year: 'numeric' });
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                current_month: currentMonth,
                language: language
            };
        } else if (strategy === 'serp') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'evergreen') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'journey') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'local') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                neighborhoods: neighborhoodSeeds.slice(0, 3),
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'authority') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language
            };
        } else if (strategy === 'persona') {
            requestData = {
                ...requestData,
                primary_keyword: group.main,
                city: city,
                brand_name: brandName,
                language: language,
                target_persona: persona
            };
        }

        aysaContentDebugLog('[AYSA] Call #' + (index + 1) + ' (' + strategy + '):', {
            main: group.main,
            page: normalizedGroupPage || '(none)'
        });

        const strategyTypeMap = {
            cluster: 'cluster_titles',
            competitor: 'competitor_derived_titles',
            intent: 'intent_layering',
            seasonal: 'seasonal_event',
            serp: 'serp_features',
            evergreen: 'evergreen_fresh_mix',
            journey: 'customer_journey',
            local: 'local_seo',
            authority: 'authority_building',
            persona: 'persona_based'
        };
        const strategyType = strategyTypeMap[strategy] || 'cluster_titles';

        return async () => {
            const result = await generateContentStrategyTitles(projectId, strategyType, requestData);
            const dataArray = Array.isArray(result?.items) ? result.items : [];
            return dataArray.map(titleData => ({
                ...titleData,
                targetKeywords: requestData._usedKeywords,
                TargetKeywords: requestData._usedKeywords,
                target_keywords: requestData._usedKeywords,
                associatedPage: requestData._associatedPage,
                AssociatedPage: requestData._associatedPage,
                associated_page: requestData._associatedPage,
                associatedPages: requestData._associatedPages,
                AssociatedPages: requestData._associatedPages,
                associated_pages: requestData._associatedPages
            }));
        };
    });
    
    // Run calls sequentially to avoid upstream 504 bursts from parallel generation.
    const successfulResults = [];
    const failedResults = [];
    for (const runCall of apiCalls) {
        try {
            const callResult = await runCall();
            successfulResults.push(Array.isArray(callResult) ? callResult : []);
        } catch (error) {
            failedResults.push(error);
        }
    }

    if (failedResults.length > 0) {
                aysaContentDebugLog('[AYSA] Some strategy generation calls failed:', failedResults);
    }

    const allTitles = successfulResults.flat();
    aysaContentDebugLog('[AYSA] Total titles from', groupsToProcess.length, 'calls:', allTitles.length);

    if (!allTitles.length) {
        const firstReason = failedResults[0]
            ? (failedResults[0].message || String(failedResults[0]))
            : 'No titles generated';
        throw new Error(firstReason);
    }
    
    // Save to DB first, then add to table (so we have IDs)
    const strategyTypeMap = {
        cluster: 'cluster_titles',
        competitor: 'competitor_derived_titles',
        intent: 'intent_layering',
        seasonal: 'seasonal_event',
        serp: 'serp_features',
        evergreen: 'evergreen_fresh_mix',
        journey: 'customer_journey',
        local: 'local_seo',
        authority: 'authority_building',
        persona: 'persona_based'
    };
    const persistStrategyType = strategyTypeMap[strategy] || strategy;

    const savedStrategies = await saveStrategiesToDb(allTitles, persistStrategyType);
    if (savedStrategies && savedStrategies.length > 0) {
        allStrategies = Array.isArray(savedStrategies) ? savedStrategies : [];
        currentPage = 1;
        refreshCurrentView();
        updateSummaryCards();
        showNotification('Strategy titles generated and saved successfully (' + savedStrategies.length + ' items).', 'success');
    } else {
        showNotification('Strategy titles were generated, but AYSA could not save them. The table was not updated.', 'warning');
    }

    closeStrategySelectionUI(modalElement);
}

// Function to save strategies to WordPress DB
async function saveStrategiesToDb(titles, strategyType) {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    
    try {
        const response = await fetchJsonWithTimeout(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_save_strategies',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: projectId,
                strategy_type: strategyType,
                strategies: JSON.stringify(titles)
            })
        }, 30000, 'save_strategies_timeout');
        
        const result = await response.json();
        if (result.success) {
            aysaContentDebugLog('[AYSA] Strategies saved to DB');
            // Reload strategies to get IDs
            return await loadStoredStrategies(true); // Return the reloaded strategies
        } else {
            aysaContentDebugLog('[AYSA] Failed to save strategies:', result);
            return null;
        }
    } catch (error) {
        aysaContentDebugLog('[AYSA] Error saving strategies:', error);
        return null;
    }
}

async function fetchJsonWithTimeout(url, options, timeoutMs, timeoutMessage) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeoutMs || 20000);
    try {
        return await fetch(url, { ...(options || {}), signal: controller.signal });
    } catch (error) {
        if (error && error.name === 'AbortError') {
            throw new Error(timeoutMessage || 'request_timeout');
        }
        throw error;
    } finally {
        clearTimeout(timeoutId);
    }
}

async function generateContentStrategyTitles(projectId, strategyType, payload) {
    const response = await fetchJsonWithTimeout(ajaxurl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'aysa_content_strategy_generate',
            nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
            project_id: String(projectId),
            strategy_type: String(strategyType || ''),
            payload: JSON.stringify(payload || {})
        })
    }, 70000, 'Generation timeout after 70s');

    const result = await response.json();
    if (!result || !result.success || !result.data) {
        throw new Error((result && result.data) ? result.data : 'content_strategy_generation_failed');
    }
    return result.data;
}

// Helper function to fetch general information (local setup step)
async function fetchGeneralInformation(projectId) {
    try {
        const response = await fetchJsonWithTimeout(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_wizard_data',
                nonce: '<?php echo wp_create_nonce("aysa_wizard_nonce"); ?>',
                step: 'general'
            })
        }, 20000, 'general_data_timeout');
        const result = await response.json();
        if (result && result.success && result.data && result.data.data) {
            return result.data.data;
        }
        return null;
    } catch (error) {
        aysaContentDebugLog('[AYSA] Error fetching general setup data:', error);
        return null;
    }
}

// Helper function to fetch SEO settings (local setup step)
async function fetchSeoSettings(projectId) {
    try {
        const response = await fetchJsonWithTimeout(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_wizard_data',
                nonce: '<?php echo wp_create_nonce("aysa_wizard_nonce"); ?>',
                step: 'seo-settings'
            })
        }, 20000, 'seo_settings_timeout');
        const result = await response.json();
        if (result && result.success && result.data && result.data.data) {
            return result.data.data;
        }
        return null;
    } catch (error) {
        aysaContentDebugLog('[AYSA] Error fetching SEO settings:', error);
        return null;
    }
}

// Helper function to fetch associations (local endpoint)
async function fetchAssociations(projectId) {
    try {
        const response = await fetchJsonWithTimeout(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_keyword_discovery_get_associations',
                nonce: '<?php echo wp_create_nonce("aysa_nonce"); ?>',
                project_id: String(projectId)
            })
        }, 25000, 'associations_timeout');
        const result = await response.json();
        if (result && result.success && result.data && Array.isArray(result.data.associations)) {
            aysaContentDebugLog('[AYSA] Associations received:', result.data.associations.length, 'items');
            return result.data.associations;
        }
        return [];
    } catch (error) {
        aysaContentDebugLog('[AYSA] Error fetching local associations:', error);
        return [];
    }
}

function normalizeAssociatedPage(rawValue) {
    const raw = String(rawValue || '').trim();
    if (!raw || raw === '-' || /^n\/?a$/i.test(raw) || /^https?:\/\/-\/?$/i.test(raw)) {
        return '';
    }

    if (/^https?:\/\//i.test(raw)) {
        return raw;
    }

    if (raw.startsWith('/')) {
        return window.location.origin + raw;
    }

    return '';
}

function normalizeAssociatedPages(rawValues) {
    const values = Array.isArray(rawValues) ? rawValues : [rawValues];
    const unique = [];
    const seen = new Set();

    values.forEach((value) => {
        const normalized = normalizeAssociatedPage(value);
        if (!normalized) {
            return;
        }
        const key = normalized.toLowerCase();
        if (seen.has(key)) {
            return;
        }
        seen.add(key);
        unique.push(normalized);
    });

    return unique;
}

function extractAssociatedPagesFromItem(item) {
    const rawList = item.associatedPages || item.AssociatedPages || item.associated_pages || [];
    const normalizedList = normalizeAssociatedPages(rawList);
    if (normalizedList.length > 0) {
        return normalizedList;
    }
    const single = item.associatedPage || item.AssociatedPage || item.associated_page || '';
    return normalizeAssociatedPages(single);
}

// Helper function to get keywords grouped by entity (1 main + all secondary from same page)
function getKeywordGroupsByEntity(associations) {
    const keywordGroups = {};
    
    associations.forEach((assoc, index) => {
        const normalizedLink = normalizeAssociatedPage(assoc.Link || assoc.link || assoc.url || '');
        const entityId = assoc.IdIntern || assoc.idIntern || assoc.id_intern || assoc.EntityId || assoc.entityId || ('fallback-' + index);
        const keyword = assoc.Keyword || assoc.keyword || '';
        const isMainRaw = (assoc.IsMain !== undefined) ? assoc.IsMain
            : ((assoc.isMain !== undefined) ? assoc.isMain
            : ((assoc.is_main !== undefined) ? assoc.is_main : false));
        const isMain = (typeof isMainRaw === 'boolean')
            ? isMainRaw
            : ['1', 'true', 'yes'].includes(String(isMainRaw).toLowerCase());
        const value = assoc.Value || assoc.value || '';
        
        if (!keywordGroups[entityId]) {
            keywordGroups[entityId] = {
                entityId: entityId,
                main: null,
                secondary: [],
                associatedPage: normalizedLink,
                associatedPages: normalizedLink ? [normalizedLink] : [],
                pageTitle: value
            };
        }
        
        if (isMain) {
            keywordGroups[entityId].main = keyword;
            if (normalizedLink) {
                keywordGroups[entityId].associatedPage = normalizedLink;
                if (!keywordGroups[entityId].associatedPages.includes(normalizedLink)) {
                    keywordGroups[entityId].associatedPages.push(normalizedLink);
                }
            }
        } else {
            keywordGroups[entityId].secondary.push(keyword);
            if (!keywordGroups[entityId].associatedPage && normalizedLink) {
                keywordGroups[entityId].associatedPage = normalizedLink;
            }
            if (normalizedLink && !keywordGroups[entityId].associatedPages.includes(normalizedLink)) {
                keywordGroups[entityId].associatedPages.push(normalizedLink);
            }
        }
    });

    // Fallback: if API row does not expose is_main, promote first secondary to main.
    Object.values(keywordGroups).forEach(group => {
        if (!group.main && Array.isArray(group.secondary) && group.secondary.length > 0) {
            group.main = group.secondary.shift();
        }
    });
    
    // Filter out groups without main keyword and shuffle
    const validGroups = Object.values(keywordGroups).filter(g => g.main);
    
    // Shuffle groups
    for (let i = validGroups.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [validGroups[i], validGroups[j]] = [validGroups[j], validGroups[i]];
    }
    
    return validGroups;
}

// Helper function to select random entity groups for title generation
function selectRandomEntityGroups(associations, count = 5) {
    const groups = getKeywordGroupsByEntity(associations);
    const withPage = groups.filter(g => normalizeAssociatedPages(g.associatedPages || g.associatedPage).length > 0);
    const withoutPage = groups.filter(g => normalizeAssociatedPages(g.associatedPages || g.associatedPage).length === 0);
    return [...withPage, ...withoutPage].slice(0, count);
}

function getSafeLinkHref(rawUrl) {
    if (!rawUrl || rawUrl === '-' || rawUrl === 'http://-' || rawUrl === 'https://-') {
        return null;
    }

    try {
        // Allow absolute http/https links.
        const absolute = new URL(rawUrl, window.location.origin);
        const isHttp = absolute.protocol === 'http:' || absolute.protocol === 'https:';
        return isHttp ? absolute.href : null;
    } catch (error) {
        return null;
    }
}

function addTitlesToTable(titles, source) {
    const tbody = document.querySelector('.aysa-proposals-table tbody');
    if (!tbody) return;
    
    // If source is 'stored', we might want to clear first? No, usually append or handled by caller.
    // But if we are reloading everything, the caller clears it.
    
    const normalizeKeywordsForRow = (rawKeywords) => {
        if (Array.isArray(rawKeywords)) {
            return rawKeywords
                .map((kw) => String(kw || '').trim())
                .filter(Boolean);
        }
        if (typeof rawKeywords === 'string') {
            const text = rawKeywords.trim();
            if (!text) {
                return [];
            }
            if ((text.startsWith('[') && text.endsWith(']')) || (text.startsWith('{') && text.endsWith('}'))) {
                try {
                    const parsed = JSON.parse(text);
                    if (Array.isArray(parsed)) {
                        return parsed
                            .map((kw) => String(kw || '').trim())
                            .filter(Boolean);
                    }
                } catch (e) {
                    // Fall through to scalar handling.
                }
            }
            return [text];
        }
        return [];
    };

    titles.forEach(titleData => {
        // Backend may return camelCase or PascalCase - try all formats
        const title = titleData.title || titleData.Title || '';
        const rawKeywords = titleData.targetKeywords || titleData.TargetKeywords || titleData.target_keywords || [];
        const keywords = normalizeKeywordsForRow(rawKeywords);
        const intent = titleData.intent || titleData.Intent || 'I';
        const associatedPages = extractAssociatedPagesFromItem(titleData);
        const associatedPage = associatedPages[0] || '-';
        const strategyType = titleData.strategy_type || source;
        const id = titleData.id || null;
        const status = titleData.status || 'proposed';
        const automationStatus = titleData.automation_status || '';
        const postId = titleData.post_id || null;
        const scheduledFor = titleData.scheduled_for_local || titleData.scheduled_for || '';
        const metaH1 = String(titleData.meta_h1 || '').trim();
        const metaDescription = String(titleData.meta_description || '').trim();
        const metaWarning = String(titleData.meta_warning || '').trim();
        const metaSource = String(titleData.meta_source || '').trim().toLowerCase();
        const competitorTitle = String(titleData.competitor_title || '').trim();
        const competitorDomain = String(titleData.competitor_domain || '').trim();
        const competitorUrl = String(titleData.competitor_url || '').trim();
        const whyBetter = String(titleData.why_better || '').trim();
        const safeStrategyClass = String(strategyType || 'unknown').toLowerCase().replace(/[^a-z0-9_-]/g, '');
        
        // Skip if already generated/published and we want to hide them?
        // User said: "if I delete content... it should not remain".
        // This means we SHOW generated ones, but if deleted they go back to proposed?
        // Or maybe we just show everything.
        
        aysaContentDebugLog('[AYSA] Adding to table - Title:', title);
        
        const row = document.createElement('tr');

        const titleCell = document.createElement('td');
        const titleWrap = document.createElement('div');
        titleWrap.className = 'aysa-title-cell';
        const strong = document.createElement('strong');
        strong.textContent = title;
        titleWrap.appendChild(strong);

        if (metaH1) {
            const h1Line = document.createElement('div');
            h1Line.className = 'aysa-meta-inline';
            h1Line.innerHTML = `<span>H1:</span> ${escapeHtml(metaH1)}`;
            titleWrap.appendChild(h1Line);
        }
        if (metaDescription) {
            const mdLine = document.createElement('div');
            mdLine.className = 'aysa-meta-inline aysa-meta-inline-desc';
            mdLine.innerHTML = `<span>Meta:</span> ${escapeHtml(metaDescription)}`;
            titleWrap.appendChild(mdLine);
        }
        if (metaWarning) {
            const warnLine = document.createElement('div');
            warnLine.className = 'aysa-meta-warning';
            warnLine.textContent = 'Needs another AI pass';
            titleWrap.appendChild(warnLine);
        }
        if (metaSource) {
            const sourceBadge = document.createElement('span');
            sourceBadge.className = `aysa-meta-source-badge ${metaSource === 'ai' ? 'is-ai' : 'is-fallback'}`;
            sourceBadge.textContent = (metaSource === 'ai') ? 'AI' : 'Backup';
            sourceBadge.title = (metaSource === 'ai')
                ? 'Generated by the AI metadata service'
                : 'Generated with the backup metadata flow because the main AI response was incomplete';
            titleWrap.appendChild(sourceBadge);
        }
        if (status === 'generated') {
            const generatedIcon = document.createElement('span');
            generatedIcon.className = 'dashicons dashicons-yes';
            generatedIcon.style.color = 'green';
            generatedIcon.title = 'Article Generated';
            titleWrap.appendChild(generatedIcon);
        }
        if (competitorDomain || competitorTitle || competitorUrl) {
            const competitorRef = document.createElement('div');
            competitorRef.className = 'aysa-competitor-ref';

            const competitorLabel = document.createElement('span');
            competitorLabel.className = 'aysa-competitor-ref-label';
            competitorLabel.textContent = 'Competitor reference';
            competitorRef.appendChild(competitorLabel);

            if (competitorDomain) {
                const competitorDomainEl = document.createElement('span');
                competitorDomainEl.className = 'aysa-competitor-ref-domain';
                competitorDomainEl.textContent = competitorDomain;
                competitorRef.appendChild(competitorDomainEl);
            }

            if (competitorTitle) {
                const competitorTitleEl = competitorUrl ? document.createElement('a') : document.createElement('span');
                competitorTitleEl.className = 'aysa-competitor-ref-title';
                competitorTitleEl.textContent = competitorTitle;
                if (competitorUrl) {
                    competitorTitleEl.href = competitorUrl;
                    competitorTitleEl.target = '_blank';
                    competitorTitleEl.rel = 'noopener noreferrer';
                }
                competitorRef.appendChild(competitorTitleEl);
            }

            titleWrap.appendChild(competitorRef);
        }
        if (whyBetter) {
            const whyBetterLine = document.createElement('div');
            whyBetterLine.className = 'aysa-meta-inline aysa-competitor-why-better';
            whyBetterLine.innerHTML = `<span>Why better:</span> ${escapeHtml(whyBetter)}`;
            titleWrap.appendChild(whyBetterLine);
        }
        titleCell.appendChild(titleWrap);

        const keywordCell = document.createElement('td');
        const keywordWrap = document.createElement('div');
        keywordWrap.className = 'aysa-keywords-cell';
        if (keywords.length > 0) {
            keywords.forEach(keyword => {
                const keywordTag = document.createElement('span');
                keywordTag.className = 'aysa-keyword-tag';
                keywordTag.textContent = String(keyword || '');
                keywordWrap.appendChild(keywordTag);
            });
        } else {
            const emptyKeyword = document.createElement('span');
            emptyKeyword.className = 'aysa-keyword-tag';
            emptyKeyword.textContent = '-';
            keywordWrap.appendChild(emptyKeyword);
        }
        keywordCell.appendChild(keywordWrap);

        const intentCell = document.createElement('td');
        const intentTag = document.createElement('span');
        intentTag.className = `aysa-intent-tag ${intent === 'I' ? 'informational' : 'commercial'}`;
        intentTag.textContent = intent;
        intentCell.appendChild(intentTag);

        const sourceCell = document.createElement('td');
        const sourceTag = document.createElement('span');
        sourceTag.className = `aysa-source-tag ${safeStrategyClass || 'unknown'}`;
        sourceTag.textContent = getStrategyTypeLabel(strategyType);
        sourceCell.appendChild(sourceTag);

        const pageCell = document.createElement('td');
        const pageWrap = document.createElement('div');
        pageWrap.className = 'aysa-pages-cell';
        if (associatedPages.length > 0) {
            associatedPages.forEach((pageUrl) => {
                const safeHref = getSafeLinkHref(pageUrl);
                if (!safeHref) {
                    return;
                }
                const pageLink = document.createElement('a');
                pageLink.href = safeHref;
                pageLink.target = '_blank';
                pageLink.rel = 'noopener noreferrer';
                pageLink.textContent = pageUrl;
                pageWrap.appendChild(pageLink);
            });
        }
        if (!pageWrap.children.length) {
            const pageDash = document.createElement('span');
            pageDash.textContent = '-';
            pageWrap.appendChild(pageDash);
        }
        pageCell.appendChild(pageWrap);

        const dateCell = document.createElement('td');
        dateCell.textContent = scheduledFor || '-';

        const statusCell = document.createElement('td');
        const statusTag = document.createElement('span');
        const normalizedStatus = String(automationStatus || status || '').toLowerCase();
        const statusText = getStrategyStatusLabel(status, automationStatus);
        statusTag.className = 'aysa-source-tag';
        statusTag.textContent = statusText;
        statusCell.appendChild(statusTag);
        if (normalizedStatus === 'blocked_no_association' && titleData.last_error) {
            const detail = document.createElement('div');
            detail.style.fontSize = '11px';
            detail.style.color = '#B45309';
            detail.style.marginTop = '4px';
            detail.textContent = String(titleData.last_error);
            statusCell.appendChild(detail);
        }

        const actionsCell = document.createElement('td');
        const actionsWrap = document.createElement('div');
        actionsWrap.className = 'aysa-actions-cell';
        if (status === 'generated' && postId) {
            const editLink = document.createElement('a');
            editLink.href = `post.php?post=${encodeURIComponent(postId)}&action=edit`;
            editLink.className = 'aysa-btn-small';
            editLink.target = '_blank';
            editLink.rel = 'noopener noreferrer';
            editLink.textContent = 'Open Draft';
            actionsWrap.appendChild(editLink);
        } else {
            const generateBtn = document.createElement('button');
            generateBtn.className = 'aysa-btn-small aysa-generate-btn';
            const tabKey = getTabKeyForStrategyType(strategyType || '');
            const isMissingPagesPlan = tabKey === 'content-expansion';
            generateBtn.textContent = isMissingPagesPlan ? 'Generate Metadata' : 'Create Article Draft';
            generateBtn.addEventListener('click', async function() {
                if (isMissingPagesPlan) {
                    const primaryKeyword = String((keywords && keywords[0]) || '').trim();
                    const inferredKeyword = primaryKeyword
                        || String(titleData.keyword || '').trim()
                        || title.replace(/^Create\s+.+?\s+for\s+/i, '').trim();
                    const inferredType = inferMissingPageTypeFromTitle(title);
                    generateBtn.disabled = true;
                    const oldLabel = generateBtn.textContent;
                    generateBtn.textContent = 'Generating...';
                    try {
                        const metaResult = await handleGenerateMissingPageMeta(inferredKeyword, inferredType, intent, id || 0);
                        showMissingPageMetaPreview(metaResult);
                    } catch (error) {
                        showNotification('SEO meta generation failed: ' + (error && error.message ? error.message : 'Unknown error'), 'error');
                    } finally {
                        generateBtn.disabled = false;
                        generateBtn.textContent = oldLabel;
                    }
                    return;
                }
                handleGenerateArticle(title, keywords, intent, associatedPage, associatedPages, id);
            });
            actionsWrap.appendChild(generateBtn);
        }
        actionsCell.appendChild(actionsWrap);

        row.appendChild(titleCell);
        row.appendChild(keywordCell);
        row.appendChild(intentCell);
        row.appendChild(sourceCell);
        row.appendChild(pageCell);
        row.appendChild(dateCell);
        row.appendChild(statusCell);
        row.appendChild(actionsCell);
        
        tbody.appendChild(row);
    });
    
    // Update summary cards
    updateSummaryCards();
}

function inferMissingPageTypeFromTitle(title) {
    const normalized = String(title || '').toLowerCase();
    if (normalized.includes('create product page')) {
        return 'product';
    }
    if (normalized.includes('create category page')) {
        return 'category';
    }
    return 'landing_page';
}

function inferKeywordFromStrategyTitle(title) {
    const match = String(title || '').match(/for\s+(.+)$/i);
    return match && match[1] ? String(match[1]).trim() : '';
}

async function handleGenerateMissingPageMeta(keyword, pageType, intent, strategyId = 0) {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    const response = await fetch(ajaxurl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'aysa_missing_page_generate_meta',
            nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
            project_id: String(projectId || 0),
            keyword: String(keyword || ''),
            page_type: String(pageType || 'landing_page'),
            intent: String(intent || 'N/A'),
            strategy_id: String(strategyId || 0)
        })
    });
    const result = await response.json();
    if (!result || !result.success || !result.data) {
        throw new Error((result && result.data) ? String(result.data) : 'Could not generate metadata');
    }
    return result.data;
}

function showMissingPageMetaPreview(data) {
    const old = document.getElementById('aysa-meta-preview-card');
    if (old) {
        old.remove();
    }

    const card = document.createElement('div');
    card.id = 'aysa-meta-preview-card';
    card.className = 'aysa-meta-preview-card';
    const warning = data.warning ? `<div class="aysa-meta-preview-warning">Note: ${escapeHtml(data.warning)}</div>` : '';
    card.innerHTML = `
        <div class="aysa-meta-preview-head">
            <strong>Generated Metadata</strong>
            <button type="button" class="aysa-meta-preview-close" aria-label="Close">×</button>
        </div>
        <div class="aysa-meta-preview-row"><span>Keyword</span><code>${escapeHtml(data.keyword || '')}</code></div>
        <div class="aysa-meta-preview-row"><span>Page Type</span><code>${escapeHtml(data.page_type || '')}</code></div>
        <div class="aysa-meta-preview-field"><label>Title</label><p>${escapeHtml(data.title || '')}</p></div>
        <div class="aysa-meta-preview-field"><label>H1</label><p>${escapeHtml(data.h1 || '')}</p></div>
        <div class="aysa-meta-preview-field"><label>Meta Description</label><p>${escapeHtml(data.meta_description || '')}</p></div>
        ${warning}
    `;
    document.body.appendChild(card);
    const closeBtn = card.querySelector('.aysa-meta-preview-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', () => card.remove());
    }
}

async function triggerRefactorMissingPageTitles() {
    if (currentTabKey !== 'content-expansion') {
        showNotification('Improve Titles is available only in the Missing Pages Plan tab.', 'info');
        return;
    }

    const baseRows = Array.isArray(currentFilteredStrategies) ? currentFilteredStrategies : [];
    const candidates = baseRows
        .filter((row) => getTabKeyForStrategyType(row.strategy_type || row.strategyType || '') === 'content-expansion')
        .filter((row) => Number(row.id || 0) > 0)
        .map((row) => {
            const kws = Array.isArray(row.targetKeywords || row.TargetKeywords || row.target_keywords)
                ? (row.targetKeywords || row.TargetKeywords || row.target_keywords)
                : [];
            const keyword = String((kws[0] || '')).trim() || inferKeywordFromStrategyTitle(row.title || row.Title || '');
            return {
                id: Number(row.id || 0),
                keyword: keyword,
                page_type: inferMissingPageTypeFromTitle(row.title || row.Title || ''),
                intent: String(row.intent || row.Intent || 'N/A')
            };
        })
        .filter((row) => row.id > 0 && row.keyword);

    if (!candidates.length) {
        showNotification('No eligible rows to refactor on current filter.', 'info');
        return;
    }

    const btn = document.getElementById('aysa-refactor-titles-btn');
    if (btn) {
        btn.disabled = true;
        btn.textContent = 'Improving...';
    }
    const statusNode = document.getElementById('aysa-generation-status');
    const statusText = document.getElementById('aysa-generation-text');
    if (statusNode && statusText) {
        statusNode.hidden = false;
        statusText.textContent = `Improving ${candidates.length} missing-page titles...`;
    }

    try {
        const projectId = <?php echo intval($aysa_content_project_id); ?>;
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_missing_pages_refactor_titles',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId || 0),
                items: JSON.stringify(candidates)
            })
        });
        const result = await response.json();
        if (!result || !result.success) {
            throw new Error((result && result.data) ? String(result.data) : 'Refactor failed');
        }
        const summary = result.data || {};
        showNotification(`Title improvement complete: ${summary.updated || 0} updated (AI ${summary.ai || 0}, fallback ${summary.fallback || 0}), ${summary.failed || 0} failed.`, 'success');
        await loadStoredStrategies();
        setActiveDashboardTab('content-expansion');
    } catch (error) {
        showNotification(`Title improvement failed: ${error && error.message ? error.message : 'Unknown error'}`, 'error');
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = 'Improve Titles';
        }
        if (statusNode) {
            statusNode.hidden = true;
        }
    }
}

function updateSummaryCards(totalCountOverride) {
    const totalCount = typeof totalCountOverride === 'number'
        ? totalCountOverride
        : (Array.isArray(currentFilteredStrategies) && currentFilteredStrategies.length > 0
            ? currentFilteredStrategies.length
            : document.querySelectorAll('.aysa-proposals-table tbody tr').length);
    const totalElement = document.querySelector('#aysa-total-articles');
    if (totalElement) {
        totalElement.textContent = totalCount;
    }
    const proposalsTitle = document.querySelector('#aysa-proposals-title');
    if (proposalsTitle) {
        proposalsTitle.textContent = `All Proposals (${totalCount})`;
    }
}

async function loadResearchOverview() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    if (!projectId) {
        return;
    }

    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_research_summary',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId)
            })
        });

        const result = await response.json();
        if (!result || !result.success || !result.data) {
            return;
        }

        const data = result.data;
        const cs = data.content_strategy || {};
        const kd = data.keyword_discovery || {};
        const comp = data.competitor || {};

        const setText = (selector, value) => {
            const el = document.querySelector(selector);
            if (el) {
                el.textContent = value;
            }
        };

        setText('#aysa-total-articles', String(cs.total || 0));
        setText('#aysa-published-articles', String(cs.published || 0));
        setText('#aysa-pending-articles', String(cs.pending || 0));
        setText('#aysa-overview-keywords', `${kd.suggested_keywords || 0} keywords`);
        setText('#aysa-overview-associations', `${kd.associations_total || 0} links`);
        setText('#aysa-overview-competitors', `${comp.domains || 0} competitors`);
        setText('#aysa-overview-gap', `${comp.gap_keywords || 0} gap keywords`);
        setText('#aysa-overview-backlinks', `${comp.backlink_domains || 0} domains`);
        setText('#aysa-overview-authority', `avg ${comp.avg_authority || 0}`);

        const proposalsTitle = document.querySelector('#aysa-proposals-title');
        if (proposalsTitle) {
            proposalsTitle.textContent = `All Proposals (${cs.total || 0})`;
        }

        if ((cs.total || 0) > 0 && (!Array.isArray(allStrategies) || allStrategies.length === 0)) {
            await loadStoredStrategies();
            await loadContentCalendarData();
        }
    } catch (error) {
        aysaContentDebugLog('[AYSA] Failed loading research overview:', error);
    }
}

async function triggerContentPlanning() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    if (!projectId) {
        showNotification('Project ID missing. Complete setup first.', 'error');
        return;
    }

    showNotification('Building a content plan...', 'info');
    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_plan_content_schedule',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId),
                strategy_scope: (currentTabKey === 'content-expansion' ? 'missing_pages' : 'all'),
                min_per_week: '3',
                max_per_week: '4',
                redistribute_pending: '1',
                force_generate_now: '0'
            })
        });
        const result = await response.json();
        if (!result.success) {
            showNotification(result.data || 'Could not build the content plan.', 'error');
            return;
        }

        const data = result.data || {};
        showNotification(data.message || 'Content plan updated.', 'success');
        // After planning, jump calendar to the nearest month containing new events.
        calendarAutoFocusEnabled = true;
        await Promise.all([loadStoredStrategies(), loadContentPlanStatus(), loadContentCalendarData()]);
    } catch (error) {
        showNotification('Content planning failed: ' + error.message, 'error');
    }
}

async function triggerAssociateMissing() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    if (!projectId) {
        showNotification('Project ID missing. Complete setup first.', 'error');
        return;
    }

    const btn = document.querySelector('.aysa-associate-missing-btn');
    const previousLabel = btn ? btn.textContent.trim() : '';
    if (btn) {
        btn.disabled = true;
        btn.textContent = 'Associating pages...';
    }

    showNotification('Trying to match missing topics to relevant pages...', 'info');
    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_content_strategy_associate_missing',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId)
            })
        });
        const result = await response.json();
        if (!result.success) {
            showNotification(result.data || 'Could not complete the page associations.', 'error');
            return;
        }

        const data = result.data || {};
        const message = data.message || 'Page association completed.';
        showNotification(message, data.updated > 0 ? 'success' : 'info');
        await Promise.all([loadStoredStrategies(), loadContentPlanStatus(), loadResearchOverview()]);
    } catch (error) {
        showNotification('Page association failed: ' + error.message, 'error');
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = previousLabel || 'Associate Missing';
        }
    }
}

async function triggerResetContentPlan() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    if (!projectId) {
        showNotification('Project ID missing. Complete setup first.', 'error');
        return;
    }

    if (!window.confirm('Delete all generated content strategy rows for this project and start fresh?')) {
        return;
    }

    const btn = document.querySelector('.aysa-reset-plan-btn');
    const previousLabel = btn ? btn.textContent.trim() : '';
    if (btn) {
        btn.disabled = true;
        btn.textContent = 'Resetting...';
    }

    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_cleanup_content_strategies',
                nonce: '<?php echo wp_create_nonce("aysa-cleanup"); ?>',
                project_id: String(projectId)
            })
        });
        const result = await response.json();
        if (!result.success) {
            const message = (result && result.data && typeof result.data === 'object' && result.data.message)
                ? result.data.message
                : (result && result.data ? String(result.data) : 'Could not reset content strategy plan.');
            showNotification(message, 'error');
            return;
        }

        const successMessage = (result && result.data && typeof result.data === 'object' && result.data.message)
            ? result.data.message
            : 'Content strategy plan cleared.';
        allStrategies = [];
        calendarEvents = [];
        calendarTodayInfo = null;
        currentPage = 1;
        updateSummaryCards(0);
        refreshCurrentView();
        renderPublicationCalendar();
        const statusNode = document.getElementById('aysa-plan-status');
        if (statusNode) {
            statusNode.textContent = 'Content plan status: not started';
        }
        showNotification(successMessage, 'success');
        await Promise.all([loadStoredStrategies(), loadContentPlanStatus(), loadContentCalendarData(), loadResearchOverview()]);
        window.setTimeout(() => window.location.reload(), 250);
    } catch (error) {
        showNotification('Content strategy cleanup failed: ' + error.message, 'error');
    } finally {
        if (btn) {
            btn.disabled = false;
            btn.textContent = previousLabel || 'Reset Plan';
        }
    }
}

async function loadContentPlanStatus() {
    const projectId = <?php echo intval($aysa_content_project_id); ?>;
    const statusNode = document.getElementById('aysa-plan-status');
    if (!statusNode || !projectId) {
        return;
    }

    try {
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams({
                action: 'aysa_get_content_plan_status',
                nonce: '<?php echo wp_create_nonce("aysa_content_strategy_nonce"); ?>',
                project_id: String(projectId)
            })
        });
        const result = await response.json();
        if (!result.success || !result.data) {
            statusNode.textContent = 'Content plan status: unavailable';
            return;
        }

        const statuses = result.data.statuses || {};
        const queued = statuses.queued || 0;
        const processing = statuses.processing || 0;
        const retry = statuses.retry || 0;
        const generated = statuses.generated || 0;
        const failed = statuses.failed || 0;
        const blocked = statuses.blocked_no_association || statuses.blocked || 0;
        const next = result.data.next && result.data.next.scheduled_for ? result.data.next.scheduled_for : '-';
        statusNode.textContent = `Content plan status: queued ${queued} | generating ${processing} | retry ${retry} | generated ${generated} | blocked ${blocked} | failed ${failed} | next ${next}`;
    } catch (error) {
        statusNode.textContent = 'Content plan status: could not be loaded';
    }
}

// Handle Generate Article - Create new WordPress post and redirect to edit
async function handleGenerateArticle(title, keywords, intent, associatedPage, associatedPages = [], strategyId = null) {
    aysaContentDebugLog('[AYSA] Generating article:', { title, keywords, intent, associatedPage, associatedPages, strategyId });
    
    // Show loading notification
    showNotification('Creating article draft...', 'info');
    
    try {
        // Prepare data
        const params = new URLSearchParams({
            action: 'aysa_create_post_from_strategy',
            nonce: '<?php echo wp_create_nonce("aysa_create_post_nonce"); ?>',
            title: title,
            keywords: JSON.stringify(keywords),
            intent: intent,
            associated_page: associatedPage,
            associated_pages: JSON.stringify(normalizeAssociatedPages(associatedPages))
        });
        
        if (strategyId) {
            params.append('strategy_id', strategyId);
        }

        // Create new WordPress post via AJAX
        const response = await fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Draft created. Redirecting to the editor...', 'success');
            loadContentCalendarData();
            
            // Redirect to post edit page with auto-generate trigger after 1 second
            setTimeout(() => {
                // Add parameter to trigger automatic content generation
                const editUrl = new URL(result.data.edit_url);
                editUrl.searchParams.set('aysa_auto_generate', '1');
                window.location.href = editUrl.toString();
            }, 1000);
        } else {
            showNotification('Could not create the article draft: ' + (result.data.message || 'Unknown error'), 'error');
        }
    } catch (error) {
        aysaContentDebugLog('[AYSA] Error creating article draft:', error);
        showNotification('Article draft creation failed: ' + error.message, 'error');
    }
}

function showNotification(message, type) {
    const bgColor = type === 'success' ? '#10B981' : (type === 'info' ? '#2563EB' : '#EF4444');
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 32px;
        right: 32px;
        background: ${bgColor};
        color: white;
        padding: 16px 24px;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        z-index: 10000;
        animation: slideIn 0.3s ease-out;
    `;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}
</script>
