<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Meta tags are handled by the main AYSA SEO system for frontend display
?>

<div class="aysa-dashboard-wrapper">
    <div class="aysa-dashboard-container">
        <!-- Header Section -->
        <div class="aysa-dashboard-header">
            <div class="aysa-dashboard-title">
                <h1>On-Page Optimization</h1>
                <p>Optimize your content for better search visibility</p>
            </div>
            <div class="aysa-dashboard-user">
                <?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>';
                }
                ?>
                <!-- <span id="aysa-user-name">User ID: <?php echo isset($aysa_user_id) ? esc_html($aysa_user_id) : 'Unknown'; ?></span> -->
            </div>
        </div>

        <!-- Mesaj AI unificat sub header - COMMENTED OUT -->
        <!--
        <div class="aysa-global-intro-text">
            <img src="<?php echo defined('AYSA_PLUGIN_URL') ? AYSA_PLUGIN_URL : plugin_dir_url(dirname(__FILE__, 2)); ?>assets/images/aysa-eyes.png" alt="Aysa Eyes" class="aysa-eyes-img" />
            <div class="aysa-chat-message aysa-ai-message">
                <p id="aysa-dynamic-text-onpage-intro" class="aysa-intro-dynamic-text"></p>
            </div>
        </div>
        -->
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                const textElement = document.getElementById('aysa-dynamic-text-onpage-intro');
                const textToType = "Optimize content, meta, images, internal links, external links, and competitor signals in one workflow.";
                let currentIndex = 0;
                const typingSpeed = 30;
                function typeWriter() {
                    if (textElement && currentIndex < textToType.length) {
                        textElement.innerHTML += textToType.charAt(currentIndex);
                        currentIndex++;
                        setTimeout(typeWriter, typingSpeed);
                    } else if (textElement) {
                        textElement.classList.add('typing-done');
                    }
                }
                if (textElement) {
                    textElement.innerHTML = '';
                    typeWriter();
                }
            });
        </script>

        <!-- Overview Panel -->
<?php
// Prepare fallback data if variables are not set
$current_metrics = isset($current_metrics) ? $current_metrics : array(
    'overallScore' => 0,
    'titleTags' => array('score' => 0, 'totalItems' => 0, 'optimizedItems' => 0),
    'metaDescriptions' => array('score' => 0, 'totalItems' => 0, 'optimizedItems' => 0),
    'headings' => array('score' => 0, 'totalItems' => 0, 'optimizedItems' => 0),
    'internalLinks' => array('score' => 0, 'totalItems' => 0, 'optimizedItems' => 0)
);

$progress_data = isset($progress_data) ? $progress_data : array(
    'changes' => array(
        'overallChange' => 0,
        'titleTagsChange' => 0,
        'metaDescriptionsChange' => 0,
        'headingsChange' => 0,
        'internalLinksChange' => 0
    )
);

