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

$aysa_root_domain = wp_parse_url(home_url(), PHP_URL_HOST) ?: 'yourdomain.com';
?>

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

    <!-- Top Tabs -->
    <div class="aysa-top-tabs">
        <a href="admin.php?page=aysa-research&tab=keyword-discovery" class="aysa-tab">Keyword Discovery</a>
        <a href="admin.php?page=aysa-research&tab=competitor-gap" class="aysa-tab">Competitor Keyword Gap</a>
        <a href="admin.php?page=aysa-research&tab=competitor-identification" class="aysa-tab">Competitor Identification</a>
        <div class="aysa-tab active">Competitor Backlink Analysis</div>
        <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-backlinks-content">
            <!-- Competitor Analysis Panel -->
            <div class="aysa-panel">
                <h2 class="aysa-panel-title">
                    <span class="aysa-icon">🔍</span>
                    Backlink 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"><?php echo esc_html($aysa_root_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 -->
                <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="United States">United States</option>
                                <option value="United Kingdom">United Kingdom</option>
                                <option value="Canada">Canada</option>
                                <option value="Australia">Australia</option>
                                <option value="Germany">Germany</option>
                                <option value="France">France</option>
                                <option value="Spain">Spain</option>
                                <option value="Italy">Italy</option>
                                <option value="Romania">Romania</option>
                                <option value="Japan">Japan</option>
                                <option value="China">China</option>
                                <option value="India">India</option>
                                <option value="Brazil">Brazil</option>
                                <option value="Russia">Russia</option>
                                <option value="South Korea">South Korea</option>
                                <option value="Mexico">Mexico</option>
                            </select>
                        </div>
                        
                        <div class="aysa-filter-group">
                            <label>Language</label>
                            <select class="aysa-filter-dropdown language">
                                <option value="English">English</option>
                                <option value="Spanish">Spanish</option>
                                <option value="French">French</option>
                                <option value="German">German</option>
                                <option value="Italian">Italian</option>
                                <option value="Romanian">Romanian</option>
                                <option value="Portuguese">Portuguese</option>
                                <option value="Russian">Russian</option>
                                <option value="Japanese">Japanese</option>
                                <option value="Chinese">Chinese</option>
                                <option value="Korean">Korean</option>
                                <option value="Hindi">Hindi</option>
                                <option value="Arabic">Arabic</option>
                            </select>
                        </div>
                        -->

                        <div class="aysa-actions-section">
                            <div class="aysa-flex-end">
                                <button class="aysa-refresh-data-btn" id="aysa-refresh-competitor-backlinks" title="Refresh competitor backlinks data from API">
                                    <span class="dashicons dashicons-update"></span> Refresh Data
                                    <span class="aysa-credit-badge cost-high">35 cr</span>
                                </button>
                                <button class="aysa-get-recommendation-btn" style="background-color: #4285f4; color: white; border: none; border-radius: 4px; padding: 8px 16px; font-weight: 500; cursor: pointer; margin-right: 10px;">Get Recommendations</button>
                                <button class="aysa-analyze-btn">Analyze Backlinks</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="aysa-gap-insights-panel" id="aysa-gap-insights-panel">
                    <div class="aysa-gap-insights-head">
                        <h3>Backlink Gap Insights</h3>
                        <p>Actionable conclusion based on your backlink profile vs competitor benchmark.</p>
                    </div>
                    <div class="aysa-gap-kpis">
                        <div class="aysa-gap-kpi"><span>Need Ref Domains</span><strong id="aysa-gap-need-ref">-</strong></div>
                        <div class="aysa-gap-kpi"><span>Need High Authority</span><strong id="aysa-gap-need-high">-</strong></div>
                        <div class="aysa-gap-kpi"><span>Need Total Links</span><strong id="aysa-gap-need-total">-</strong></div>
                        <div class="aysa-gap-kpi"><span>Target Dofollow Ratio</span><strong id="aysa-gap-target-dofollow">-</strong></div>
                    </div>
                    <div class="aysa-gap-conclusion" id="aysa-gap-conclusion">Run Refresh Data to generate conclusion.</div>
                    <div class="aysa-gap-two-col">
                        <div>
                            <h4>Recommended Anchor Tag Cloud (Needed Links)</h4>
                            <div class="aysa-gap-chip-wrap" id="aysa-gap-keyword-cloud"></div>
                        </div>
                        <div>
                            <h4>Missing Anchor Opportunities</h4>
                            <div class="aysa-gap-chip-wrap" id="aysa-gap-anchor-gaps"></div>
                        </div>
                    </div>
                </div>

                <!-- Results Section -->
                <div class="aysa-results-section" style="display: none;">
                    <div class="aysa-results-header">
                        <h2>Backlink Analysis Results</h2>
                    </div>

                    <div class="aysa-results-container">
                        <div class="aysa-results-panel" id="aysa-backlinks-results">
                            <div class="aysa-results-table">
                                <table class="aysa-backlinks-table">
                                    <thead>
                                        <tr>
                                            <th>Opportunity Domain</th>
                                            <th>Common Signals</th>
                                            <th>Opportunity</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Results will be populated dynamically -->
                                    </tbody>
                                </table>
                            </div>

                            <div class="aysa-pagination">
                                <div class="aysa-pagination-info">
                                    Showing <span class="aysa-pagination-start">0</span> - <span class="aysa-pagination-end">0</span> of <span class="aysa-pagination-total">0</span> results
                                </div>
                                <div class="aysa-pagination-controls">
                                    <button class="aysa-pagination-prev" disabled>Previous</button>
                                    <div class="aysa-pagination-pages"></div>
                                    <button class="aysa-pagination-next" disabled>Next</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Competitor Backlinks Task Section -->
            <div class="aysa-modern-tasks-section">
                <div class="aysa-tasks-header">
                    <h3>🚀 Your Backlink Action Plan</h3>
                    <button class="aysa-add-task-btn">+ Add Task</button>
                </div>
                
                <!-- Automated Tasks Group -->
                <div class="aysa-task-group">
                    <div class="aysa-task-group-header">
                        <span class="aysa-task-group-icon">🤖</span>
                        <h4>Automated Tasks</h4>
                        <span class="aysa-task-group-badge aysa-badge-auto">AUTO</span>
                    </div>
                    <ul class="aysa-task-list aysa-automated-backlink-tasks">
                        <!-- Automated backlink tasks will be populated via API -->
                    </ul>
                </div>

                <!-- Manual Tasks Group -->
                <div class="aysa-task-group">
                    <div class="aysa-task-group-header">
                        <span class="aysa-task-group-icon">✋</span>
                        <h4>Manual Tasks</h4>
                        <span class="aysa-task-group-badge aysa-badge-manual">MANUAL</span>
                    </div>
                    <ul class="aysa-task-list aysa-manual-backlink-tasks">
                        <!-- Manual backlink tasks will be populated via API -->
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Backlink Details Modal -->
<div class="aysa-modal" id="backlink-details-modal">
    <div class="aysa-modal-content">
        <div class="aysa-modal-header">
            <h2>Backlink Details: <span id="backlink-domain"></span></h2>
            <span class="aysa-modal-close">&times;</span>
        </div>
        <div class="aysa-modal-body">
            <div class="aysa-modal-loading">Loading details...</div>
            <div class="aysa-backlinks-details-container" style="display: none;">
                <table class="aysa-backlinks-details-table">
                    <thead>
                        <tr>
                            <th>Source URL</th>
                            <th>Anchor Text</th>
                            <th>Link Type</th>
                            <th>First Seen</th>
                            <th>Last Seen</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Details will be populated dynamically -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Recommendation Modal HTML -->
<div class="aysa-modal" id="recommendation-modal">
    <div class="aysa-modal-content">
        <div class="aysa-modal-header">
            <h2>Backlink Recommendation: <span id="recommendation-domain"></span></h2>
            <span class="aysa-modal-close">&times;</span>
        </div>
        <div class="aysa-modal-body">
            <div class="aysa-modal-loading">Loading recommendation...</div>
            <div class="aysa-recommendation-container" style="display: none;">
                <div class="aysa-recommendation-section">
                    <h3>Număr linkuri</h3>
                    <div id="recommendation-links-count" class="aysa-recommendation-value"></div>
                </div>
                
                <div class="aysa-recommendation-section">
                    <h3>Recommended keywords</h3>
                    <div id="recommendation-keywords" class="aysa-recommendation-value"></div>
                </div>
                
                <div class="aysa-recommendation-section">
                    <h3>Publisher opportunities</h3>
                    <div id="recommendation-sites" class="aysa-recommendation-value"></div>
                </div>
                
                <div class="aysa-recommendation-section">
                    <h3>Estimated total cost</h3>
                    <div id="recommendation-cost" class="aysa-recommendation-value"></div>
                </div>
                
                <div class="aysa-recommendation-actions">
                    <button class="buy-links-btn">Buy Links</button>
                </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;
}

/* Domain Tabs */
.aysa-domain-tabs-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 16px 0;
    padding: 0 16px;
    overflow-x: auto;
    max-width: 100%;
}

.aysa-domain-tab {
    display: flex;
    align-items: center;
    background: #f1f3f4;
    border: none;
    border-radius: 16px;
    padding: 6px 12px;
    font-size: 13px;
    color: #5f6368;
    cursor: pointer;
    transition: background 0.2s, color 0.2s, box-shadow 0.2s;
    white-space: nowrap;
    position: relative;
}

.aysa-domain-tab.active {
    background-color: #1a73e8;
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(26,115,232,0.10);
    z-index: 1;
}

.aysa-domain-tab:not(.active):hover {
    background: #e8f0fe;
    color: #1a73e8;
}

.aysa-tab-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-left: 8px;
    border: 2px solid #fff;
    border-top: 2px solid #1a73e8;
    border-radius: 50%;
    animation: spin 0.7s linear infinite;
}

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

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

.aysa-competitor-backlinks-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;
}

.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 {
    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 Section */
.aysa-results-section {
    margin-top: 20px;
}

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

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

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

.aysa-filter-btn {
    padding: 6px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background: white;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s ease;
}

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

.aysa-tab-buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    border-bottom: 1px solid #e0e0e0;
    padding-bottom: 10px;
}

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

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

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

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

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

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

