<?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;
}

// Add WordPress AJAX action handler for getting categories, pages, and products
add_action('wp_ajax_aysa_get_items', 'aysa_get_items');
function aysa_get_items() {
    // Verify nonce for security
    check_ajax_referer('aysa_get_items_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }
    
    // Get the item type from the request
    $type = isset($_POST['type']) ? sanitize_text_field($_POST['type']) : '';
    
    if (empty($type)) {
        wp_send_json_error('Type is required');
        return;
    }
    
    $items = array();
    
    switch ($type) {
        case 'Category':
            // Get product categories
            $args = array(
                'taxonomy'   => 'product_cat',
                'orderby'    => 'name',
                'hide_empty' => false,
            );
            $categories = get_terms($args);
            
            if (!is_wp_error($categories)) {
                foreach ($categories as $cat) {
                    $items[] = array(
                        'id'   => $cat->term_id,
                        'name' => $cat->name
                    );
                }
            }
            break;
            
        case 'Page':
            // Get pages (exclude drafts)
            $pages = get_pages(array(
                'post_status' => 'publish'
            ));
            
            if (!is_wp_error($pages)) {
                foreach ($pages as $page) {
                    $items[] = array(
                        'id'   => $page->ID,
                        'name' => $page->post_title
                    );
                }
            }
            break;
            
        case 'Product':
            // Get products
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => -1,
                'post_status'    => 'publish'
            );
            $products = get_posts($args);
            
            if (!is_wp_error($products)) {
                foreach ($products as $product) {
                    $items[] = array(
                        'id'   => $product->ID,
                        'name' => $product->post_title
                    );
                }
            }
            break;
            
        default:
            wp_send_json_error('Invalid type');
            return;
    }
    
    wp_send_json_success($items);
}

// Ensure dashicons are loaded
wp_enqueue_style('dashicons');
?>

<div class="aysa-admin aysa-competitor-gap">
    <!-- Page Title -->
    <div class="aysa-page-title">
        <h1>Competitor Keyword Gap</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>
        <div class="aysa-tab active">Competitor Keyword Gap</div>
        <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=content-strategy" class="aysa-tab">Content Strategy</a>
        <a href="admin.php?page=aysa-research&tab=sitemap-competition" class="aysa-tab">Sitemap Competition</a>
        
    </div>

    <!-- Main Content -->
    <div class="aysa-content">
        <div class="aysa-competitor-gap-content">
            <div class="aysa-panel">
                <h2 class="aysa-panel-title">
                    <span class="aysa-icon">🔍</span>
                    Competitor Analysis
                </h2>
                
                <!-- Domains Section (first row) -->
                <div class="aysa-domains-section">
                    <div class="aysa-domain-box">
                        <div class="aysa-domain-header">
                            <label>Root domain</label>
                            <i class="aysa-chevron-down"></i>
                        </div>
                        <div class="aysa-domain-content">
                            <div class="aysa-domain-label">
                                <span class="aysa-you-label">You</span>
                                <span class="aysa-your-domain"></span>
                            </div>
                        </div>
                    </div>
                    <div class="aysa-domain-box aysa-add-competitor">
                        <div class="aysa-domain-header">
                            <label>Add competitor domain</label>
                            <i class="aysa-chevron-down"></i>
                        </div>
                        <div class="aysa-domain-content">
                            <div class="aysa-domain-placeholder">
                                <input type="text" class="aysa-domain-input" placeholder="Enter domain">
                                <button class="aysa-add-btn">Add</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Competitor Domain Boxes Container (second row) -->
                <div class="aysa-competitor-boxes"></div>
                
                <div class="aysa-filters-section">
                    <div class="aysa-filter-box">
                        <input type="text" placeholder="Filter by keyword" class="aysa-filter-input">
                        <i class="aysa-search-icon"></i>
                    </div>
                    
                    <div class="aysa-filters-row">
                        <!-- Location and Language filters removed as per task requirements -->
                        <!--
                        <div class="aysa-filter-group">
                            <label>Location</label>
                            <select class="aysa-filter-dropdown location">
                                <option value="Romania">Romania</option>
                                <option value="United States">United States</option>
                                <option value="United Kingdom">United Kingdom</option>
                                <option value="Germany">Germany</option>
                            </select>
                        </div>
                        
                        <div class="aysa-filter-group">
                            <label>Language</label>
                            <select class="aysa-filter-dropdown language">
                                <option value="Romanian">Romanian</option>
                                <option value="English">English</option>
                                <option value="German">German</option>
                            </select>
                        </div>
                        -->
                        
                        <div class="aysa-actions-section">
                            <div class="aysa-flex-end">
                                <button class="aysa-refresh-data-btn" id="aysa-refresh-competitor-gap" title="Refresh competitor gap data from API">
                                    <span class="dashicons dashicons-update"></span> Refresh Data
                                    <span class="aysa-credit-badge cost-very-high">60 cr</span>
                                </button>
                                <button class="aysa-compare-btn">Compare</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Competitor Analysis Results Table -->
                <div class="aysa-competitor-analysis-results" style="margin-top: 20px; display: none;">
                    <h3>Competitor Analysis Results</h3>
                    <div class="aysa-table-responsive">
                        <table class="aysa-competitor-table">
                            <thead>
                                <tr>
                                    <th rowspan="2">Domain</th>
                                    <th rowspan="2">Domain Authority</th>
                                    <th colspan="5">Organic</th>
                                    <th colspan="5">Paid</th>
                                </tr>
                                <tr>
                                    <th>KW<br>(1-3)</th>
                                    <th>KW<br>(4-10)</th>
                                    <th>KW<br>(11-20)</th>
                                    <th>Total<br>KW</th>
                                    <th>ETV</th>
                                    <th>KW<br>(1-3)</th>
                                    <th>KW<br>(4-10)</th>
                                    <th>KW<br>(11-20)</th>
                                    <th>Total<br>KW</th>
                                    <th>ETV</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Loading indicator -->
                                <tr class="aysa-loading-row">
                                    <td colspan="12" class="aysa-loading-cell">
                                        <div class="aysa-loading-container">
                                            <span class="dashicons dashicons-update aysa-spinning"></span>
                                            <span class="aysa-loading-text">Loading competitor data...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <div class="aysa-results-container">
                <div class="aysa-results-panel">
                    <div class="aysa-tabs-container">
                        <div class="aysa-tab-buttons">
                            <button class="aysa-tab-btn active">You</button>
                            <!-- Competitor tabs will be added dynamically -->
                        </div>

                        <div class="aysa-filter-pills">
                            <button class="aysa-pill active">All</button>
                            <button class="aysa-pill">Missing</button>
                            <button class="aysa-pill">Common</button>
                        </div>
                    </div>
                    
                    <div class="aysa-results-table">
                        <div class="aysa-table-actions">
                            <div class="aysa-bulk-actions" style="display: none;">
                                <div class="aysa-selection-info">
                                    <span class="aysa-selected-count">0</span> keywords selected
                                </div>
                                <div class="aysa-bulk-buttons">
                                    <button class="aysa-bulk-associate-btn">
                                        <span class="dashicons dashicons-networking"></span>
                                        Add to Keyword Research
                                    </button>
                                    <button class="aysa-clear-selection-btn">
                                        <span class="dashicons dashicons-dismiss"></span>
                                        Clear Selection
                                    </button>
                                </div>
                            </div>
                        </div>
                        <table class="aysa-keywords-table">
                            <thead>
                                <tr>
                                    <th class="aysa-select-col">
                                        <input type="checkbox" id="select-all-keywords" class="aysa-checkbox-all">
                                    </th>
                                    <th>Keyword</th>
                                    <th>Volume</th>
                                    <th class="aysa-action-col">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Înlocuim datele dummy cu un loading indicator -->
                                <tr class="aysa-loading-row">
                                    <td colspan="4" class="aysa-loading-cell">
                                        <div class="aysa-loading-container">
                                            <span class="dashicons dashicons-update aysa-spinning"></span>
                                            <span class="aysa-loading-text">Initializing data...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="aysa-overlap-panel">
                    <div class="aysa-overlap-header">
                        <h3>Keyword Overlap</h3>
                        <div class="aysa-competitor-selector">
                            <!-- Competitor selector will be added dynamically -->
                        </div>
                    </div>
                    <div class="aysa-overlap-chart">
                        <div class="aysa-venn-diagram">
                            <div class="aysa-venn-circles">
                                <div class="aysa-venn-circle aysa-venn-left"></div>
                                <div class="aysa-venn-circle aysa-venn-right"></div>
                            </div>
                        </div>
                        <div class="aysa-overlap-legend">
                            <!-- Legend items will be added dynamically -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

/* 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: #f8f9fa;
    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 Area */
.aysa-content {
    padding: 20px;
    flex-grow: 1;
}

.aysa-competitor-gap-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* Panel Styles */
.aysa-panel {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 20px;
}

.aysa-panel-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
}

/* Domains Section */
.aysa-domains-section {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 20px;
}

.aysa-domain-box {
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    flex: 1;
    min-width: 200px;
    max-width: 300px;
}

