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

// Enqueue local Chart fallback (no external CDN dependency).
wp_enqueue_script('chart-js', AYSA_PLUGIN_URL . 'assets/js/vendor/chartjs-stub.js', array(), AYSA_VERSION, true);
?>

<div class="aysa-admin aysa-competitor-identification">
    <!-- Page Title -->
    <div class="aysa-page-title">
        <h1>Aysa.ai - SEO Competitor Identification</h1>
        <div class="aysa-title-right">
            <?php 
            // Use the credits component
            if (class_exists('Aysa_Credits_Component')) {
                Aysa_Credits_Component::display();
            } else {
                echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
            }
            ?>
        </div>
    </div>

    <!-- Top Tabs -->
    <div class="aysa-top-tabs">
                <a href="admin.php?page=aysa-research&tab=keyword-discovery" class="aysa-tab">Keyword Discovery</a>
        <a href="admin.php?page=aysa-research&tab=competitor-gap" class="aysa-tab">Competitor Keyword Gap</a>
        <div class="aysa-tab active">Competitor Identification</div>
        <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-identification-content">
            <!-- Competitor Analysis Panel -->
            <div class="aysa-panel">
                <h2 class="aysa-panel-title">
                    <span class="aysa-icon">🔍</span>
                    Competitor Analysis
                </h2>

                <!-- Domains Section -->
                <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" id="aysa-current-domain"><span class="aysa-loading-spinner"></span></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>

                <!-- Filters Section -->
                <div class="aysa-filters-section">
                    <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-identification" title="Refresh competitor identification data from API">
                                    <span class="dashicons dashicons-update"></span> Refresh Data
                                </button>
                                <button class="aysa-analyze-btn">Analyze</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="aysa-seed-overview">
                    <div class="aysa-seed-overview-head">
                        <h3>Seed Keywords Competitor Discovery</h3>
                        <p>Top competitors extracted from Google SERP for seed keywords from Setup SEO Profile.</p>
                    </div>
                    <div class="aysa-seed-overview-meta">
                        <div><strong>Seed keywords:</strong> <span id="aysa-seed-keywords-count">0</span></div>
                        <div><strong>Unique competitors:</strong> <span id="aysa-seed-competitors-count">0</span></div>
                        <div><strong>Active / Suggested:</strong> <span id="aysa-seed-competitor-status-counts">0 / 0</span></div>
                        <div><strong>Data source:</strong> <span id="aysa-seed-provider">-</span></div>
                        <div><strong>Last refresh:</strong> <span id="aysa-seed-last-refresh">-</span></div>
                    </div>
                    <div class="aysa-seed-chip-wrap" id="aysa-seed-keywords-list"></div>
                    <div class="aysa-seed-rank-layout">
                        <div class="aysa-seed-rank-main">
                            <div class="aysa-seed-table-wrap aysa-seed-matrix-wrap">
                                <table class="aysa-seed-table aysa-seed-matrix-table">
                                    <thead>
                                        <tr>
                                            <th>Seed Keyword</th>
                                            <th>Top 10 Ranking (1→10)</th>
                                        </tr>
                                    </thead>
                                    <tbody id="aysa-seed-keyword-top10-body">
                                        <tr><td colspan="2">Loading...</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <aside class="aysa-seed-rank-side">
                            <h4>Top Competitors (Unique)</h4>
                            <div id="aysa-seed-competitors-body" class="aysa-seed-competitor-list">
                                <div class="aysa-seed-competitor-item">Loading...</div>
                            </div>
                        </aside>
                    </div>
                </div>

                <!-- Results Section -->
                <div class="aysa-results-container">
                    <div class="aysa-results-panel">
                        <div class="aysa-results-table">
                            <table class="aysa-keywords-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>
                                    <!-- Table rows will be populated by JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <div class="aysa-overlap-panel">
                        <div class="aysa-overlap-header">
                            <h3>Keyword Position Distribution</h3>
                            <div class="aysa-domain-selector">
                                <select class="aysa-domain-select">
                                    <!-- Domain options will be populated by JavaScript -->
                                </select>
                            </div>
                        </div>
                        <div class="aysa-chart-container">
                            <canvas id="keywordDistributionChart"></canvas>
                        </div>
                        
                        <div class="aysa-metrics">
                            <div class="aysa-metric">
                                <span class="aysa-metric-label">New Keywords</span>
                                <span class="aysa-metric-value new-keywords">0</span>
                            </div>
                            <div class="aysa-metric">
                                <span class="aysa-metric-label">Improved</span>
                                <span class="aysa-metric-value improved-keywords">0</span>
                            </div>
                            <div class="aysa-metric">
                                <span class="aysa-metric-label">Declined</span>
                                <span class="aysa-metric-value declined-keywords">0</span>
                            </div>
                            <div class="aysa-metric">
                                <span class="aysa-metric-label">Lost</span>
                                <span class="aysa-metric-value lost-keywords">0</span>
                            </div>
                        </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 */
.aysa-content {
    padding: 20px;
    flex-grow: 1;
    max-width: 100%;
    overflow-x: auto;
}

.aysa-competitor-identification-content {
    width: 100%;
}

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