.aysa-link-type {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-link-type.dofollow {
    background: #e6f4ea;
    color: #34a853;
}

.aysa-link-type.nofollow {
    background: #fce8e6;
    color: #ea4335;
}

/* Competitor Boxes */
.aysa-competitor-boxes {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 20px;
}

.aysa-competitor-boxes .aysa-domain-box {
    flex: 1;
    min-width: 200px;
    max-width: 300px;
}

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

.aysa-modal-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 0;
    border: 1px solid #ddd;
    border-radius: 8px;
    width: 90%;
    max-width: 1200px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    max-height: 90vh;
    display: flex;
    flex-direction: column;
}

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

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

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

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

.aysa-modal-body {
    padding: 20px;
    overflow-y: auto;
    flex: 1;
}

.aysa-modal-loading {
    text-align: center;
    padding: 30px;
    color: #666;
    font-size: 16px;
}

.aysa-backlinks-details-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

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

.aysa-backlinks-details-table th {
    color: #666;
    font-weight: 500;
    background-color: #fafafa;
}

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

.view-details-btn {
    background-color: #1a73e8;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
    font-size: 12px;
}

.view-details-btn:hover {
    background-color: #1765cc;
}

/* Additional styling for backlink details */
.aysa-source-url {
    display: flex;
    flex-direction: column;
}

.aysa-domain-from {
    font-size: 11px;
    color: #666;
    margin-top: 2px;
}