$chart_data = isset($chart_data) ? $chart_data : array(
    'weeks' => array(),
    'overallScores' => array(),
    'titleTagsScores' => array(),
    'metaDescriptionsScores' => array(),
    'headingsScores' => array(),
    'internalLinksScores' => array()
);
?>

        <div class="aysa-panel aysa-onpage-quickstart">
            <h2 class="aysa-section-title">Start Here (3 simple steps)</h2>
            <div class="aysa-onpage-steps">
                <div class="aysa-onpage-step"><strong>1.</strong> Open <strong>Associations</strong> and find the keyword/page pair.</div>
                <div class="aysa-onpage-step"><strong>2.</strong> Click <strong>Generate</strong>, then open <strong>Details</strong> to review suggestions.</div>
                <div class="aysa-onpage-step"><strong>3.</strong> In <strong>Review Queue</strong>, approve only what is correct.</div>
            </div>
        </div>

        <!-- Associations Management Section - Moved above the graph -->
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Keyword to Page Map</h2>
            <input type="hidden" id="aysa-current-project-id" value="<?php echo esc_attr((string) intval(get_option('aysa_project_id', 0))); ?>">
            <div class="aysa-info-box">
                <h3>What you can do here</h3>
                <ul>
                    <li>See which keyword is linked to which page/product/category</li>
                    <li>Open one row and edit SEO suggestions clearly, field by field</li>
                    <li>Use filters to focus only on what needs work now</li>
                </ul>
            </div>
            
            <!-- Tabs for Associations Management -->
            <div class="aysa-associations-tabs">
                <button type="button" class="aysa-tab-button active" data-tab="associations">Associations</button>
                <button type="button" class="aysa-tab-button" data-tab="optimization-schedule">Review Queue</button>
            </div>
            
            <!-- Associations Tab Content -->
            <div class="aysa-tab-content active" id="associations-tab">
                <div class="aysa-entity-type-tabs" id="aysa-entity-type-tabs">
                    <button type="button" class="aysa-entity-tab active" data-entity-tab="all">All Entities</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="product">Products</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="category">Categories</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="article">Articles</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="other">Other Entities</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="unlinked">No Keywords</button>
                    <button type="button" class="aysa-entity-tab" data-entity-tab="no-content">No Content</button>
                </div>

                <div id="aysa-coverage-summary" class="aysa-coverage-summary"></div>

                <div id="aysa-unlinked-entities-panel" class="aysa-unlinked-panel aysa-hidden">
                    <h3>Entities without keyword associations</h3>
                    <p>These entities exist in WordPress but are not linked to any keyword yet.</p>
                    <div class="aysa-unlinked-toolbar">
                        <div class="aysa-unlinked-settings">
                            <label>Max keywords
                                <input type="number" id="aysa-unlinked-max-keywords" min="1" max="10" value="3">
                            </label>
                            <label>Min words
                                <input type="number" id="aysa-unlinked-min-words" min="1" max="6" value="2">
                            </label>
                            <label>Max words
                                <input type="number" id="aysa-unlinked-max-words" min="1" max="8" value="4">
                            </label>
                            <label>Min score
                                <input type="number" id="aysa-unlinked-min-score" min="0" max="100" value="20">
                            </label>
                        </div>
                        <div class="aysa-unlinked-actions">
                            <button type="button" class="aysa-btn aysa-btn-primary" id="aysa-suggest-keywords-btn">Suggest Keyword Ideas</button>
                            <small id="aysa-suggest-keywords-status">Suggest: 10 rows/click</small>
                        </div>
                    </div>
                    <div class="aysa-table-responsive">
                        <table class="aysa-optimization-table" id="aysa-unlinked-entities-table">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Entity</th>
                                    <th>ID</th>
                                    <th>Suggested keywords</th>
                                    <th>Consumption</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td colspan="6" class="aysa-loading-cell">Loading entities...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div id="aysa-no-content-panel" class="aysa-unlinked-panel aysa-hidden">
                    <h3>Entities without AYSA content</h3>
                    <p>These entities are not marked as AYSA-generated yet and can be auto-generated in small batches.</p>
                    <div class="aysa-unlinked-toolbar">
                        <div class="aysa-unlinked-settings"></div>
                        <div class="aysa-unlinked-actions">
                            <button type="button" class="aysa-btn aysa-btn-secondary" id="aysa-content-gen-btn">Generate Content</button>
                            <small id="aysa-content-gen-status">Generate content for up to 3 eligible rows per run.</small>
                        </div>
                    </div>
                    <div class="aysa-table-responsive">
                        <table class="aysa-optimization-table" id="aysa-no-content-entities-table">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Entity</th>
                                    <th>ID</th>
                                    <th>Generated result</th>
                                    <th>Consumption</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td colspan="6" class="aysa-loading-cell">Loading entities...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Add Filters Section -->
                <div class="aysa-filters-section">
                    <div class="aysa-filter-group">
                    <input type="text" id="keyword-filter" class="aysa-filter-input" placeholder="Find keyword...">
                    <select id="associated-on-filter" class="aysa-filter-select">
                        <option value="">All Types</option>
                        <option value="Category">Category</option>
                        <option value="Product">Product</option>
                        <option value="Page">Page</option>
                        <option value="Post">Article</option>
                    </select>
                    <select id="status-filter" class="aysa-filter-select">
                        <option value="" selected>All Statuses</option>
                        <option value="needs-work">Needs Work</option>
                        <option value="good">Good</option>
                        <option value="poor">Poor</option>
                        <option value="processed">Processed</option>
                    </select>
                    <select id="links-filter" class="aysa-filter-select">
                        <option value="">All Links</option>
                        <option value="high-internal">High Internal</option>
                        <option value="low-internal">Low Internal</option>
                        <option value="high-external">High External</option>
                        <option value="low-external">Low External</option>
                    </select>
                    <select id="social-filter" class="aysa-filter-select">
                        <option value="">All Social</option>
                        <option value="high-social">High Mentions</option>
                        <option value="low-social">Low Mentions</option>
                    </select>
                    <button id="clear-filters" class="aysa-btn aysa-btn-secondary">Reset Filters</button>
                </div>
            </div>
            
                <div class="aysa-table-responsive">
                    <table class="aysa-optimization-table" id="aysa-associations-table">
                        <thead>
                            <tr>
                                <th>Entity Type</th>
                                <th>Page</th>
                                <th>Main Keyword</th>
                                <th>All Keywords</th>
                                <th>Optimized</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr class="aysa-loading-row">
                                <td colspan="6" class="aysa-loading-cell">
                                    <div class="aysa-loading-spinner"></div>
                                    <span>Loading associations data...</span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Optimization Schedule Tab Content -->
            <div class="aysa-tab-content" id="optimization-schedule-tab">
                <!-- Pending Reviews Section -->
                <div class="aysa-pending-reviews-container">
                    <h3>Pending Reviews</h3>
                    <p>Review and approve SEO suggestions before applying them to your content.</p>
                    
                    <!-- Bulk Actions for Pending Reviews -->
                    <div class="aysa-bulk-actions">
                        <h4 class="aysa-bulk-actions-title">Bulk Actions</h4>
                        <div class="aysa-bulk-actions-row">
                            <button class="aysa-btn aysa-btn-primary aysa-btn-success" id="approve-all-pending-reviews">
                                <span class="dashicons dashicons-yes-alt aysa-icon-mr-5"></span>
                                Approve All Pending Reviews
                            </button>
                            <button class="aysa-btn aysa-btn-secondary aysa-btn-danger" id="reject-all-pending-reviews">
                                <span class="dashicons dashicons-dismiss aysa-icon-mr-5"></span>
                                Reject All Pending Reviews
                            </button>
                            <span id="bulk-action-status" class="aysa-bulk-action-status"></span>
                        </div>
                    </div>
                    
                    <div class="aysa-table-responsive">
                        <table class="aysa-optimization-table" id="aysa-pending-reviews-table">
                            <thead>
                                <tr>
                                    <th>Content</th>
                                    <th>Type</th>
                                    <th>Keyword</th>
                                    <th>Generated</th>
                                    <th>Preview</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="aysa-loading-row">
                                    <td colspan="6" class="aysa-loading-cell">
                                        <div class="aysa-loading-spinner"></div>
                                        <span>Loading pending reviews...</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="aysa-schedule-container">
                    <h3>Optimization Schedule</h3>
                    <p>Manage and view scheduled optimization tasks for your content.</p>
                    
                    <div class="aysa-schedule-filters">
                        <select class="aysa-filter-select">
                            <option value="">All Schedules</option>
                            <option value="daily">Daily</option>
                            <option value="weekly">Weekly</option>
                            <option value="monthly">Monthly</option>
                        </select>
                        <select class="aysa-filter-select">
                            <option value="">All Types</option>
                            <option value="title-tags">Title Tags</option>
                            <option value="meta-descriptions">Meta Descriptions</option>
                            <option value="content">Content</option>
                            <option value="links">Links</option>
                        </select>
                        
                    </div>
                    
                    <div class="aysa-table-responsive">
                        <table class="aysa-optimization-table" id="aysa-schedule-table">
                            <thead>
                                <tr>
                                    <th>Schedule Name</th>
                                    <th>Type</th>
                                    <th>Frequency</th>
                                    <th>Next Run</th>
                                    <th>Last Run</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="aysa-loading-row">
                                    <td colspan="7" class="aysa-loading-cell">
                                        <div class="aysa-loading-spinner"></div>
                                        <span>Loading schedule data...</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Weekly Progress Chart - Moved below Associations Management -->
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Weekly Progress Trend</h2>
            <?php if (!empty($chart_data['weeks'])): ?>
            <div class="aysa-progress-chart-container">
                <canvas id="aysa-progress-chart" width="400" height="200"></canvas>
            </div>
            <?php else: ?>
            <div class="aysa-no-data">
                <p>No chart data available yet. Data will appear as optimization progress is tracked.</p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Association Detail Modal -->
        <div id="aysa-association-modal" class="aysa-modal">
            <div class="aysa-modal-content">
                <div class="aysa-modal-header">
                    <h2 class="aysa-modal-title">Association Details</h2>
                    <span class="aysa-modal-close">&times;</span>
                </div>
                <div class="aysa-modal-body">
                    <!-- Tabs for different optimization sections -->
                    <div class="aysa-modal-tabs">
                        <button class="aysa-modal-tab active" data-tab="title-tags">Title Tags</button>
                        <button class="aysa-modal-tab" data-tab="meta-descriptions">Meta Descriptions</button>
                        <button class="aysa-modal-tab" data-tab="content-optimization">Content Optimization</button>
                        <button class="aysa-modal-tab" data-tab="links-social">Links & Social</button>
                    </div>
                    
                    <!-- Title Tags Tab Content -->
                    <div class="aysa-modal-tab-content active" id="title-tags-content">
                        <h3>Title Tags Optimization</h3>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Current Title:</div>
                            <div class="aysa-modal-info-value" id="current-title"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Length:</div>
                            <div class="aysa-modal-info-value" id="title-length"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Status:</div>
                            <div class="aysa-modal-info-value" id="title-status"></div>
                        </div>
                        <div class="aysa-modal-edit-section">
                            <h4>Suggested Optimization</h4>
                            <textarea id="title-suggestion" class="aysa-modal-textarea"></textarea>
                            <button class="aysa-btn aysa-btn-primary aysa-modal-save" data-section="title">Save Changes</button>
                        </div>
                    </div>
                    
                    <!-- Meta Descriptions Tab Content -->
                    <div class="aysa-modal-tab-content" id="meta-descriptions-content">
                        <h3>Meta Descriptions Optimization</h3>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Current Description:</div>
                            <div class="aysa-modal-info-value" id="current-description"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Length:</div>
                            <div class="aysa-modal-info-value" id="description-length"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Status:</div>
                            <div class="aysa-modal-info-value" id="description-status"></div>
                        </div>
                        <div class="aysa-modal-edit-section">
                            <h4>Suggested Optimization</h4>
                            <textarea id="description-suggestion" class="aysa-modal-textarea"></textarea>
                            <button class="aysa-btn aysa-btn-primary aysa-modal-save" data-section="description">Save Changes</button>
                        </div>
                    </div>
                    
                    <!-- Content Optimization Tab Content -->
                    <div class="aysa-modal-tab-content" id="content-optimization-content">
                        <h3>Content Optimization</h3>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Word Count:</div>
                            <div class="aysa-modal-info-value" id="word-count"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Keyword Density:</div>
                            <div class="aysa-modal-info-value" id="keyword-density"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Status:</div>
                            <div class="aysa-modal-info-value" id="content-status"></div>
                        </div>
                        <div class="aysa-modal-edit-section">
                            <h4>Content Improvement Suggestions</h4>
                            <ul id="content-suggestions" class="aysa-modal-suggestions-list"></ul>
                        </div>
                    </div>
                    
                    <!-- Links & Social Tab Content -->
                    <div class="aysa-modal-tab-content" id="links-social-content">
                        <h3>Links & Social Metrics</h3>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Internal Links:</div>
                            <div class="aysa-modal-info-value" id="internal-links-count"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">External Links (Backlinks):</div>
                            <div class="aysa-modal-info-value" id="external-links-count"></div>
                        </div>
                        <div class="aysa-modal-info-row">
                            <div class="aysa-modal-info-label">Social Mentions:</div>
                            <div class="aysa-modal-info-value" id="social-mentions-count"></div>
                        </div>
                        <div class="aysa-modal-edit-section">
                            <h4>Links Assessment</h4>
                            <div id="links-analysis" class="aysa-modal-analysis">
                                <p>Internal links analysis will be displayed here based on the current metrics.</p>
                                <p>External links (backlinks) overview and opportunities will be shown here.</p>
                                <p>Social mentions breakdown by platform will be provided here.</p>
                            </div>
                            <button class="aysa-btn aysa-btn-primary aysa-modal-refresh-links" data-section="links">Refresh Data</button>
                        </div>
                    </div>
                </div>
                <div class="aysa-modal-footer">
                    <button class="aysa-btn aysa-btn-secondary" id="aysa-modal-close-btn">Close</button>
                </div>
            </div>
        </div>

    </div>