.aysa-panel-title {
    font-size: 18px;
    margin: 0 0 20px;
    font-weight: 500;
    display: flex;
    align-items: center;
}

.aysa-icon {
    margin-right: 10px;
}

/* 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;
    flex: 1;
    min-width: 200px;
    max-width: 300px;
    overflow: hidden;
    box-sizing: border-box;
}

.aysa-add-competitor {
    flex: 1;
    min-width: 200px;
    max-width: 300px;
    box-sizing: border-box;
}

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

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

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

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

.aysa-you-label {
    background-color: #e8f0fe;
    color: #1a73e8;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
}

.aysa-competitor-dot {
    width: 10px;
    height: 10px;
    background-color: #fbbc04;
    border-radius: 50%;
    display: inline-block;
}

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

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

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

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

.aysa-filters-row {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: flex-end;
}

.aysa-filter-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
    min-width: 150px;
}

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

.aysa-filter-dropdown {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: white;
    font-size: 14px;
}

.aysa-actions-section {
    flex-grow: 1;
}

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

.aysa-analyze-btn {
    background-color: #1a73e8;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-weight: 500;
    cursor: pointer;
}

/* Results Container */
.aysa-results-container {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

@media (min-width: 1200px) {
    .aysa-results-container {
        grid-template-columns: 2fr 1fr;
    }
}

.aysa-results-panel {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.aysa-results-table {
    overflow-x: auto;
    padding: 0 20px 20px;
}

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

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

.aysa-keywords-table th {
    background-color: #f8f9fa;
    font-weight: 500;
    color: #666;
    white-space: nowrap;
}

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

/* Overlap Panel */
.aysa-overlap-panel {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.aysa-overlap-header {
    display: flex;
    flex-direction: column;
    margin-bottom: 15px;
}

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

.aysa-chart-container {
    height: 300px;
    margin-bottom: 20px;
}

.aysa-metrics {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    justify-content: space-around;
}

.aysa-metric {
    text-align: center;
    min-width: 80px;
}

.aysa-metric-label {
    display: block;
    font-size: 12px;
    color: #666;
    margin-bottom: 5px;
}

.aysa-metric-value {
    font-size: 18px;
    font-weight: 500;
}

.aysa-domain-selector {
    margin-top: 10px;
}

.aysa-domain-select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: white;
    font-size: 14px;
    width: 100%;
}

/* Domain Authority Comparison Styling */
.aysa-authority-higher {
    color: #34a853;
    font-weight: 500;
}

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

/* Add or restore CSS for .aysa-competitor-boxes to display as a flex row */
.aysa-competitor-boxes {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-top: 15px;
}

.aysa-seed-overview {
    margin-top: 18px;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    background: #f8fafc;
    padding: 16px;
}

.aysa-seed-overview-head h3 {
    margin: 0 0 4px;
    font-size: 18px;
}

.aysa-seed-overview-head p {
    margin: 0;
    color: #475569;
}

.aysa-seed-overview-meta {
    display: grid;
    grid-template-columns: repeat(4, minmax(160px, 1fr));
    gap: 10px;
    margin-top: 12px;
    font-size: 13px;
}

.aysa-seed-chip-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 12px;
}

.aysa-seed-chip {
    display: inline-block;
    background: #e2e8f0;
    color: #0f172a;
    border-radius: 999px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 600;
}

.aysa-seed-table-wrap {
    margin-top: 12px;
    overflow-x: auto;
}

.aysa-seed-table {
    width: 100%;
    border-collapse: collapse;
    background: #fff;
    border: 1px solid #dbe1ea;
}

.aysa-seed-table th,
.aysa-seed-table td {
    border-bottom: 1px solid #eef2f7;
    padding: 10px 12px;
    text-align: left;
    font-size: 13px;
}

.aysa-seed-table th {
    background: #f1f5f9;
    font-weight: 700;
    color: #1e293b;
}

.aysa-seed-table tr:last-child td {
    border-bottom: none;
}

.aysa-seed-rank-layout {
    margin-top: 14px;
    display: grid;
    grid-template-columns: minmax(0, 1fr) 280px;
    gap: 12px;
    align-items: start;
}

.aysa-seed-matrix-wrap {
    margin-top: 0;
}

.aysa-seed-matrix-table {
    table-layout: auto;
    min-width: 0;
}

.aysa-seed-matrix-table th:first-child {
    position: sticky;
    left: 0;
    z-index: 2;
    background: #fff;
    width: 220px;
    min-width: 220px;
}

.aysa-seed-matrix-table th:first-child {
    background: #f1f5f9;
    z-index: 3;
}

.aysa-seed-rank-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.aysa-seed-rank-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    max-width: 210px;
    background: #eff6ff;
    border: 1px solid #bfdbfe;
    border-radius: 999px;
    padding: 4px 9px;
    font-size: 12px;
    line-height: 1.2;
}

.aysa-seed-rank-index {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 18px;
    height: 18px;
    border-radius: 999px;
    background: #1d4ed8;
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    flex: 0 0 18px;
}

.aysa-seed-rank-name {
    color: #0f172a;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.aysa-seed-rank-badge.is-own {
    background: #ecfdf3;
    border-color: #86efac;
}