.aysa-link-type {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-link-type.dofollow {
    background: #e6f4ea;
    color: #34a853;
}

.aysa-link-type.nofollow {
    background: #fce8e6;
    color: #ea4335;
}

/* New styles for the Buy Links button and link status */
.buy-links-btn {
    background-color: #2f7d32 !important;
    color: white !important;
    border: none !important;
    border-radius: 4px !important;
    padding: 12px 24px !important;
    cursor: pointer !important;
    font-size: 16px !important;
    font-weight: 600 !important;
    margin: 20px auto !important;
    display: block !important;
    width: 200px !important;
    text-align: center !important;
    z-index: 99999 !important;
    position: relative !important;
    box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important;
    transition: all 0.3s ease !important;
}

.buy-links-btn:hover {
    background-color: #1b5e20 !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 6px 12px rgba(0,0,0,0.3) !important;
}

.link-status {
    display: inline-block;
    font-size: 12px;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.status-badge.in-progress {
    background-color: #fff3e0;
    color: #e65100;
}

.status-badge.completed {
    background-color: #e8f5e9;
    color: #2e7d32;
}

/* Wallet Alert Modal */
#wallet-alert-modal .aysa-modal-content {
    max-width: 500px;
}

.aysa-modal-actions {
    margin-top: 20px;
    text-align: right;
}

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

.aysa-topup-btn:hover {
    background-color: #1b5e20;
}

/* Status Indicators */
.link-status {
    display: inline-block;
    font-size: 12px;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.status-badge.in-progress {
    background-color: #fff3e0;
    color: #e65100;
}

.status-badge.completed {
    background-color: #e8f5e9;
    color: #2e7d32;
}

/* New styles for recommendations */
.recommendation-cell {
    padding: 12px 16px;
}

.recommendation-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.recommendation-stats {
    display: flex;
    align-items: center;
    gap: 8px;
}

.recommendation-label {
    font-size: 12px;
    color: #666;
    min-width: 120px;
}

.recommendation-value {
    font-size: 12px;
    font-weight: 500;
    color: #333;
}

/* Recommendation Button Style */
.get-recommendation-btn {
    background-color: #4285f4;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
    font-size: 12px;
}

.get-recommendation-btn:hover {
    background-color: #3367d6;
}

/* Recommendation Modal Styles */
.aysa-recommendation-container {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.aysa-recommendation-section {
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    padding: 15px;
    background-color: #f8f9fa;
}

.aysa-recommendation-section h3 {
    margin: 0 0 10px 0;
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.aysa-recommendation-value {
    font-size: 14px;
    line-height: 1.5;
}

.aysa-recommendation-actions {
    display: block !important;
    text-align: center !important;
    margin-top: 30px !important;
    padding: 20px !important;
    background-color: #f8f9fa !important;
    border-radius: 8px !important;
    border: 2px solid #e9ecef !important;
}

.aysa-keyword-chip {
    display: inline-block;
    background-color: #e8f0fe;
    color: #1a73e8;
    padding: 4px 10px;
    border-radius: 16px;
    margin-right: 8px;
    margin-bottom: 8px;
    font-size: 12px;
}

.aysa-site-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #eee;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-bottom: 8px;
}

.aysa-site-info {
    display: flex;
    flex-direction: column;
}

.aysa-site-domain {
    font-weight: 500;
    color: #333;
    margin-bottom: 2px;
}

.aysa-site-meta {
    display: flex;
    gap: 8px;
    font-size: 11px;
    color: #666;
}

.aysa-site-country, .aysa-site-language {
    background-color: #f1f3f4;
    padding: 2px 6px;
    border-radius: 4px;
}

.aysa-site-metrics {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;
}

.aysa-site-authority {
    background-color: #e0f2f1;
    color: #00897b;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-site-price {
    background-color: #e3f2fd;
    color: #1565c0;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
}

/* Add custom styles for site URLs */
.aysa-site-urls {
    margin-top: 5px;
    max-height: 60px;
    overflow-y: auto;
    padding: 5px;
    background: #f5f5f5;
    border-radius: 4px;
}

.aysa-site-url {
    display: block;
    font-size: 11px;
    color: #1a73e8;
    text-decoration: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 2px 0;
}

.aysa-site-url:hover {
    text-decoration: underline;
}

/* Task Section Styles */
.aysa-modern-tasks-section {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    margin-top: 30px;
}

.aysa-tasks-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 18px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9edf0;
}

.aysa-tasks-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #334155;
    margin: 0;
}

.aysa-add-task-btn {
    background-color: #3b82f6;
    color: white;
    border: none;
    border-radius: 6px;
    padding: 8px 15px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.aysa-add-task-btn:hover {
    background-color: #2563eb;
}

.aysa-task-group {
    margin-bottom: 20px;
}

.aysa-task-group:last-child {
    margin-bottom: 0;
}

.aysa-task-group-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
    padding: 10px 0;
    border-bottom: 1px solid #f1f5f9;
}

.aysa-task-group-icon {
    font-size: 20px;
}

.aysa-task-group-header h4 {
    font-size: 16px;
    font-weight: 600;
    color: #334155;
    margin: 0;
    flex-grow: 1;
}

.aysa-task-group-badge {
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.aysa-badge-auto {
    background-color: #dbeafe;
    color: #1d4ed8;
}

.aysa-badge-manual {
    background-color: #fef3c7;
    color: #d97706;
}

.aysa-task-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.aysa-task-item {
    padding: 12px 0;
    border-bottom: 1px solid #f1f5f9;
    transition: background-color 0.15s ease;
}

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

.aysa-task-item:hover {
    background-color: #f8fafc;
}

.aysa-task-content {
    display: flex;
    align-items: center;
    gap: 12px;
}

.aysa-task-checkbox {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.aysa-task-label {
    flex-grow: 1;
    font-size: 15px;
    color: #475569;
    cursor: pointer;
}

.aysa-task-detail-btn {
    background-color: #f1f5f9;
    color: #64748b;
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    font-size: 12px;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

.aysa-task-detail-btn:hover {
    background-color: #e2e8f0;
}

.aysa-delete-btn {
    background: none;
    border: none;
    color: #94a3b8;
    font-size: 18px;
    font-weight: bold;
    cursor: pointer;
    padding: 0 5px;
    border-radius: 4px;
    transition: color 0.2s ease, background-color 0.2s ease;
}

.aysa-delete-btn:hover {
    color: #ef4444;
    background-color: #fee2e2;
}

.aysa-task-progress {
    margin-top: 8px;
    margin-left: 30px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.progress-container {
    flex-grow: 1;
    height: 6px;
    background-color: #f1f5f9;
    border-radius: 3px;
    overflow: hidden;
}

.progress-bar {
    height: 100%;
    background-color: var(--progress-color, #3b82f6);
    width: var(--percentage, 0%);
    transition: width 0.3s ease;
}

.progress-text {
    font-size: 12px;
    color: #64748b;
    white-space: nowrap;
}

.aysa-task-item[data-status="completed"] .aysa-task-label {
    text-decoration: line-through;
    color: #94a3b8;
}

.aysa-task-item[data-status="completed"] .progress-bar {
    background-color: #22c55e;
}

/* Pagination Styles */
.aysa-pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background-color: #fff;
    border-top: 1px solid #e0e0e0;
}

.aysa-pagination-info {
    color: #666;
    font-size: 13px;
}

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

.aysa-pagination-prev,
.aysa-pagination-next {
    padding: 6px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background: white;
    cursor: pointer;
    font-size: 13px;
    color: #666;
}

.aysa-pagination-prev:disabled,
.aysa-pagination-next:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.aysa-pagination-pages {
    display: flex;
    gap: 5px;
}

.aysa-pagination-page {
    padding: 6px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background: white;
    cursor: pointer;
    font-size: 13px;
    color: #666;
}

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

.aysa-gap-insights-panel {
    margin: 14px 0 10px;
    border: 1px solid #dbe6f5;
    border-radius: 10px;
    background: #f8fbff;
    padding: 14px;
}

.aysa-gap-insights-head h3 {
    margin: 0 0 4px;
}

.aysa-gap-insights-head p {
    margin: 0;
    color: #526581;
}

.aysa-gap-kpis {
    margin-top: 10px;
    display: grid;
    gap: 10px;
    grid-template-columns: repeat(4, minmax(150px, 1fr));
}

.aysa-gap-kpi {
    border: 1px solid #d8e3f2;
    border-radius: 8px;
    background: #fff;
    padding: 10px;
}

.aysa-gap-kpi span {
    display: block;
    font-size: 12px;
    color: #64748b;
}

.aysa-gap-kpi strong {
    font-size: 22px;
    color: #0f172a;
}

.aysa-gap-conclusion {
    margin-top: 10px;
    border-left: 4px solid #2563eb;
    background: #fff;
    padding: 10px 12px;
    color: #1e293b;
}

.aysa-gap-two-col {
    margin-top: 12px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

.aysa-gap-two-col h4 {
    margin: 0 0 6px;
    font-size: 13px;
    color: #334155;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.aysa-gap-chip-wrap {
    min-height: 44px;
    border: 1px dashed #cfdae8;
    border-radius: 8px;
    background: #fff;
    padding: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.aysa-gap-chip {
    border: 1px solid #bfdbfe;
    background: #eff6ff;
    border-radius: 999px;
    color: #1e3a8a;
    padding: 3px 9px;
    font-size: 12px;
    font-weight: 600;
}

@media (max-width: 1200px) {
    .aysa-gap-kpis {
        grid-template-columns: repeat(2, minmax(150px, 1fr));
    }
    .aysa-gap-two-col {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // Set your own domain
    $('.aysa-your-domain').text(window.location.hostname);
    const COMP_BACKLINKS_NONCE = '<?php echo esc_js(wp_create_nonce("aysa_nonce")); ?>';
    const COMP_BACKLINKS_API_BASE = <?php echo json_encode((class_exists('Aysa_API_Config') ? rtrim(Aysa_API_Config::get_api_base_url(), '/') : 'https://api.aysa.ai')); ?>;
    const COMP_BACKLINKS_DEBUG = window.AYSA_DEBUG === true;
    function compBacklinksDebugLog() {
        if (!COMP_BACKLINKS_DEBUG) {
            return;
        }
        console.log.apply(console, arguments);
    }
    
    // Project ID resolver for local-first flow.
    function getProjectId() {
        if (typeof aysaParams !== 'undefined' && aysaParams.project_id && aysaParams.project_id > 0) {
            return aysaParams.project_id;
        }

        const storedProjectId = parseInt(localStorage.getItem('aysa_project_id') || '0', 10);
        if (storedProjectId > 0) {
            return storedProjectId;
        }

        const phpProjectId = <?php echo intval(get_option('aysa_project_id', 0)); ?>;
        if (phpProjectId > 0) {
            localStorage.setItem('aysa_project_id', String(phpProjectId));
            return phpProjectId;
        }

        return 0;
    }

    // Keep compatibility with old flow.
    function getSeoSettings(projectId) {
        return $.Deferred().resolve({
            targetedCountry: 'Romania',
            primaryLanguage: 'Romanian',
            projectId: projectId
        }).promise();
    }

    // Read setup competitors (source of truth: Setup SEO Profile).
    function getCompetitors(projectId) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_competitor_backlinks_setup_competitors',
                nonce: COMP_BACKLINKS_NONCE,
                project_id: projectId
            }
        });
    }

    function getCachedBacklinks(projectId, domains) {
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_competitor_backlinks_get_cached',
                nonce: COMP_BACKLINKS_NONCE,
                project_id: projectId,
                domains: JSON.stringify(domains || [])
            }
        });
    }

    function renderGapInsights(data) {
        const gap = data && data.gap ? data.gap : {};
        const benchmark = data && data.benchmark ? data.benchmark : {};

        $('#aysa-gap-need-ref').text((gap.needed_ref_domains ?? '-'));
        $('#aysa-gap-need-high').text((gap.needed_high_authority_links ?? '-'));
        $('#aysa-gap-need-total').text((gap.needed_total_backlinks ?? '-'));
        const targetDofollow = benchmark.dofollow_ratio !== undefined ? `${benchmark.dofollow_ratio}%` : '-';
        $('#aysa-gap-target-dofollow').text(targetDofollow);
        $('#aysa-gap-conclusion').text(gap.conclusion || 'No conclusion available yet.');

        const recommendedCloud = (gap && Array.isArray(gap.recommended_anchor_cloud))
            ? gap.recommended_anchor_cloud
            : [];
        const fallbackCloud = Array.isArray(benchmark.keyword_cloud) ? benchmark.keyword_cloud : [];
        const missingAnchors = Array.isArray(gap.missing_anchor_opportunities) ? gap.missing_anchor_opportunities : [];

        const $cloudWrap = $('#aysa-gap-keyword-cloud');
        $cloudWrap.empty();
        if (!recommendedCloud.length && !fallbackCloud.length) {
            $cloudWrap.append('<span class="aysa-gap-chip">No recommended tags yet</span>');
        } else {
            const source = recommendedCloud.length ? recommendedCloud : fallbackCloud;
            source.slice(0, 20).forEach((item) => {
                const term = String(item.term || '').trim();
                if (!term) return;
                const count = recommendedCloud.length
                    ? Number(item.needed_links || 0)
                    : Number(item.count || 0);
                const suffix = recommendedCloud.length ? 'links' : 'mentions';
                $cloudWrap.append($('<span class="aysa-gap-chip"></span>').text(`${term} (${count} ${suffix})`));
            });
        }

        const $anchorWrap = $('#aysa-gap-anchor-gaps');
        $anchorWrap.empty();
        if (!missingAnchors.length) {
            $anchorWrap.append('<span class="aysa-gap-chip">No missing anchors detected</span>');
        } else {
            missingAnchors.slice(0, 12).forEach((item) => {
                const anchor = String(item.anchor || '').trim();
                if (!anchor) return;
                const count = Number(item.count || 0);
                $anchorWrap.append($('<span class="aysa-gap-chip"></span>').text(`${anchor} (${count})`));
            });
        }
    }

    function loadGapInsights(competitors = [], forceRefresh = false) {
        const projectId = getProjectId();
        if (!projectId) return $.Deferred().reject('missing_project').promise();
        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_competitor_backlinks_gap_insights',
                nonce: COMP_BACKLINKS_NONCE,
                project_id: projectId,
                force_refresh: forceRefresh ? 1 : 0,
                competitors: JSON.stringify(competitors || [])
            }
        }).done(function(resp) {
            if (resp && resp.success && resp.data) {
                renderGapInsights(resp.data);
            } else {
                $('#aysa-gap-conclusion').text('Could not generate backlink gap insights.');
            }
        }).fail(function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data : 'Backlink gap insights request failed.';
            $('#aysa-gap-conclusion').text(message);
        });
    }

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

    function sanitizeExternalUrl(rawUrl) {
        if (!rawUrl || rawUrl === 'N/A') {
            return '#';
        }
        try {
            const parsed = new URL(rawUrl);
            return (parsed.protocol === 'http:' || parsed.protocol === 'https:') ? parsed.href : '#';
        } catch (error) {
            return '#';
        }
    }

    // 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 displayFallbackCompetitorsBacklinks(data) {
        compBacklinksDebugLog('Displaying fallback competitors for backlinks:', data);
        
        if (!data) {
            compBacklinksDebugLog('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;
        }
        
        compBacklinksDebugLog('Extracted competitors for backlinks:', 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-error-modal" id="aysaErrorModal" style="display: none; position: fixed; z-index: 9999; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5);">
                <div class="aysa-error-modal-content" style="background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 500px; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
                    <div class="aysa-error-modal-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #eee;">
                        <h3 style="margin: 0; color: #333;">Notice</h3>
                        <span class="aysa-error-modal-close" style="color: #aaa; font-size: 28px; font-weight: bold; cursor: pointer;">&times;</span>
                    </div>
                    <div class="aysa-error-modal-body" style="color: #666; line-height: 1.5;">
                        <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-error-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();
            }
        });
    }
    
    // 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('');
    });
    
    // Remove competitor
    $(document).on('click', '.aysa-remove-btn', function() {
        $(this).closest('.aysa-domain-box').remove();
    });
    
    // Store backlink data for each domain
    let backlinkDataByDomain = {};
    let competitorDomains = [];
    let competitorLoadingState = {};
    let allBacklinkDetails = {}; // Store all backlink details for each domain

    // Global variables for pagination
    let currentPage = 1;
    const itemsPerPage = 25;
    let totalPages = 1;
    let currentCompetitors = [];

    // Function to analyze backlinks for a domain (returns a promise)
    async function analyzeBacklinks(domain, options = {}) {
        if (!domain) return { domain, fresh: false };
        const forceRefresh = Boolean(options && options.forceRefresh);
        competitorLoadingState[domain] = 'loading';
        updateDomainTabsUI();
        try {
            const response = await getBacklinkCompetitors(domain, 50, { forceRefresh });
            let competitorItems = [];
            let freshData = false;
            
            // Check if fresh data was fetched
            if (response && response.message && response.message.includes('New data fetched from DataForSEO')) {
                freshData = true;
                compBacklinksDebugLog(`Fresh backlinks data fetched for ${domain}`);
            }
            
            if (response?.tasks?.[0]?.result?.[0]?.items) {
                competitorItems = response.tasks[0].result[0].items;
            }
            
            // Always consider it successful if we get a valid response structure, even with empty items
            // This allows the tab to display "No competitors found" rather than "Error loading data"
            if (!response?.tasks?.[0]?.result?.[0]) {
                throw new Error('Invalid response structure received');
            }
            
            // Set empty array if no items, but don't throw an error
            if (!competitorItems || competitorItems.length === 0) {
                competitorItems = [];
                compBacklinksDebugLog('No competitor items found for domain:', domain);
            }
            backlinkDataByDomain[domain] = competitorItems;
            competitorLoadingState[domain] = 'loaded';
            
            return { domain, fresh: freshData };
        } catch (error) {
            competitorLoadingState[domain] = 'error';
            backlinkDataByDomain[domain] = [];
            console.error('Error analyzing backlinks:', error);
            return { domain, fresh: false, error: true };
        } finally {
            updateDomainTabsUI();
        }
    }

    // Create clickable domain tabs for competitor domains
    function createDomainTabs(domains, activeDomain) {
        const $resultsHeader = $('.aysa-results-header');
        $('.aysa-domain-tabs-container').remove();
        const $tabsContainer = $('<div class="aysa-domain-tabs-container"></div>');
        domains.forEach((domain) => {
            const isActive = domain === activeDomain;
            const state = competitorLoadingState[domain];
            let spinner = '';
            if (state === 'loading') {
                spinner = '<span class="aysa-tab-spinner"></span>';
            } else if (state === 'error') {
                spinner = '<span style="color:#ea4335;font-size:16px;margin-left:6px;">&#9888;</span>';
            }
            const $tab = $(`<button class="aysa-domain-tab${isActive ? ' active' : ''}" data-domain="${domain}">${domain}${spinner}</button>`);
            $tabsContainer.append($tab);
        });
        $resultsHeader.after($tabsContainer);
        $('.aysa-domain-tab').off('click').on('click', function() {
            const domain = $(this).data('domain');
            $('.aysa-domain-tab').removeClass('active');
            $(this).addClass('active');
            if (competitorLoadingState[domain] === 'loaded') {
                displayCompetitorData(backlinkDataByDomain[domain]);
            } else if (competitorLoadingState[domain] === 'loading') {
                $('.aysa-backlinks-table tbody').html('<tr><td colspan="4" style="text-align: center; padding: 20px;">Loading...</td></tr>');
            } else if (competitorLoadingState[domain] === 'error') {
                $('.aysa-backlinks-table tbody').html('<tr><td colspan="4" style="text-align: center; padding: 20px; color:#ea4335;">Error loading data. <button class="aysa-retry-btn" data-domain="'+domain+'">Retry</button></td></tr>');
            }
        });
        // Retry button handler
        $('.aysa-backlinks-table').off('click', '.aysa-retry-btn').on('click', '.aysa-retry-btn', function() {
            const domain = $(this).data('domain');
            competitorLoadingState[domain] = 'loading';
            updateDomainTabsUI();
            analyzeBacklinks(domain).then(() => {
                displayCompetitorData(backlinkDataByDomain[domain]);
            });
        });
    }

    // Update the domain tabs UI (for loading/error states)
    function updateDomainTabsUI() {
        const activeDomain = $('.aysa-domain-tab.active').data('domain') || competitorDomains[0];
        createDomainTabs(competitorDomains, activeDomain);
        // Always show the results section when updating tabs
        $('.aysa-results-section').show();
        if (competitorLoadingState[activeDomain] === 'loaded') {
            currentPage = 1; // Reset to first page when switching domains
            displayCompetitorData(backlinkDataByDomain[activeDomain]);
        } else if (competitorLoadingState[activeDomain] === 'loading') {
            $('.aysa-backlinks-table tbody').html('<tr><td colspan="4" style="text-align: center; padding: 20px;">Loading...</td></tr>');
        } else if (competitorLoadingState[activeDomain] === 'error') {
            $('.aysa-backlinks-table tbody').html('<tr><td colspan="4" style="text-align: center; padding: 20px; color:#ea4335;">Error loading data. <button class="aysa-retry-btn" data-domain="'+activeDomain+'">Retry</button></td></tr>');
        }
    }

    // Analyze all competitors in parallel
    async function analyzeAllCompetitors(domains, options = {}) {
        competitorDomains = domains;
        competitorLoadingState = {};
        backlinkDataByDomain = {};
        createDomainTabs(domains, domains[0]);
        
        // Start all analyses in parallel
        const results = await Promise.all(domains.map(domain => analyzeBacklinks(domain, options)));
        
        // Check for fresh data notifications
        const freshDataDomains = results.filter(result => result && result.fresh).map(result => result.domain);
        const errorDomains = results.filter(result => result && result.error).map(result => result.domain);
        
        // Show notifications
        if (freshDataDomains.length > 0) {
            showNotification(`✨ Fresh backlinks data automatically fetched for ${freshDataDomains.length} domain(s): ${freshDataDomains.join(', ')}`, 'success');
        } else if (errorDomains.length === 0) {
            showNotification('Backlinks analysis completed successfully!', 'success');
        }
        
        if (errorDomains.length > 0) {
            showNotification(`Analysis failed for ${errorDomains.length} domain(s): ${errorDomains.join(', ')}`, 'error');
        }
        
        // After all are done, show the first
        $('.aysa-results-section').show();
        updateDomainTabsUI();
    }

    function hydrateFromCachedBacklinks(projectId, domains) {
        competitorDomains = domains.slice();
        competitorLoadingState = {};
        backlinkDataByDomain = {};

        return getCachedBacklinks(projectId, domains).then(function(resp) {
            const map = (resp && resp.success && resp.data && resp.data.domains && typeof resp.data.domains === 'object')
                ? resp.data.domains
                : {};

            domains.forEach((domain) => {
                const row = map[domain] || {};
                const rawItems = Array.isArray(row.items) ? row.items : [];
                if (!rawItems.length) {
                    competitorLoadingState[domain] = 'loaded';
                    backlinkDataByDomain[domain] = [];
                    return;
                }

                const normalized = rawItems.map((item) => ({
                    domain_from: item.domain_from || item.source_domain || item.referring_domain || '',
                    url_from: item.url_from || item.source_url || '',
                    domain_to: item.domain_to || item.target_domain || domain,
                    url_to: item.url_to || item.target_url || '',
                    anchor: item.anchor || item.anchor_text || '',
                    first_seen: item.first_seen || '',
                    prev_seen: item.prev_seen || '',
                    last_seen: item.last_seen || '',
                    dofollow: Boolean(item.dofollow),
                    domain_rank: Number(item.domain_rank || 0),
                    broken_backlink: Boolean(item.broken_backlink),
                    link_spam_score: Number(item.link_spam_score || 0),
                    opportunity_tag: item.opportunity_tag || '',
                    quality_flags: Array.isArray(item.quality_flags) ? item.quality_flags : []
                }));
                const processed = processBacklinksResponse({ data: { backlinks: normalized } }, domain, 20);
                const competitorItems = processed?.tasks?.[0]?.result?.[0]?.items || [];
                backlinkDataByDomain[domain] = competitorItems;
                competitorLoadingState[domain] = 'loaded';
            });

            createDomainTabs(domains, domains[0]);
            $('.aysa-results-section').show();
            updateDomainTabsUI();

            const withData = domains.filter((d) => Array.isArray(backlinkDataByDomain[d]) && backlinkDataByDomain[d].length > 0);
            if (withData.length === 0) {
                showNotification('No local backlink snapshots found yet. Click Refresh Data to fetch and save.', 'info');
            } else {
                showNotification(`Loaded local backlink snapshots for ${withData.length}/${domains.length} competitors.`, 'success');
            }
        }).fail(function() {
            competitorDomains = domains.slice();
            competitorLoadingState = {};
            backlinkDataByDomain = {};
            domains.forEach((d) => {
                competitorLoadingState[d] = 'loaded';
                backlinkDataByDomain[d] = [];
            });
            createDomainTabs(domains, domains[0]);
            $('.aysa-results-section').show();
            updateDomainTabsUI();
            showNotification('Could not load local backlink snapshots.', 'error');
        });
    }

    // Analyze backlinks button
    $('.aysa-analyze-btn').click(async function() {
        const competitors = $('.aysa-competitor-domain').map(function() {
            return $(this).text().trim();
        }).get();
        if (competitors.length === 0) {
            alert('Please add at least one competitor domain to analyze.');
            return;
        }
        // Local-only analyze by default; use Refresh Data for live fetch + credit usage.
        analyzeAllCompetitors(competitors, { forceRefresh: false });
    });

    // On page load, fetch competitors and analyze all
    function initializePageWithSeoSettings() {
        const projectId = getProjectId();
        if (!projectId) {
            console.error('No project ID found');
            return;
        }
        getSeoSettings(projectId).then(function(seoSettings) {
            if (!seoSettings) {
                console.error('No SEO settings found');
                return;
            }
            // Location and Language dropdowns removed - no longer need to update them
            // if (seoSettings.targetedCountry) {
            //     $('.aysa-filter-dropdown.location').val(seoSettings.targetedCountry);
            // }
            // if (seoSettings.primaryLanguage) {
            //     $('.aysa-filter-dropdown.language').val(seoSettings.primaryLanguage);
            // }
            getCompetitors(projectId).then(function(resp) {
                const domains = (resp && resp.success && resp.data && Array.isArray(resp.data.competitors))
                    ? resp.data.competitors
                    : [];
                $('.aysa-competitor-boxes').empty();
                const normalizedDomains = [];
                domains.forEach((competitor) => {
                    if (addCompetitorToUI(String(competitor))) {
                        normalizedDomains.push(normalizeCompetitorDomain(String(competitor)));
                    }
                });
                const cleanDomains = normalizedDomains.filter(Boolean);
                if (cleanDomains.length > 0) {
                    hydrateFromCachedBacklinks(projectId, cleanDomains);
                    loadGapInsights(cleanDomains, false);
                } else {
                    showNotification('No competitors configured in Setup SEO Profile.', 'info');
                }
            }).fail(function(xhr, status, error) {
                console.error('Error fetching competitors:', error);
            });
        }).fail(function(xhr, status, error) {
            console.error('Error fetching SEO settings:', error);
        });
    }

    // Function to process backlinks response data
    function processBacklinksResponse(response, target, limit) {
        compBacklinksDebugLog('Processing backlinks response:', response);
        
        // Preserve the original message for notifications
        const originalMessage = response && response.message ? response.message : null;
        
        // Handle different response structures from backend
        let backlinks = [];
        let precomputedCompetitors = null;
        
        // New backend structure: response.data.backlinks and response.data.competitors
        if (response && response.data) {
            if (response.data.backlinks && Array.isArray(response.data.backlinks)) {
                backlinks = response.data.backlinks;
            }
            if (response.data.competitors && Array.isArray(response.data.competitors)) {
                precomputedCompetitors = response.data.competitors;
            }
        }
        // Direct structure: response.backlinks and response.competitors
        else if (response && response.backlinks && Array.isArray(response.backlinks)) {
            backlinks = response.backlinks;
            if (response.competitors && Array.isArray(response.competitors)) {
                precomputedCompetitors = response.competitors;
            }
        }
        // Old structure: response is directly array of backlinks
        else if (response && Array.isArray(response) && response.length > 0) {
            backlinks = response;
        }
        
        compBacklinksDebugLog('Processed backlinks data:', { 
            backlinksCount: backlinks.length, 
            hasPrecomputedCompetitors: !!precomputedCompetitors,
            precomputedCompetitors: precomputedCompetitors,
            sampleBacklinks: backlinks.slice(0, 3)
        });
        
        // Process the backlink details to extract competitor information
        if (backlinks && backlinks.length > 0) {
            // Store all backlink details for this target domain
            allBacklinkDetails[target] = backlinks.map(item => ({
                type: item.Type || item.type || "N/A",
                domainFrom: item.DomainFrom || item.domainFrom || item.domain_from || "N/A",
                urlFrom: item.UrlFrom || item.urlFrom || item.url_from || "N/A",
                domainTo: item.DomainTo || item.domainTo || item.domain_to || "N/A",
                urlTo: item.UrlTo || item.urlTo || item.url_to || "N/A",
                dofollow: item.Dofollow !== undefined ? item.Dofollow : 
                          item.dofollow !== undefined ? item.dofollow : false,
                anchor: item.Anchor || item.anchor || "N/A",
                firstSeen: item.FirstSeen || item.firstSeen || item.first_seen || "N/A",
                prevSeen: item.PrevSeen || item.prevSeen || item.prev_seen || "N/A",
                lastSeen: item.LastSeen || item.lastSeen || item.last_seen || "N/A",
                domainRank: Number(item.DomainRank || item.domainRank || item.domain_rank || 0),
                brokenBacklink: Boolean(item.BrokenBacklink !== undefined ? item.BrokenBacklink : item.broken_backlink),
                linkSpamScore: Number(item.LinkSpamScore || item.linkSpamScore || item.link_spam_score || 0),
                opportunityTag: item.OpportunityTag || item.opportunityTag || item.opportunity_tag || '',
                qualityFlags: Array.isArray(item.QualityFlags) ? item.QualityFlags : (Array.isArray(item.quality_flags) ? item.quality_flags : [])
            }));
            
            let competitors = [];
            
            // Check if precomputed competitors are valid (contain actual domain data)
            const hasValidPrecomputedCompetitors = precomputedCompetitors && 
                precomputedCompetitors.length > 0 && 
                precomputedCompetitors.some(comp => comp.Domain || comp.domain || comp.target);
            
            if (hasValidPrecomputedCompetitors) {
                compBacklinksDebugLog('Using precomputed competitors from backend');
                competitors = precomputedCompetitors
                    .filter(comp => comp.Domain || comp.domain || comp.target) // Filter out invalid entries
                    .map(comp => ({
                        target: comp.Domain || comp.domain || comp.target,
                        intersections: comp.CommonBacklinks || comp.commonBacklinks || comp.intersections || 0,
                        rank: comp.Rank || comp.rank || 0,
                        avgAuthority: Number(comp.avgAuthority || comp.avg_authority || 0),
                        dofollowRatio: Number(comp.dofollowRatio || comp.dofollow_ratio || 0),
                        opportunityTag: comp.opportunityTag || comp.opportunity_tag || 'review'
                    })).slice(0, limit);
            } else {
                compBacklinksDebugLog('Computing competitors from backlinks data');
                // Group backlinks by domainFrom to count intersections
                const domainCounts = {};
                backlinks.forEach(backlink => {
                    const domainFrom = backlink.DomainFrom || backlink.domainFrom || backlink.domain_from;
                    if (domainFrom && domainFrom !== target) {
                        if (!domainCounts[domainFrom]) {
                            domainCounts[domainFrom] = {
                                target: domainFrom,
                                intersections: 0,
                                rank: 0,
                                dofollowCount: 0,
                                authoritySum: 0,
                                authorityCount: 0,
                                brokenCount: 0,
                                spamFlags: 0,
                                explicitOpportunityTags: {}
                            };
                        }
                        domainCounts[domainFrom].intersections++;
                        if (backlink.Dofollow || backlink.dofollow) {
                            domainCounts[domainFrom].dofollowCount++;
                        }
                        const domainRank = Number(backlink.DomainRank || backlink.domainRank || backlink.domain_rank || 0);
                        if (domainRank > 0) {
                            domainCounts[domainFrom].authoritySum += domainRank;
                            domainCounts[domainFrom].authorityCount++;
                        }
                        if (backlink.BrokenBacklink || backlink.brokenBacklink || backlink.broken_backlink) {
                            domainCounts[domainFrom].brokenCount++;
                        }
                        const spamScore = Number(backlink.LinkSpamScore || backlink.linkSpamScore || backlink.link_spam_score || 0);
                        if (spamScore >= 25) {
                            domainCounts[domainFrom].spamFlags++;
                        }
                        const explicitTag = String(backlink.OpportunityTag || backlink.opportunityTag || backlink.opportunity_tag || '').trim();
                        if (explicitTag) {
                            domainCounts[domainFrom].explicitOpportunityTags[explicitTag] = (domainCounts[domainFrom].explicitOpportunityTags[explicitTag] || 0) + 1;
                        }
                    }
                });
                
                // Convert to array and sort by intersections
                competitors = Object.values(domainCounts)
                    .map((entry) => {
                        const avgAuthority = entry.authorityCount > 0 ? Math.round(entry.authoritySum / entry.authorityCount) : 0;
                        const dofollowRatio = entry.intersections > 0 ? Math.round((entry.dofollowCount / entry.intersections) * 100) : 0;
                        const explicitTags = Object.entries(entry.explicitOpportunityTags || {}).sort((a, b) => b[1] - a[1]);
                        let opportunityTag = 'review';
                        if (explicitTags.length > 0) {
                            opportunityTag = explicitTags[0][0];
                        } else if (entry.brokenCount > 0) {
                            opportunityTag = 'fix_or_reclaim';
                        } else if (entry.spamFlags > 0) {
                            opportunityTag = 'low_quality_noise';
                        } else if (avgAuthority >= 70 && dofollowRatio >= 50) {
                            opportunityTag = 'authority_outreach';
                        } else if (avgAuthority >= 35 && dofollowRatio >= 35) {
                            opportunityTag = 'outreach_candidate';
                        }
                        return {
                            target: entry.target,
                            intersections: entry.intersections,
                            rank: entry.rank,
                            avgAuthority,
                            dofollowRatio,
                            opportunityTag
                        };
                    })
                    .sort((a, b) => b.intersections - a.intersections)
                    .slice(0, limit);
                
                // If no competitors found, create at least one entry with 0 intersections
                if (competitors.length === 0 && backlinks.length > 0) {
                    const firstDomain = backlinks[0].DomainFrom || backlinks[0].domainFrom || backlinks[0].domain_from || 'N/A';
                    competitors.push({
                        target: firstDomain,
                        intersections: 0,
                        rank: 1,
                        avgAuthority: 0,
                        dofollowRatio: 0,
                        opportunityTag: 'review'
                    });
                }
                
                // Assign ranks based on intersections
                competitors.forEach((competitor, index) => {
                    competitor.rank = index + 1;
                });
            }
            
            compBacklinksDebugLog('Final competitors generated:', competitors);
            
            // Return in the expected format with preserved message
            return {
                message: originalMessage,
                tasks: [{
                    result: [{
                        items: competitors
                    }]
                }]
            };
        } else {
            // Return empty result in expected format with preserved message
            return {
                message: originalMessage,
                tasks: [{
                    result: [{
                        items: []
                    }]
                }]
            };
        }
    }

    // Function to get backlink competitors data - tries GET first, then POST if no data found
    async function getBacklinkCompetitors(target, limit = 50, options = {}) {
        const projectId = getProjectId();
        if (!projectId) {
            throw new Error('Project ID missing.');
        }
        const forceRefresh = Boolean(options && options.forceRefresh);

        const response = await $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'aysa_adverlink_backlink_audit',
                nonce: COMP_BACKLINKS_NONCE,
                domain: target,
                limit: Math.max(10, Math.min(500, limit * 5)),
                project_id: projectId,
                force_refresh: forceRefresh ? 1 : 0
            }
        });

        if (!response || response.success !== true || !response.data) {
            const message = (response && response.data) ? String(response.data) : 'Backlink audit request failed.';
            throw new Error(message);
        }

        const rawItems = Array.isArray(response.data.items) ? response.data.items : [];
        const normalized = rawItems.map((item) => ({
            domain_from: item.domain_from || item.source_domain || item.referring_domain || '',
            url_from: item.url_from || item.source_url || '',
            domain_to: item.domain_to || item.target_domain || target,
            url_to: item.url_to || item.target_url || '',
            anchor: item.anchor || item.anchor_text || '',
            first_seen: item.first_seen || '',
            prev_seen: item.prev_seen || '',
            last_seen: item.last_seen || '',
            dofollow: Boolean(item.dofollow),
            domain_rank: Number(item.domain_rank || 0),
            broken_backlink: Boolean(item.broken_backlink),
            link_spam_score: Number(item.link_spam_score || 0),
            opportunity_tag: item.opportunity_tag || '',
            quality_flags: Array.isArray(item.quality_flags) ? item.quality_flags : []
        }));

        return processBacklinksResponse({ data: { backlinks: normalized } }, target, limit);
    }
    
    // Function to display competitor data with pagination
    function displayCompetitorData(competitors) {
        compBacklinksDebugLog('Displaying competitor data:', competitors);
        const $tbody = $('.aysa-backlinks-table tbody');
        $tbody.empty();
        
        if (!competitors || competitors.length === 0) {
            $tbody.append(`
                <tr>
                    <td colspan="4" style="text-align: center; padding: 20px;">
                        No competitor data found. Try analyzing different domains.
                    </td>
                </tr>
            `);
            updatePagination(0);
            return;
        }

        // Store current competitors and calculate total pages
        currentCompetitors = competitors;
        totalPages = Math.ceil(competitors.length / itemsPerPage);
        currentPage = Math.min(currentPage, totalPages);
        
        // Get current page items
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, competitors.length);
        const currentPageItems = competitors.slice(startIndex, endIndex);
        
        // Display current page items
        currentPageItems.forEach(competitor => {
            const intersections = competitor.intersections || 0;
            const domain = competitor.target || '';
            const avgAuthority = Number(competitor.avgAuthority || 0);
            const dofollowRatio = Number(competitor.dofollowRatio || 0);
            const opportunityTag = String(competitor.opportunityTag || 'review').replace(/_/g, ' ');
            const $row = $('<tr>').attr('data-domain', domain);
            $row.append($('<td>').text(domain));
            $row.append($('<td>').text(`${intersections.toLocaleString()}${avgAuthority ? ` | DR ${avgAuthority}` : ''}${dofollowRatio ? ` | ${dofollowRatio}% dofollow` : ''}`));
            $row.append($('<td>').text(opportunityTag));

            const $viewBtn = $('<button>', { class: 'view-details-btn', type: 'button' }).text('View Details');
            $viewBtn.attr('data-domain', domain);
            $row.append($('<td>').append($viewBtn));
            $tbody.append($row);
        });

        // Update pagination controls
        updatePagination(competitors.length);

        // Add click handlers for view details buttons
        $('.view-details-btn').click(function() {
            const domain = $(this).data('domain');
            showBacklinkDetails(domain);
        });
    }

    // Function to update pagination controls
    function updatePagination(totalItems) {
        const $paginationInfo = $('.aysa-pagination-info');
        const $paginationPages = $('.aysa-pagination-pages');
        const $prevButton = $('.aysa-pagination-prev');
        const $nextButton = $('.aysa-pagination-next');

        // Update info text
        const start = totalItems === 0 ? 0 : (currentPage - 1) * itemsPerPage + 1;
        const end = Math.min(start + itemsPerPage - 1, totalItems);
        $paginationInfo.find('.aysa-pagination-start').text(start);
        $paginationInfo.find('.aysa-pagination-end').text(end);
        $paginationInfo.find('.aysa-pagination-total').text(totalItems);

        // Update page buttons
        $paginationPages.empty();
        for (let i = 1; i <= totalPages; i++) {
            const $pageButton = $(`<button class="aysa-pagination-page${i === currentPage ? ' active' : ''}">${i}</button>`);
            $paginationPages.append($pageButton);
        }

        // Update prev/next buttons
        $prevButton.prop('disabled', currentPage === 1);
        $nextButton.prop('disabled', currentPage === totalPages);

        // Add click handlers
        $('.aysa-pagination-page').click(function() {
            const newPage = parseInt($(this).text());
            if (newPage !== currentPage) {
                currentPage = newPage;
                displayCompetitorData(currentCompetitors);
            }
        });

        $prevButton.off('click').click(function() {
            if (currentPage > 1) {
                currentPage--;
                displayCompetitorData(currentCompetitors);
            }
        });

        $nextButton.off('click').click(function() {
            if (currentPage < totalPages) {
                currentPage++;
                displayCompetitorData(currentCompetitors);
            }
        });
    }

    // Function to get potential sites
    async function getPotentialSites(authority, count, keywords) {
        try {
            compBacklinksDebugLog('Starting site search with authority:', authority, 'and count:', count);
            compBacklinksDebugLog('Using keywords:', keywords);
            
            // Get the currently active domain tab to get its keywords
            const domain = $('.aysa-domain-tab.active').data('domain') || $('#recommendation-domain').text();
            if (!domain) {
                console.error('No active domain found');
                return [];
            }
            
            // Verify we have keywords
            if (!keywords || keywords.length === 0) {
                console.error('No keywords provided for domain:', domain);
                return [];
            }
            
            // Take only the first keyword
            const keyword = keywords[0];
            compBacklinksDebugLog('Using keyword for site search:', keyword);
            
            // Store all results
            const allSites = [];
            
            try {
                compBacklinksDebugLog('Starting search for sites matching keyword:', keyword);
                
                // Use the new-search-design endpoint with streaming
                const response = await fetchSitesForKeyword(keyword);
                
                if (response && response.length > 0) {
                    compBacklinksDebugLog(`Found ${response.length} sites for keyword: ${keyword}`);
                    
                    // Add unique sites to our collection
                    for (const site of response) {
                        if (!allSites.some(s => s.domain === site.domain)) {
                            compBacklinksDebugLog('Adding new site:', site);
                            allSites.push(site);
                            // Update the UI with the new site
                            updateRecommendationSites(allSites);
                        }
                        
                        // If we have enough sites, stop adding more
                        if (allSites.length >= count) {
                            break;
                        }
                    }
                } else {
                    compBacklinksDebugLog(`No sites found for keyword: ${keyword}`);
                }
            } catch (error) {
                console.error('Error fetching sites for keyword:', keyword, error);
            }
            
            compBacklinksDebugLog(`Returning ${allSites.length} sites for recommendations`);
            return allSites;
        } catch (error) {
            if (COMP_BACKLINKS_DEBUG) {
                console.error('Error in getPotentialSites:', error);
            }
            return [];
        }
    }

    // Function to fetch sites for a specific keyword
    function fetchSitesForKeyword(keyword) {
        return new Promise((resolve, reject) => {
            // Get country and language from SEO settings instead of dropdowns
            const projectId = getProjectId();
            let country = 'Romania'; // Default fallback
            let language = 'Romanian'; // Default fallback
            
            // Get values from stored SEO settings
            getSeoSettings(projectId).then(function(seoSettings) {
                if (seoSettings) {
                    country = seoSettings.targetedCountry || country;
                    language = seoSettings.primaryLanguage || language;
                }
                
                compBacklinksDebugLog('Fetching sites for keyword:', keyword, country, language);
                
                // Use a new endpoint that doesn't use streaming
                const url = `${COMP_BACKLINKS_API_BASE}/search/plugin-search?keyword=${encodeURIComponent(keyword)}&country=${encodeURIComponent(country)}&language=${encodeURIComponent(language)}`;
                compBacklinksDebugLog('API URL:', url);
                
                $('#recommendation-sites').html('<div style="text-align: center; padding: 30px;"><div style="margin-top: 15px;">Loading publisher opportunities...</div></div>');
                
                // Disable buy button while loading
                compBacklinksDebugLog('Disabling buy button while loading sites');
                $('.buy-links-btn').prop('disabled', true).css('opacity', '0.5');
                
                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'json',
                    timeout: 60000, // Increased timeout to 60 seconds
                    success: function(response) {
                        compBacklinksDebugLog('API response received:', response);
                        const sites = [];
                        if (response && Array.isArray(response)) {
                            response.forEach(result => {
                                if (result && result.domain) {
                                    const domainStr = result.domain.domain.replace(/^https?:\/\//, '');
                                    const site = {
                                        domain: domainStr,
                                        authority: result.domain.domainAuthority || 0,
                                        id: result.domain.id,
                                        country: result.domain.country,
                                        language: result.domain.language,
                                        price: result.domain.price || result.domain.totalPrice || 0,
                                        urls: result.urls || []
                                    };
                                    if (!sites.some(s => s.domain === site.domain)) {
                                        sites.push(site);
                                    }
                                }
                            });
                        }
                        compBacklinksDebugLog('Parsed sites:', sites);
                        
                        // Enable buy button after loading
                        compBacklinksDebugLog('Re-enabling buy button after sites loaded');
                        $('.buy-links-btn').prop('disabled', false).css('opacity', '1');
                        
                        resolve(sites);
                    },
                    error: function(xhr, status, error) {
                        if (COMP_BACKLINKS_DEBUG) {
                            console.error('Error fetching sites:', status, error);
                        }
                        $('#recommendation-sites').html('<div style="color: #ea4335; text-align: center; padding: 20px;">Error loading sites. Please try again.</div>');
                        
                        // Enable buy button even on error
                        compBacklinksDebugLog('Re-enabling buy button after site loading error');
                        $('.buy-links-btn').prop('disabled', false).css('opacity', '1');
                        
                        resolve([]);
                    }
                });
            }).catch(function(error) {
                if (COMP_BACKLINKS_DEBUG) {
                    console.error('Error getting SEO settings:', error);
                }
                // Fallback to default values
                compBacklinksDebugLog('Using fallback values - country:', country, 'language:', language);
                resolve([]);
            });
        });
    }

    // Function to update the sites section in the recommendation modal
    function updateRecommendationSites(sites) {
        compBacklinksDebugLog('Updating UI with sites:', sites);
        
        // If no sites found
        if (!sites || sites.length === 0) {
            $('#recommendation-sites').html('<div style="text-align: center; padding: 20px;">No sites found for this keyword.</div>');
            return;
        }
        
        // Create table structure without repeating the section header (it's already in the modal)
        const tableHtml = `
            <table class="aysa-backlinks-table" style="width: 100%; border-collapse: collapse;">
                <thead>
                    <tr>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">Domain</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">Authority</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">Country</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">Language</th>
                        <th style="padding: 12px; text-align: left; border-bottom: 1px solid #ddd;">Price</th>
                    </tr>
                </thead>
                <tbody>
                    ${sites.map(site => `
                        <tr>
                            <td style="padding: 12px; border-bottom: 1px solid #ddd;">
                                <div style="font-weight: bold;">${site.domain}</div>
                                ${site.urls && site.urls.length > 0 ? `
                                    <div style="font-size: 12px; color: #666; margin-top: 4px;">
                                        <div><a href="${site.urls[0]}" target="_blank" style="color: #1a73e8; text-decoration: none;">${site.urls[0]}</a></div>
                                    </div>
                                ` : ''}
                            </td>
                            <td style="padding: 12px; border-bottom: 1px solid #ddd;">
                                <span style="background: #e0f2f1; color: #00897b; padding: 2px 8px; border-radius: 12px; font-size: 12px;">
                                    ${site.authority}
                                </span>
                            </td>
                            <td style="padding: 12px; border-bottom: 1px solid #ddd;">
                                ${site.country ? `
                                    <span style="background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 12px;">
                                        ${site.country}
                                    </span>
                                ` : '-'}
                            </td>
                            <td style="padding: 12px; border-bottom: 1px solid #ddd;">
                                ${site.language ? `
                                    <span style="background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 12px;">
                                        ${site.language}
                                    </span>
                                ` : '-'}
                            </td>
                            <td style="padding: 12px; border-bottom: 1px solid #ddd;">
                                <span style="background: #e3f2fd; color: #1565c0; padding: 2px 8px; border-radius: 12px; font-size: 12px;">
                                    $${site.price || ((site.authority / 10) * 10).toFixed(2)}
                                </span>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
        
        $('#recommendation-sites').html(tableHtml);
    }

    // Function to show recommendation in modal
    async function showRecommendation(domain, intersections, rank) {
        // Show modal
        compBacklinksDebugLog('Showing recommendation modal for domain:', domain);
        $('#recommendation-domain').text(domain);
        $('#recommendation-modal').show();
        $('.aysa-modal-loading').show();
        $('.aysa-recommendation-container').hide();
        
        // Ensure buy button is visible when modal opens
        setTimeout(() => {
            if ($('.buy-links-btn').length > 0) {
                compBacklinksDebugLog('Buy button found in modal');
            } else if (COMP_BACKLINKS_DEBUG) {
                console.error('Buy button NOT found in modal!');
            }
        }, 100);
        try {
        // Calculate number of recommended links based on intersections
            const baseLinks = Math.ceil(intersections * 0.1); // 10% of intersections
        const links = Math.min(Math.max(baseLinks, 5), 50); // Between 5 and 50 links
        
        // Calculate estimated cost using domain authority
            const domainAuthority = rank;
        const basePrice = getBasePrice(domainAuthority);
        const linkTypeMultiplier = 1.0; // NormalFollow
        const exclusivityMultiplier = 1.0; // Not exclusive
        const vat = 0.19;
        
        // Calculate price per link
        const pricePerLink = calculatePrice(basePrice, linkTypeMultiplier, exclusivityMultiplier, vat);
        const totalCost = pricePerLink * links;
        
            // Get target keywords from API - only call this once
            compBacklinksDebugLog('Getting keywords for domain:', domain);
            const keywords = await getRecommendedKeywords(window.location.hostname, domain);
            compBacklinksDebugLog('Received keywords:', keywords);
            
            // Display keywords as chips
            const keywordsHtml = keywords.map(keyword => `<span class="aysa-keyword-chip">${keyword}</span>`).join('');
            $('#recommendation-keywords').html(keywordsHtml || 'No keywords found');
            
            // Show the recommendation container with loading state
            $('.aysa-modal-loading').hide();
            $('.aysa-recommendation-container').show();
            
            // Initialize empty sites section
            const sitesPlaceholderHtml = '<div class="aysa-loading-sites">Loading publisher opportunities...</div>';
            $('#recommendation-sites').html(sitesPlaceholderHtml);
            
            // Get potential sites from API using the keywords we just retrieved
            const sites = await getPotentialSites(domainAuthority, links, keywords);
            compBacklinksDebugLog('Sites fetched in showRecommendation:', sites);
            
            // Update number of links based on actual sites found
            const actualLinkCount = sites.length;
            
            // Calculate actual total cost based on real site prices
            let actualTotalCost = 0;
            sites.forEach(site => {
                const sitePrice = parseFloat(site.price || ((site.authority / 10) * 10).toFixed(2));
                actualTotalCost += sitePrice;
            });
            
            // If we couldn't calculate a real cost, use the estimated one
            if (actualTotalCost === 0) {
                actualTotalCost = totalCost;
            }
            
            // Populate recommendation data with actual number of sites found
            $('#recommendation-links-count').text(actualLinkCount);
            $('#recommendation-cost').text(actualTotalCost.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
            
            // Add buy links button handler with debugging
            compBacklinksDebugLog('Setting up buy button handler for domain:', domain);
            $('.buy-links-btn').off('click').on('click', function() {
                compBacklinksDebugLog('Buy button clicked! Domain:', domain, 'Keywords:', keywords, 'Cost:', actualTotalCost);
                handleBuyLinks(domain, keywords, actualTotalCost);
            });
            
            // Make sure button is enabled and visible
            $('.buy-links-btn').prop('disabled', false).css({
                'opacity': '1',
                'display': 'inline-block',
                'visibility': 'visible'
            }).text('Buy Links');
        } catch (error) {
            if (COMP_BACKLINKS_DEBUG) {
                console.error('Error getting recommendation data:', error);
            }
            $('.aysa-modal-loading').hide();
            $('.aysa-recommendation-container').html('<p style="color: #ea4335;">Error loading recommendation data. Please try again.</p>');
            $('.aysa-recommendation-container').show();
        }
    }

    // Function to get recommended keywords from API
    async function getRecommendedKeywords(clientDomain, competitorDomain) {
        try {
            compBacklinksDebugLog('Getting keyword recommendations for domains:', clientDomain, competitorDomain);
            
            // Get language from SEO settings instead of dropdown
            const projectId = getProjectId();
            const seoSettings = await getSeoSettings(projectId);
            const language = seoSettings ? seoSettings.primaryLanguage || 'Romanian' : 'Romanian';
            compBacklinksDebugLog('Using language from SEO settings:', language);
            
            const response = await $.ajax({
                url: `${COMP_BACKLINKS_API_BASE}/api/chatgpt/generate-competitive-keywords`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    clientDomain: clientDomain,
                    competitorDomain: competitorDomain,
                    language: language
                }),
                timeout: 30000 // 30 second timeout
            });
            
            compBacklinksDebugLog('Keyword recommendations response:', response);
            
            if (response && response.keywords && Array.isArray(response.keywords)) {
                return response.keywords;
            } else {
                throw new Error('The keyword recommendation service returned an invalid response.');
            }
        } catch (error) {
            if (COMP_BACKLINKS_DEBUG) {
                console.error('Error fetching recommended keywords:', error);
            }
            throw error; // Re-throw to be handled by caller
        }
    }
    
    // Function to get base price based on domain authority
    function getBasePrice(domainAuthority) {
        if (domainAuthority <= 10) return 5;
        if (domainAuthority <= 20) return 10;
        if (domainAuthority <= 30) return 20;
        if (domainAuthority <= 40) return 30;
        if (domainAuthority <= 50) return 40;
        if (domainAuthority <= 60) return 50;
        if (domainAuthority <= 70) return 60;
        if (domainAuthority <= 80) return 70;
        if (domainAuthority <= 90) return 80;
        if (domainAuthority <= 99) return 90;
        return 100;
    }
    
    // Function to calculate price with VAT
    function calculatePrice(basePrice, linkTypeMultiplier, exclusivityMultiplier, vat) {
        const price = basePrice * linkTypeMultiplier * exclusivityMultiplier;
        // Use the service type helper for consistent VAT calculation
        if (window.AysaServiceTypeHelper) {
            return window.AysaServiceTypeHelper.calculatePriceWithVAT(price, vat);
        }
        // Fallback to original logic
        const vatValue = price * vat;
        return Math.round((price + vatValue) * 100) / 100;
    }
    

    
    // Function to display backlink details in the modal
    function showBacklinkDetails(domain) {
        // Show modal
        $('#backlink-domain').text(domain);
        $('#backlink-details-modal').show();
        $('.aysa-modal-loading').show();
        $('.aysa-backlinks-details-container').hide();
        
        // Find the target domain that has backlinks from this domain
        let relevantBacklinks = [];
        
        // Search through all stored backlink details
        Object.keys(allBacklinkDetails).forEach(targetDomain => {
            const domainBacklinks = allBacklinkDetails[targetDomain];
            const filteredBacklinks = domainBacklinks.filter(backlink => 
                backlink.domainFrom === domain
            );
            relevantBacklinks = relevantBacklinks.concat(filteredBacklinks);
        });
        
        compBacklinksDebugLog('Filtered backlinks for domain:', domain, relevantBacklinks);
        
        // Hide loading and show content
        $('.aysa-modal-loading').hide();
        
        // Populate details table
        const $tbody = $('.aysa-backlinks-details-table tbody');
        $tbody.empty();
        
        if (!relevantBacklinks || relevantBacklinks.length === 0) {
            const $row = $('<tr>');
            $row.append(
                $('<td>', {
                    colspan: 5,
                    style: 'text-align: center; padding: 20px;'
                }).text(`No backlink data found for ${domain}.`)
            );
            $tbody.append($row);
        } else {
            relevantBacklinks.forEach(backlink => {
                const dateOptions = { year: 'numeric', month: 'short', day: 'numeric' };
                const firstSeen = backlink.firstSeen && backlink.firstSeen !== 'N/A' ? 
                    new Date(backlink.firstSeen.split(' ')[0]).toLocaleDateString(undefined, dateOptions) : 'N/A';
                const lastSeen = backlink.lastSeen && backlink.lastSeen !== 'N/A' ? 
                    new Date(backlink.lastSeen.split(' ')[0]).toLocaleDateString(undefined, dateOptions) : 'N/A';

                const safeUrl = sanitizeExternalUrl(backlink.urlFrom);
                const sourceText = truncateUrl(backlink.urlFrom, 40);
                const anchorText = backlink.anchor && backlink.anchor !== 'N/A' ? backlink.anchor : '-';
                const domainFromText = backlink.domainFrom || '-';
                const linkTypeText = backlink.dofollow ? 'DoFollow' : 'NoFollow';
                const linkTypeClass = backlink.dofollow ? 'dofollow' : 'nofollow';

                const $sourceWrapper = $('<div>', { class: 'aysa-source-url' });
                const $sourceLink = $('<a>', {
                    href: safeUrl,
                    target: '_blank',
                    rel: 'noopener noreferrer'
                }).text(sourceText);
                $sourceWrapper.append($sourceLink);
                $sourceWrapper.append($('<div>', { class: 'aysa-domain-from' }).text(domainFromText));

                const $row = $('<tr>');
                $row.append($('<td>').append($sourceWrapper));
                $row.append($('<td>').text(anchorText));
                $row.append(
                    $('<td>').append(
                        $('<span>', { class: `aysa-link-type ${linkTypeClass}` }).text(linkTypeText)
                    )
                );
                $row.append($('<td>').text(firstSeen));
                $row.append($('<td>').text(lastSeen));
                $tbody.append($row);
            });
        }
        
        $('.aysa-backlinks-details-container').show();
    }
    
    // Helper function to truncate URLs for display
    function truncateUrl(url, maxLength) {
        if (!url) return '-';
        
        // Remove protocol (http:// or https://)
        let cleanUrl = url.replace(/^https?:\/\//i, '');
        
        if (cleanUrl.length <= maxLength) return cleanUrl;
        return cleanUrl.substring(0, maxLength) + '...';
    }
    
    // Close modal when clicking the X or outside the modal
    $('.aysa-modal-close').click(function() {
        $('#backlink-details-modal').hide();
        $('#recommendation-modal').hide();
    });
    
    $(window).click(function(event) {
        if ($(event.target).is('#backlink-details-modal')) {
            $('#backlink-details-modal').hide();
        }
        if ($(event.target).is('#recommendation-modal')) {
            $('#recommendation-modal').hide();
        }
    });

    // Function to show wallet alert
    function showWalletAlert(domain, currentBalance, requiredBalance) {
        const alertMessage = `You need ${requiredBalance.toLocaleString('en-US', { style: 'currency', currency: 'USD' })} in your Wallet to activate this recommendation. You currently have ${currentBalance.toLocaleString('en-US', { style: 'currency', currency: 'USD' })}.`;
        
        // Remove any existing alert modal
        $('#wallet-alert-modal').remove();
        
        // Create and show modal
        const $modal = $(`
            <div class="aysa-modal" id="wallet-alert-modal">
                <div class="aysa-modal-content">
                    <div class="aysa-modal-header">
                        <h2>Insufficient Wallet Balance</h2>
                        <span class="aysa-modal-close">&times;</span>
                    </div>
                    <div class="aysa-modal-body">
                        <p>${alertMessage}</p>
                        <div class="aysa-modal-actions">
                            <button class="aysa-topup-btn">Top Up Wallet</button>
                        </div>
                    </div>
                </div>
            </div>
        `);

        $('body').append($modal);
        $('#wallet-alert-modal').show();

        // Handle top-up button click
        $('.aysa-topup-btn').click(function() {
            const amountNeeded = requiredBalance - currentBalance;
            if (
                window.AysaCredits &&
                typeof window.AysaCredits.startTopupCheckout === 'function'
            ) {
                window.AysaCredits.startTopupCheckout(Math.ceil(amountNeeded), {
                    onError: function(message) {
                        alert(message || 'Could not generate the payment link.');
                    },
                    onMissingLink: function(message) {
                        alert(message || 'The order was created, but the payment link is missing.');
                    }
                });
                $('#wallet-alert-modal').remove();
                return;
            }

            alert('Wallet checkout is not available on this screen yet.');
        });

        // Handle modal close
        $('#wallet-alert-modal .aysa-modal-close').click(function() {
            $('#wallet-alert-modal').remove();
        });
        
        // Close when clicking outside the modal
        $(window).click(function(event) {
            if ($(event.target).is('#wallet-alert-modal')) {
                $('#wallet-alert-modal').remove();
            }
        });
    }

    // Function to handle buy links
    async function handleBuyLinks(domain, keywords, budget) {
        try {
            compBacklinksDebugLog('Preparing order for:', domain, keywords, budget);
            
            // Check if button exists before proceeding
            if ($('.buy-links-btn').length === 0) {
                if (COMP_BACKLINKS_DEBUG) {
                    console.error('Buy button not found in DOM!');
                }
                alert('Buy button is unavailable. Please refresh the page.');
                return;
            }
            
            // Disable the button while processing
            $('.buy-links-btn').prop('disabled', true).css('opacity', '0.5').text('Processing...');
            compBacklinksDebugLog('Buy button disabled for processing');
            
            // Get the sites from the recommendations table
            const sites = [];
            $('#recommendation-sites table tbody tr').each(function() {
                const $row = $(this);
                const site = {
                    domain: $row.find('td:nth-child(1) div:first-child').text().trim(),
                    authority: parseInt($row.find('td:nth-child(2) span').text().trim()),
                    url: $row.find('td:nth-child(1) a').attr('href') || '',
                    price: parseFloat($row.find('td:nth-child(5) span').text().replace('$', '').trim())
                };
                sites.push(site);
            });
            
            // Get the client domain (your domain)
            const clientDomain = window.location.hostname;
            
            // Get Project ID using the existing function
            const projectId = getProjectId();
            
            if (!projectId) {
                throw new Error('Project ID could not be found. Please complete the plugin setup first.');
            }
            
            // Get country and language from SEO settings instead of filters
            const seoSettings = await getSeoSettings(projectId);
            const country = seoSettings ? seoSettings.targetedCountry || 'Romania' : 'Romania';
            const language = seoSettings ? seoSettings.primaryLanguage || 'Romanian' : 'Romanian';
            
            // Use the first keyword as the main keyword for the order
            const mainKeyword = keywords[0] || 'default keyword';
            
            // Calculate number of links to buy based on available sites
            const numberOfLinksToBuy = sites.length;
            
            compBacklinksDebugLog('Order details:', {
                projectId: projectId,
                country: country,
                language: language,
                mainKeyword: mainKeyword,
                totalSites: sites.length,
                numberOfLinksToBuy: numberOfLinksToBuy,
                clientDomain: clientDomain,
                competitorDomain: domain
            });
            
            compBacklinksDebugLog('Sites found for order:', sites);
            compBacklinksDebugLog('Number of links to buy:', numberOfLinksToBuy);
            
            // Prepare the WordToLinks data
            const wordToLinks = sites.map((site, index) => {
                // Use a keyword from the list if available, otherwise use the first keyword
                const keyword = keywords[index % keywords.length] || keywords[0];
                
                // Extract just the domain name
                const publisherDomain = site.domain.split('/')[0].replace(/^https?:\/\//, '');
                
                return {
                    keyword: keyword,
                    url: `https://${clientDomain}`,
                    title: `${keyword} - Backlink from ${publisherDomain}`,
                    exclusivity: false,
                    typeOfLink: 'NormalFollow',
                    publisherWebsite: publisherDomain,
                    monthlyValue: site.price || 5.00,
                    domainAuthority: site.authority || 0,
                    targetUrl: site.url || `https://${publisherDomain}`,
                    country: country,
                    language: language
                };
            });
            
            // Create the order payload with all required fields
            const orderData = {
                wordToLinks: wordToLinks,
                country: country,
                keyword: mainKeyword,
                language: language,
                clientDomain: clientDomain,
                competitorDomain: domain,
                totalBudget: budget,
                projectId: projectId,
                numberOfLinksToBuy: numberOfLinksToBuy,
                NumberOfLinksToBuy: numberOfLinksToBuy // Both formats in case API expects different naming
            };
            
            // Validate required fields before sending
            if (!country || !mainKeyword || !language || !projectId) {
                throw new Error(`Order data is incomplete. Country=${country}, Keyword=${mainKeyword}, Language=${language}, ProjectId=${projectId}`);
            }
            
            if (!wordToLinks || wordToLinks.length === 0) {
                throw new Error('No publisher sites are available for this order.');
            }
            
            if (numberOfLinksToBuy <= 0) {
                throw new Error(`The number of links must be greater than 0. Found ${numberOfLinksToBuy} available sites.`);
            }
            
            compBacklinksDebugLog('Sending order data:', orderData);
            compBacklinksDebugLog('Validation passed - Required fields:', {
                projectId: projectId,
                country: country,
                keyword: mainKeyword, 
                language: language,
                wordToLinksCount: wordToLinks.length,
                numberOfLinksToBuy: numberOfLinksToBuy
            });
            
            // Send the order to the API
            const response = await $.ajax({
                url: `${COMP_BACKLINKS_API_BASE}/api/order/process-order`,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(orderData)
            });
            
            compBacklinksDebugLog('Order response:', response);

            if (response.success) {
                // Close the recommendation modal
                $('#recommendation-modal').hide();
                
                // Show success message
                alert(`The order was placed successfully. Order ID: ${response.orderId}`);
                
                // Update UI to show "In Progress" status in the table
                updateLinkStatus(domain, 'in_progress');
            } else {
                // Handle insufficient credits scenario
                if (response.message && response.message.includes("Insufficient")) {
                    showWalletAlert(domain, response.currentCredits, response.requiredCredits);
                } else {
                alert(response.message || 'Could not place the order.');
                }
            }
        } catch (error) {
            if (COMP_BACKLINKS_DEBUG) {
                console.error('Error ordering links:', error);
            }
            
            // Enhanced error handling
            let errorMessage = 'An error occurred while placing the order.';
            
            if (error.responseJSON && error.responseJSON.errors) {
                // API validation errors
                const errors = error.responseJSON.errors;
                const errorDetails = Object.keys(errors).map(key => `${key}: ${errors[key].join(', ')}`).join('\n');
                errorMessage = `Validation errors:\n${errorDetails}`;
                if (COMP_BACKLINKS_DEBUG) {
                    console.error('API validation errors:', errors);
                }
            } else if (error.responseText) {
                // Other API errors
                errorMessage = `API error: ${error.responseText}`;
                if (COMP_BACKLINKS_DEBUG) {
                    console.error('API error response:', error.responseText);
                }
            } else if (error.message) {
                // JavaScript errors
                errorMessage = error.message;
                if (COMP_BACKLINKS_DEBUG) {
                    console.error('JavaScript error:', error.message);
                }
            }
            
            alert(errorMessage);
        } finally {
            // Re-enable the button
            compBacklinksDebugLog('Re-enabling buy button');
            $('.buy-links-btn').prop('disabled', false).css({
                'opacity': '1',
                'display': 'inline-block',
                'visibility': 'visible'
            }).text('Buy Links');
            compBacklinksDebugLog('Buy button re-enabled successfully');
        }
    }

    // Function to update link status in UI
    function updateLinkStatus(domain, status) {
        const $row = $(`.aysa-backlinks-table tr[data-domain="${domain}"]`);
        const $recommendationCell = $row.find('td:last-child');
        
        let statusText = '';
        let statusClass = '';
        
        switch(status) {
            case 'in_progress':
                statusText = 'În lucru';
                statusClass = 'in-progress';
                break;
            case 'completed':
                statusText = 'Complet';
                statusClass = 'completed';
                break;
        }
        
        $recommendationCell.html(`
            <div class="link-status">
                <span class="status-badge ${statusClass}">${statusText}</span>
            </div>
        `);
    }

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

    // Add click handler for the Get Recommendation button
    $('.aysa-get-recommendation-btn').click(function() {
        // Get the first competitor from the list
        const firstCompetitor = $('.aysa-competitor-domain').first().text().trim();
        
        if (!firstCompetitor) {
            alert('Please add at least one competitor domain first.');
            return;
        }
        
        // For the rank and intersections, we'll use estimates or get from the UI if available
        let rank = 50; // Default rank
        let intersections = 100; // Default intersections
        
        // If we have data in the table, try to get more accurate values
        const $firstRow = $('.aysa-backlinks-table tbody tr').first();
        if ($firstRow.length) {
            const domain = $firstRow.data('domain');
            if (domain === firstCompetitor) {
                intersections = parseInt($firstRow.find('td').eq(1).text().replace(/,/g, '')) || 100;
                rank = parseInt($firstRow.find('td').eq(2).text()) || 50;
            }
        }
        
        compBacklinksDebugLog(`Showing recommendation for first competitor: ${firstCompetitor}, intersections: ${intersections}, rank: ${rank}`);
        
        // Show recommendation using the first competitor
        showRecommendation(firstCompetitor, intersections, rank);
    });

    // 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" style="margin: 10px 0; position: relative;">
                <p>${message}</p>
                <button type="button" class="notice-dismiss" style="position: absolute; top: 0; right: 1px; padding: 9px; background: none; border: none; color: #72777c; cursor: pointer;">
                    <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();
            });
        });
    }

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

    // Function to refresh competitor backlinks data via POST
    function refreshCompetitorBacklinksData() {
        const $button = $('#aysa-refresh-competitor-backlinks');
        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...'
        );

        getCompetitors(projectId).done(async function(resp) {
            const domains = (resp && resp.success && resp.data && Array.isArray(resp.data.competitors))
                ? resp.data.competitors
                : [];
            if (domains.length === 0) {
                showNotification('No competitors configured in Setup SEO Profile.', 'error');
                return;
            }
            $('.aysa-competitor-boxes').empty();
            const cleanDomains = [];
            domains.forEach((domain) => {
                if (addCompetitorToUI(String(domain))) {
                    cleanDomains.push(normalizeCompetitorDomain(String(domain)));
                }
            });
            const filtered = cleanDomains.filter(Boolean);
            if (filtered.length === 0) {
                showNotification('No valid competitor domains found in Setup SEO Profile.', 'error');
                return;
            }
            await analyzeAllCompetitors(filtered, { forceRefresh: true });
            await loadGapInsights(filtered, true);
            showNotification(`Competitor backlinks refreshed for ${filtered.length} domain(s).`, 'success');
        }).fail(function(xhr) {
            const message = xhr && xhr.responseJSON && xhr.responseJSON.data
                ? xhr.responseJSON.data
                : 'Failed to load competitors from Setup SEO Profile.';
            showNotification(message, 'error');
        }).always(function() {
            $button.prop('disabled', false).removeClass('loading').html(
                '<span class="dashicons dashicons-update"></span> Refresh Data'
            );
        });
    }
});
</script> 