</div>

<style>
/* Base Styles */
.aysa-dashboard-wrapper {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    color: #333;
    background-color: #f8f9fa;
    padding: 20px;
    width: 100%;
    min-height: 100vh;
    box-sizing: border-box;
}

.aysa-dashboard-container {
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Header Styles */
.aysa-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-dashboard-title h1 {
    font-size: 22px;
    margin: 0 0 5px;
    font-weight: 500;
    color: #333;
}

.aysa-dashboard-title p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-dashboard-user {
    display: flex;
    align-items: center;
    gap: 15px;
}

.aysa-btn-text {
    background: none;
    color: #1a73e8;
    padding: 0;
    border: none;
    font-size: 14px;
    cursor: pointer;
}

.aysa-btn-text:hover {
    text-decoration: underline;
}

/* Search Intent Badge Styles */
.aysa-intent-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: capitalize;
    white-space: nowrap;
}

.aysa-intent-loading {
    background-color: #f3f4f6;
    color: #6b7280;
}

.aysa-intent-informational {
    background-color: #dbeafe;
    color: #1e40af;
}

.aysa-intent-navigational {
    background-color: #d1fae5;
    color: #059669;
}

.aysa-intent-transactional {
    background-color: #fef3c7;
    color: #d97706;
}

.aysa-intent-commercial {
    background-color: #fce7f3;
    color: #be185d;
}