.aysa-seed-rank-badge.is-own .aysa-seed-rank-index {
    background: #15803d;
}

.aysa-seed-rank-own-tag {
    color: #166534;
    font-weight: 700;
    font-size: 10px;
    text-transform: uppercase;
}

.aysa-seed-rank-cell {
    display: flex;
    flex-direction: column;
    gap: 2px;
    line-height: 1.2;
}

.aysa-seed-rank-domain {
    color: #0f172a;
    font-size: 12px;
    font-weight: 600;
    word-break: break-word;
}

.aysa-seed-rank-pos {
    color: #64748b;
    font-size: 11px;
}

.aysa-seed-rank-empty {
    color: #94a3b8;
    font-size: 12px;
}

.aysa-seed-rank-side {
    border: 1px solid #dbe1ea;
    border-radius: 8px;
    background: #fff;
    padding: 10px;
}

.aysa-seed-rank-side h4 {
    margin: 0 0 8px;
    font-size: 13px;
    color: #334155;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.aysa-seed-competitor-list {
    display: flex;
    flex-direction: column;
    gap: 7px;
    max-height: 420px;
    overflow: auto;
}

.aysa-seed-competitor-item {
    border: 1px solid #e2e8f0;
    border-radius: 7px;
    padding: 7px 8px;
    font-size: 12px;
    line-height: 1.35;
    background: #f8fafc;
}

.aysa-seed-competitor-item strong {
    color: #0f172a;
}

.aysa-seed-competitor-meta {
    margin-top: 2px;
    color: #475569;
}

.aysa-seed-own-chip {
    margin-left: 6px;
    padding: 1px 6px;
    border-radius: 999px;
    background: #dcfce7;
    color: #166534;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
}