.aysa-domain-header {
    background: #f8f9fa;
    padding: 8px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-domain-header label {
    font-size: 12px;
    color: #666;
}

.aysa-chevron-down::after {
    content: '▼';
    font-size: 8px;
    color: #666;
}

.aysa-domain-content {
    padding: 10px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.aysa-domain-label {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-you-label {
    display: inline-block;
    background: #f1f3f4;
    color: #666;
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 3px;
}

.aysa-domain-content-inner {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-competitor-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    background: #34a853;
    border-radius: 50%;
}

.aysa-domain-placeholder {
    display: flex;
    width: 100%;
    gap: 8px;
}

.aysa-remove-btn {
    background: none;
    border: none;
    color: #999;
    cursor: pointer;
    font-size: 18px;
    padding: 0;
}

/* Filters Section */
.aysa-filters-section {
    margin-bottom: 20px;
    margin-top: 30px;
}

.aysa-filter-box {
    position: relative;
    margin-bottom: 15px;
}

.aysa-filter-input {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-search-icon {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
}

.aysa-filters-row {
    display: flex;
    gap: 10px;
}

.aysa-filter-group {
    display: flex;
    flex-direction: column;
    margin-right: 15px;
}

.aysa-filter-group label {
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
}

.aysa-filter-dropdown {
    padding: 8px 12px;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    cursor: pointer;
    font-size: 13px;
    min-width: 150px;
}

.aysa-icon {
    color: #1a73e8;
    margin-right: 10px;
}

/* Actions Section */
.aysa-actions-section {
    margin-top: 20px;
}

.aysa-flex-end {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.aysa-cancel-btn {
    padding: 8px 16px;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
}

.aysa-compare-btn {
    padding: 8px 16px;
    background: #34a853;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    font-weight: 500;
}

/* Results Container */
.aysa-results-container {
    display: flex;
    gap: 20px;
}

.aysa-results-panel {
    flex: 1;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
}

.aysa-overlap-panel {
    flex: 1;
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden;
}

/* Tabs Container */
.aysa-tabs-container {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-tab-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.aysa-tab-btn {
    background: none;
    border: none;
    padding: 6px 12px;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
}

.aysa-tab-btn.active {
    background: #e8f0fe;
    color: #1a73e8;
    font-weight: 500;
}

.aysa-filter-pills {
    display: flex;
    gap: 8px;
}

.aysa-pill {
    background: none;
    border: 1px solid #e0e0e0;
    padding: 6px 12px;
    font-size: 13px;
    border-radius: 4px;
    cursor: pointer;
}

.aysa-pill.active {
    background: #e8f0fe;
    border-color: #1a73e8;
    color: #1a73e8;
}

/* Results Table */
.aysa-results-table {
    padding: 0;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    overflow: hidden;
}

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

.aysa-results-table th {
    text-align: left;
    padding: 12px 15px;
    font-size: 13px;
    font-weight: 500;
    color: #666;
    background: #fafafa;
    border-bottom: 1px solid #e8e8e8;
}

.aysa-results-table td {
    padding: 12px 15px;
    font-size: 14px;
    border-bottom: 1px solid #e8e8e8;
}

.aysa-keyword-cell {
    width: auto;
}

.aysa-keyword-link {
    color: #4285f4;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.aysa-arrow {
    font-size: 12px;
    color: #999;
    display: inline-block;
    margin-left: 2px;
}

.aysa-volume-cell {
    text-align: right;
    color: #333;
    width: 100px;
}

.aysa-action-col {
    width: 120px;
    text-align: right;
    padding-right: 16px;
}

.aysa-action-btn.associate {
    background-color: #4285f4;
    border: none;
    border-radius: 4px;
    padding: 6px 16px;
    font-size: 13px;
    color: white;
    cursor: pointer;
    transition: background-color 0.2s;
    min-width: 80px;
}

.aysa-action-btn.associate:hover {
    background-color: #3367d6;
}

/* Action Dropdown Styles */
.aysa-action-dropdown {
    position: relative;
    display: inline-block;
}

.aysa-action-btn {
    background-color: #4285f4;
    border: none;
    border-radius: 4px;
    padding: 6px 16px;
    font-size: 13px;
    color: white;
    cursor: pointer;
    transition: background-color 0.2s;
    min-width: 80px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.aysa-action-btn:hover {
    background-color: #3367d6;
}

.aysa-action-btn:after {
    content: '▼';
    font-size: 10px;
    margin-left: 4px;
}

.aysa-dropdown-content {
    display: none;
    position: absolute;
    background-color: white;
    min-width: 200px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    border-radius: 4px;
    z-index: 1000;
    border: 1px solid #ddd;
    right: 0;
    top: 100%;
    margin-top: 2px;
}

.aysa-action-dropdown.open .aysa-dropdown-content {
    display: block;
}

.aysa-dropdown-item {
    color: #333;
    padding: 10px 16px;
    text-decoration: none;
    display: block;
    font-size: 14px;
    border-bottom: 1px solid #f1f1f1;
    transition: background-color 0.2s;
}

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

.aysa-dropdown-item:hover {
    background-color: #f8f9fa;
    color: #333;
    text-decoration: none;
}

.aysa-add-keyword-item {
    color: #28a745 !important;
}

.aysa-add-keyword-item:hover {
    background-color: #f8fff8;
    color: #1e7e34 !important;
}

.aysa-dropdown-item.dropdown-item-associated {
    background-color: #e8f5e8;
    color: #2e7d2e;
}

.aysa-dropdown-item.dropdown-item-associated .dashicons {
    color: #2e7d2e;
}

.aysa-dropdown-divider {
    height: 1px;
    background-color: #e0e0e0;
    margin: 4px 0;
}

.aysa-dropdown-content.aysa-dropdown-loading .aysa-dropdown-item {
    opacity: 0.5;
    pointer-events: none;
}

.aysa-dropdown-content.aysa-dropdown-processing .aysa-dropdown-item {
    opacity: 0.5;
    pointer-events: none;
}

.aysa-disabled-link {
    opacity: 0.5;
    pointer-events: none;
    cursor: not-allowed;
}

.aysa-secondary-dropdown {
    position: absolute;
    left: 100%;
    top: 0;
    background: white;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    min-width: 220px;
    max-height: 200px;
    overflow-y: auto;
    z-index: 1001;
}

.aysa-loading-item {
    padding: 12px 16px;
    color: #666;
    text-align: center;
    font-style: italic;
}

.aysa-dropdown-item-secondary {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    color: #333;
    text-decoration: none;
    border-bottom: 1px solid #f1f1f1;
    cursor: pointer;
    transition: background-color 0.2s;
}

.aysa-dropdown-item-secondary:hover {
    background-color: #f8f9fa;
}

.aysa-dropdown-item-secondary.aysa-item-associated,
.aysa-dropdown-item.aysa-item-associated {
    background-color: #e8f5e8;
    color: #2e7d2e;
}

.aysa-dropdown-item.aysa-item-has-associations {
    background-color: #fff3cd;
    color: #856a00;
}

.aysa-spinning {
    animation: aysa-spin 1s linear infinite;
}

@keyframes aysa-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.aysa-keywords-table tr:hover {
    background-color: #f8f9fa;
}

/* Bulk Selection Styles */
.aysa-select-col {
    width: 40px !important;
    text-align: center !important;
    padding: 8px !important;
}

.aysa-checkbox-all,
.aysa-keyword-checkbox {
    width: 16px;
    height: 16px;
    cursor: pointer;
    accent-color: #4285f4;
}

.aysa-bulk-actions {
    padding: 16px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 4px 4px 0 0;
}

.aysa-selection-info {
    font-size: 14px;
    color: #666;
    font-weight: 500;
}

.aysa-selected-count {
    color: #4285f4;
    font-weight: 600;
}

.aysa-bulk-buttons {
    display: flex;
    gap: 12px;
    align-items: center;
}

.aysa-bulk-associate-btn {
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    color: white;
    border: none;
    border-radius: 6px;
    padding: 10px 16px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(66, 133, 244, 0.3);
}

.aysa-bulk-associate-btn:hover:not(:disabled) {
    background: linear-gradient(135deg, #3367d6 0%, #2451cc 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(66, 133, 244, 0.4);
}

.aysa-bulk-associate-btn:disabled {
    background: #ccc;
    color: #888;
    cursor: not-allowed;
    box-shadow: none;
    opacity: 0.6;
}

.aysa-bulk-associate-btn.aysa-btn-waiting {
    background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
    cursor: not-allowed;
}

.aysa-clear-selection-btn {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    color: #666;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 16px;
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease;
}

.aysa-clear-selection-btn:hover {
    background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
    color: #495057;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Selected row styling */
.aysa-keywords-table tr.aysa-row-selected {
    background-color: #e3f2fd !important;
    border-left: 3px solid #4285f4;
}

.aysa-keywords-table tr.aysa-row-selected:hover {
    background-color: #bbdefb !important;
}

/* Processing state for bulk operations */
.aysa-keywords-table tr.aysa-row-processing {
    background-color: #fff3e0 !important;
    opacity: 0.7;
}

.aysa-keywords-table tr.aysa-row-success {
    background-color: #e8f5e8 !important;
    border-left: 3px solid #4caf50;
}

.aysa-keywords-table tr.aysa-row-error {
    background-color: #fde7e7 !important;
    border-left: 3px solid #f44336;
}

/* Selected Keywords Association Modal Styles */
.aysa-selected-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999999;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.aysa-selected-modal-overlay.aysa-modal-show {
    opacity: 1;
    visibility: visible;
}

.aysa-selected-modal {
    background: white;
    border-radius: 8px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    max-width: 500px;
    width: 90%;
    max-height: 90vh;
    overflow: hidden;
    transform: scale(0.7) translateY(-50px);
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.aysa-selected-modal-overlay.aysa-modal-show .aysa-selected-modal {
    transform: scale(1) translateY(0);
}

.aysa-selected-modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    color: white;
}

.aysa-selected-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-selected-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    color: white;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
    opacity: 0.8;
}

.aysa-selected-modal-close:hover {
    background-color: rgba(255, 255, 255, 0.1);
    opacity: 1;
    transform: scale(1.1);
}

.aysa-selected-modal-body {
    padding: 24px;
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.aysa-selected-icon {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(66, 133, 244, 0.4);
}

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

.aysa-selected-message {
    flex-grow: 1;
}

.aysa-selected-message p {
    margin: 0 0 12px 0;
    font-size: 16px;
    line-height: 1.5;
    color: #333;
}

.aysa-selected-message p:last-child {
    margin-bottom: 0;
}

.aysa-selected-warning {
    font-size: 14px !important;
    color: #6c757d !important;
    font-style: italic;
}

.aysa-selected-modal-footer {
    padding: 20px 24px;
    border-top: 1px solid #e5e5e5;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: #f8f9fa;
}

.aysa-selected-btn-cancel,
.aysa-selected-btn-confirm {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    min-width: 100px;
    position: relative;
    overflow: hidden;
}

.aysa-selected-btn-cancel {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    color: #6c757d;
    border: 1px solid #dee2e6;
}

.aysa-selected-btn-cancel:hover {
    background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
    color: #495057;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.aysa-selected-btn-confirm {
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
}

.aysa-selected-btn-confirm:hover {
    background: linear-gradient(135deg, #3367d6 0%, #2451cc 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(66, 133, 244, 0.4);
}

.aysa-selected-btn-confirm:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(66, 133, 244, 0.3);
}

/* Competitor Association Modal Styles */
.aysa-competitor-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999999;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.aysa-competitor-modal-overlay.aysa-modal-show {
    opacity: 1;
    visibility: visible;
}

.aysa-competitor-modal {
    background: white;
    border-radius: 8px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    max-width: 500px;
    width: 90%;
    max-height: 90vh;
    overflow: hidden;
    transform: scale(0.7) translateY(-50px);
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.aysa-competitor-modal-overlay.aysa-modal-show .aysa-competitor-modal {
    transform: scale(1) translateY(0);
}

.aysa-competitor-modal-header {
    padding: 20px 24px;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    color: white;
}

.aysa-competitor-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-competitor-modal-close {
    background: none;
    border: none;
    font-size: 24px;
    color: white;
    cursor: pointer;
    padding: 0;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.2s ease;
    opacity: 0.8;
}

.aysa-competitor-modal-close:hover {
    background-color: rgba(255, 255, 255, 0.1);
    opacity: 1;
    transform: scale(1.1);
}

.aysa-competitor-modal-body {
    padding: 24px;
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.aysa-competitor-icon {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(66, 133, 244, 0.4);
}

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

.aysa-competitor-message {
    flex-grow: 1;
}

.aysa-competitor-message p {
    margin: 0 0 12px 0;
    font-size: 16px;
    line-height: 1.5;
    color: #333;
}

.aysa-competitor-message p:last-child {
    margin-bottom: 0;
}

.aysa-competitor-warning {
    font-size: 14px !important;
    color: #6c757d !important;
    font-style: italic;
}

.aysa-competitor-modal-footer {
    padding: 20px 24px;
    border-top: 1px solid #e5e5e5;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: #f8f9fa;
}

.aysa-competitor-btn-cancel,
.aysa-competitor-btn-confirm {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    min-width: 100px;
    position: relative;
    overflow: hidden;
}

.aysa-competitor-btn-cancel {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    color: #6c757d;
    border: 1px solid #dee2e6;
}

.aysa-competitor-btn-cancel:hover {
    background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
    color: #495057;
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.aysa-competitor-btn-confirm {
    background: linear-gradient(135deg, #4285f4 0%, #3367d6 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
}

.aysa-competitor-btn-confirm:hover {
    background: linear-gradient(135deg, #3367d6 0%, #2451cc 100%);
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(66, 133, 244, 0.4);
}

.aysa-competitor-btn-confirm:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(66, 133, 244, 0.3);
}

/* Overlap Section */
.aysa-overlap-header {
    padding: 15px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-overlap-header h3 {
    font-size: 16px;
    font-weight: 500;
    margin: 0;
}

.aysa-overlap-chart {
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20px;
}

.aysa-venn-diagram {
    width: 100%;
    height: 300px;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.aysa-venn-circles {
    position: relative;
    width: 100%;
    height: 280px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.aysa-venn-circle {
    position: absolute;
    width: 280px;
    height: 280px;
    border-radius: 50%;
    opacity: 0.7;
    transition: all 0.3s ease;
    mix-blend-mode: multiply;
}

.aysa-venn-left {
    background: #90caf9;
    z-index: 1;
}

.aysa-venn-right {
    background: #a5d6a7;
    z-index: 1;
}

.aysa-venn-intersection {
    display: none;
}

.aysa-overlap-legend {
    display: flex;
    flex-direction: column;
    gap: 15px;
    width: 100%;
    max-width: 300px;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.aysa-legend-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px;
    border-radius: 4px;
    transition: background-color 0.2s ease;
}

.aysa-legend-item:hover {
    background-color: #f8f9fa;
}

.aysa-checkbox-wrapper {
    position: relative;
    display: inline-block;
    width: 20px;
    height: 20px;
}

.aysa-checkbox-label {
    position: absolute;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    background-color: #fff;
    border: 2px solid #ddd;
    border-radius: 4px;
    transition: all 0.2s ease;
}

.aysa-checkbox:checked + .aysa-checkbox-label {
    border-width: 0;
}

.aysa-checkbox-blue:checked + .aysa-checkbox-label {
    background: linear-gradient(135deg, #1a73e8 0%, #1557b0 100%);
}

.aysa-checkbox-green:checked + .aysa-checkbox-label {
    background: linear-gradient(135deg, #34a853 0%, #2d8745 100%);
}

.aysa-domain-name {
    flex-grow: 1;
    font-size: 14px;
    color: #333;
}

.aysa-keyword-count {
    font-weight: 600;
    color: #1a73e8;
    background: #e8f0fe;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 13px;
    min-width: 40px;
    text-align: center;
}

.aysa-competitor-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
}

.aysa-competitor-btn {
    background: none;
    border: 1px solid #e0e0e0;
    padding: 6px 12px;
    font-size: 13px;
    border-radius: 4px;
    cursor: pointer;
}

.aysa-competitor-btn.active {
    background: #e8f0fe;
    border-color: #1a73e8;
    color: #1a73e8;
}

.aysa-keywords-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
    background-color: white;
    border-top: 1px solid #e8e8e8;
}

.aysa-keywords-table th, 
.aysa-keywords-table td {
    padding: 12px 16px;
    text-align: left;
    border-bottom: 1px solid #e8e8e8;
    background-color: #fff;
}

.aysa-keywords-table tr {
    border-bottom: 1px solid #e8e8e8;
}

.aysa-keywords-table th {
    color: #666;
    font-weight: 500;
    font-size: 13px;
    background-color: #fafafa;
    border-bottom: 1px solid #e8e8e8;
}

.aysa-keyword-cell {
    width: auto;
}

.aysa-keyword-link {
    color: #4285f4;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.aysa-arrow {
    font-size: 12px;
    color: #999;
    display: inline-block;
    margin-left: 2px;
}

.aysa-volume-cell {
    text-align: right;
    color: #333;
    width: 100px;
}

.aysa-action-col {
    width: 120px;
    text-align: right;
    padding-right: 16px;
}

.aysa-action-btn.associate {
    background-color: #4285f4;
    border: none;
    border-radius: 4px;
    padding: 6px 16px;
    font-size: 13px;
    color: white;
    cursor: pointer;
    transition: background-color 0.2s;
    min-width: 80px;
}

.aysa-action-btn.associate:hover {
    background-color: #3367d6;
}

.aysa-keywords-table tr:hover {
    background-color: #f8f9fa;
}

.aysa-results-table {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    overflow: hidden;
}

/* Remove external link icon since we're using the arrow */
.aysa-external-link {
    display: none;
}

/* Style for add competitor input and button */
.aysa-domain-input {
    flex-grow: 1;
    padding: 6px 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.aysa-add-btn {
    background-color: #1a73e8;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
}

/* Stilizare pentru loading indicator */
.aysa-loading-row {
    background: #f9f9f9 !important;
}

.aysa-loading-cell {
    text-align: center !important;
    padding: 40px 20px !important;
}

.aysa-loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 15px;
}

.aysa-loading-container .dashicons {
    font-size: 32px;
    width: 32px;
    height: 32px;
    color: #1a73e8;
}

.aysa-loading-text {
    font-size: 16px;
    color: #666;
}

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

.aysa-spinning {
    animation: aysa-spin 1.5s linear infinite;
}

/* Stiluri pentru mesajele de tip empty */
.aysa-empty-message {
    text-align: center !important;
    padding: 40px 20px !important;
    color: #666;
    font-size: 15px;
    background-color: #f9f9f9;
}

/* Competitor boxes in second row */
.aysa-competitor-boxes {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-top: 15px;
    margin-bottom: 30px;
}

/* Competitor analysis results table */
.aysa-competitor-analysis-results h3 {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #333;
}

.aysa-table-responsive {
    overflow-x: auto;
    margin-bottom: 20px;
    border: 1px solid #e0e0e0;
    border-radius: 3px;
}

.aysa-competitor-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
    background-color: white;
    border: none;
}

.aysa-competitor-table th, 
.aysa-competitor-table td {
    padding: 10px 8px;
    text-align: center;
    border: 1px solid #e0e0e0;
}

.aysa-competitor-table th {
    background-color: #f8f9fa;
    font-weight: 500;
    color: #666;
}

.aysa-competitor-table th:first-child,
.aysa-competitor-table td:first-child {
    text-align: left;
}

.aysa-competitor-table tbody tr:nth-child(even) {
    background-color: #f9f9f9;
}

.aysa-competitor-table tbody tr:hover {
    background-color: #f5f8ff;
}

.aysa-authority-higher {
    color: #34a853;
    font-weight: 500;
}

.aysa-authority-lower {
    color: #ea4335;
    font-weight: 500;
}

.aysa-btn-associated {
    background-color: #4caf50 !important;
}

/* Visual styling for associated keyword rows */
.aysa-keywords-table tr.aysa-row-associated {
    background-color: #e8f5e8 !important;
    border-left: 3px solid #4caf50;
}

.aysa-keywords-table tr.aysa-row-associated:hover {
    background-color: #d4edda !important;
}

.aysa-keywords-table tr.aysa-row-associated td {
    background-color: transparent;
}

/* Visual styling for common keyword rows (same as associated but different semantic meaning) */
.aysa-keywords-table tr.aysa-row-common {
    background-color: #e8f5e8 !important;
    border-left: 3px solid #4caf50;
}

.aysa-keywords-table tr.aysa-row-common:hover {
    background-color: #d4edda !important;
}

.aysa-keywords-table tr.aysa-row-common td {
    background-color: transparent;
}

.aysa-keywords-table tr.aysa-row-in-research {
    background-color: #e7f6ec !important;
    border-left: 3px solid #2e7d32;
}

.aysa-keywords-table tr.aysa-row-in-research:hover {
    background-color: #d9f0e2 !important;
}

.aysa-keywords-table tr.aysa-row-in-research td {
    background-color: transparent;
}

.aysa-inline-pill {
    display: inline-block;
    margin-left: 8px;
    padding: 2px 8px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 600;
    line-height: 1.4;
    vertical-align: middle;
}

.aysa-inline-pill-success {
    color: #1b5e20;
    background: #d5f1dc;
    border: 1px solid #a7dfb5;
}

.aysa-associate-all {
    margin-top: 15px;
    width: 100%;
    text-align: center;
}

.aysa-associate-all-btn {
    background-color: #4285f4;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
    cursor: pointer;
    font-weight: 500;
    transition: background-color 0.2s;
    width: 100%;
}

.aysa-associate-all-btn:hover {
    background-color: #3367d6;
}

.aysa-associate-all-btn.aysa-btn-associated {
    background-color: #4caf50 !important;
}

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

.aysa-spinning {
    animation: spin 1.5s linear infinite;
}

/* Notification styles */
.aysa-notification {
    position: fixed;
    top: 30px;
    right: 30px;
    padding: 12px 20px;
    border-radius: 8px;
    color: white;
    font-size: 14px;
    font-weight: 500;
    z-index: 9999;
    box-shadow: 0 4px 12px rgba(0,0,0,0.12);
    animation: slideIn 0.6s cubic-bezier(0.16, 1, 0.3, 1);
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 280px;
    max-width: 350px;
    backdrop-filter: blur(8px);
    border: 1px solid rgba(255,255,255,0.1);
    transform-origin: right top;
}

.aysa-notification::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 4px;
    border-radius: 8px 0 0 8px;
}

.aysa-notification-info {
    background: linear-gradient(135deg, rgba(33, 150, 243, 0.95), rgba(33, 150, 243, 0.85));
}

.aysa-notification-info::before {
    background: linear-gradient(to bottom, #1976D2, #2196F3);
}

.aysa-notification-success {
    background: linear-gradient(135deg, rgba(76, 175, 80, 0.95), rgba(76, 175, 80, 0.85));
}

.aysa-notification-success::before {
    background: linear-gradient(to bottom, #2E7D32, #4CAF50);
}

.aysa-notification-error {
    background: linear-gradient(135deg, rgba(244, 67, 54, 0.95), rgba(244, 67, 54, 0.85));
}

.aysa-notification-error::before {
    background: linear-gradient(to bottom, #D32F2F, #F44336);
}

.aysa-notification-loading {
    background: linear-gradient(135deg, rgba(255, 152, 0, 0.95), rgba(255, 152, 0, 0.85));
}

.aysa-notification-loading::before {
    background: linear-gradient(to bottom, #F57C00, #FF9800);
}

.aysa-notification .dashicons {
    font-size: 20px;
    width: 20px;
    height: 20px;
    filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
}

@keyframes slideIn {
    from {
        transform: translateX(100%) scale(0.8);
        opacity: 0;
    }
    to {
        transform: translateX(0) scale(1);
        opacity: 1;
    }
}

@keyframes fadeOut {
    from {
        transform: translateX(0) scale(1);
        opacity: 1;
    }
    to {
        transform: translateX(100%) scale(0.8);
        opacity: 0;
    }
}

.aysa-notification.fade-out {
    animation: fadeOut 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}

/* Add styles for waiting button state */
.aysa-btn-waiting {
    background-color: #cccccc !important;
    cursor: not-allowed !important;
    opacity: 0.7 !important;
    color: #666666 !important;
}

/* Make sure the associate button shows up as disabled */
.aysa-action-btn.associate:disabled {
    background-color: #cccccc !important;
    cursor: not-allowed !important;
    opacity: 0.7 !important;
    color: #666666 !important;
}

@keyframes pulse {
    0% { opacity: 0.7; }
    50% { opacity: 1; }
    100% { opacity: 0.7; }
}

.aysa-btn-pulsing {
    animation: pulse 1.5s infinite ease-in-out;
}
</style>

<script>
jQuery(document).ready(function($) {
    const aysaAdminNonce = '<?php echo esc_js(wp_create_nonce('aysa_nonce')); ?>';
    const aysaWizardNonce = '<?php echo esc_js(wp_create_nonce('aysa_wizard_nonce')); ?>';
    const aysaStoredProjectId = '<?php echo esc_js((string) intval(get_option('aysa_project_id', 0))); ?>';

    // Initialize keyword discovery data on page load
    async function loadKeywordDiscoveryData() {
        const projectId = getProjectId();
        if (!projectId) {
            console.log('⚠️ No project ID found, cannot load keyword discovery data');
            window.aysaKeywords = [];
            return;
        }

        console.log('🔄 Loading Keyword Discovery data from local WordPress DB...');
        
        try {
            const nonce = '<?php echo wp_create_nonce("aysa_keyword_cache_nonce"); ?>';
            const fetchLocalKeywords = async (sourceMode) => {
                const response = await fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body: new URLSearchParams({
                        action: 'aysa_keyword_discovery_local_keywords',
                        nonce: nonce,
                        project_id: String(projectId),
                        source_mode: sourceMode
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error while loading ${sourceMode}: ${response.status}`);
                }

                const payload = await response.json();
                if (!payload || !payload.success) {
                    throw new Error((payload && payload.data) ? String(payload.data) : `Failed local keyword load (${sourceMode})`);
                }

                const rows = (payload.data && Array.isArray(payload.data.keywords)) ? payload.data.keywords : [];
                return rows;
            };

            // Competitor Gap uses all known local keywords for overlap/missing/common logic.
            const [gscAutoKeywords, suggestionKeywords] = await Promise.all([
                fetchLocalKeywords('gsc_auto'),
                fetchLocalKeywords('keyword_suggestions')
            ]);

            const dedup = new Map();
            [...gscAutoKeywords, ...suggestionKeywords].forEach((row) => {
                const key = String((row && (row.keyword || row.Keyword)) || '').trim().toLowerCase();
                if (!key || dedup.has(key)) {
                    return;
                }
                dedup.set(key, row);
            });
            const keywords = Array.from(dedup.values());

            console.log('✅ Loaded Keyword Discovery data from local DB:', keywords.length, 'keywords');
            
            // Convert SearchIntent format to expected format
            window.aysaKeywords = keywords.map(item => {
                if (typeof item === 'string') {
                    return { keyword: item };
                } else if (item.keyword) {
                    return { 
                        keyword: item.keyword,
                        intent: item.intent,
                        intentProbability: item.probability,
                        ...item 
                    };
                } else if (item.Keyword) {
                    return { 
                        keyword: item.Keyword,
                        intent: item.Intent,
                        ...item 
                    };
                }
                return item;
            });
            
        } catch (error) {
            console.error('❌ Failed to load keyword discovery data from local DB:', error);
            
            // Fallback to localStorage
            const storedResults = localStorage.getItem('aysa_keyword_suggestions');
            if (storedResults) {
                try {
                    const parsedData = JSON.parse(storedResults);
                    if (Array.isArray(parsedData)) {
                        window.aysaKeywords = parsedData;
                        console.log('✅ Fallback: Loaded from localStorage:', parsedData.length, 'keywords');
                        return;
                    }
                } catch (e) {
                    console.error('❌ Failed to parse stored keyword suggestions:', e);
                }
            }
            
            // If everything fails, initialize empty array
            console.log('⚠️ No Keyword Discovery data found, initializing empty array');
            window.aysaKeywords = [];
        }
    }

    // Load keyword discovery data immediately (async)
    loadKeywordDiscoveryData().then(() => {
        console.log('✅ Keyword Discovery data loading completed');
    }).catch(error => {
        console.error('❌ Error during keyword discovery data loading:', error);
    });

    // Normalize and validate competitor domains to avoid invalid values and DOM injection.
    function normalizeCompetitorDomain(rawValue) {
        if (!rawValue || typeof rawValue !== 'string') {
            return null;
        }

        let candidate = rawValue.trim().toLowerCase();
        if (!candidate) {
            return null;
        }

        if (!candidate.startsWith('http://') && !candidate.startsWith('https://')) {
            candidate = `https://${candidate}`;
        }

        try {
            const parsed = new URL(candidate);
            const hostname = (parsed.hostname || '').toLowerCase();
            const isValidDomain = /^(?:xn--)?[a-z0-9-]+(?:\.(?:xn--)?[a-z0-9-]+)+$/.test(hostname);
            return isValidDomain ? hostname : null;
        } catch (error) {
            return null;
        }
    }

    // Adaugă vizual competitorii în UI
    function addCompetitorToUI(domain) {
        const displayDomain = normalizeCompetitorDomain(domain);
        if (!displayDomain) {
            return false;
        }

        let exists = false;
        $('.aysa-competitor-domain').each(function() {
            if (String($(this).text() || '').trim().toLowerCase() === displayDomain) {
                exists = true;
                return false;
            }
        });
        if (exists) {
            return false;
        }

        const $newBox = $('<div>', { class: 'aysa-domain-box competitor-box' });
        const $header = $('<div>', { class: 'aysa-domain-header' })
            .append($('<label>').text('Root domain'))
            .append($('<i>', { class: 'aysa-chevron-down' }));

        const $domainText = $('<span>', { class: 'aysa-competitor-domain' }).text(displayDomain);
        const $contentInner = $('<div>', { class: 'aysa-domain-content-inner' })
            .append($('<span>', { class: 'aysa-competitor-dot' }))
            .append($domainText);

        const $content = $('<div>', { class: 'aysa-domain-content' })
            .append($contentInner)
            .append($('<button>', { class: 'aysa-remove-btn', type: 'button', text: '×' }));

        $newBox.append($header).append($content);
        $('.aysa-competitor-boxes').append($newBox);
        return true;
    }

    function getCompetitorsFromUI() {
        const competitors = [];
        $('.aysa-competitor-domain').each(function() {
            const domain = String($(this).text() || '').trim();
            if (domain) {
                competitors.push('https://' + domain);
            }
        });
        return competitors;
    }

    function extractCompetitorsFromCompetitionStep(raw) {
        const list = [];
        if (!raw || typeof raw !== 'object') {
            return list;
        }

        Object.keys(raw).forEach(function(key) {
            if (!/^competitor\d+$/i.test(key)) {
                return;
            }
            const normalized = normalizeCompetitorDomain(raw[key]);
            if (normalized) {
                list.push(normalized);
            }
        });

        return list;
    }

    function loadSetupCompetitionCompetitors() {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_get_wizard_data',
                nonce: aysaWizardNonce || aysaAdminNonce,
                step: 'competition'
            }
        }).then(function(response) {
            if (!response || !response.success) {
                return [];
            }
            const raw = (response.data && response.data.data) ? response.data.data : {};
            const domains = extractCompetitorsFromCompetitionStep(raw);
            domains.forEach(function(domain) {
                addCompetitorToUI(domain);
            });
            return getCompetitorsFromUI();
        }).fail(function() {
            return [];
        });
    }
    
    // Arată inițial starea de loading în tabel
    const $resultsTable = $('.aysa-results-table table tbody');
    $resultsTable.html(`
        <tr class="aysa-loading-row">
            <td colspan="4" class="aysa-loading-cell">
                <div class="aysa-loading-container">
                    <span class="dashicons dashicons-update aysa-spinning"></span>
                    <span class="aysa-loading-text">Initializing data...</span>
                </div>
            </td>
        </tr>
    `);
    
    // Get project ID from API
    function getProjectId() {
        // First try to get from localStorage
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId) {
            return projectId;
        }
        // Local fallback from WordPress option to avoid blocking sync HTTP calls.
        const fallback = parseInt(aysaStoredProjectId || '0', 10);
        if (Number.isFinite(fallback) && fallback > 0) {
            localStorage.setItem('aysa_project_id', String(fallback));
            return String(fallback);
        }
        return null;
    }

    // Get SEO settings for the project
    function getSeoSettings(projectId) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_get_wizard_data',
                nonce: aysaWizardNonce || aysaAdminNonce,
                step: 'seo-settings'
            }
        }).then(function(response) {
            if (!response || !response.success) {
                throw new Error((response && response.data && response.data.message) ? response.data.message : 'Failed to fetch local SEO settings');
            }

            const raw = (response.data && response.data.data) ? response.data.data : {};
            return {
                targetedCountry: raw.targeted_country || raw.targetedCountry || 'Romania',
                primaryLanguage: raw.primary_language || raw.primaryLanguage || 'Romanian',
                targetedRegion: raw.targeted_region || raw.targetedRegion || '',
                targetedCity: raw.targeted_city || raw.targetedCity || ''
            };
        });
    }

    // Get keyword gap data
    function callSetupApiProxy(endpoint, method = 'GET', payload = {}) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_setup_api_proxy',
                nonce: aysaAdminNonce,
                endpoint: endpoint,
                method: method,
                payload: JSON.stringify(payload || {})
            }
        }).then(function(response) {
            if (!response || !response.success) {
                throw new Error((response && response.data && response.data.message) ? response.data.message : 'Proxy request failed');
            }

            let result = response.data ? response.data.result : null;
            if (typeof result === 'string') {
                try {
                    result = JSON.parse(result);
                } catch (e) {
                    // Keep raw string if backend returned non-JSON text.
                }
            }
            return result;
        });
    }

    function fetchKeywordGapLocalFallback(projectId) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_keyword_discovery_get_keywords_and_competitors',
                nonce: aysaAdminNonce,
                project_id: projectId
            }
        }).then(function(localResponse) {
            if (!localResponse || !localResponse.success) {
                throw new Error('Local fallback unavailable');
            }

            const payload = (localResponse.data && localResponse.data.payload) ? localResponse.data.payload : {};
            const fallbackKeywords = Array.isArray(localResponse.data && localResponse.data.keywords) ? localResponse.data.keywords : [];
            const fallbackCompetitors = Array.isArray(payload.competitors) ? payload.competitors : [];
            const safeCompetitors = fallbackCompetitors.length > 0
                ? fallbackCompetitors
                : [`https://${window.location.hostname}`];

            const normalized = {
                rankedKeywords: fallbackKeywords,
                searchVolume: fallbackKeywords.map(() => 0),
                competitors: safeCompetitors,
                competitorRankedKeywords: safeCompetitors.map(() => []),
                competitorSearchVolumes: safeCompetitors.map(() => [])
            };

            displayFallbackCompetitors(payload);
            return normalized;
        });
    }

    function pollKeywordGapAsyncStatus(projectId, requestHash, attemptsLeft = 45) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_research_async_status',
                nonce: aysaAdminNonce,
                task: 'competitor_gap',
                project_id: projectId
            }
        }).then(function(response) {
            if (!(response && response.success && response.data)) {
                throw new Error('Keyword gap status request failed.');
            }

            const status = response.data || {};
            if (requestHash && status.request_hash && status.request_hash !== requestHash && !status.result) {
                throw new Error('Keyword gap worker returned mismatched request state.');
            }
            if (status.status === 'completed' && status.result) {
                return status.result;
            }
            if (status.status === 'failed') {
                throw new Error(String(status.error || 'Keyword gap worker failed.'));
            }
            if (attemptsLeft <= 0) {
                throw new Error('Keyword gap worker timed out.');
            }

            return new Promise(function(resolve, reject) {
                window.setTimeout(function() {
                    pollKeywordGapAsyncStatus(projectId, requestHash, attemptsLeft - 1).then(resolve).catch(reject);
                }, 3000);
            });
        });
    }

    function getKeywordGapData(target, locationName, languageName, projectId, competitorList = [], limit = 200, forceRefresh = false) {
        console.log('Fetching keyword gap data with params:', {
            target,
            locationName,
            languageName,
            ProjectId: projectId,
            limit,
            competitors: competitorList,
            forceRefresh
        });

        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_research_async_start',
                nonce: aysaAdminNonce,
                task: 'competitor_gap',
                project_id: projectId,
                target: target,
                location_name: locationName,
                language_name: languageName,
                limit: limit,
                competitors: JSON.stringify(Array.isArray(competitorList) ? competitorList : []),
                force_refresh: forceRefresh ? 1 : 0
            }
        }).then(function(response) {
            if (!response || !response.success) {
                const message = (response && response.data) ? response.data : 'Keywords gap local endpoint failed';
                throw new Error(String(message));
            }
            const payload = response.data || {};
            if (payload.status === 'completed' && payload.result) {
                return payload.result;
            }
            showNotification('Keyword gap is running in the background...', 'loading');
            return pollKeywordGapAsyncStatus(projectId, payload.request_hash || '');
        }).catch(function(error) {
            console.warn('Keyword gap endpoint failed, using local keywords/competitors fallback.', error);
            return fetchKeywordGapLocalFallback(projectId).then(function(result) {
                showNotification('Loaded local fallback data for competitor gap.', 'warning');
                return result;
            });
        });
    }

    // Function to display competitors from fallback data
    function displayFallbackCompetitors(data) {
        console.log('Displaying fallback competitors:', data);
        
        if (!data) {
            console.log('No fallback data available');
            return;
        }

        // Clear existing competitor boxes
        $('.aysa-competitor-boxes').empty();
        
        // Update root domain (your domain)
        const currentDomain = window.location.hostname;
        $('.aysa-your-domain').text(currentDomain);
        
        // Extract competitors from the data structure
        let competitors = [];
        if (Array.isArray(data)) {
            // If data is an array, extract competitors from each item
            data.forEach(function(item) {
                if (item.competitors && Array.isArray(item.competitors)) {
                    competitors = competitors.concat(item.competitors);
                }
            });
        } else if (data.competitors && Array.isArray(data.competitors)) {
            // If data is a single object with competitors array
            competitors = data.competitors;
        }
        
        console.log('Extracted competitors:', competitors);
        
        // Display competitors using the same logic as normal flow
        if (competitors && competitors.length > 0) {
            competitors.forEach((competitor, index) => {
                try {
                    // Handle both URL and domain formats
                    let domain;
                    if (competitor.startsWith('http://') || competitor.startsWith('https://')) {
                        domain = new URL(competitor).hostname;
                    } else {
                        domain = competitor;
                    }
                    
                    // Don't add if it's the same as current domain
                    if (domain !== currentDomain) {
                        addCompetitorToUI(domain);
                    }
                } catch (error) {
                    console.error('Invalid competitor URL:', competitor, error);
                    // If URL parsing fails, try using it as domain directly
                    if (competitor !== currentDomain) {
                        addCompetitorToUI(competitor);
                    }
                }
            });
        }
    }

    // Function to show error modal
    function showErrorModal(message) {
        const modalHtml = `
            <div class="aysa-modal" id="aysaErrorModal">
                <div class="aysa-modal-content">
                    <div class="aysa-modal-header">
                        <h3>Notice</h3>
                        <span class="aysa-modal-close">&times;</span>
                    </div>
                    <div class="aysa-modal-body">
                        <p>${message}</p>
                    </div>
                </div>
            </div>
        `;

        // Remove existing modal if any
        $('#aysaErrorModal').remove();
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Show modal
        const modal = $('#aysaErrorModal');
        modal.show();
        
        // Close modal on click
        $('.aysa-modal-close').click(function() {
            modal.hide();
            modal.remove();
        });
        
        // Close modal when clicking outside
        $(window).click(function(event) {
            if ($(event.target).is(modal)) {
                modal.hide();
                modal.remove();
            }
        });
    }

    // Function to automatically associate competitor keywords
    async function associateCompetitorKeywords(keywords) {
        try {
            // Show loading notification
            showNotification('Generating keyword associations...', 'loading');

            // Get categories, pages, and products from WordPress
            const categories = await getWordPressItems('Category');
            const pages = await getWordPressItems('Page');
            const products = await getWordPressItems('Product');

            // Format the data according to the API's expected structure
            const requestData = {
                ProjectId: getProjectId(),
                Keywords: keywords,
                Categories: categories.map(cat => ({
                    Id: cat.id,
                    Name: cat.name
                })),
                Pages: pages.map(page => ({
                    Id: page.id,
                    Name: page.name
                })),
                Products: products.map(product => ({
                    Id: product.id,
                    Name: product.name
                }))
            };

            console.log('Sending request data for competitor keywords:', requestData);

            // Make API call to generate associations
            const apiBaseUrl = ((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '');
            const response = await fetch(`${apiBaseUrl}/api/ChatGPT/generate-keyword-associations`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.title || 'Failed to generate associations');
            }

            const result = await response.json();
            console.log('Association API Response:', result);
            
            if (!result || !result.createdAssociations) {
                throw new Error('Invalid response format from server');
            }

            // Show success notification
            showNotification('Successfully associated competitor keywords!', 'success');
            
            // Return the created associations
            return result.createdAssociations;
        } catch (error) {
            console.error('Error generating associations:', error);
            showNotification('Error generating associations: ' + error.message, 'error');
            return null;
        }
    }

    async function addKeywordsToKeywordResearch(keywordEntries) {
        const projectId = getProjectId();
        if (!projectId) {
            throw new Error('Project ID missing');
        }

        const keywords = [];
        const volumes = {};

        (Array.isArray(keywordEntries) ? keywordEntries : []).forEach((entry) => {
            const keyword = String(entry && entry.keyword ? entry.keyword : '').trim();
            if (!keyword) {
                return;
            }
            keywords.push(keyword);
            const volumeVal = Number(entry && entry.volume !== undefined ? entry.volume : NaN);
            if (Number.isFinite(volumeVal) && volumeVal >= 0) {
                volumes[keyword] = Math.round(volumeVal);
            }
        });

        if (keywords.length === 0) {
            throw new Error('No valid keywords selected');
        }

        const response = await $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_competitor_gap_add_to_keyword_research',
                nonce: aysaAdminNonce,
                project_id: projectId,
                keywords: JSON.stringify(keywords),
                volumes: JSON.stringify(volumes),
            },
        });

        if (!response || !response.success) {
            throw new Error((response && response.data) ? response.data : 'Add to keyword research failed');
        }

        return response.data;
    }
    
    // Function to get WordPress items
    async function getWordPressItems(type) {
        try {
            const response = await fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    action: 'aysa_get_items',
                    type: type,
                    nonce: '<?php echo wp_create_nonce("aysa_get_items_nonce"); ?>'
                })
            });

            if (!response.ok) {
                throw new Error(`Failed to get ${type}`);
            }

            const result = await response.json();
            if (!result.success) {
                throw new Error(result.message || `Failed to get ${type}`);
            }

            return result.data || [];
        } catch (error) {
            console.error(`Error getting ${type}:`, error);
            return [];
        }
    }
    
    // Function to show notifications
    function showNotification(message, type = 'info') {
        const $notification = $('<div class="aysa-notification"></div>');
        $notification.addClass(`aysa-notification-${type}`);
        
        // Add icon based on type
        let iconClass = '';
        switch(type) {
            case 'success':
                iconClass = 'dashicons-yes';
                break;
            case 'error':
                iconClass = 'dashicons-no';
                break;
            case 'loading':
                iconClass = 'dashicons-update aysa-spinning';
                break;
            default:
                iconClass = 'dashicons-info';
        }
        
        $notification.html(`
            <span class="dashicons ${iconClass}"></span>
            <span>${message}</span>
        `);
        
        // Add to page
        $('body').append($notification);
        
        // Remove after 3 seconds with fade out animation
        setTimeout(() => {
            $notification.addClass('fade-out');
            setTimeout(() => {
                $notification.remove();
            }, 600);
        }, 3000);
    }

    // Banned keywords filtering functions (shared with keyword discovery)
    let bannedKeywordsCache = null;
    let bannedKeywordsCacheTime = 0;
    const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds

    /**
     * Get banned keywords from the server with caching
     */
    async function getBannedKeywords() {
        const now = Date.now();
        
        // Return cached data if still valid
        if (bannedKeywordsCache && (now - bannedKeywordsCacheTime) < CACHE_DURATION) {
            console.log('Using cached banned keywords:', bannedKeywordsCache.length);
            return bannedKeywordsCache;
        }
        
        try {
            const response = await $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_get_banned_keywords',
                    project_id: getProjectId() || 0,
                    nonce: '<?php echo wp_create_nonce("aysa_banned_keywords_nonce"); ?>',
                    limit: 1000 // Get all banned keywords
                }
            });
            
            if (response.success && response.data && response.data.keywords) {
                bannedKeywordsCache = response.data.keywords.map(item => item.keyword.toLowerCase().trim());
                bannedKeywordsCacheTime = now;
                console.log('Fetched banned keywords from server:', bannedKeywordsCache.length);
                return bannedKeywordsCache;
            } else {
                console.warn('Failed to fetch banned keywords:', response.data || response);
                return [];
            }
        } catch (error) {
            console.error('Error fetching banned keywords:', error);
            return [];
        }
    }

    /**
     * Filter out banned keywords from a keyword array
     */
    async function filterBannedKeywords(keywords) {
        if (!Array.isArray(keywords) || keywords.length === 0) {
            return keywords;
        }
        
        const bannedKeywords = await getBannedKeywords();
        if (bannedKeywords.length === 0) {
            return keywords; // No banned keywords, return original array
        }
        
        const originalCount = keywords.length;
        const filteredKeywords = keywords.filter(keywordItem => {
            const keyword = keywordItem.keyword ? keywordItem.keyword.toLowerCase().trim() : 
                           (typeof keywordItem === 'string' ? keywordItem.toLowerCase().trim() : '');
            
            if (!keyword) return true; // Keep items without keywords
            
            const isBanned = bannedKeywords.includes(keyword);
            if (isBanned) {
                console.log('Filtering out banned keyword:', keywordItem.keyword || keywordItem);
            }
            return !isBanned;
        });
        
        const filteredCount = originalCount - filteredKeywords.length;
        if (filteredCount > 0) {
            console.log(`Filtered out ${filteredCount} banned keywords from ${originalCount} total keywords`);
            showNotification(`Filtered out ${filteredCount} banned keyword${filteredCount > 1 ? 's' : ''} from competitor keywords`, 'info');
        }
        
        return filteredKeywords;
    }
    
    // Function to save competitorKeywords to localStorage
    async function saveCompetitorKeywordsToStorage(competitorKeywords, competitorVolumes) {
        if (!competitorKeywords || !competitorKeywords.length) return;

        // Get current keyword suggestions or initialize empty array
        let currentSuggestions = [];
        const storedResults = localStorage.getItem('aysa_keyword_suggestions');
        if (storedResults) {
            try {
                currentSuggestions = JSON.parse(storedResults);
            } catch (e) {
                console.error('Failed to parse stored keyword suggestions:', e);
                currentSuggestions = [];
            }
        }

        // Create keyword objects from competitor keywords
        let competitorSuggestions = competitorKeywords.map((keyword, index) => {
            return {
                keyword: keyword,
                searchVolume: competitorVolumes[index] || 0,
                difficulty: Math.floor(Math.random() * 60) + 20, // Random difficulty
                intent: 'commercial,informational', // Default intent
                competitors: 'Competitor',
                backlinksNeeded: Math.floor(Math.random() * 10) + 1 // Random backlinks
            };
        });

        // 🚫 Filter out banned keywords from competitor suggestions
        console.log('🚫 Filtering banned keywords from competitor suggestions...');
        competitorSuggestions = await filterBannedKeywords(competitorSuggestions);

        // Merge existing keywords with new competitor keywords
        // Filter out duplicates by keyword
        const keywordsMap = {};
        [...currentSuggestions, ...competitorSuggestions].forEach(item => {
            keywordsMap[item.keyword] = item;
        });
        
        const mergedSuggestions = Object.values(keywordsMap);

        // Save back to localStorage
        localStorage.setItem('aysa_keyword_suggestions', JSON.stringify(mergedSuggestions));
        console.log(`Saved ${competitorKeywords.length} competitor keywords to storage. Total keywords: ${mergedSuggestions.length}`);
        
        return mergedSuggestions;
    }

    // Load associations when page loads
    if (window.AYSA_DEBUG === true) {
        console.log('Calling loadAssociations...');
    }
    loadAssociations();

    // Function to load all associations
    function loadAssociations() {
        if (window.AYSA_DEBUG === true) {
            console.log('Inside loadAssociations function');
        }
        
        // Get project ID from localStorage
        const projectId = getProjectId();
        if (window.AYSA_DEBUG === true) {
            console.log('Project ID for associations:', projectId);
        }
        
        console.log('Loading associations via WordPress AJAX/local source');
        
        // Introducem o mică întârziere pentru a permite afișarea loading-ului inițial
        setTimeout(() => {
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'aysa_keyword_discovery_get_associations',
                    nonce: aysaAdminNonce,
                    project_id: projectId || '',
                    local_only: 1
                },
                success: function(response) {
                    const associations = (response && response.success && response.data && Array.isArray(response.data.associations))
                        ? response.data.associations
                        : [];
                    console.log('Successfully loaded associations:', associations.length);

                    if (associations.length > 0) {
                        // Store associations for later use
                        window.aysaAssociations = associations;
                        
                        // Check if any keywords in the table are already associated
                        updateAssociatedButtons();
                    } else {
                        console.warn('No associations found or invalid response format');
                        window.aysaAssociations = [];
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading associations:', {
                        status: status,
                        error: error,
                        response: xhr.responseText,
                        statusText: xhr.statusText
                    });
                    
                    // Inițializăm cu un array gol pentru a evita erorile
                    window.aysaAssociations = [];
                }
            });
        }, 500); // O mică întârziere pentru a permite afișarea stării de loading
    }

    // Shared keyword-gap data used across async callbacks and tab handlers.
    window.aysaCompetitorKeywordSets = Array.isArray(window.aysaCompetitorKeywordSets) ? window.aysaCompetitorKeywordSets : [];

    // Helper used by multiple keyword-gap flows, including association refresh callbacks.
    function getCombinedKeywordList() {
        const keywordDiscoveryList = window.aysaKeywords ?
            window.aysaKeywords.map(kw => kw.keyword ? kw.keyword.toLowerCase() : (typeof kw === 'string' ? kw.toLowerCase() : '')) : [];

        const associatedKeywords = window.aysaAssociations ?
            window.aysaAssociations.map(a => a.keyword.toLowerCase()) : [];

        return [...new Set([...keywordDiscoveryList, ...associatedKeywords])];
    }

    // Function to update associate buttons based on existing associations
    function updateAssociatedButtons() {
        if (!window.aysaAssociations || !Array.isArray(window.aysaAssociations)) {
            return;
        }
        
        // Update all table rows and action buttons
        $('.aysa-keywords-table tbody tr').each(function() {
            const $row = $(this);
            const keyword = String($row.data('keyword') || '').trim();
            
            // Skip loading/empty rows
            if (!keyword || $row.hasClass('aysa-loading-row')) {
                return;
            }
            
            // Check if keyword is already associated
            const isAssociated = window.aysaAssociations.some(a => a.keyword === keyword);
            
            if (isAssociated) {
                // Add visual styling to the row
                $row.addClass('aysa-row-associated').removeClass('aysa-row-common');
                
                // Update action button if it exists - keep it clickable for disassociation
                const $actionBtn = $row.find('.aysa-action-btn');
                if ($actionBtn.length > 0 && !$actionBtn.hasClass('associate')) {
                    $actionBtn.text('Associated').addClass('aysa-btn-associated');
                    // Don't disable - it should remain clickable for dropdown functionality
                }
                
                // Update associate button if it exists (for non-competitor tabs)
                const $associateBtn = $row.find('.aysa-action-btn.associate');
                if ($associateBtn.length > 0) {
                    $associateBtn.text('Associated').addClass('aysa-btn-associated').prop('disabled', true);
                }
            } else {
                // Remove associated styling and check if it's common
                $row.removeClass('aysa-row-associated');
                
                // Check if keyword is common (present in both Keyword Discovery and competitor keywords)
                let isCommonKeyword = false;
                
                const combinedKeywordList = getCombinedKeywordList();
                
                if (combinedKeywordList.length > 0) {
                    // Determine if this is a competitor tab based on active tab
                    const activeTab = $('.aysa-tab-btn.active');
                    const isCompetitorTab = activeTab.length > 0 && !activeTab.text().trim().toLowerCase().includes('you');
                    
                    if (isCompetitorTab) {
                        // For competitor tab, check if keyword is in combined list (Keyword Discovery + Associated)
                        isCommonKeyword = combinedKeywordList.includes(keyword.toLowerCase());
                    } else {
                        // For your tab, check if keyword is in combined list (Keyword Discovery + Associated)
                        isCommonKeyword = combinedKeywordList.includes(keyword.toLowerCase());
                    }
                }
                
                // Apply common styling if keyword is common but not associated
                if (isCommonKeyword) {
                    $row.addClass('aysa-row-common');
                } else {
                    $row.removeClass('aysa-row-common');
                }
                
                // Reset action button styling
                const $actionBtn = $row.find('.aysa-action-btn');
                if ($actionBtn.length > 0) {
                    $actionBtn.text('Action').removeClass('aysa-btn-associated');
                }
                
                const $associateBtn = $row.find('.aysa-action-btn.associate');
                if ($associateBtn.length > 0) {
                    $associateBtn.text('Associate').removeClass('aysa-btn-associated').prop('disabled', false);
                }
            }
        });
        
        // Check if all keywords for a competitor are associated
        $('.aysa-tab-btn').each(function() {
            const competitorIndex = $(this).data('competitor-index');
            if (typeof competitorIndex !== 'undefined') {
                checkAllKeywordsAssociated(competitorIndex);
            }
        });
    }

    // Function to check if all keywords from a competitor are associated
    function checkAllKeywordsAssociated(competitorIndex) {
        if (!window.aysaAssociations || !Array.isArray(window.aysaAssociations)) {
            return false;
        }
        
        const competitorKeywordSets = Array.isArray(window.aysaCompetitorKeywordSets) ? window.aysaCompetitorKeywordSets : [];
        const competitorKeywords = competitorKeywordSets[competitorIndex] || [];
        if (competitorKeywords.length === 0) {
            return false;
        }
        
        // Check if all competitor keywords are associated
        const allAssociated = competitorKeywords.every(keyword => 
            window.aysaAssociations.some(a => a.keyword === keyword)
        );
        
        // Update the Associate All button
        if (allAssociated) {
            $(`.aysa-associate-all-btn[data-competitor-index="${competitorIndex}"]`)
                .text('All Keywords Associated')
                .addClass('aysa-btn-associated')
                .prop('disabled', true);
        }
        
        return allAssociated;
    }

    // Modify the displayKeywordGapData function to add action button for association
    function displayKeywordGapData(data) {
        const $resultsTable = $('.aysa-results-table table tbody');
        
        // Arată indicator de loading până se încarcă datele
        if (!$resultsTable.find('.aysa-loading-row').length) {
            $resultsTable.html(`
                <tr class="aysa-loading-row">
                    <td colspan="4" class="aysa-loading-cell">
                        <div class="aysa-loading-container">
                            <span class="dashicons dashicons-update aysa-spinning"></span>
                            <span class="aysa-loading-text">Loading keyword data...</span>
                        </div>
                    </td>
                </tr>
            `);
        }
        
        // Dacă nu avem date sau avem un obiect gol, arată un mesaj relevant
        if (!data || (!data.rankedKeywords && !data.competitors)) {
            $resultsTable.html(`
                <tr>
                    <td colspan="4" class="aysa-empty-message">
                        No data available. Please try again with different parameters.
                    </td>
                </tr>
            `);
            return;
        }

        // Remove duplicate keywords from our keywords array
        const uniqueKeywords = [...new Set(data?.rankedKeywords || [])];
        const ourKeywords = uniqueKeywords;
        const ourVolumes = data?.searchVolume || [];
        const competitors = data?.competitors || [];
        const competitorKeywordSets = data?.competitorRankedKeywords || [];
        const competitorVolumes = data?.competitorSearchVolumes || [];
        const inKeywordResearch = (data && data.inKeywordResearch && typeof data.inKeywordResearch === 'object')
            ? data.inKeywordResearch
            : {};

        // Keep competitor keyword sets available for callbacks that run outside this scope
        // (e.g. loadAssociations -> updateAssociatedButtons -> checkAllKeywordsAssociated).
        window.aysaCompetitorKeywordSets = competitorKeywordSets;

        // Function to format volume numbers with commas
        function formatVolume(volume) {
            if (!volume || volume === '0') return '0';
            return parseInt(volume).toLocaleString();
        }

        // Helper function to get combined keyword list (Keyword Discovery + Associated)
        function getCombinedKeywordList() {
            // Get keywords from Keyword Discovery (the complete list from the discovery page)
            const keywordDiscoveryList = window.aysaKeywords ? 
                window.aysaKeywords.map(kw => kw.keyword ? kw.keyword.toLowerCase() : (typeof kw === 'string' ? kw.toLowerCase() : '')) : [];
            
            // Add associated keywords to the list (they should also be considered as "discovered")
            const associatedKeywords = window.aysaAssociations ? 
                window.aysaAssociations.map(a => a.keyword.toLowerCase()) : [];
            
            // Combine both lists and remove duplicates
            return [...new Set([...keywordDiscoveryList, ...associatedKeywords])];
        }

        // Function to display keywords in table
        function displayKeywords(keywords, volumes, isCompetitor = false, filterType = 'All', competitorIndex = 0) {
            $resultsTable.empty();
            if (!keywords || keywords.length === 0) {
                $resultsTable.append(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            No keywords found. Try adjusting your search parameters.
                        </td>
                    </tr>
                `);
                return;
            }

            // Filter keywords based on selected filter type
            let filteredKeywords = [];
            let filteredVolumes = [];
            
            if (filterType === 'All') {
                // Display all keywords
                filteredKeywords = keywords;
                filteredVolumes = volumes;
            } else if (filterType === 'Missing') {
                // Show only keywords that are not in Keyword Discovery OR Associated
                const combinedKeywordList = getCombinedKeywordList();
                
                console.log('🔍 Missing Filter - Combined List:', combinedKeywordList.length, 'keywords');
                
                if (isCompetitor) {
                    // For competitor tab, show competitor keywords not in combined list (Keyword Discovery + Associated)
                    filteredKeywords = keywords.filter(kw => !combinedKeywordList.includes(kw.toLowerCase()));
                    // Get corresponding volumes
                    filteredVolumes = filteredKeywords.map(kw => {
                        const idx = keywords.indexOf(kw);
                        return idx !== -1 ? volumes[idx] : '0';
                    });
                } else {
                    // For your tab, show your keywords not in combined list (Keyword Discovery + Associated)
                    filteredKeywords = keywords.filter(kw => !combinedKeywordList.includes(kw.toLowerCase()));
                    // Get corresponding volumes
                    filteredVolumes = filteredKeywords.map(kw => {
                        const idx = keywords.indexOf(kw);
                        return idx !== -1 ? volumes[idx] : '0';
                    });
                }
            } else if (filterType === 'Common') {
                // Show only keywords that are also in Keyword Discovery OR Associated
                const combinedKeywordList = getCombinedKeywordList();
                
                console.log('🔍 Common Filter - Combined List:', combinedKeywordList.length, 'keywords');
                
                if (isCompetitor) {
                    // For competitor tab, show competitor keywords also in combined list (Keyword Discovery + Associated)
                    filteredKeywords = keywords.filter(kw => combinedKeywordList.includes(kw.toLowerCase()));
                    // Get corresponding volumes
                    filteredVolumes = filteredKeywords.map(kw => {
                        const idx = keywords.indexOf(kw);
                        return idx !== -1 ? volumes[idx] : '0';
                    });
                } else {
                    // For your tab, show your keywords also in combined list (Keyword Discovery + Associated)
                    filteredKeywords = keywords.filter(kw => combinedKeywordList.includes(kw.toLowerCase()));
                    // Get corresponding volumes
                    filteredVolumes = filteredKeywords.map(kw => {
                        const idx = keywords.indexOf(kw);
                        return idx !== -1 ? volumes[idx] : '0';
                    });
                }
            }

            // Display filtered keywords
            if (filteredKeywords.length === 0) {
                $resultsTable.append(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            No ${filterType.toLowerCase()} keywords found.
                        </td>
                    </tr>
                `);
                return;
            }

            filteredKeywords.forEach((keyword, index) => {
                const searchVolume = filteredVolumes[index] || '0';
                const isInResearch = !!inKeywordResearch[keyword];
                
                // Check if keyword is already associated
                const isAssociated = window.aysaAssociations && 
                                    Array.isArray(window.aysaAssociations) && 
                                    window.aysaAssociations.some(a => a.keyword === keyword);
                
                const associateButtonClass = isAssociated ? 'aysa-action-btn associate aysa-btn-associated' : 'aysa-action-btn associate';
                const associateButtonText = isAssociated ? 'Associated' : 'Associate';
                
                // Build dropdown content based on associations
                let dropdownContent = '';
                if (isCompetitor) {
                    const keywordAssociations = window.aysaAssociations ? 
                        window.aysaAssociations.filter(a => a.keyword === keyword) : [];
                    
                    // Check for specific associations
                    const hasCategory = keywordAssociations.some(a => a.associatedOn === 'Category');
                    const hasProduct = keywordAssociations.some(a => a.associatedOn === 'Product');  
                    const hasPage = keywordAssociations.some(a => a.associatedOn === 'Page');
                    
                    dropdownContent = `
                        <a href="#" class="aysa-dropdown-item ${hasCategory ? 'dropdown-item-associated' : ''}">
                            Associate Category
                        </a>
                        <a href="#" class="aysa-dropdown-item ${hasProduct ? 'dropdown-item-associated' : ''}">
                            Associate Product
                        </a>
                        <a href="#" class="aysa-dropdown-item ${hasPage ? 'dropdown-item-associated' : ''}">
                            Associate Page
                        </a>
                        <div class="aysa-dropdown-divider"></div>
                        <a href="#" class="aysa-dropdown-item aysa-reassociate-item">
                            Associate
                        </a>
                        <div class="aysa-dropdown-divider"></div>
                        <a href="#" class="aysa-dropdown-item aysa-add-keyword-item" style="color: #28a745;">
                            Add keyword
                        </a>
                    `;
                }
                
                // Determine button text and styling based on association status
                const actionButtonText = isAssociated ? 'Associated' : 'Action';
                const actionButtonClass = isAssociated ? 'aysa-action-btn aysa-btn-associated' : 'aysa-action-btn';
                // Don't disable the button - it should remain clickable for disassociation
                
                const associateButton = isCompetitor ? 
                    `<td class="aysa-action-col">
                        <div class="aysa-action-dropdown">
                            <button class="${actionButtonClass}">${actionButtonText}</button>
                            <div class="aysa-dropdown-content" style="position: absolute; right: 0; top: 100%;">
                                ${dropdownContent}
                            </div>
                        </div>
                    </td>` : 
                    '<td class="aysa-action-col"></td>';
                
                // Check if keyword is common (present in Keyword Discovery or already associated) but not currently associated
                let isCommonKeyword = false;
                if (!isAssociated) {
                    const combinedKeywordList = getCombinedKeywordList();
                    
                    if (isCompetitor) {
                        // For competitor tab, check if keyword is in combined list (Keyword Discovery + Associated)
                        isCommonKeyword = combinedKeywordList.includes(keyword.toLowerCase());
                        
                        // Debug specific keywords
                        if (keyword.toLowerCase().includes('comanda flori') || keyword.toLowerCase().includes('california flowers')) {
                            console.log('🔍 KEYWORD CHECK:', keyword);
                            console.log('- In Combined List:', isCommonKeyword);
                            console.log('- Combined list contains:', combinedKeywordList.filter(kw => kw.includes('comanda flori') || kw.includes('california')));
                        }
                    } else {
                        // For your tab, check if keyword is in combined list (Keyword Discovery + Associated)
                        isCommonKeyword = combinedKeywordList.includes(keyword.toLowerCase());
                    }
                }
                
                // Add class to row if keyword is associated OR common
                const rowClass = isInResearch
                    ? 'aysa-row-in-research'
                    : (isAssociated ? 'aysa-row-associated' : (isCommonKeyword ? 'aysa-row-common' : ''));
                const keywordLabel = isInResearch
                    ? `${keyword || ''} <span class="aysa-inline-pill aysa-inline-pill-success">Added to research</span>`
                    : (keyword || '');
                    
                $resultsTable.append(`
                    <tr data-keyword="${keyword}" data-volume="${searchVolume}" class="${rowClass}">
                        <td class="aysa-select-col">
                            <input type="checkbox" class="aysa-keyword-checkbox" data-keyword="${keyword}" ${isInResearch ? 'disabled' : ''}>
                        </td>
                        <td class="aysa-keyword-cell">
                            <a href="#" class="aysa-keyword-link">${keywordLabel} <span class="aysa-arrow">↗</span></a>
                        </td>
                        <td class="aysa-volume-cell">${formatVolume(searchVolume)}</td>
                        ${associateButton}
                    </tr>
                `);
            });
            
            // Check if all competitor keywords are associated and update the "Associate All" button
            if (isCompetitor) {
                checkAllKeywordsAssociated(competitorIndex);
            }
        }

        // Update competitor tabs
        const $tabButtons = $('.aysa-tab-buttons');
        $tabButtons.empty();
        $tabButtons.append('<button class="aysa-tab-btn active">You</button>');
        
        competitors.forEach((competitor, index) => {
            const domain = new URL(competitor).hostname;
            $tabButtons.append(`
                <button class="aysa-tab-btn" data-competitor-index="${index}">${domain}</button>
            `);
        });

        // Update competitor selector
        const $competitorSelector = $('.aysa-competitor-selector');
        $competitorSelector.empty();
        competitors.forEach((competitor, index) => {
            const domain = new URL(competitor).hostname;
            $competitorSelector.append(`
                <button class="aysa-competitor-btn ${index === 0 ? 'active' : ''}" 
                        data-competitor-index="${index}">${domain}</button>
            `);
        });

        // Track active filter and competitor
        let activeFilterType = 'All';
        let activeCompetitorIndex = 0;

        // Initial display of your keywords
        displayKeywords(ourKeywords, ourVolumes, false, activeFilterType, activeCompetitorIndex);

        // Update domain boxes
        const currentDomain = window.location.hostname;
        $('.aysa-your-domain').text(currentDomain);

        // Display competitor domains from data
        if (competitors && competitors.length > 0) {
            // First clear all existing competitor boxes
            $('.aysa-competitor-boxes').empty();
            
            // Add each competitor from the data
            competitors.forEach((competitor, index) => {
                try {
                    const domain = new URL(competitor).hostname;
                    addCompetitorToUI(domain);
                } catch (error) {
                    console.error('Invalid competitor URL:', competitor, error);
                }
            });
        }

        // Function to update Venn diagram for a specific competitor
        function updateVennDiagram(competitorIndex) {
            const competitorKeywords = competitorKeywordSets[competitorIndex] || [];
            const commonKeywords = ourKeywords.filter(keyword => 
                competitorKeywords.includes(keyword)
            );

            const circleSize = 280; // Fixed size for both circles

            if (commonKeywords.length === 0) {
                // No overlap - separate circles
                $('.aysa-venn-left').css({
                    'width': `${circleSize}px`,
                    'height': `${circleSize}px`,
                    'left': 'calc(50% - 240px)',
                    'transform': 'translateX(0)'
                });
                
                $('.aysa-venn-right').css({
                    'width': `${circleSize}px`,
                    'height': `${circleSize}px`,
                    'left': 'calc(50% + 40px)',
                    'transform': 'translateX(0)'
                });
            } else {
                // Has overlap - calculate overlap based on common keywords
                const overlapRatio = commonKeywords.length / Math.max(ourKeywords.length, competitorKeywords.length);
                const overlapDistance = Math.min(120, 60 + (overlapRatio * 80));
                
                $('.aysa-venn-left').css({
                    'width': `${circleSize}px`,
                    'height': `${circleSize}px`,
                    'left': '50%',
                    'transform': `translateX(-${circleSize - overlapDistance}px)`
                });
                
                $('.aysa-venn-right').css({
                    'width': `${circleSize}px`,
                    'height': `${circleSize}px`,
                    'left': '50%',
                    'transform': `translateX(-${overlapDistance}px)`
                });
            }

            // Update legend
            $('.aysa-overlap-legend').empty();
            
            // Your domain legend item
            $('.aysa-overlap-legend').append(`
                <div class="aysa-legend-item">
                    <span class="aysa-checkbox-wrapper">
                        <input type="checkbox" checked class="aysa-checkbox aysa-checkbox-blue">
                        <span class="aysa-checkbox-label"></span>
                    </span>
                    <span class="aysa-domain-name">${currentDomain}</span>
                    <span class="aysa-keyword-count">${ourKeywords.length}</span>
                </div>
            `);

            // Competitor legend item
            const competitorDomain = new URL(competitors[competitorIndex]).hostname;
            $('.aysa-overlap-legend').append(`
                <div class="aysa-legend-item">
                    <span class="aysa-checkbox-wrapper">
                        <input type="checkbox" checked class="aysa-checkbox aysa-checkbox-green">
                        <span class="aysa-checkbox-label"></span>
                    </span>
                    <span class="aysa-domain-name">${competitorDomain}</span>
                    <span class="aysa-keyword-count">${competitorKeywords.length}</span>
                </div>
            `);
            
            // Add button to associate all competitor keywords
            $('.aysa-overlap-legend').append(`
                <div class="aysa-associate-all">
                    <button class="aysa-associate-all-btn" data-competitor-index="${competitorIndex}">
                        Associate All Keywords
                    </button>
                </div>
            `);
        }

        // Initialize with first competitor
        updateVennDiagram(0);

        // Handle tab switching
        $('.aysa-tab-btn').off('click').on('click', function() {
            $('.aysa-tab-btn').removeClass('active');
            $(this).addClass('active');
            const competitorIndex = $(this).data('competitor-index');
            // Sincronizez și tabul din Keyword Overlap (dreapta)
            if (typeof competitorIndex !== 'undefined') {
                $('.aysa-competitor-btn').removeClass('active');
                $(`.aysa-competitor-btn[data-competitor-index="${competitorIndex}"]`).addClass('active');
                updateVennDiagram(competitorIndex);
            }
            if (typeof competitorIndex === 'undefined') {
                // "You" tab
                displayKeywords(ourKeywords, ourVolumes, false, activeFilterType, activeCompetitorIndex);
            } else {
                // Competitor tab
                activeCompetitorIndex = competitorIndex;
                const competitorKeywords = competitorKeywordSets[competitorIndex] || [];
                const competitorVols = competitorVolumes[competitorIndex] || [];
                displayKeywords(competitorKeywords, competitorVols, true, activeFilterType, competitorIndex);
            }
        });

        // Handle filter pill selection
        $('.aysa-pill').off('click').on('click', function() {
            $('.aysa-pill').removeClass('active');
            $(this).addClass('active');
            
            // Get selected filter
            activeFilterType = $(this).text();
            
            // Get active tab
            const activeTabIndex = $('.aysa-tab-btn.active').data('competitor-index');
            
            if (typeof activeTabIndex === 'undefined') {
                // "You" tab
                displayKeywords(ourKeywords, ourVolumes, false, activeFilterType, activeCompetitorIndex);
            } else {
                // Competitor tab
                const competitorKeywords = competitorKeywordSets[activeTabIndex] || [];
                const competitorVols = competitorVolumes[activeTabIndex] || [];
                displayKeywords(competitorKeywords, competitorVols, true, activeFilterType, activeTabIndex);
            }
        });

        // Handle competitor selector for Venn diagram
        $('.aysa-competitor-btn').off('click').on('click', function() {
            $('.aysa-competitor-btn').removeClass('active');
            $(this).addClass('active');
            
            const competitorIndex = $(this).data('competitor-index');
            activeCompetitorIndex = competitorIndex;
            
            // Update both Venn diagram and tab selection
            updateVennDiagram(competitorIndex);
            $('.aysa-tab-btn').removeClass('active');
            $(`.aysa-tab-btn[data-competitor-index="${competitorIndex}"]`).addClass('active');
            
            // Update keyword display
            const competitorKeywords = competitorKeywordSets[competitorIndex] || [];
            const competitorVols = competitorVolumes[competitorIndex] || [];
            displayKeywords(competitorKeywords, competitorVols, true, activeFilterType, competitorIndex);
        });

        // Add click handler for action button dropdown
        $resultsTable.on('click', '.aysa-action-btn', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // Get the parent dropdown container
            const $dropdown = $(this).closest('.aysa-action-dropdown');
            
            // Reset loading states and close all other open dropdowns first
            $('.aysa-dropdown-content').removeClass('aysa-dropdown-loading aysa-dropdown-processing');
            $('.aysa-dropdown-content a').removeClass('aysa-disabled-link').css({
                'pointer-events': 'auto',
                'opacity': '1',
                'cursor': 'pointer'
            });
            
            // Re-enable all action buttons
            $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                'pointer-events': 'auto',
                'opacity': '1',
                'cursor': 'pointer',
                'background-color': '',
                'color': ''
            });
            
            $('.aysa-action-dropdown.open').not($dropdown).removeClass('open');
            $('.aysa-secondary-dropdown').remove();
            
            // Get keyword for this row
            const keyword = String($(this).closest('tr').data('keyword') || '').trim();
            
            // Check if there are any associations for this keyword and rebuild dropdown
            if (window.aysaAssociations && Array.isArray(window.aysaAssociations)) {
                const keywordAssociations = window.aysaAssociations.filter(a => a.keyword === keyword);
                
                // Check for specific associations
                const hasCategory = keywordAssociations.some(a => a.associatedOn === 'Category');
                const hasProduct = keywordAssociations.some(a => a.associatedOn === 'Product');  
                const hasPage = keywordAssociations.some(a => a.associatedOn === 'Page');
                
                // Rebuild dropdown content with updated associations
                const dropdownContent = `
                    <a href="#" class="aysa-dropdown-item ${hasCategory ? 'dropdown-item-associated' : ''}">
                        Associate Category
                    </a>
                    <a href="#" class="aysa-dropdown-item ${hasProduct ? 'dropdown-item-associated' : ''}">
                        Associate Product
                    </a>
                    <a href="#" class="aysa-dropdown-item ${hasPage ? 'dropdown-item-associated' : ''}">
                        Associate Page
                    </a>
                    <div class="aysa-dropdown-divider"></div>
                    <a href="#" class="aysa-dropdown-item aysa-reassociate-item">
                        Associate
                    </a>
                    <div class="aysa-dropdown-divider"></div>
                    <a href="#" class="aysa-dropdown-item aysa-add-keyword-item" style="color: #28a745;">
                        Add keyword
                    </a>
                `;
                
                // Update the dropdown content
                $dropdown.find('.aysa-dropdown-content').html(dropdownContent);
            }
            
            // Toggle the open class for this dropdown
            $dropdown.toggleClass('open');
        });
        
        // Close dropdown when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.aysa-action-dropdown').length) {
                $('.aysa-action-dropdown.open').removeClass('open');
            }
        });
        
        // Prevent dropdown from closing when clicking inside it
        $resultsTable.on('click', '.aysa-dropdown-content', function(e) {
            e.stopPropagation();
        });

        // Add click handler for association options
        $resultsTable.on('click', '.aysa-dropdown-item', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const $link = $(this);
            const action = $link.text().trim();
            const $row = $link.closest('tr');
            const keyword = String($row.data('keyword') || '').trim();
            const volume = $row.find('.aysa-volume-cell').text().trim();
            
            // Prevent spam clicking - check if any operation is in progress
            if ($link.hasClass('aysa-disabled-link') || $('.aysa-dropdown-loading').length > 0) {
                return;
            }
            
            if (action === 'Disassociate') {
                // Handle disassociation
                handleDisassociation(keyword, $row);
            } else if (action === 'Add keyword') {
                // Handle adding keyword to suggestedkeywords table
                handleAddKeyword(keyword, volume, $row);
            } else if (action.includes('Associate') && !action.includes('Category') && !action.includes('Product') && !action.includes('Page')) {
                // Handle reassociation (original functionality) - this is the standalone "Associate" option
                handleReassociation(keyword, volume, $row);
            } else if (action.includes('Associate')) {
                // Disable all dropdown links and add loading state
                const $mainDropdown = $link.closest('.aysa-dropdown-content');
                $mainDropdown.addClass('aysa-dropdown-loading');
                $mainDropdown.find('a').addClass('aysa-disabled-link').css({
                    'pointer-events': 'none',
                    'opacity': '0.5',
                    'cursor': 'not-allowed'
                });
                
                // Disable all other action buttons in the table while loading items
                $('.aysa-action-btn').not($row.find('.aysa-action-btn')).addClass('aysa-action-disabled').css({
                    'pointer-events': 'none',
                    'opacity': '0.4',
                    'cursor': 'not-allowed',
                    'background-color': '#f8f9fa',
                    'color': '#6c757d'
                });
                
                // Add loading indicator to the clicked link
                const originalText = $link.text();
                $link.html(`<span class="dashicons dashicons-update aysa-spinning"></span> ${originalText}`);
                
                // Remove any existing secondary dropdowns
                $('.aysa-secondary-dropdown').remove();
                
                // Determine the association type
                let associationType = '';
                if (action.includes('Category')) {
                    associationType = 'Category';
                } else if (action.includes('Product')) {
                    associationType = 'Product';
                } else if (action.includes('Page')) {
                    associationType = 'Page';
                }
                
                // Create secondary dropdown
                const $secondaryDropdown = $('<div class="aysa-secondary-dropdown"></div>');
                const $loadingItem = $('<div class="aysa-loading-item">Loading items...</div>');
                $secondaryDropdown.append($loadingItem);
                
                // Position the secondary dropdown
                $secondaryDropdown.css({
                    position: 'absolute',
                    left: '-220px',
                    top: '0',
                    width: '200px',
                    backgroundColor: 'white',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                    borderRadius: '4px',
                    zIndex: 100000,
                    border: '1px solid #ddd'
                });
                
                // Add to the main dropdown container
                $mainDropdown.append($secondaryDropdown);
                
                // Load items based on type
                loadAssociationItems(associationType, keyword, $secondaryDropdown, $mainDropdown, $link, originalText);
            }
        });
        
        // Add click handler for "Associate All Keywords" button
        $(document).on('click', '.aysa-associate-all-btn', function(e) {
            e.preventDefault();
            // Skip if button is already associated/disabled or processing
            if ($(this).hasClass('aysa-btn-associated') || $(this).prop('disabled') || $(this).hasClass('aysa-btn-waiting')) {
                return;
            }
            
            const $button = $(this);
            const competitorIndex = $button.data('competitor-index');
            const competitorKeywords = competitorKeywordSets[competitorIndex] || [];
            const competitorVols = competitorVolumes[competitorIndex] || [];
            
            if (competitorKeywords.length === 0) {
                showNotification('No competitor keywords to associate', 'info');
                return;
            }
            
            // Show custom confirmation modal
            showCompetitorAssociationModal(competitorKeywords.length, () => {
                // Associate all keywords
                $button.text('Wait...')
                    .prop('disabled', true)
                    .addClass('aysa-btn-waiting aysa-btn-pulsing');
                
                // Change text for all individual buttons
                $('.aysa-action-btn.associate:not(.aysa-btn-associated)')
                    .text('Wait...')
                    .prop('disabled', true)
                    .addClass('aysa-btn-waiting');
                
                associateCompetitorKeywords(competitorKeywords).then(async (result) => {
                    // Save to localStorage for discovery page
                    await saveCompetitorKeywordsToStorage(competitorKeywords, competitorVols);
                    
                    // Update button
                    $button.text('All Keywords Associated')
                        .addClass('aysa-btn-associated')
                        .removeClass('aysa-btn-waiting aysa-btn-pulsing');
                    
                    // Update all individual associate buttons
                    $('.aysa-action-btn.associate')
                        .text('Associated')
                        .addClass('aysa-btn-associated')
                        .removeClass('aysa-btn-waiting');
                    
                    // Update stored associations
                    if (result && result.createdAssociations) {
                        if (!window.aysaAssociations) {
                            window.aysaAssociations = [];
                        }
                        window.aysaAssociations = window.aysaAssociations.concat(result.createdAssociations);
                    }
                }).catch(error => {
                    // If error occurs, restore the buttons
                    console.error('Error associating keywords:', error);
                    showNotification(`Error associating keywords: ${error.message}`, 'error');
                    $button.text('Associate All')
                        .prop('disabled', false)
                        .removeClass('aysa-btn-waiting aysa-btn-pulsing');
                    
                    $('.aysa-action-btn.associate:not(.aysa-btn-associated)')
                        .text('Associate')
                        .prop('disabled', false)
                        .removeClass('aysa-btn-waiting');
                });
            });
        });
    }

    // Show custom selected keywords add confirmation modal
    function showSelectedKeywordsAssociationModal(keywordCount, onConfirm) {
        const modalHtml = `
            <div class="aysa-selected-modal-overlay">
                <div class="aysa-selected-modal">
                    <div class="aysa-selected-modal-header">
                        <h3>Add to Keyword Research</h3>
                        <button class="aysa-selected-modal-close">&times;</button>
                    </div>
                    <div class="aysa-selected-modal-body">
                        <div class="aysa-selected-icon">
                            <span class="dashicons dashicons-networking"></span>
                        </div>
                        <div class="aysa-selected-message">
                            <p>Add <strong>${keywordCount} selected keywords</strong> to Keyword Research?</p>
                            <p class="aysa-selected-warning">Keywords will be saved in local database and enriched with available metrics.</p>
                        </div>
                    </div>
                    <div class="aysa-selected-modal-footer">
                        <button class="aysa-selected-btn-cancel">Cancel</button>
                        <button class="aysa-selected-btn-confirm">Add to Keyword Research</button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Add event handlers
        $('.aysa-selected-modal-close, .aysa-selected-btn-cancel, .aysa-selected-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                $('.aysa-selected-modal-overlay').remove();
            }
        });
        
        // Prevent modal from closing when clicking inside modal content
        $('.aysa-selected-modal').on('click', function(e) {
            e.stopPropagation();
        });
        
        // Handle confirm
        $('.aysa-selected-btn-confirm').on('click', function() {
            $('.aysa-selected-modal-overlay').remove();
            onConfirm();
        });
        
        // Show modal with animation
        setTimeout(() => {
            $('.aysa-selected-modal-overlay').addClass('aysa-modal-show');
        }, 10);
    }

    // Show custom competitor association confirmation modal
    function showCompetitorAssociationModal(keywordCount, onConfirm) {
        const modalHtml = `
            <div class="aysa-competitor-modal-overlay">
                <div class="aysa-competitor-modal">
                    <div class="aysa-competitor-modal-header">
                        <h3>Confirm Association</h3>
                        <button class="aysa-competitor-modal-close">&times;</button>
                    </div>
                    <div class="aysa-competitor-modal-body">
                        <div class="aysa-competitor-icon">
                            <span class="dashicons dashicons-networking"></span>
                        </div>
                        <div class="aysa-competitor-message">
                            <p>Are you sure you want to associate all <strong>${keywordCount} keywords</strong> from this competitor?</p>
                            <p class="aysa-competitor-warning">This will create associations for all keywords automatically.</p>
                        </div>
                    </div>
                    <div class="aysa-competitor-modal-footer">
                        <button class="aysa-competitor-btn-cancel">Cancel</button>
                        <button class="aysa-competitor-btn-confirm">Associate All Keywords</button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Add event handlers
        $('.aysa-competitor-modal-close, .aysa-competitor-btn-cancel, .aysa-competitor-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                $('.aysa-competitor-modal-overlay').remove();
            }
        });
        
        // Prevent modal from closing when clicking inside modal content
        $('.aysa-competitor-modal').on('click', function(e) {
            e.stopPropagation();
        });
        
        // Handle confirm
        $('.aysa-competitor-btn-confirm').on('click', function() {
            $('.aysa-competitor-modal-overlay').remove();
            onConfirm();
        });
        
        // Show modal with animation
        setTimeout(() => {
            $('.aysa-competitor-modal-overlay').addClass('aysa-modal-show');
        }, 10);
    }

    // Initialize the page
    const projectId = getProjectId();
    if (!projectId) {
        // Dacă nu există un proiect, afișăm un mesaj corespunzător
        $('.aysa-results-table table tbody').html(`
            <tr>
                <td colspan="4" class="aysa-empty-message">
                    No project found. Please create a project first.
                </td>
            </tr>
        `);
        return;
    }

    // Afișăm un mesaj de loading pentru a informa utilizatorul
    $('.aysa-compare-btn').text('Preparing data...').prop('disabled', true);

    // Adăugăm o întârziere artificială pentru a asigura că utilizatorul vede indicatorul de loading
    setTimeout(() => {
        // Get SEO settings + setup competitors and then fetch keyword gap data
        Promise.all([
            getSeoSettings(projectId),
            loadSetupCompetitionCompetitors()
        ]).then(function(results) {
            const seoSettings = results[0];
            const competitors = Array.isArray(results[1]) ? results[1] : [];
            console.log('SEO Settings:', seoSettings);
            
            // Make sure we have the required settings
            if (!seoSettings || !seoSettings.targetedCountry || !seoSettings.primaryLanguage) {
                console.error('Missing required SEO settings');
                $('.aysa-results-table table tbody').html(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            Please configure your SEO settings first.
                        </td>
                    </tr>
                `);
                $('.aysa-compare-btn').text('Compare').prop('disabled', false);
                return;
            }

            const target = window.location.hostname;
            console.log('Current hostname:', target);

            getKeywordGapData(
                target,
                seoSettings.targetedCountry,
                seoSettings.primaryLanguage,
                projectId,
                competitors
            ).then(function(data) {
                console.log('Keyword gap data received:', data);
                displayKeywordGapData(data);
                $('.aysa-compare-btn').text('Compare').prop('disabled', false);
            }).catch(function(error) {
                console.error('Error fetching keyword gap data:', error);
                $('.aysa-results-table table tbody').html(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            Failed to fetch keyword gap data. Please try again later.
                        </td>
                    </tr>
                `);
                $('.aysa-compare-btn').text('Compare').prop('disabled', false);
            });
        }).catch(function(error) {
            console.error('Error fetching SEO settings:', error);
            $('.aysa-results-table table tbody').html(`
                <tr>
                    <td colspan="4" class="aysa-empty-message">
                        Failed to fetch SEO settings. Please check your configuration.
                    </td>
                </tr>
            `);
            $('.aysa-compare-btn').prop('disabled', false).text('Compare');
        });
    }, 800); // Întârziere de 800ms pentru a permite afișarea stării de loading

    // Toggle tabs
    $('.aysa-tab-btn').on('click', function() {
        $('.aysa-tab-btn').removeClass('active');
        $(this).addClass('active');
    });
    
    // Toggle filter pills
    $('.aysa-pill').on('click', function() {
        $('.aysa-pill').removeClass('active');
        $(this).addClass('active');
    });
    
    // Compare button functionality
    $('.aysa-compare-btn').on('click', function() {
        const projectId = getProjectId();
        if (!projectId) {
            $('.aysa-results-table table tbody').html(`
                <tr>
                    <td colspan="4" class="aysa-empty-message">
                        No project found. Please create a project first.
                    </td>
                </tr>
            `);
            return;
        }

        // Show loading state
        $(this).prop('disabled', true).text('Comparing...');

        // Arată indicator de loading în tabel
        $('.aysa-results-table table tbody').html(`
            <tr class="aysa-loading-row">
                <td colspan="4" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Comparing keywords...</span>
                    </div>
                </td>
            </tr>
        `);

        // Adăugăm o întârziere artificială pentru a asigura că utilizatorul vede indicatorul de loading
        setTimeout(() => {
            // Get SEO settings + setup competitors and then fetch keyword gap data
            Promise.all([
                getSeoSettings(projectId),
                loadSetupCompetitionCompetitors()
            ]).then(function(results) {
                const seoSettings = results[0];
                console.log('SEO Settings for comparison:', seoSettings);
                
                // Make sure we have the required settings
                if (!seoSettings || !seoSettings.targetedCountry || !seoSettings.primaryLanguage) {
                    console.error('Missing required SEO settings');
                    $('.aysa-results-table table tbody').html(`
                        <tr>
                            <td colspan="4" class="aysa-empty-message">
                                Please configure your SEO settings first.
                            </td>
                        </tr>
                    `);
                    $('.aysa-compare-btn').prop('disabled', false).text('Compare');
                    return;
                }

                // Location and Language dropdowns removed - no longer need to update them
                // $('.aysa-filter-dropdown.location').val(seoSettings.targetedCountry);
                // $('.aysa-filter-dropdown.language').val(seoSettings.primaryLanguage);

                const target = window.location.hostname;
                console.log('Current hostname for comparison:', target);

                // Get competitors from UI (already enriched with setup competitors)
                const competitors = getCompetitorsFromUI();

                getKeywordGapData(
                    target,
                    seoSettings.targetedCountry,
                    seoSettings.primaryLanguage,
                    projectId,
                    competitors
                ).then(function(data) {
                    console.log('Keyword gap comparison data received:', data);
                    displayKeywordGapData(data);
                    $('.aysa-compare-btn').prop('disabled', false).text('Compare');
                    
                    // Check if dashicons are loaded
                    if (!$('body').hasClass('wp-admin')) {
                        // Ensure dashicons are loaded for notifications
                        $('<link>').appendTo('head').attr({
                            type: 'text/css',
                            rel: 'stylesheet',
                            href: '/wp-includes/css/dashicons.min.css'
                        });
                    }
                }).catch(function(error) {
                    console.error('Error fetching keyword gap data for comparison:', error);
                    $('.aysa-results-table table tbody').html(`
                        <tr>
                            <td colspan="4" class="aysa-empty-message">
                                Failed to fetch keyword gap data. Please try again later.
                            </td>
                        </tr>
                    `);
                    $('.aysa-compare-btn').prop('disabled', false).text('Compare');
                });
            }).catch(function(error) {
                console.error('Error fetching SEO settings for comparison:', error);
                $('.aysa-results-table table tbody').html(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            Failed to fetch SEO settings. Please check your configuration.
                        </td>
                    </tr>
                `);
                $('.aysa-compare-btn').prop('disabled', false).text('Compare');
            });
        }, 800); // Întârziere de 800ms pentru a permite afișarea stării de loading
    });

    // Suprascriu handlerul pentru butonul Add competitor
    $('.aysa-add-btn').off('click').on('click', function() {
        const rawInputDomain = $('.aysa-domain-input').val().trim();
        if (!rawInputDomain) return;

        const normalizedDomain = normalizeCompetitorDomain(rawInputDomain);
        if (!normalizedDomain) {
            showNotification('Invalid competitor domain format.', 'error');
            return;
        }

        const domain = `https://${normalizedDomain}`;

        // Ia projectId din localStorage sau altă sursă
        const projectId = getProjectId();
        if (!projectId) {
            alert('Project ID not found!');
            return;
        }

        // Ia datele existente
        $.ajax({
            url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/KeywordsAndCompetitors/ByProject/${projectId}`,
            type: 'GET',
            success: function(existingData) {
                let competitors = existingData.competitors || [];
                // Normalizează domeniul pentru comparație (fără http/https)
                let cleanDomain = normalizedDomain;
                if (competitors.includes(cleanDomain) || competitors.includes(domain)) {
                    alert('Competitor already exists!');
                    return;
                }
                // Adaugă domeniul cu https://
                competitors.push(domain);
                // Fă update cu noul competitor
                $.ajax({
                    url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/KeywordsAndCompetitors/${existingData.id}`,
                    type: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    data: JSON.stringify({
                        id: existingData.id,
                        projectId: existingData.projectId,
                        keywords: existingData.keywords || [],
                        competitors: competitors
                    }),
                    success: function() {
                        addCompetitorToUI(domain);
                        $('.aysa-domain-input').val('');
                        
                        // Trigger automatic analysis after adding competitor
                        triggerAutomaticAnalysis('added');
                    },
                    error: function() {
                        alert('Failed to add competitor!');
                    }
                });
            },
            error: function() {
                alert('Failed to fetch existing competitors!');
            }
        });
    });

    // Function to trigger automatic analysis after adding or removing a competitor
    function triggerAutomaticAnalysis(action = 'changed') {
        const projectId = getProjectId();
        if (!projectId) {
            console.error('No project ID found for automatic analysis');
            return;
        }

        // Show loading state
        $('.aysa-results-table table tbody').html(`
            <tr class="aysa-loading-row">
                <td colspan="4" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Auto-refreshing analysis...</span>
                    </div>
                </td>
            </tr>
        `);

        // Show visual feedback that auto-refresh is happening
        const message = action === 'added' ? 'Competitor added! Auto-refreshing analysis...' : 
                       action === 'removed' ? 'Competitor removed! Auto-refreshing analysis...' :
                       'Competitors updated! Auto-refreshing analysis...';
        showNotification(message, 'info');

        // Get SEO settings + setup competitors and then fetch keyword gap data
        Promise.all([
            getSeoSettings(projectId),
            loadSetupCompetitionCompetitors()
        ]).then(function(results) {
            const seoSettings = results[0];
            console.log('SEO Settings for automatic analysis:', seoSettings);
            
            // Make sure we have the required settings
            if (!seoSettings || !seoSettings.targetedCountry || !seoSettings.primaryLanguage) {
                console.error('Missing required SEO settings for automatic analysis');
                $('.aysa-results-table table tbody').html(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            Please configure your SEO settings first.
                        </td>
                    </tr>
                `);
                return;
            }

            const target = window.location.hostname;
            console.log('Current hostname for automatic analysis:', target);

            // Get competitors from UI (already enriched with setup competitors)
            const competitors = getCompetitorsFromUI();

            console.log('Competitors for automatic analysis:', competitors);

            getKeywordGapData(
                target,
                seoSettings.targetedCountry,
                seoSettings.primaryLanguage,
                projectId,
                competitors
            ).then(function(data) {
                console.log('Automatic analysis data received:', data);
                displayKeywordGapData(data);
                showNotification('Analysis refreshed successfully!', 'success');
            }).catch(function(error) {
                console.error('Error in automatic analysis:', error);
                
                $('.aysa-results-table table tbody').html(`
                    <tr>
                        <td colspan="4" class="aysa-empty-message">
                            Auto-refresh failed. Please try clicking Compare manually.
                        </td>
                    </tr>
                `);
                showNotification('Auto-refresh failed. Please try Compare manually.', 'error');
            });
        }).catch(function(error) {
            console.error('Failed to get SEO settings for automatic analysis:', error);
            $('.aysa-results-table table tbody').html(`
                <tr>
                    <td colspan="4" class="aysa-empty-message">
                        Failed to get SEO settings. Please try Compare manually.
                    </td>
                </tr>
            `);
            showNotification('Failed to get settings. Please try Compare manually.', 'error');
        });
    }

    // Remove competitor
    $(document).on('click', '.aysa-remove-btn', function() {
        const $box = $(this).closest('.aysa-domain-box');
        const displayDomain = $box.find('.aysa-competitor-domain').text().trim();
        // Reconstruiește domeniul cu https:// pentru baza de date
        const dbDomain = 'https://' + displayDomain.replace(/^https?:\/\//, '');

        // Ia projectId din localStorage
        const projectId = getProjectId();
        if (!projectId) {
            alert('Project ID not found!');
            return;
        }

        // Ia datele existente
        $.ajax({
            url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/KeywordsAndCompetitors/ByProject/${projectId}`,
            type: 'GET',
            success: function(existingData) {
                let competitors = existingData.competitors || [];
                // Elimină domeniul din listă (cu sau fără https)
                competitors = competitors.filter(c => c.replace(/^https?:\/\//, '') !== displayDomain);
                // Fă update cu lista nouă
                $.ajax({
                    url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/KeywordsAndCompetitors/${existingData.id}`,
                    type: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    data: JSON.stringify({
                        id: existingData.id,
                        projectId: existingData.projectId,
                        keywords: existingData.keywords || [],
                        competitors: competitors
                    }),
                    success: function() {
                        $box.remove();
                        
                        // Trigger automatic analysis after removing competitor
                        triggerAutomaticAnalysis('removed');
                    },
                    error: function() {
                        alert('Failed to remove competitor from database!');
                    }
                });
            },
            error: function() {
                alert('Failed to fetch existing competitors!');
            }
        });
    });

    // Handle reassociation (original functionality moved to dropdown)
    function handleReassociation(keyword, volume, $row) {
        const $actionBtn = $row.find('.aysa-action-btn');
        
        // Prevent spam clicking - check if button is already processing
        if ($actionBtn.hasClass('aysa-btn-waiting') || $actionBtn.prop('disabled')) {
            return;
        }
        
        // Change button text and disable it during association
        $actionBtn.text('Wait...')
            .prop('disabled', true)
            .addClass('aysa-btn-waiting aysa-btn-pulsing');
        
        // Associate single keyword using original logic
        associateCompetitorKeywords([keyword]).then(async (result) => {
            // Save to localStorage for discovery page
            await saveCompetitorKeywordsToStorage([keyword], [volume]);
            
            // Update button to show success
            $actionBtn.text('Action')
                .prop('disabled', false)
                .removeClass('aysa-btn-waiting aysa-btn-pulsing');
            
            // Show notification
            showNotification(`Keyword "${keyword}" has been associated!`, 'success');
            
            // Update stored associations
            if (result && result.createdAssociations) {
                if (!window.aysaAssociations) {
                    window.aysaAssociations = [];
                }
                window.aysaAssociations = window.aysaAssociations.concat(result.createdAssociations);
                
                // Check if all keywords for this competitor are now associated
                const activeCompetitorIndex = $('.aysa-tab-btn.active').data('competitor-index');
                if (typeof activeCompetitorIndex !== 'undefined') {
                    checkAllKeywordsAssociated(activeCompetitorIndex);
                }
            }
        }).catch(error => {
            // If error occurs, restore the button
            console.error('Error associating keyword:', error);
            showNotification(`Error associating keyword: ${error.message}`, 'error');
            $actionBtn.text('Action')
                .prop('disabled', false)
                .removeClass('aysa-btn-waiting aysa-btn-pulsing');
        });
    }

    // Handle disassociation functionality
    function handleDisassociation(keyword, $row) {
        // Show confirmation modal
        if (!confirm(`Are you sure you want to disassociate the keyword "${keyword}"? This will remove all associations for this keyword.`)) {
            return;
        }
        
        const $actionBtn = $row.find('.aysa-action-btn');
        
        // Change button text and add loading state
        $actionBtn.html('<span class="dashicons dashicons-update aysa-spinning"></span> Removing...')
            .prop('disabled', true)
            .addClass('aysa-btn-waiting');
        
        // Close the dropdown
        $('.aysa-action-dropdown.open').removeClass('open');
        
        // Get all associations for this keyword
        const keywordAssociations = window.aysaAssociations ? 
            window.aysaAssociations.filter(a => a.keyword === keyword) : [];
        
        if (keywordAssociations.length === 0) {
            showNotification('No associations found for this keyword', 'info');
            // Restore button
            $actionBtn.text('Action')
                .prop('disabled', false)
                .removeClass('aysa-btn-waiting aysa-btn-associated');
            $row.removeClass('aysa-row-associated');
            return;
        }
        
        // Delete all associations for this keyword
        const deletePromises = keywordAssociations.map(association => {
            const apiBaseUrl = ((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '');
            return fetch(`${apiBaseUrl}/api/Association/${association.id}`, {
                method: 'DELETE'
            });
        });
        
        Promise.all(deletePromises).then(responses => {
            // Check if all deletions were successful
            const allSuccessful = responses.every(response => response.ok);
            
            if (allSuccessful) {
                // Remove associations from local storage
                window.aysaAssociations = window.aysaAssociations.filter(a => a.keyword !== keyword);
                
                // Update visual styling
                $row.removeClass('aysa-row-associated');
                $actionBtn.text('Action')
                    .removeClass('aysa-btn-associated aysa-btn-waiting')
                    .prop('disabled', false);
                
                showNotification(`Keyword "${keyword}" has been disassociated!`, 'success');
                
                // Reload associations to ensure consistency
                loadAssociations();
            } else {
                throw new Error('Some associations could not be deleted');
            }
        }).catch(error => {
            console.error('Error disassociating keyword:', error);
            showNotification(`Error disassociating keyword: ${error.message}`, 'error');
            
            // Restore button
            $actionBtn.text('Associated')
                .removeClass('aysa-btn-waiting')
                .prop('disabled', false);
        });
    }

    // Handle adding keyword to suggestedkeywords table
    function handleAddKeyword(keyword, volume, $row) {
        // Show confirmation modal
        if (!confirm(`Add "${keyword}" to Keyword Discovery?`)) {
            return;
        }
        
        const $actionBtn = $row.find('.aysa-action-btn');
        
        // Change button text and add loading state
        $actionBtn.html('<span class="dashicons dashicons-update aysa-spinning"></span> Adding...')
            .prop('disabled', true)
            .addClass('aysa-btn-waiting');
        
        // Close the dropdown
        $('.aysa-action-dropdown.open').removeClass('open');
        
        // Get project ID
        const projectId = getProjectId();
        if (!projectId) {
            showNotification('Project ID not found', 'error');
            // Restore button
            $actionBtn.text('Action')
                .prop('disabled', false)
                .removeClass('aysa-btn-waiting');
            return;
        }
        
        // Prepare data for suggestedkeywords table (matching the format from keyword-discovery.php)
        const keywordData = {
            ProjectId: projectId,
            Keyword: keyword,
            SearchVolume: parseInt(volume.replace(/,/g, '')) || 0,
            Difficulty: 50,
            Intent: 'N/A',
            Competition: 'Medium'
        };
        
        console.log('🔄 Adding keyword to suggestedkeywords:', keywordData);
        
        // Make API call to add keyword to suggestedkeywords table (using correct endpoint)
        $.ajax({
            url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/SuggestedKeywords/insert-one`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(keywordData),
            success: function(response) {
                console.log('✅ Keyword added successfully:', response);
                
                // Check if the response indicates success
                if (response.success && response.data) {
                    showNotification(`Keyword "${keyword}" added to Keyword Discovery!`, 'success');
                    
                    // Add to local window.aysaKeywords array for immediate UI update
                    if (!window.aysaKeywords) {
                        window.aysaKeywords = [];
                    }
                    window.aysaKeywords.push({
                        keyword: keyword,
                        searchVolume: volume,
                        source: 'Competitor Gap Analysis'
                    });
                    
                    // Update row styling to reflect it's now in discovery
                    $row.addClass('aysa-row-common');
                    
                    console.log('🔄 Updated window.aysaKeywords:', window.aysaKeywords.length, 'keywords');
                } else {
                    // Handle unexpected response format
                    console.warn('Unexpected response format:', response);
                    showNotification(`Keyword "${keyword}" may have been added, but response was unexpected.`, 'warning');
                }
                
                // Restore button
                $actionBtn.text('Action')
                    .prop('disabled', false)
                    .removeClass('aysa-btn-waiting');
            },
            error: function(xhr, status, error) {
                console.error('❌ Error adding keyword:', error);
                console.error('Response:', xhr.responseText);
                
                let errorMessage = 'Failed to add keyword';
                
                // Handle 409 Conflict (keyword already exists)
                if (xhr.status === 409) {
                    try {
                        const errorData = JSON.parse(xhr.responseText);
                        errorMessage = errorData.message || 'Keyword already exists.';
                    } catch (e) {
                        errorMessage = 'Keyword already exists.';
                    }
                } else {
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        if (errorResponse.message) {
                            errorMessage = errorResponse.message;
                        }
                    } catch (e) {
                        errorMessage = `Failed to add keyword (${xhr.status})`;
                    }
                }
                
                showNotification(`Error: ${errorMessage}`, 'error');
                
                // Restore button
                $actionBtn.text('Action')
                    .prop('disabled', false)
                    .removeClass('aysa-btn-waiting');
            }
        });
    }

    // Load association items function
    function loadAssociationItems(associationType, keyword, $secondaryDropdown, $mainDropdown, $link, originalText) {
        // Make AJAX request to get items
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_items',
                type: associationType,
                nonce: '<?php echo wp_create_nonce('aysa_get_items_nonce'); ?>'
            },
            success: function(response) {
                // Re-enable dropdown links
                $mainDropdown.removeClass('aysa-dropdown-loading');
                $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer'
                });
                
                // Re-enable all action buttons in the table
                $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer',
                    'background-color': '',
                    'color': ''
                });
                
                // Restore original text
                $link.text(originalText);
                
                if (response.success && response.data) {
                    $secondaryDropdown.empty();
                    
                    if (response.data.length === 0) {
                        $secondaryDropdown.append('<div class="aysa-loading-item">No ' + associationType.toLowerCase() + 's found</div>');
                    } else {
                        // Get current associations for this keyword
                        const currentAssociations = window.aysaAssociations?.filter(a => 
                            a.keyword === keyword && a.associatedOn === associationType
                        ) || [];
                        
                        response.data.forEach(function(item) {
                            const $item = $('<div class="aysa-dropdown-item"></div>');
                            $item.text(item.name);
                            $item.data('id', item.id);
                            $item.data('type', associationType);
                            
                            // Check if this item is currently associated with this keyword
                            const isAssociated = currentAssociations.some(a => a.idIntern === item.id);
                            if (isAssociated) {
                                $item.addClass('aysa-item-associated');
                            }
                            
                            // Check if this item has any associations with any keywords (mark with yellow)
                            const hasAnyAssociations = window.aysaAssociations?.some(a => 
                                a.associatedOn === associationType && a.idIntern === item.id
                            );
                            if (hasAnyAssociations && !isAssociated) {
                                $item.addClass('aysa-item-has-associations');
                            }
                            
                            // Add click handler for item selection
                            $item.on('click', function() {
                                const $clickedItem = $(this);
                                const $row = $link.closest('tr');
                                
                                // Prevent multiple clicks
                                if ($clickedItem.hasClass('aysa-processing')) {
                                    return;
                                }
                                
                                const itemId = $clickedItem.data('id');
                                const itemType = $clickedItem.data('type');
                                const itemName = $clickedItem.text();
                                const isAssociated = $clickedItem.hasClass('aysa-item-associated');
                                
                                // Disable all dropdown options and secondary dropdown items during association
                                $mainDropdown.addClass('aysa-dropdown-processing');
                                $mainDropdown.find('a').addClass('aysa-disabled-link').css({
                                    'pointer-events': 'none',
                                    'opacity': '0.5',
                                    'cursor': 'not-allowed'
                                });
                                
                                // Disable all action buttons in the table
                                $('.aysa-action-btn').not($row.find('.aysa-action-btn')).addClass('aysa-action-disabled').css({
                                    'pointer-events': 'none',
                                    'opacity': '0.4',
                                    'cursor': 'not-allowed',
                                    'background-color': '#f8f9fa',
                                    'color': '#6c757d'
                                });
                                
                                // Disable all secondary dropdown items
                                $secondaryDropdown.find('.aysa-dropdown-item').not($clickedItem).css({
                                    'pointer-events': 'none',
                                    'opacity': '0.3',
                                    'cursor': 'not-allowed'
                                });
                                
                                // Add processing state
                                $clickedItem.addClass('aysa-processing');
                                $clickedItem.css('pointer-events', 'none');
                                
                                // Add loading indicator
                                const originalText = $clickedItem.text();
                                $clickedItem.html(`<span class="dashicons dashicons-update aysa-spinning"></span> ${isAssociated ? 'Removing...' : 'Adding...'}`);
                                
                                if (isAssociated) {
                                    // Find the association ID for this item
                                    const association = window.aysaAssociations?.find(a => 
                                        a.keyword === keyword && 
                                        a.associatedOn === itemType && 
                                        a.idIntern === itemId
                                    );
                                    
                                    if (association) {
                                        // Disassociate
                                        // Get project ID from localStorage
                                        const projectId = getProjectId();
                                        
                                        // Build the API URL with optional projectId parameter
                                        let apiUrl = `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/Association/${association.id}`;
                                        if (projectId) {
                                            apiUrl += `?projectId=${projectId}`;
                                        }
                                        
                                        $.ajax({
                                            url: apiUrl,
                                            type: 'DELETE',
                                            success: function() {
                                                showNotification(`Successfully disassociated "${keyword}" from ${itemType.toLowerCase()} "${itemName}"`, 'success');
                                                
                                                // Re-enable all dropdown options
                                                $mainDropdown.removeClass('aysa-dropdown-processing');
                                                $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer'
                                                });
                                                
                                                // Re-enable all action buttons in the table
                                                $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer',
                                                    'background-color': '',
                                                    'color': ''
                                                });
                                                
                                                // Remove association from window.aysaAssociations
                                                if (window.aysaAssociations) {
                                                    window.aysaAssociations = window.aysaAssociations.filter(a => a.id !== association.id);
                                                }
                                                
                                                // Update the item styling
                                                $clickedItem.removeClass('aysa-item-associated aysa-processing')
                                                    .text(itemName);
                                                
                                                // Check if item still has other associations (for yellow styling)
                                                const stillHasAssociations = window.aysaAssociations?.some(a => 
                                                    a.associatedOn === itemType && a.idIntern === itemId
                                                );
                                                if (stillHasAssociations) {
                                                    $clickedItem.addClass('aysa-item-has-associations');
                                                } else {
                                                    $clickedItem.removeClass('aysa-item-has-associations');
                                                }
                                                
                                                // Close dropdowns like in keyword discovery
                                                $('.aysa-secondary-dropdown').remove();
                                                $('.aysa-action-dropdown').removeClass('open');
                                                
                                                // Re-enable all secondary dropdown items
                                                $secondaryDropdown.find('.aysa-dropdown-item').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer'
                                                });
                                                
                                                // Update the main dropdown text to reflect the change
                                                $link.html(originalText);
                                            },
                                            error: function(xhr, status, error) {
                                                console.error('Failed to disassociate:', error);
                                                showNotification(`Failed to disassociate "${keyword}" from ${itemType.toLowerCase()}`, 'error');
                                                
                                                // Restore item
                                                $clickedItem.text(originalText);
                                                
                                                // Re-enable everything
                                                $mainDropdown.removeClass('aysa-dropdown-processing');
                                                $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer'
                                                });
                                                
                                                $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer',
                                                    'background-color': '',
                                                    'color': ''
                                                });
                                                
                                                $secondaryDropdown.find('.aysa-dropdown-item-secondary').css({
                                                    'pointer-events': 'auto',
                                                    'opacity': '1',
                                                    'cursor': 'pointer'
                                                });
                                                
                                                $link.html(originalText);
                                            }
                                        });
                                    }
                                } else {
                                    // Associate
                                    const projectId = getProjectId();
                                    if (!projectId) {
                                        showNotification('Project ID not found', 'error');
                                        return;
                                    }
                                    
                                    // Create association object
                                    const association = {
                                        keyword: keyword,
                                        associatedOn: itemType,
                                        idIntern: itemId,
                                        value: itemName
                                    };
                                    
                                    // Add projectId if available
                                    if (projectId) {
                                        association.projectId = parseInt(projectId);
                                    }
                                    
                                    $.ajax({
                                        url: `${((window.aysaParams && window.aysaParams.api_base_url) || (window.aysa_ajax && window.aysa_ajax.api_base_url) || 'https://api.aysa.ai').replace(/\/+$/, '')}/api/Association/upsert`,
                                        type: 'PUT',
                                        contentType: 'application/json',
                                        data: JSON.stringify(association),
                                        success: function(result) {
                                            showNotification(`Successfully associated "${keyword}" with ${itemType.toLowerCase()} "${itemName}"`, 'success');
                                            
                                            // Re-enable all dropdown options
                                            $mainDropdown.removeClass('aysa-dropdown-processing');
                                            $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer'
                                            });
                                            
                                            // Re-enable all action buttons in the table
                                            $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer',
                                                'background-color': '',
                                                'color': ''
                                            });
                                            
                                            // Add association to window.aysaAssociations
                                            if (!window.aysaAssociations) {
                                                window.aysaAssociations = [];
                                            }
                                            
                                            // Add new association to the local array
                                            window.aysaAssociations.push({
                                                keyword: keyword,
                                                associatedOn: itemType,
                                                idIntern: itemId,
                                                value: itemName,
                                                id: result.id || Date.now() // Use response ID or fallback
                                            });
                                            
                                            // Update item appearance
                                            $clickedItem.addClass('aysa-item-associated')
                                                .removeClass('aysa-processing aysa-item-has-associations')
                                                .text(itemName);
                                            
                                            // Close dropdowns like in keyword discovery
                                            $('.aysa-secondary-dropdown').remove();
                                            $('.aysa-action-dropdown').removeClass('open');
                                            
                                            // Re-enable all secondary dropdown items
                                            $secondaryDropdown.find('.aysa-dropdown-item').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer'
                                            });
                                            
                                            // Update the main dropdown text to reflect the change
                                            $link.html(originalText);
                                        },
                                        error: function(xhr, status, error) {
                                            console.error('Failed to associate:', error);
                                            showNotification(`Failed to associate "${keyword}" with ${itemType.toLowerCase()}`, 'error');
                                            
                                            // Restore item
                                            $clickedItem.text(originalText);
                                            
                                            // Re-enable everything
                                            $mainDropdown.removeClass('aysa-dropdown-processing');
                                            $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer'
                                            });
                                            
                                            $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer',
                                                'background-color': '',
                                                'color': ''
                                            });
                                            
                                            $secondaryDropdown.find('.aysa-dropdown-item').css({
                                                'pointer-events': 'auto',
                                                'opacity': '1',
                                                'cursor': 'pointer'
                                            });
                                            
                                            $link.html(originalText);
                                        }
                                    });
                                }
                            });
                            
                            $secondaryDropdown.append($item);
                        });
                    }
                } else {
                    $secondaryDropdown.html('<div class="aysa-loading-item">Failed to load ' + associationType.toLowerCase() + 's</div>');
                }
                
                // Restore the link text
                $link.html(originalText);
                
                // Re-enable dropdown options
                $mainDropdown.removeClass('aysa-dropdown-loading');
                $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer'
                });
                
                // Re-enable all action buttons
                $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer',
                    'background-color': '',
                    'color': ''
                });
            },
            error: function() {
                $secondaryDropdown.html('<div class="aysa-loading-item">Error loading ' + associationType.toLowerCase() + 's</div>');
                
                // Restore the link text
                $link.text(originalText);
                
                // Re-enable dropdown options
                $mainDropdown.removeClass('aysa-dropdown-loading');
                $mainDropdown.find('a').removeClass('aysa-disabled-link').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer'
                });
                
                // Re-enable all action buttons
                $('.aysa-action-btn').removeClass('aysa-action-disabled').css({
                    'pointer-events': 'auto',
                    'opacity': '1',
                    'cursor': 'pointer',
                    'background-color': '',
                    'color': ''
                });
            }
        });
    }

    // Bulk Selection Functionality
    let selectedKeywords = [];
    
    // Handle select all checkbox
    $(document).on('change', '#select-all-keywords', function() {
        const isChecked = $(this).is(':checked');
        $('.aysa-keyword-checkbox:not(:disabled)').prop('checked', isChecked);
        updateSelectedKeywords();
    });
    
    // Handle individual keyword checkboxes
    $(document).on('change', '.aysa-keyword-checkbox', function() {
        updateSelectedKeywords();
        
        // Update select-all checkbox state
        const totalCheckboxes = $('.aysa-keyword-checkbox:not(:disabled)').length;
        const checkedCheckboxes = $('.aysa-keyword-checkbox:not(:disabled):checked').length;
        
        if (checkedCheckboxes === 0) {
            $('#select-all-keywords').prop('indeterminate', false).prop('checked', false);
        } else if (checkedCheckboxes === totalCheckboxes) {
            $('#select-all-keywords').prop('indeterminate', false).prop('checked', true);
        } else {
            $('#select-all-keywords').prop('indeterminate', true).prop('checked', false);
        }
    });
    
    // Update selected keywords array and UI
    function updateSelectedKeywords() {
        selectedKeywords = [];
        $('.aysa-keyword-checkbox:checked').each(function() {
            const keyword = $(this).data('keyword');
            const $row = $(this).closest('tr');
            const volume = $row.data('volume');
            selectedKeywords.push({ keyword, volume, row: $row });
        });
        
        // Update selected count
        $('.aysa-selected-count').text(selectedKeywords.length);
        
        // Show/hide bulk actions
        if (selectedKeywords.length > 0) {
            $('.aysa-bulk-actions').show();
            // Add selected styling to rows
            $('.aysa-keyword-checkbox:checked').closest('tr').addClass('aysa-row-selected');
            $('.aysa-keyword-checkbox:not(:checked)').closest('tr').removeClass('aysa-row-selected');
        } else {
            $('.aysa-bulk-actions').hide();
            $('.aysa-keywords-table tr').removeClass('aysa-row-selected');
        }
    }
    
    // Handle bulk add button
    $(document).on('click', '.aysa-bulk-associate-btn', function(e) {
        e.preventDefault();
        
        // Prevent spam clicking - check if button is disabled
        if ($(this).prop('disabled') || $(this).hasClass('aysa-btn-waiting')) {
            return;
        }
        
        if (selectedKeywords.length === 0) {
            showNotification('No keywords selected', 'info');
            return;
        }
        
        const $button = $(this);
        const keywordList = selectedKeywords.map(k => k.keyword);
        const volumeList = selectedKeywords.map(k => k.volume);
        
        // Show custom confirmation modal
        showSelectedKeywordsAssociationModal(selectedKeywords.length, () => {
            // Add selected keywords to keyword research
            $button.html(`<span class="dashicons dashicons-update aysa-spinning"></span> Processing...`)
                .prop('disabled', true)
                .addClass('aysa-btn-waiting');
            
            // Disable clear selection button during processing
            $('.aysa-clear-selection-btn').prop('disabled', true);
            
            // Mark all selected rows as processing
            selectedKeywords.forEach(keywordObj => {
                keywordObj.row.addClass('aysa-row-processing');
            });
            
            addKeywordsToKeywordResearch(selectedKeywords).then((result) => {
                // Mark selected rows as success
                selectedKeywords.forEach(keywordObj => {
                    keywordObj.row.removeClass('aysa-row-processing').addClass('aysa-row-success');
                    keywordObj.row.addClass('aysa-row-in-research');
                    keywordObj.row.find('.aysa-keyword-checkbox').prop('checked', false).prop('disabled', true);
                });
                
                // Show success notification
                const persisted = (result && result.persisted) ? result.persisted : {};
                const totalDone = Number((persisted.inserted || 0)) + Number((persisted.updated || 0));
                showNotification(`Added ${totalDone}/${keywordList.length} keywords to Keyword Research.`, 'success');
                
                // Clear selection after successful association
                setTimeout(() => {
                    clearSelection();
                    // Reset row states after 3 seconds
                    $('.aysa-keywords-table tr').removeClass('aysa-row-success aysa-row-error aysa-row-processing');
                }, 3000);
                
            }).catch(error => {
                console.error('Error adding keywords to research:', error);
                showNotification(`Error adding keywords: ${error.message}`, 'error');
                
                // Mark selected rows as error
                selectedKeywords.forEach(keywordObj => {
                    keywordObj.row.removeClass('aysa-row-processing').addClass('aysa-row-error');
                });
                
                // Reset row states after 3 seconds
                setTimeout(() => {
                    $('.aysa-keywords-table tr').removeClass('aysa-row-success aysa-row-error aysa-row-processing');
                }, 3000);
                
            }).finally(() => {
                // Re-enable button
                $button.html(`<span class="dashicons dashicons-networking"></span> Add to Keyword Research`)
                    .prop('disabled', false)
                    .removeClass('aysa-btn-waiting');
                
                // Re-enable clear selection button
                $('.aysa-clear-selection-btn').prop('disabled', false);
            });
        });
    });

    
    // Handle clear selection
    $(document).on('click', '.aysa-clear-selection-btn', function() {
        clearSelection();
    });
    
    // Clear all selections
    function clearSelection() {
        $('.aysa-keyword-checkbox, #select-all-keywords').prop('checked', false).prop('indeterminate', false);
        selectedKeywords = [];
        updateSelectedKeywords();
    }
    
    // Initialize root domain on page load
    const currentDomain = window.location.hostname;
    $('.aysa-your-domain').text(currentDomain);

    // Handle refresh data button click
    $('#aysa-refresh-competitor-gap').on('click', function() {
        refreshCompetitorGapData();
    });

    // Function to refresh competitor gap data via POST
    function refreshCompetitorGapData() {
        const $button = $('#aysa-refresh-competitor-gap');
        const projectId = getProjectId();
        
        if (!projectId) {
            showNotification('No project found. Please create a project first.', 'error');
            return;
        }

        // Note: Competitors are automatically retrieved from database by backend

        // Show loading state
        $button.prop('disabled', true).addClass('loading').html(
            '<span class="dashicons dashicons-update"></span> Refreshing...'
        );

        // Get SEO settings for location and language
        getSeoSettings(projectId).then(function(seoSettings) {
            if (!seoSettings || !seoSettings.targetedCountry || !seoSettings.primaryLanguage) {
                showNotification('Please configure your SEO settings first.', 'error');
                $button.prop('disabled', false).removeClass('loading').html(
                    '<span class="dashicons dashicons-update"></span> Refresh Data'
                );
                return;
            }

            loadSetupCompetitionCompetitors().then(function() {
                const competitors = getCompetitorsFromUI();
                return getKeywordGapData(
                    currentDomain,
                    seoSettings.targetedCountry,
                    seoSettings.primaryLanguage,
                    projectId,
                    competitors,
                    200,
                    true
                );
            }).then(function(response) {
                console.log('Competitor gap data refreshed successfully:', response);
                showNotification('Competitor gap data refreshed and saved locally.', 'success');
                displayKeywordGapData(response);
                $('.aysa-results-section').show();
            }).catch(function(error) {
                console.error('Error refreshing competitor gap data:', error);
                showNotification('Failed to refresh competitor gap data.', 'error');
            }).finally(function() {
                $button.prop('disabled', false).removeClass('loading').html(
                    '<span class="dashicons dashicons-update"></span> Refresh Data'
                );
            });
        }).catch(function(error) {
            console.error('Error getting SEO settings:', error);
            showNotification('Error getting SEO settings. Please try again.', 'error');
            $button.prop('disabled', false).removeClass('loading').html(
                '<span class="dashicons dashicons-update"></span> Refresh Data'
            );
        });
    }
});
</script> 