.aysa-intent-unknown {
    background-color: #f3f4f6;
    color: #6b7280;
}

/* Panel Styles */
.aysa-panel {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px;
    color: #202124;
}

.aysa-onpage-quickstart {
    background: linear-gradient(180deg, #eef6ff 0%, #ffffff 90%);
    border: 1px solid #d8e7fb;
}

.aysa-onpage-steps {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 10px;
}

.aysa-onpage-step {
    background: #fff;
    border: 1px solid #dde6f3;
    border-radius: 8px;
    padding: 10px 12px;
    font-size: 13px;
    line-height: 1.4;
}

/* Overview Panel */
.aysa-overview-panel {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-optimization-status {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-status-label {
    font-weight: 500;
    margin-right: 15px;
    min-width: 120px;
}

.aysa-status-bar-container {
    flex: 1;
    height: 8px;
    background-color: #f1f3f4;
    border-radius: 4px;
    overflow: hidden;
    margin-right: 15px;
}

.aysa-status-bar {
    height: 100%;
    background-color: #1a73e8;
    border-radius: 4px;
}

.aysa-status-percentage {
    font-weight: 500;
    min-width: 40px;
    text-align: right;
}

/* Metrics Grid */
.aysa-metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.aysa-metric-card {
    background-color: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    border: 1px solid #e0e0e0;
}

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

.aysa-metric-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
}

.aysa-metric-icon .dashicons {
    color: white;
    font-size: 16px;
    width: 16px;
    height: 16px;
}

.aysa-metric-trend {
    font-size: 13px;
    font-weight: 500;
}

.aysa-metric-trend.positive {
    color: #34a853;
}

.aysa-metric-trend.negative {
    color: #ea4335;
}

.aysa-metric-name {
    font-size: 13px;
    color: #5f6368;
    margin-bottom: 5px;
}

.aysa-metric-value {
    font-size: 24px;
    font-weight: 500;
    color: #202124;
}

/* Info Box */
.aysa-info-box {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-info-box h3 {
    font-size: 14px;
    font-weight: 500;
    margin: 0 0 10px;
    color: #202124;
}

.aysa-info-box ul {
    margin: 0;
    padding-left: 20px;
    color: #5f6368;
    font-size: 13px;
}

.aysa-info-box li {
    margin-bottom: 5px;
}

/* Table Styles */
.aysa-table-responsive {
    overflow-x: auto;
    position: relative;
}

.aysa-optimization-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
}

.aysa-optimization-table th {
    text-align: left;
    padding: 12px 15px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    color: #5f6368;
    font-weight: 500;
}

.aysa-optimization-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e0e0e0;
}

#aysa-pending-reviews-table th {
    position: relative;
    z-index: 1;
    pointer-events: none;
}

#aysa-pending-reviews-table td,
#aysa-pending-reviews-table .aysa-action-buttons,
#aysa-pending-reviews-table .aysa-btn-preview,
#aysa-pending-reviews-table .aysa-btn-approve,
#aysa-pending-reviews-table .aysa-btn-reject {
    position: relative;
    z-index: 2;
}

.aysa-entity-url-cell {
    max-width: 460px;
    font-size: 12px;
    line-height: 1.4;
    white-space: normal;
    word-break: break-all;
}

.aysa-entity-url-cell a {
    color: #1a73e8;
    text-decoration: none;
}

.aysa-entity-url-cell a:hover {
    text-decoration: underline;
}