@media (max-width: 1400px) {
    .aysa-seed-rank-layout {
        grid-template-columns: 1fr;
    }

    .aysa-seed-matrix-table th:first-child,
    .aysa-seed-matrix-table td:first-child {
        position: static;
        width: auto;
        min-width: 160px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    let chart = null;
    let competitorDataCache = [];
    const COMP_DISCOVERY_NONCE = '<?php echo esc_js(wp_create_nonce("aysa_nonce")); ?>';
    const DEFAULT_PROJECT_ID = <?php echo intval(get_option('aysa_project_id', 0)); ?>;
    
    // Set your own domain
    $('.aysa-your-domain').text(window.location.hostname);
    
    // Format number with commas
    function formatNumber(num) {
        if (num === undefined || num === null) return '0';
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    // Format currency
    function formatCurrency(value) {
        if (value === undefined || value === null) return '$0';
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        }).format(value);
    }
    
    // Get project ID from API
    function getProjectId() {
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId) {
            return projectId;
        }
        if (DEFAULT_PROJECT_ID > 0) {
            localStorage.setItem('aysa_project_id', String(DEFAULT_PROJECT_ID));
            return String(DEFAULT_PROJECT_ID);
        }
        return '';
    }

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

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

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

    function getCompetitors(projectId, forceRefresh = false) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            timeout: 45000,
            data: {
                action: 'aysa_research_async_start',
                nonce: COMP_DISCOVERY_NONCE,
                task: 'competitor_identification',
                project_id: projectId,
                force_refresh: forceRefresh ? 1 : 0,
                top_n: 10
            }
        }).then(function(response) {
            if (!(response && response.success && response.data)) {
                const message = response && response.data ? response.data : 'Could not start competitor discovery.';
                throw new Error(String(message));
            }
            const payload = response.data || {};
            if (payload.status === 'completed' && payload.result) {
                return { success: true, data: payload.result };
            }
            showNotification('Competitor discovery is running in the background...', 'loading');
            return pollCompetitorDiscoveryAsyncStatus(projectId, payload.request_hash || '');
        });
    }

    // Legacy compatibility for Analyze flow in this tab.
    function getSeoSettings(projectId) {
        return $.Deferred().resolve({
            targetedCountry: 'Romania',
            primaryLanguage: 'Romanian',
            projectId: projectId
        }).promise();
    }

    function renderSeedCompetitorOverview(payload) {
        const data = payload || {};
        const seedKeywords = Array.isArray(data.seed_keywords) ? data.seed_keywords : [];
        const competitors = Array.isArray(data.unique_competitors) ? data.unique_competitors : [];
        const activeCompetitors = Array.isArray(data.active_competitors) ? data.active_competitors : [];
        const suggestedCompetitors = Array.isArray(data.suggested_competitors) ? data.suggested_competitors : [];
        const keywordsRows = Array.isArray(data.keywords) ? data.keywords : [];

        $('#aysa-seed-keywords-count').text(seedKeywords.length);
        $('#aysa-seed-competitors-count').text(competitors.length);
        $('#aysa-seed-competitor-status-counts').text(`${activeCompetitors.length} / ${suggestedCompetitors.length}`);
        $('#aysa-seed-provider').text(data.provider || '-');
        $('#aysa-seed-last-refresh').text(data.cached ? 'cached' : 'live');

        const $chips = $('#aysa-seed-keywords-list');
        $chips.empty();
        if (seedKeywords.length === 0) {
            $chips.append('<span class=\"aysa-seed-chip\">No seed keywords configured.</span>');
        } else {
            seedKeywords.forEach((kw) => {
                $chips.append($('<span class=\"aysa-seed-chip\"></span>').text(kw));
            });
        }

        const $list = $('#aysa-seed-competitors-body');
        $list.empty();
        if (competitors.length === 0) {
            $list.append('<div class=\"aysa-seed-competitor-item\">No competitors found for current seed keywords.</div>');
        } else {
            competitors.forEach((row, idx) => {
                const domain = String(row.domain || '');
                const isOwn = Boolean(row.is_own);
                const hits = Number(row.keyword_hits || 0);
                const appearances = Number(row.appearances || 0);
                const best = row.best_position === null || row.best_position === undefined ? 'N/A' : `#${row.best_position}`;
                const competitorStatus = String(row.competitor_status || (activeCompetitors.some((item) => item && item.domain === domain) ? 'active' : 'suggested'));
                const $item = $('<div class=\"aysa-seed-competitor-item\"></div>');
                const $title = $('<strong></strong>').text(`${idx + 1}. ${domain}`);
                const $titleWrap = $('<div></div>').append($title);
                if (isOwn) {
                    $titleWrap.append($('<span class=\"aysa-seed-own-chip\"></span>').text('Your site'));
                } else {
                    $titleWrap.append($('<span class=\"aysa-seed-own-chip\"></span>').text(competitorStatus === 'active' ? 'Active' : 'Suggested'));
                }
                $item.append($titleWrap);
                $item.append($('<div class=\"aysa-seed-competitor-meta\"></div>').text(`hits: ${hits} | appearances: ${appearances} | best: ${best}`));
                if (row.status_reason) {
                    $item.append($('<div class=\"aysa-seed-competitor-meta\"></div>').text(String(row.status_reason)));
                }
                $list.append($item);
            });
        }

        const $perKeywordBody = $('#aysa-seed-keyword-top10-body');
        $perKeywordBody.empty();
        if (keywordsRows.length === 0) {
            $perKeywordBody.append('<tr><td colspan=\"2\">No per-keyword competitor data found.</td></tr>');
        } else {
            keywordsRows.forEach((row) => {
                const keyword = String(row.keyword || '');
                const comp = Array.isArray(row.competitors) ? row.competitors : [];
                const $row = $('<tr></tr>');
                $row.append($('<td></td>').text(keyword || 'N/A'));
                const $rankCell = $('<td></td>');
                if (comp.length === 0) {
                    $rankCell.append($('<span class=\"aysa-seed-rank-empty\"></span>').text('No competitors found'));
                } else {
                    const $badges = $('<div class=\"aysa-seed-rank-badges\"></div>');
                    comp.slice(0, 10).forEach((item, idx) => {
                        if (!item || !item.domain) {
                            return;
                        }
                        const domain = String(item.domain).trim();
                        const isOwn = Boolean(item.is_own);
                        const $badge = $('<span class=\"aysa-seed-rank-badge\"></span>');
                        if (isOwn) {
                            $badge.addClass('is-own');
                        }
                        $badge.append($('<span class=\"aysa-seed-rank-index\"></span>').text(String(idx + 1)));
                        $badge.append($('<span class=\"aysa-seed-rank-name\"></span>').text(domain));
                        if (isOwn) {
                            $badge.append($('<span class=\"aysa-seed-rank-own-tag\"></span>').text('You'));
                        }
                        $badges.append($badge);
                    });
                    $rankCell.append($badges);
                }
                $row.append($rankCell);
                $perKeywordBody.append($row);
            });
        }

        $('.aysa-competitor-boxes').empty();
        competitors.slice(0, 10).forEach((row) => {
            if (row && row.domain) {
                addCompetitorToUI(String(row.domain));
            }
        });

        // Keep the old chart/table section as optional second step:
        // if needed, user can still click Analyze after reviewing discovered domains.
        if (keywordsRows.length > 0) {
            showNotification('Competitor discovery loaded from seed keywords.', 'success');
        }
    }

    function loadSeedCompetitorDiscovery(forceRefresh = false) {
        const projectId = getProjectId();
        if (!projectId) {
            showNotification('No project found. Please configure Setup SEO Profile first.', 'error');
            return $.Deferred().reject('missing_project').promise();
        }

        const $button = $('#aysa-refresh-competitor-identification');
        $button.prop('disabled', true).addClass('loading').html(
            '<span class=\"dashicons dashicons-update\"></span> Refreshing...'
        );

        return getCompetitors(projectId, forceRefresh)
            .done(function(response) {
                if (!response || response.success !== true || !response.data) {
                    showNotification('Could not load competitor discovery data.', 'error');
                    return;
                }
                renderSeedCompetitorOverview(response.data);
            })
            .fail(function(xhr) {
                const message = xhr && xhr.responseJSON && xhr.responseJSON.data
                    ? xhr.responseJSON.data
                    : 'Failed to load competitor discovery data.';
                showNotification(message, 'error');
            })
            .always(function() {
                $button.prop('disabled', false).removeClass('loading').html(
                    '<span class=\"dashicons dashicons-update\"></span> Refresh Data'
                );
            });
    }
    
    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;
        }
    }

    // Add competitor
    $('.aysa-add-btn').click(function() {
        const domain = normalizeCompetitorDomain($('.aysa-domain-input').val().trim());
        if (!domain) {
            showNotification('Invalid competitor domain format.', 'error');
            return;
        }

        addCompetitorToUI(domain);
        $('.aysa-domain-input').val('');
    });

    // Add a competitor to the UI
    function addCompetitorToUI(domain) {
        const normalizedDomain = normalizeCompetitorDomain(domain);
        if (!normalizedDomain) {
            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 $contentInner = $('<div>', { class: 'aysa-domain-content-inner' })
            .append($('<span>', { class: 'aysa-competitor-dot' }))
            .append($('<span>', { class: 'aysa-competitor-domain' }).text(normalizedDomain));

        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 to display competitors from fallback data
    function displayFallbackCompetitorsIdentification(data) {
        console.log('Displaying fallback competitors for identification:', data);
        
        if (!data) {
            console.log('No fallback data available');
            return;
        }

        // Clear existing competitor boxes
        $('.aysa-competitor-boxes').empty();
        
        // 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 for identification:', 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
                    const currentDomain = window.location.hostname;
                    if (domain !== currentDomain) {
                        addCompetitorToUI(domain);
                    }
                } catch (error) {
                    console.error('Invalid competitor URL:', competitor, error);
                    // If URL parsing fails, try using it as domain directly
                    const currentDomain = window.location.hostname;
                    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();
            }
        });
    }
    
    // Remove competitor
    $(document).on('click', '.aysa-remove-btn', function() {
        $(this).closest('.aysa-domain-box').remove();
    });
    
    // Function to get domain rank overview data - tries GET first, then POST if no data found
    function getDomainRankOverview(target, locationName, languageName, projectId, tag) {
        console.log('Fetching domain rank overview with params:', {
            target,
            locationName,
            languageName,
            projectId,
            tag
        });

        // First, try to get existing data with GET
        const apiUrl = AysaAPI.getEndpointUrl('dataforseo_domain_rank');
        
        const getParams = {
            projectId: projectId,
            target: target,
            locationName: locationName,
            languageName: languageName,
            offset: 0,
            tag: tag
        };

        console.log('Step 1: Trying GET request for existing domain rank data...');
        
        return $.ajax({
            url: apiUrl,
            type: 'GET',
            data: getParams
        }).then(function(response) {
            console.log('GET request successful for domain rank, data found:', response);
            
            // Check if backend fetched new data due to competitor changes
            if (response && response.message && response.message.includes('New data fetched from DataForSEO')) {
                console.log('✨ Backend automatically fetched fresh domain rank data due to competitor changes');
            }
            
            return response;
        }).catch(function(jqXHR, textStatus, errorThrown) {
            console.log('GET request failed or no domain rank data found, trying POST to fetch new data...');
            
            if (jqXHR.status === 404 || (jqXHR.responseJSON && jqXHR.responseJSON.message && jqXHR.responseJSON.message.includes('No Domain Rank Overview data found'))) {
                // No data found, make POST request to fetch new data
                console.log('Step 2: Making POST request to fetch new domain rank data from DataForSEO...');
                
                const postData = {
                    target: target,
                    locationName: locationName,
                    languageName: languageName,
                    projectId: projectId,
                    offset: 0,
                    tag: tag
                };

                return $.ajax({
                    url: apiUrl,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData)
                }).then(function(postResponse) {
                    console.log('POST request successful for domain rank, new data fetched:', postResponse);
                    // Return the data portion from the POST response
                    return postResponse.data || postResponse;
                });
            } else {
                // Other error, reject the promise
                console.error('Error fetching domain rank overview:', jqXHR);
                return $.Deferred().reject(jqXHR);
            }
        });
    }
    
    // Function to calculate domain authority
    function calculateDomainAuthority(domain) {
        // Temporary fallback: domain-authority endpoint returns 500 in staging for all tested competitors.
        // Avoid repeated failing requests; use 0 until backend endpoint is stabilized.
        return Promise.resolve(0);
    }
    
    function initializePageWithSeoSettings() {
        loadSeedCompetitorDiscovery(false);
    }
    
    // Analyze competitors
    $('.aysa-analyze-btn').click(function() {
        const competitors = [];
        $('.aysa-domain-box').each(function() {
            const domain = $(this).find('.aysa-competitor-domain').text().trim();
            if (domain && domain !== '') {
                competitors.push(domain);
            }
        });
        
        if (competitors.length === 0) {
            alert('Please add at least one competitor domain.');
            return;
        }
        
        // Get location and language from SEO settings instead of removed dropdowns
        const projectId = getProjectId();
        if (!projectId) {
            alert('Project ID not found');
            return;
        }
        
        $(this).prop('disabled', true).text('Analyzing...');
        
        // Get SEO settings first to get location and language
        getSeoSettings(projectId).then(function(seoSettings) {
            const location = seoSettings.targetedCountry || 'United States';
            const language = seoSettings.primaryLanguage || 'English';
            
            // Clear previous data to avoid duplicates
            competitorDataCache = [];
            console.log('Cleared competitor data cache for fresh analysis');
            
            // Add your own domain first (without calculating DA)
            const yourDomain = $('.aysa-your-domain').text().trim();
            competitorDataCache.push({
                domain: yourDomain,
                authority: 'N/A',  // Not calculating for localhost/own domain
                isYou: true
            });
            
            // Add competitors with domain authority calculation
            const competitorPromises = competitors.map(domain => {
                console.log('Starting authority calculation for domain:', domain);
                
                const daPromise = calculateDomainAuthority(domain)
                    .then(authority => {
                        console.log(`Authority score received for ${domain}:`, authority);
                        return authority; // Return just the number
                    });
                    
                const seoDataPromise = getDomainRankOverview(domain, location, language, projectId, domain + '-check')
                    .then(response => {
                        console.log('Domain rank overview response for', domain, ':', response);
                        
                        // Handle the correct DataForSEO API response structure
                        let taskData = null;
                        
                        // Handle different response structures
                        // 1. New backend structure with capitalized properties: response.data.Tasks[0].Result[0].Items[0]
                        if (response && response.data && response.data.Tasks && response.data.Tasks.length > 0) {
                            const task = response.data.Tasks[0];
                            if (task.Result && task.Result.length > 0 && task.Result[0].Items && task.Result[0].Items.length > 0) {
                                taskData = task.Result[0].Items[0];
                            }
                        }
                        // 2. New backend structure with lowercase properties: response.data.tasks[0].result[0].items[0]
                        else if (response && response.data && response.data.tasks && response.data.tasks.length > 0) {
                            const task = response.data.tasks[0];
                            if (task.result && task.result.length > 0 && task.result[0].items && task.result[0].items.length > 0) {
                                taskData = task.result[0].items[0];
                            }
                        }
                        // 3. Fallback for old structure: response.tasks[0].result[0]
                        else if (response && response.tasks && response.tasks.length > 0) {
                            const task = response.tasks[0];
                            if (task.result && task.result.length > 0) {
                                taskData = task.result[0];
                            }
                        }
                        
                        // Include message in task data if fresh data was fetched
                        if (taskData && response && response.message) {
                            taskData._freshDataMessage = response.message;
                        }
                        
                        console.log('Processed task data for', domain, ':', taskData);
                        return taskData;
                    });
                
                return Promise.all([daPromise, seoDataPromise])
                    .then(([authorityScore, seoData]) => {
                        console.log('Promise.all results:', { authorityScore, seoData });
                        
                        if (seoData) {
                            const competitorData = {
                                ...seoData,
                                domain: domain,
                                authority: authorityScore, // Direct number value
                                message: seoData._freshDataMessage || null // Include fresh data indicator
                            };
                            console.log('Final competitor data with authority:', competitorData);
                            competitorDataCache.push(competitorData);
                        } else {
                            const basicData = {
                                domain: domain,
                                authority: authorityScore // Direct number value
                            };
                            console.log('Basic competitor data with authority:', basicData);
                            competitorDataCache.push(basicData);
                        }
                    });
            });
        
            Promise.all(competitorPromises)
                .then(() => {
                    updateCompetitorTable(competitorDataCache);
                    updateDomainSelector(competitorDataCache);
                    if (competitorDataCache.length > 1) { // If we have at least one competitor
                        // Get first competitor (skip your own domain)
                        const firstCompetitor = competitorDataCache.find(item => !item.isYou);
                        if (firstCompetitor) {
                            updateChart(firstCompetitor.domain, firstCompetitor);
                        }
                    }
                    $('.aysa-analyze-btn').prop('disabled', false).text('Analyze');
                    
                    // Check if any data was fetched fresh from DataForSEO
                    const freshDataCount = competitorDataCache.filter(item => 
                        item.message && item.message.includes('New data fetched from DataForSEO')).length;
                    
                    if (freshDataCount > 0) {
                        showNotification(`✨ Fresh competitor data automatically fetched for ${freshDataCount} domain(s)!`, 'success');
                    } else {
                        showNotification('Competitor analysis completed successfully!', 'success');
                    }
                })
                .catch(error => {
                    console.error('Error analyzing competitors:', error);
                    alert('Error analyzing competitors. Please try again.');
                    $('.aysa-analyze-btn').prop('disabled', false).text('Analyze');
                });
        }).fail(function(xhr, status, error) {
            console.error('Error fetching SEO settings for analysis:', error);
            alert('Error fetching SEO settings. Please check your configuration.');
            $('.aysa-analyze-btn').prop('disabled', false).text('Analyze');
        });
    });
    
    // Update domain selector
    function updateDomainSelector(competitors) {
        const $select = $('.aysa-domain-select');
        $select.empty();
        
        competitors.forEach(competitor => {
            if (competitor.isYou) return; // Skip your own domain in the selector
            
            const domain = competitor.domain || '';
            const $option = $('<option>', { value: domain }).text(domain);
            $select.append($option);
        });
        
        // Add change event to the selector
        $select.off('change').on('change', function() {
            const selectedDomain = $(this).val();
            const selectedData = competitorDataCache.find(item => 
                item.domain === selectedDomain
            );
            
            if (selectedData) {
                updateChart(selectedDomain, selectedData);
            }
        });
    }
    
    // Update competitor table
    function updateCompetitorTable(competitors) {
        const $tbody = $('.aysa-keywords-table tbody');
        $tbody.empty();
        
        if (competitors.length === 0) {
            $tbody.append(`
                <tr>
                    <td colspan="12" class="aysa-td-center-padded">
                        No competitors analyzed yet. Add competitors and click Analyze to see results.
                    </td>
                </tr>
            `);
            return;
        }
        
        // Get your own domain data first
        const yourDomainData = competitors.find(item => item.isYou);
        const yourDomainAuthority = yourDomainData ? yourDomainData.authority : 'N/A';
        
        // Then add competitors (excluding your own domain)
        competitors.forEach(competitor => {
            if (competitor.isYou) return; // Skip your own domain
            
            console.log('Processing competitor for table:', competitor);
            
            const domain = competitor.domain || '';
            const authority = typeof competitor.authority === 'number' ? competitor.authority : 0;
            
            console.log(`Table row data - Domain: ${domain}, Authority value:`, authority);
            console.log('Competitor object:', competitor);
            
            // Initialize values
            let orgTop3 = 0, orgTop10 = 0, orgTop20 = 0, orgTotal = 0, orgEtv = 0;
            let paidTop3 = 0, paidTop10 = 0, paidTop20 = 0, paidTotal = 0, paidEtv = 0;
            
            // Extract metrics - support both capitalized and lowercase structures
            if (competitor.Metrics) {
                const org = competitor.Metrics.Organic || {};
                const paid = competitor.Metrics.Paid || {};
                
                // Organic metrics - support both capitalized and lowercase properties
                orgTop3 = (org.Pos1 || org.pos1 || 0) + (org.Pos2To3 || org.pos2To3 || 0);
                orgTop10 = org.Pos4To10 || org.pos4To10 || 0;
                orgTop20 = org.Pos11To20 || org.pos11To20 || 0;
                orgTotal = org.Count || org.count || 0;
                orgEtv = org.Etv || org.etv || 0;
                
                // Paid metrics
                paidTop3 = (paid.Pos1 || paid.pos1 || 0) + (paid.Pos2To3 || paid.pos2To3 || 0);
                paidTop10 = paid.Pos4To10 || paid.pos4To10 || 0;
                paidTop20 = paid.Pos11To20 || paid.pos11To20 || 0;
                paidTotal = paid.Count || paid.count || 0;
                paidEtv = paid.Etv || paid.etv || 0;
            }
            // Support direct metrics structure (lowercase)
            else if (competitor.metrics) {
                const org = competitor.metrics.organic || {};
                const paid = competitor.metrics.paid || {};
                
                orgTop3 = (org.pos1 || 0) + (org.pos2To3 || 0);
                orgTop10 = org.pos4To10 || 0;
                orgTop20 = org.pos11To20 || 0;
                orgTotal = org.count || 0;
                orgEtv = org.etv || 0;
                
                paidTop3 = (paid.pos1 || 0) + (paid.pos2To3 || 0);
                paidTop10 = paid.pos4To10 || 0;
                paidTop20 = paid.pos11To20 || 0;
                paidTotal = paid.count || 0;
                paidEtv = paid.etv || 0;
            }
            // Fallback for old structure
            else if (competitor.result && competitor.result[0] && competitor.result[0].items && competitor.result[0].items[0]) {
                const result = competitor.result[0].items[0];
                const org = result.metrics.organic;
                const paid = result.metrics.paid || {};
                
                orgTop3 = (org.pos1 || 0) + (org.pos2To3 || 0);
                orgTop10 = org.pos4To10 || 0;
                orgTop20 = org.pos11To20 || 0;
                orgTotal = org.count || 0;
                orgEtv = org.etv || 0;
                
                paidTop3 = (paid.pos1 || 0) + (paid.pos2To3 || 0);
                paidTop10 = paid.pos4To10 || 0;
                paidTop20 = paid.pos11To20 || 0;
                paidTotal = paid.count || 0;
                paidEtv = paid.etv || 0;
            }
            
            console.log(`Extracted metrics for ${domain}:`, {
                orgTop3, orgTop10, orgTop20, orgTotal, orgEtv,
                paidTop3, paidTop10, paidTop20, paidTotal, paidEtv
            });
            
            const $row = $('<tr>');
            $row.append($('<td>').text(domain));
            $row.append($('<td>').text(authority));
            $row.append($('<td>').text(formatNumber(orgTop3)));
            $row.append($('<td>').text(formatNumber(orgTop10)));
            $row.append($('<td>').text(formatNumber(orgTop20)));
            $row.append($('<td>').text(formatNumber(orgTotal)));
            $row.append($('<td>').text(formatCurrency(orgEtv)));
            $row.append($('<td>').text(formatNumber(paidTop3)));
            $row.append($('<td>').text(formatNumber(paidTop10)));
            $row.append($('<td>').text(formatNumber(paidTop20)));
            $row.append($('<td>').text(formatNumber(paidTotal)));
            $row.append($('<td>').text(formatCurrency(paidEtv)));
            $tbody.append($row);
        });
    }
    
    // Update chart
    function updateChart(domain, data) {
        // Handle different metric structures
        let metrics = null;
        if (data.Metrics && data.Metrics.Organic) {
            metrics = data.Metrics.Organic;
        }
        // Support direct metrics structure (lowercase)
        else if (data.metrics && data.metrics.organic) {
            metrics = data.metrics.organic;
        }
        // Fallback for old structure
        else if (data.result && data.result[0] && data.result[0].items && data.result[0].items[0]) {
            const result = data.result[0].items[0];
            metrics = result.metrics.organic;
        }
        
        if (!metrics) {
            console.log('No metrics found for chart update');
            return;
        }
        
        console.log('Chart metrics for', domain, ':', metrics);
        const ctx = document.getElementById('keywordDistributionChart');
        
        if (chart) {
            chart.destroy();
        }
        
        chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['1-3', '4-10', '11-20', '21-30', '31-40', '41-50', '51-100'],
                datasets: [{
                    label: 'Keywords',
                    data: [
                        (metrics.Pos1 || metrics.pos1 || 0) + (metrics.Pos2To3 || metrics.pos2To3 || 0),
                        metrics.Pos4To10 || metrics.pos4To10 || 0,
                        metrics.Pos11To20 || metrics.pos11To20 || 0,
                        metrics.Pos21To30 || metrics.pos21To30 || 0,
                        metrics.Pos31To40 || metrics.pos31To40 || 0,
                        metrics.Pos41To50 || metrics.pos41To50 || 0,
                        (metrics.Pos51To60 || metrics.pos51To60 || 0) + 
                        (metrics.Pos61To70 || metrics.pos61To70 || 0) + 
                        (metrics.Pos71To80 || metrics.pos71To80 || 0) + 
                        (metrics.Pos81To90 || metrics.pos81To90 || 0) + 
                        (metrics.Pos91To100 || metrics.pos91To100 || 0)
                    ],
                    backgroundColor: '#4285f4',
                    borderWidth: 0,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Number of Keywords'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Position Range'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: true,
                        text: domain,
                        font: {
                            size: 16
                        },
                        padding: {
                            bottom: 15
                        }
                    }
                }
            }
        });
        
        // Update metrics - support both capitalized and lowercase properties
        const newKw = metrics.IsNew || metrics.isNew || 0;
        const improved = metrics.IsUp || metrics.isUp || 0;
        const declined = metrics.IsDown || metrics.isDown || 0;
        const lost = metrics.IsLost || metrics.isLost || 0;
        
        console.log(`Updating statistics for ${domain}:`, { newKw, improved, declined, lost });
        
        $('.new-keywords').text(formatNumber(newKw));
        $('.improved-keywords').text(formatNumber(improved));
        $('.declined-keywords').text(formatNumber(declined));
        $('.lost-keywords').text(formatNumber(lost));
    }
    
    // Initialize table with empty state
    initEmptyState();
    
    // Set up empty state
    function initEmptyState() {
        // Display empty message in table
        const $tbody = $('.aysa-keywords-table tbody');
        $tbody.empty();
        $tbody.append(`
            <tr>
                <td colspan="12" class="aysa-td-center-padded">
                    Add competitors and click Analyze to see results.
                </td>
            </tr>
        `);
        
        // Clear domain selector
        const $select = $('.aysa-domain-select');
        $select.empty();
        $select.append('<option value="">Select a domain after analysis</option>');
        
        // Reset metrics to 0
        $('.new-keywords').text('0');
        $('.improved-keywords').text('0');
        $('.declined-keywords').text('0');
        $('.lost-keywords').text('0');
    }
    
    // Update current domain
    const currentDomain = window.location.hostname;
    $('#aysa-current-domain').text(currentDomain);
    
    // Function to format numbers with commas
    function formatNumber(num) {
        if (num === null || num === undefined) return '0';
        return parseInt(num).toLocaleString();
    }

    // Function to format currency values
    function formatCurrency(amount) {
        if (amount === null || amount === undefined || amount === 0) return '$0';
        return '$' + Math.round(amount).toLocaleString();
    }

    // Function to show notification messages
    function showNotification(message, type = 'info') {
        // Remove any existing notifications
        $('.aysa-notification').remove();
        
        // Create notification element
        const notificationClass = type === 'success' ? 'notice-success' : 
                                type === 'error' ? 'notice-error' : 'notice-info';
        
        const notification = $(`
            <div class="notice ${notificationClass} is-dismissible aysa-notification aysa-notification-inline">
                <p>${message}</p>
                <button type="button" class="notice-dismiss aysa-notification-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `);
        
        // Add to page
        $('.wrap').prepend(notification);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            notification.fadeOut(() => {
                notification.remove();
            });
        }, 5000);
        
        // Handle dismiss button
        notification.find('.notice-dismiss').on('click', function() {
            notification.fadeOut(() => {
                notification.remove();
            });
        });
    }

    // Initialize the page with SEO settings and competitors
    initializePageWithSeoSettings();

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

    function refreshCompetitorIdentificationData() {
        loadSeedCompetitorDiscovery(true);
    }
});
</script> 