/* Status Indicators */
.aysa-status {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-status.good {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-status.warning {
    background-color: #fef7e0;
    color: #e37400;
}

.aysa-status.bad {
    background-color: #fce8e6;
    color: #ea4335;
}

/* Button Styles */
.aysa-btn {
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    border: none;
}

.aysa-btn-primary {
    background-color: #1a73e8;
    color: white;
}

.aysa-btn-secondary {
    background-color: #f8f9fa;
    color: #5f6368;
    border: 1px solid #dadce0;
}

.aysa-btn-icon {
    padding: 6px;
    width: 32px;
    height: 32px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 4px;
    background-color: #f8f9fa;
    border: 1px solid #dadce0;
    color: #5f6368;
}

.aysa-btn-icon:hover {
    background-color: #e8f0fe;
    border-color: #1a73e8;
    color: #1a73e8;
}

.aysa-btn-small {
    padding: 4px 8px;
    font-size: 12px;
}

.aysa-btn-history {
    background-color: #fff3e0;
    border-color: #ff9800;
    color: #ff9800;
}

.aysa-btn-generate {
    background-color: #e8f5e8;
    border-color: #4caf50;
    color: #4caf50;
}

/* Tab Styles */
.aysa-associations-tabs {
    display: flex;
    border-bottom: 1px solid #e0e0e0;
    margin-bottom: 20px;
}

.aysa-tab-button {
    padding: 12px 20px;
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    color: #5f6368;
    transition: all 0.2s;
}

.aysa-tab-button.active {
    color: #1a73e8;
    border-bottom-color: #1a73e8;
}

.aysa-tab-button:hover {
    color: #1a73e8;
    background-color: #f8f9fa;
}

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

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

.aysa-entity-type-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 0 0 14px;
}

.aysa-entity-tab {
    border: 1px solid #d0dae7;
    background: #f7fbff;
    color: #1f4c7a;
    border-radius: 16px;
    font-size: 12px;
    font-weight: 600;
    padding: 6px 12px;
    cursor: pointer;
}

.aysa-entity-tab.active {
    background: #1a73e8;
    color: #fff;
    border-color: #1a73e8;
}

.aysa-coverage-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 10px;
    margin-bottom: 14px;
}

.aysa-coverage-card {
    border: 1px solid #d8e2ee;
    border-radius: 8px;
    padding: 10px;
    background: #fff;
}

.aysa-coverage-card h4 {
    margin: 0 0 6px;
    font-size: 13px;
}

.aysa-coverage-meta {
    margin: 0;
    font-size: 12px;
    color: #5f6368;
}

.aysa-unlinked-panel {
    border: 1px solid #e3e7ed;
    border-radius: 8px;
    padding: 14px;
    margin-bottom: 14px;
    background: #fbfcff;
}

.aysa-unlinked-toolbar {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    flex-wrap: wrap;
    margin: 8px 0 12px;
}

.aysa-unlinked-settings {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: flex-end;
}

.aysa-unlinked-settings label {
    display: flex;
    flex-direction: column;
    font-size: 12px;
    color: #445;
    font-weight: 600;
}

.aysa-unlinked-settings input {
    width: 86px;
    margin-top: 4px;
}

.aysa-unlinked-actions {
    display: flex;
    flex-direction: column;
    gap: 6px;
    justify-content: center;
}

.aysa-suggestion-keyword {
    display: inline-block;
    margin: 2px 6px 2px 0;
    padding: 2px 7px;
    border-radius: 999px;
    background: #ecf3ff;
    border: 1px solid #cddfff;
    color: #1f4c7a;
    font-size: 11px;
    font-weight: 600;
}

.aysa-suggestion-meta {
    margin-top: 4px;
    font-size: 11px;
    color: #58606a;
}

.aysa-cost-pill {
    display: inline-block;
    border-radius: 999px;
    padding: 3px 8px;
    border: 1px solid #f1c77e;
    background: #fff5df;
    color: #8a5a00;
    font-size: 11px;
    font-weight: 700;
}

.aysa-unlinked-chip {
    display: inline-block;
    margin: 2px 4px 2px 0;
    padding: 2px 8px;
    border-radius: 999px;
    border: 1px solid #d5deea;
    background: #f5f8fc;
    font-size: 11px;
}

.aysa-entity-keywords .aysa-keyword-group {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 4px;
    flex-wrap: wrap;
}

.aysa-entity-keywords .aysa-keyword-title {
    margin-right: 2px;
    font-size: 11px;
    line-height: 1.25;
}

.aysa-entity-keywords .aysa-keyword-title-main {
    color: #0b3d91;
    font-weight: 700;
}

.aysa-entity-keywords .aysa-unlinked-chip-main {
    background: #eaf2ff;
    border-color: #8ab4f8;
    color: #0b3d91;
    font-weight: 700;
}

.aysa-entity-keywords .aysa-keyword-title-secondary {
    color: #4b5563;
    font-weight: 600;
}

.aysa-entity-keywords .aysa-unlinked-chip-secondary {
    background: #f8fafc;
    border-color: #d6dee8;
    color: #334155;
    font-weight: 500;
}

/* Action Buttons Container */
.aysa-action-buttons {
    display: flex;
    align-items: center;
    gap: 4px;
}

.aysa-status-meta {
    margin-top: 4px;
    font-size: 11px;
    color: #6b7280;
    line-height: 1.2;
}

.aysa-association-quality {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 600;
}

.aysa-association-quality-score {
    color: #6b7280;
    font-weight: 500;
}

.aysa-content-source-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
    line-height: 1.4;
}

.aysa-content-source-badge.aysa-source-generated {
    background: #e8f0fe;
    color: #1a56db;
}

.aysa-content-source-badge.aysa-source-original {
    background: #ecfdf3;
    color: #047857;
}

.aysa-content-source-badge.aysa-source-unknown {
    background: #f3f4f6;
    color: #6b7280;
}

.aysa-seo-score-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 700;
}

/* Status Badges */
.aysa-status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.aysa-status-good {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-status-warning {
    background-color: #fef7e0;
    color: #e37400;
}

.aysa-status-bad {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-status-active {
    background-color: #e8f5e8;
    color: #4caf50;
}

/* Schedule Container */
.aysa-schedule-container {
    padding: 20px 0;
}

.aysa-schedule-filters {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    align-items: center;
}

.aysa-schedule-filters .aysa-filter-select {
    min-width: 150px;
}

/* No Data Message */
.aysa-no-data {
    text-align: center;
    padding: 40px 20px;
    color: #5f6368;
    font-style: italic;
}

.aysa-btn-secondary {
    background-color: #f8f9fa;
    color: #5f6368;
    border: 1px solid #e0e0e0;
}

/* Color Classes */
.aysa-blue { background-color: #1a73e8; }
.aysa-green { background-color: #34a853; }
.aysa-purple { background-color: #9334e6; }
.aysa-orange { background-color: #fa7b17; }

/* Modal Styles */
.aysa-modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
}

.aysa-modal-content {
    position: relative;
    background-color: #fff;
    margin: 5% auto;
    padding: 0;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    width: 80%;
    max-width: 900px;
    animation: modalFadeIn 0.3s;
}

@keyframes modalFadeIn {
    from {opacity: 0; transform: translateY(-20px);}
    to {opacity: 1; transform: translateY(0);}
}

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

.aysa-modal-title {
    margin: 0;
    font-size: 18px;
    font-weight: 500;
}

.aysa-modal-close {
    color: #aaa;
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
}

.aysa-modal-close:hover {
    color: #333;
}

.aysa-modal-body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
}

.aysa-modal-footer {
    padding: 15px 20px;
    border-top: 1px solid #e0e0e0;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

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

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

.aysa-form-control {
    width: 100%;
    padding: 8px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    line-height: 1.5;
    box-sizing: border-box;
}

.aysa-form-control:focus {
    border-color: #1a73e8;
    outline: none;
    box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}

textarea.aysa-form-control {
    min-height: 100px;
    resize: vertical;
}

.aysa-character-count {
    font-size: 12px;
    color: #5f6368;
    margin-top: 5px;
    text-align: right;
}

.aysa-character-count-exceeded {
    color: #ea4335;
    font-weight: 500;
}

.aysa-modal-tabs {
    display: flex;
    margin-bottom: 20px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-modal-tab {
    background: none;
    border: none;
    padding: 10px 15px;
    font-size: 14px;
    font-weight: 500;
    color: #5f6368;
    cursor: pointer;
    position: relative;
}

.aysa-modal-tab.active {
    color: #1a73e8;
}

.aysa-modal-tab.active:after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #1a73e8;
}

.aysa-modal-tab-content {
    display: none;
}

.aysa-modal-tab-content.active {
    display: block;
}

.aysa-modal-info-row {
    display: flex;
    margin-bottom: 15px;
}

.aysa-modal-info-label {
    font-weight: 500;
    min-width: 150px;
    color: #5f6368;
}

.aysa-modal-info-value {
    flex: 1;
}

.aysa-modal-edit-section {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e0e0e0;
}

.aysa-modal-edit-section h4 {
    margin: 0 0 10px;
    font-size: 14px;
    font-weight: 500;
}

.aysa-modal-textarea {
    width: 100%;
    min-height: 100px;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    resize: vertical;
}

.aysa-modal-suggestions-list {
    margin: 0;
    padding-left: 20px;
}

.aysa-modal-suggestions-list li {
    margin-bottom: 8px;
}

/* Loading styles */
.aysa-loading-cell {
    text-align: center;
    padding: 30px !important;
}

.aysa-loading-spinner {
    display: inline-block;
    width: 24px;
    height: 24px;
    border: 3px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #1a73e8;
    animation: spin 1s ease-in-out infinite;
    margin-right: 10px;
    vertical-align: middle;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* Responsive Adjustments */
@media screen and (max-width: 1024px) {
    .aysa-metrics-grid {
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
}

@media screen and (max-width: 768px) {
    .aysa-dashboard-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .aysa-dashboard-user {
        flex-wrap: wrap;
    }
    
    .aysa-metrics-grid {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    }
    
    .aysa-optimization-table {
        min-width: 800px;
    }
    

}

<!-- Enhanced CSS for Progress Display -->
<style>
/* Progress-specific styles */
.aysa-status-change {
    font-size: 12px;
    margin-top: 5px;
    font-weight: 500;
}

.aysa-status-change.positive {
    color: #34a853;
}

.aysa-status-change.negative {
    color: #ea4335;
}

.aysa-metric-details {
    font-size: 11px;
    color: #666;
    margin-top: 4px;
}

.aysa-progress-chart-container {
    margin-top: 30px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

.aysa-progress-chart-container h3 {
    margin: 0 0 20px 0;
    font-size: 16px;
    font-weight: 500;
}

/* Icon color variants */
.aysa-metric-icon.aysa-blue {
    background-color: #1a73e8;
}

.aysa-metric-icon.aysa-green {
    background-color: #34a853;
}

.aysa-metric-icon.aysa-purple {
    background-color: #9334e6;
}

.aysa-metric-icon.aysa-orange {
    background-color: #f59e0b;
}

/* Pending Reviews Section */
.aysa-pending-reviews-container {
    margin-bottom: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

.aysa-pending-reviews-container h3 {
    margin: 0 0 10px 0;
    color: #1a73e8;
    font-size: 18px;
}

.aysa-pending-reviews-container p {
    margin: 0 0 20px 0;
    color: #666;
    font-size: 14px;
}

/* Button Styles for New Workflow */
.aysa-btn-success {
    background-color: #34a853;
    color: white;
    border: none;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
}

.aysa-btn-success:hover {
    background-color: #2d8f47;
}

.aysa-btn-danger {
    background-color: #ea4335;
    color: white;
    border: none;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
}

.aysa-btn-danger:hover {
    background-color: #d33b2c;
}

.aysa-btn-preview {
    background-color: #1a73e8;
    color: white;
    border: none;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s;
}

.aysa-btn-preview:hover {
    background-color: #1557b0;
}

/* SEO Preview Modal */
#aysa-seo-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
}

#aysa-seo-preview-modal .aysa-modal-content {
    background: white;
    border-radius: 8px;
    max-width: 600px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.aysa-preview-section {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    background: #f8f9fa;
}

.aysa-preview-section h3 {
    margin: 0 0 10px 0;
    font-size: 16px;
    color: #1a73e8;
}

.aysa-preview-current,
.aysa-preview-suggested {
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 4px;
}

.aysa-preview-current {
    background: #fff3cd;
    border: 1px solid #ffeaa7;
}

.aysa-preview-suggested {
    background: #d4edda;
    border: 1px solid #c3e6cb;
}

.aysa-preview-current strong,
.aysa-preview-suggested strong {
    color: #333;
    font-weight: 600;
}

/* Status Badge Updates */
.aysa-status-badge.aysa-status-approved {
    background-color: #34a853;
    color: white;
}

.aysa-status-badge.aysa-status-pending {
    background-color: #fbbc04;
    color: #333;
}
</style>

<!-- JavaScript for Chart and Progress Display -->
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    // Initialize progress chart if data is available
    <?php if (!empty($chart_data['weeks'])): ?>
    initProgressChart(<?php echo json_encode($chart_data); ?>);
    <?php endif; ?>
    
    // Initialize tab functionality
    initTabFunctionality();
    
    // Keep On-Page load lightweight: do not auto-run Search Intent batch on page open.
    // Manual trigger remains available for debugging/testing.
    window.manualSearchIntentTest = function() {
        loadSearchIntentsForKeywords();
    };
});

// Tab functionality for Associations Management
function initTabFunctionality() {
    const tabButtons = document.querySelectorAll('.aysa-tab-button');
    const tabContents = document.querySelectorAll('.aysa-tab-content');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const targetTab = this.getAttribute('data-tab');
            
            // Remove active class from all buttons and contents
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));
            
            // Add active class to clicked button
            this.classList.add('active');
            
            // Show corresponding tab content
            const targetContent = document.getElementById(targetTab + '-tab');
            if (targetContent) {
                targetContent.classList.add('active');
            }
        });
    });

    // Fallback handling for entity tabs (works even if external JS is delayed)
    const entityTabs = document.querySelectorAll('.aysa-entity-tab');
    entityTabs.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            entityTabs.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            const tab = this.getAttribute('data-entity-tab');
            const unlinkedPanel = document.getElementById('aysa-unlinked-entities-panel');
            const tableWrap = document.querySelector('#aysa-associations-table') ? document.querySelector('#aysa-associations-table').closest('.aysa-table-responsive') : null;

            if (tab === 'unlinked') {
                if (unlinkedPanel) unlinkedPanel.style.display = 'block';
                if (tableWrap) tableWrap.style.display = 'none';
            } else {
                if (unlinkedPanel) unlinkedPanel.style.display = 'none';
                if (tableWrap) tableWrap.style.display = '';
            }

            // If the external filtering logic exists, use it (source of truth)
            if (window.applyFilters && typeof window.applyFilters === 'function') {
                window.applyFilters();
            }
        });
    });
}

// Initialize progress chart
function initProgressChart(chartData) {
    const ctx = document.getElementById('aysa-progress-chart');
    if (!ctx || typeof Chart === 'undefined') {
        // Try to load Chart.js if not available
        const script = document.createElement('script');
        script.src = '<?php echo esc_js(AYSA_PLUGIN_URL . 'assets/js/vendor/chartjs-stub.js'); ?>';
        script.onload = function() {
            createChart(ctx, chartData);
        };
        document.head.appendChild(script);
        return;
    }
    
    createChart(ctx, chartData);
}

function createChart(ctx, chartData) {
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: chartData.weeks,
            datasets: [
                {
                    label: 'Overall Score',
                    data: chartData.overallScores,
                    borderColor: '#1a73e8',
                    backgroundColor: 'rgba(26, 115, 232, 0.1)',
                    tension: 0.4
                },
                {
                    label: 'Title Tags',
                    data: chartData.titleTagsScores,
                    borderColor: '#34a853',
                    backgroundColor: 'rgba(52, 168, 83, 0.1)',
                    tension: 0.4
                },
                {
                    label: 'Meta Descriptions',
                    data: chartData.metaDescriptionsScores,
                    borderColor: '#fbbc04',
                    backgroundColor: 'rgba(251, 188, 4, 0.1)',
                    tension: 0.4
                },
                {
                    label: 'Internal Links',
                    data: chartData.internalLinksScores,
                    borderColor: '#ea4335',
                    backgroundColor: 'rgba(234, 67, 53, 0.1)',
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Weekly Progress Tracking'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            }
        }
    });
}

// Search Intent functionality for Associations table
function initSearchIntentForAssociations() {
    // Monitor table for dynamic content loading
    const table = document.getElementById('aysa-associations-table');
    if (!table) {
        return;
    }

    // Lightweight one-time check only.
    const realRows = table.querySelectorAll('tbody tr:not(.aysa-loading-row):not(.aysa-sample-row)');
    if (realRows.length > 0) {
        loadSearchIntentsForKeywords();
    }
}

function loadSearchIntentsForKeywords() {
    const table = document.getElementById('aysa-associations-table');
    if (!table) {
        return;
    }
    
    const tbody = table.querySelector('tbody');
    if (!tbody) {
        return;
    }
    
    const tableRows = tbody.querySelectorAll('tr');
    const keywords = [];
    
    tableRows.forEach((row, index) => {
        // Skip only explicit loading/empty rows. Do not infer by text, because valid rows
        // can temporarily contain "loading" badges in individual cells.
        const isLoadingRow = row.classList.contains('aysa-loading-row') ||
                           row.classList.contains('aysa-empty-row');
        
        const isSampleRow = row.classList.contains('aysa-sample-row') ||
                          row.textContent.toLowerCase().includes('sample');
        
        if (isLoadingRow || isSampleRow) {
            return;
        }
        
        if (row.cells.length < 6) { // Need at least 6 cells for search intent column
            return;
        }
        
        const keywordCell = row.cells[4]; // 5th column (0-indexed) - Keyword
        const intentCell = row.cells[5];  // 6th column for intent - Search Intent
        
        if (keywordCell && keywordCell.textContent.trim()) {
            const keyword = keywordCell.textContent.trim();
            
            // Set loading state immediately
            if (intentCell) {
                intentCell.innerHTML = '<span class="aysa-intent-badge aysa-intent-loading">Loading...</span>';
            }
            
            keywords.push({
                keyword: keyword,
                rowIndex: index,
                row: row
            });
        }
    });
    
    if (keywords.length === 0) {
        return;
    }
    
    // Call API for batch search intent
    fetchSearchIntentBatch(keywords);
}

function fetchSearchIntentBatch(keywords) {
    const projectId = getProjectId();
    
    if (!projectId) {
        // Show error state in all badges
        keywords.forEach(keywordData => {
            const intentCell = keywordData.row.cells[5];
            if (intentCell) {
                intentCell.innerHTML = '<span class="aysa-intent-badge aysa-intent-unknown">No Project ID</span>';
            }
        });
        return;
    }
    
    // Local-first: process intents via WordPress AJAX handler (which saves to local DB).
    makeBatchIntentCall(keywords, projectId);
}

// Function to normalize diacritics for keyword comparison
function normalizeKeyword(keyword) {
    return keyword
        .toLowerCase()
        .normalize('NFD') // Decompose accented characters
        .replace(/[\u0300-\u036f]/g, '') // Remove diacritical marks
        .trim();
}

function checkExistingIntents(keywords, projectId) {
    makeBatchIntentCall(keywords, projectId);
}

function makeBatchIntentCall(keywords, projectId) {
    const requestData = {
        action: 'aysa_keyword_discovery_intent_batch',
        nonce: (typeof aysa_ajax !== 'undefined' ? aysa_ajax.nonce : ''),
        project_id: parseInt(projectId),
        keywords: JSON.stringify(keywords.map(k => k.keyword))
    };

    const ajaxUrl = (typeof aysa_ajax !== 'undefined' && aysa_ajax.ajax_url)
        ? aysa_ajax.ajax_url
        : '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';

    fetch(ajaxUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams(requestData).toString()
    })
    .then(response => {
        if (response.ok) {
            return response.json();
        } else {
            throw new Error('Failed to fetch search intents via AJAX');
        }
    })
    .then(data => {
        if (!data || !data.success) {
            throw new Error((data && data.data) ? String(data.data) : 'Intent batch failed');
        }
        updateIntentBadgesInTable(keywords, data.data || {});
    })
    .catch(error => {
        // Show error state in badges
        keywords.forEach(keywordData => {
            const intentCell = keywordData.row.cells[5]; // 6th column (index 5)
            if (intentCell) {
                intentCell.innerHTML = '<span class="aysa-intent-badge aysa-intent-unknown">Error</span>';
            }
        });
    });
}

function updateIntentBadgesInTable(keywords, apiData) {
    keywords.forEach(keywordData => {
        const intentCell = keywordData.row.cells[5]; // 6th column (index 5) - Search Intent column
        
        if (!intentCell) return;
        
        // Find intent for this keyword in API response
        let intent = 'unknown';
        const intentsMap = (apiData && typeof apiData === 'object' && apiData.intents && typeof apiData.intents === 'object')
            ? apiData.intents
            : null;
        if (intentsMap) {
            const normalized = normalizeKeyword(keywordData.keyword);
            const item = intentsMap[normalized] || intentsMap[keywordData.keyword] || null;
            if (item && item.intent) {
                intent = String(item.intent).toLowerCase();
            }
        }
        
        // Update badge
        const badgeClass = `aysa-intent-${intent}`;
        const displayIntent = intent.charAt(0).toUpperCase() + intent.slice(1);
        
        intentCell.innerHTML = `<span class="aysa-intent-badge ${badgeClass}">${displayIntent}</span>`;
    });
}

// Helper function to get project ID (should exist from other functionality)
function getProjectId() {
    // Try multiple sources for project ID
    
    // 1. localStorage
    let projectId = localStorage.getItem('aysa_project_id');
    if (projectId) {
        return projectId;
    }
    
    // 2. sessionStorage
    projectId = sessionStorage.getItem('aysa_project_id');
    if (projectId) {
        return projectId;
    }
    
    // 3. Try to get from global variables
    if (typeof window.aysaProjectId !== 'undefined') {
        return window.aysaProjectId;
    }
    
    // 4. Try to get from PHP variable
    <?php if (isset($aysa_project_id) && !empty($aysa_project_id)): ?>
    projectId = '<?php echo $aysa_project_id; ?>';
    if (projectId) {
        return projectId;
    }
    <?php endif; ?>
    
    // 5. Try to extract from current URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    projectId = urlParams.get('project_id') || urlParams.get('projectId');
    if (projectId) {
        return projectId;
    }
    
    return '';
}
</script>
