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

// Get the monthly recommendations - COMMENTED OUT (DUMMY DATA)
/*
$monthly_recommendations = array(
    'keywords' => array('pending' => 3, 'approved' => 2),
    'technical' => array('pending' => 5, 'approved' => 1),
    'content' => array('pending' => 4, 'approved' => 3),
    'offpage' => array('pending' => 2, 'approved' => 1),
    'conversion' => array('pending' => 3, 'approved' => 2)
);
*/
?>

<div class="aysa-dashboard-wrapper">
    <div class="aysa-dashboard-container">
        <!-- Header Section -->
        <div class="aysa-dashboard-header">
            <div class="aysa-dashboard-title">
                <h1>Adjustment and Improvement</h1>
                <p>Automated and cyclic SEO optimization system</p>
            </div>
            <div class="aysa-dashboard-user">
                <?php 
                // Use the credits component
                if (class_exists('Aysa_Credits_Component')) {
                    Aysa_Credits_Component::display();
                } else {
                    echo '<div class="aysa-credits-component"><span class="aysa-credits-value">Credits: <span class="aysa-credits-amount"><span class="aysa-loading-spinner"></span></span></span></div>';
                }
                ?>
            </div>
        </div>

        <!-- Monthly Recommendations Panel - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-panel aysa-recommendations-panel">
            <div class="aysa-recommendations-header">
                <h2 class="aysa-section-title">Monthly Optimization Report - <?php echo date('F Y'); ?></h2>
                <div class="aysa-actions">
                    <button class="aysa-btn aysa-btn-primary" id="approveAllBtn">Approve All Recommendations</button>
                    <button class="aysa-btn aysa-btn-secondary" id="viewReportBtn">View Full Report</button>
                </div>
            </div>
            
            <div class="aysa-recommendations-grid">
                <div class="aysa-recommendation-card">
                    <div class="aysa-recommendation-header">
                        <span class="aysa-metric-icon aysa-blue"><span class="dashicons dashicons-search"></span></span>
                        <h3>Keywords</h3>
                    </div>
                    <div class="aysa-recommendation-stats">
                        <div class="aysa-stat">
                            <span class="aysa-stat-label">Pending</span>
                            <span class="aysa-stat-value"><?php echo $monthly_recommendations['keywords']['pending']; ?></span>
                        </div>
                        <div class="aysa-stat">
                            <span class="aysa-stat-label">Approved</span>
                            <span class="aysa-stat-value"><?php echo $monthly_recommendations['keywords']['approved']; ?></span>
                        </div>
                    </div>
                    <button class="aysa-btn aysa-btn-outline">View Proposals</button>
                </div>
                
                <div class="aysa-recommendation-card">
                    <div class="aysa-recommendation-header">
                        <span class="aysa-metric-icon aysa-green"><span class="dashicons dashicons-performance"></span></span>
                        <h3>Technical</h3>
                    </div>
                    <div class="aysa-recommendation-stats">
                        <div class="aysa-stat">
                            <span class="aysa-stat-label">Pending</span>
                            <span class="aysa-stat-value"><?php echo $monthly_recommendations['technical']['pending']; ?></span>
                        </div>
                        <div class="aysa-stat">
                            <span class="aysa-stat-label">Approved</span>
                            <span class="aysa-stat-value"><?php echo $monthly_recommendations['technical']['approved']; ?></span>
                        </div>
                    </div>
                    <button class="aysa-btn aysa-btn-outline">View Proposals</button>
                </div>
            </div>
        </div>
        END COMMENTED SECTION -->

        <!-- Overview Panel - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-overview-panel">
            <h2 class="aysa-section-title">Improvement Overview</h2>
            <div class="aysa-metrics-grid">
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-blue"><span class="dashicons dashicons-search"></span></span>
                        <span class="aysa-metric-trend positive">+8%</span>
                    </div>
                    <div class="aysa-metric-name">Keyword Performance</div>
                    <div class="aysa-metric-value">85%</div>
                </div>
                
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-green"><span class="dashicons dashicons-performance"></span></span>
                        <span class="aysa-metric-trend positive">+12%</span>
                    </div>
                    <div class="aysa-metric-name">Technical Score</div>
                    <div class="aysa-metric-value">92%</div>
                </div>
                
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-purple"><span class="dashicons dashicons-edit"></span></span>
                        <span class="aysa-metric-trend positive">+5%</span>
                    </div>
                    <div class="aysa-metric-name">Content Quality</div>
                    <div class="aysa-metric-value">88%</div>
                </div>
                
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-orange"><span class="dashicons dashicons-share"></span></span>
                        <span class="aysa-metric-trend positive">+15%</span>
                    </div>
                    <div class="aysa-metric-name">Off-Page Impact</div>
                    <div class="aysa-metric-value">78%</div>
                </div>
            </div>
        </div>
        END COMMENTED SECTION -->

        <!-- Keyword Reevaluation Section -->
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Keyword Re-evaluation</h2>
            <div class="aysa-info-box">
                <h3>Monthly Performance Analysis</h3>
                <p>Automated analysis and recommendations for keyword strategy optimization</p>
            </div>
            
            <!-- Keyword Performance Summary -->
            <div class="aysa-keyword-summary">
                <div class="aysa-summary-stat">
                    <span class="aysa-summary-value">32</span>
                    <span class="aysa-summary-label">Monitored Keywords</span>
                </div>
                <div class="aysa-summary-stat">
                    <span class="aysa-summary-value">8</span>
                    <span class="aysa-summary-label">Needs Attention</span>
                </div>
                <div class="aysa-summary-stat">
                    <span class="aysa-summary-value">5</span>
                    <span class="aysa-summary-label">New Proposals</span>
                </div>
                <div class="aysa-summary-stat">
                    <span class="aysa-summary-value">15</span>
                    <span class="aysa-summary-label">Good Performance</span>
                </div>
            </div>
            
            <!-- Keyword Recommendations with Tabs -->
            <div class="aysa-recommendations-section">
                <h3 class="aysa-subsection-title">Optimization Recommendations</h3>
                
                <!-- Tab Navigation -->
                <div class="aysa-tabs-nav">
                    <button class="aysa-tab-btn active" data-tab="domain-authority">
                        <span class="aysa-tab-icon">🎯</span>
                        Domain Authority Tasks
                    </button>
                    <button class="aysa-tab-btn" data-tab="associations">
                        <span class="aysa-tab-icon">🔗</span>
                        Association Tasks
                    </button>
                    <button class="aysa-tab-btn" data-tab="general">
                        <span class="aysa-tab-icon">📋</span>
                        General Tasks
                    </button>
                    <button class="aysa-tab-btn" data-tab="orders">
                        <span class="aysa-tab-icon">🛒</span>
                        Orders
                    </button>
                    <button class="aysa-tab-btn" data-tab="automated-seo">
                        <span class="aysa-tab-icon">🤖</span>
                        Automated SEO
                    </button>
                    <button class="aysa-tab-btn" data-tab="queue-management">
                        <span class="aysa-tab-icon">⚙️</span>
                        Queue Management
                    </button>
                    <button class="aysa-tab-btn" data-tab="automation">
                        <span class="aysa-tab-icon">🔧</span>
                        Settings
                    </button>
                    <button class="aysa-tab-btn" data-tab="banned-keywords">
                        <span class="aysa-tab-icon">🚫</span>
                        Deleted Keywords
                    </button>
                </div>
                
                <!-- Tab Content -->
                <div class="aysa-tabs-content">
                    <!-- Domain Authority Tasks Tab -->
                    <div class="aysa-tab-pane active" id="domain-authority-tab">
                        <div class="aysa-domain-authority-section">
                            <div class="aysa-section-header">
                                <div class="aysa-header-content">
                                    <div class="aysa-header-text">
                                        <h3>🎯 Domain Authority Improvement Tasks</h3>
                                        <p>Automated tasks based on competitor analysis to improve your domain authority through strategic link building.</p>
                                    </div>
                                    <div class="aysa-automation-toggle-container">
                                        <div class="aysa-toggle-wrapper">
                                            <label class="aysa-toggle-switch">
                                                <input type="checkbox" id="da-automation-toggle">
                                                <span class="aysa-toggle-slider"></span>
                                            </label>
                                            <div class="aysa-toggle-info">
                                                <span class="aysa-toggle-label">Automation</span>
                                                <span class="aysa-toggle-status" id="da-automation-status">Disabled</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Pending Reviews Section -->
                            <div class="aysa-pending-reviews-section" id="pending-reviews-group">
                                <div class="aysa-pending-reviews-header">
                                    <h4>
                                        <span class="aysa-task-group-icon">⚠️</span>
                                        Pending Reviews
                                        <span class="aysa-task-group-badge aysa-badge-review">Needs Approval</span>
                                    </h4>
                                    <p class="aysa-task-group-description">Automated tasks with low confidence scores requiring manual review before execution.</p>
                                    <button class="button button-primary" id="generate-real-review" style="margin-left: 15px; font-size: 12px;">Generate Task via Automation</button>
                                </div>
                                <div class="aysa-review-list" id="domain-authority-pending-reviews">
                                    <div class="aysa-loading-spinner">
                                        <span class="dashicons dashicons-update aysa-spinning"></span>
                                        <span>Loading pending reviews...</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="aysa-task-groups">
                                <!-- AI Generated Tasks -->
                                <div class="aysa-task-group">
                                    <div class="aysa-task-group-header">
                                        <h4>
                                            <span class="aysa-task-group-icon">🤖</span>
                                            AI Generated Tasks
                                            <span class="aysa-task-group-badge aysa-badge-auto">Automated</span>
                                        </h4>
                                    </div>
                                    <ul class="aysa-task-list" id="automated-domain-authority-tasks">
                                        <li class="aysa-loading-task">
                                            <div class="aysa-loading-spinner">
                                                <span class="dashicons dashicons-update aysa-spinning"></span>
                                                <span>Loading domain authority tasks...</span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                                
                                <!-- Manual Tasks -->
                                <div class="aysa-task-group">
                                    <div class="aysa-task-group-header">
                                        <h4>
                                            <span class="aysa-task-group-icon">👤</span>
                                            Manual Tasks
                                            <span class="aysa-task-group-badge aysa-badge-manual">Manual</span>
                                        </h4>
                                    </div>
                                    <ul class="aysa-task-list" id="manual-domain-authority-tasks">
                                        <li class="aysa-loading-task">
                                            <div class="aysa-loading-spinner">
                                                <span class="dashicons dashicons-update aysa-spinning"></span>
                                                <span>Loading manual tasks...</span>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Association Tasks Tab -->
                    <div class="aysa-tab-pane" id="associations-tab">
                        <?php include_once AYSA_PLUGIN_DIR . 'admin/partials/aysa-cron-status.php'; ?>
                        
                        <div class="aysa-table-responsive">
                            <table class="aysa-optimization-table">
                                <thead>
                                    <tr>
                                        <th>Action</th>
                                        <th>Current Keyword</th>
                                        <th>Proposal</th>
                                        <th>Reason</th>
                                        <th>Estimated Impact</th>
                                        <th>Approval</th>
                                    </tr>
                                </thead>
                                <tbody class="aysa-association-tasks">
                                    <tr class="aysa-loading-task">
                                        <td colspan="6" style="text-align: center; padding: 20px; color: #64748b; font-style: italic;">
                                            Loading association tasks...
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- General Tasks Tab -->
                    <div class="aysa-tab-pane" id="general-tab">
                        <div class="aysa-table-responsive">
                            <table class="aysa-optimization-table">
                                <thead>
                                    <tr>
                                        <th>Action</th>
                                        <th>Current Keyword</th>
                                        <th>Proposal</th>
                                        <th>Reason</th>
                                        <th>Estimated Impact</th>
                                        <th>Approval</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Keep existing static recommendations here -->
                                    <tr>
                                        <td><span class="aysa-action-tag replace">Replace</span></td>
                                        <td>
                                            <div class="aysa-keyword-details">
                                                <span class="aysa-keyword-text">seo wordpress</span>
                                                <span class="aysa-keyword-stats">Position: 12 | Vol: 1.2K</span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="aysa-keyword-details">
                                                <span class="aysa-keyword-text">wordpress seo plugin</span>
                                                <span class="aysa-keyword-stats">Vol: 2.5K | Competition: Medium</span>
                                            </div>
                                        </td>
                                        <td>Low conversion, downward trend</td>
                                        <td><span class="aysa-impact high">+45% traffic</span></td>
                                        <td>
                                            <div class="aysa-approval-buttons">
                                                <button class="aysa-btn aysa-btn-success">Approve</button>
                                                <button class="aysa-btn aysa-btn-danger">Reject</button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><span class="aysa-action-tag add">Add</span></td>
                                        <td>-</td>
                                        <td>
                                            <div class="aysa-keyword-details">
                                                <span class="aysa-keyword-text">ai seo optimization</span>
                                                <span class="aysa-keyword-stats">Vol: 800 | Trend: +125%</span>
                                            </div>
                                        </td>
                                        <td>Trending keyword, low competition</td>
                                        <td><span class="aysa-impact medium">+25% traffic</span></td>
                                        <td>
                                            <div class="aysa-approval-buttons">
                                                <button class="aysa-btn aysa-btn-success">Approve</button>
                                                <button class="aysa-btn aysa-btn-danger">Reject</button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- Orders Tab -->
                    <div class="aysa-tab-pane" id="orders-tab">
                        <div class="aysa-orders-section">
                            <div class="aysa-orders-header">
                                <h3>
                                    <span class="aysa-orders-icon">🛒</span>
                                    Link Purchase Orders
                                </h3>
                                <p class="aysa-orders-description">Track the status of your domain authority link purchases</p>
                </div>
                            
                            <div class="aysa-orders-filters">
                                <select id="aysa-orders-status-filter" class="aysa-select">
                                    <option value="all">All Orders</option>
                                    <option value="pending">Pending</option>
                                    <option value="processing">Processing</option>
                                    <option value="completed">Completed</option>
                                    <option value="error">Error</option>
                                </select>
                                <button class="aysa-btn aysa-btn-primary" id="aysa-refresh-orders">
                                    <span class="dashicons dashicons-update"></span> Refresh
                                </button>
                            </div>
                            
                            <div class="aysa-orders-table-container">
                                <table class="aysa-orders-table">
                                    <thead>
                                        <tr>
                                            <th>Order ID</th>
                                            <th>Task</th>
                                            <th>Links Requested</th>
                                            <th>Links Purchased</th>
                                            <th>Progress</th>
                                            <th>Status</th>
                                            <th>Created</th>
                                            <th>Last Update</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="aysa-orders-list">
                                        <tr class="aysa-loading-row">
                                            <td colspan="9" style="text-align: center; padding: 40px;">
                                                <span class="dashicons dashicons-update aysa-spinning"></span>
                                                Loading orders...
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="aysa-orders-empty" id="aysa-orders-empty" style="display: none;">
                                <div class="aysa-empty-state">
                                    <span class="aysa-empty-icon">📦</span>
                                    <h4>No Orders Found</h4>
                                    <p>You haven't placed any link purchase orders yet. Complete domain authority tasks to create orders.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Order Details Modal -->
                    <div id="aysa-order-details-modal" class="aysa-modal" style="display: none;">
                        <div class="aysa-modal-overlay"></div>
                        <div class="aysa-modal-content">
                            <div class="aysa-modal-header">
                                <h3 id="aysa-order-modal-title">Order Details</h3>
                                <button class="aysa-modal-close" onclick="window.closeOrderDetailsModal()">×</button>
                            </div>
                            <div class="aysa-modal-body" id="aysa-order-modal-body">
                                <!-- Order details will be loaded here -->
                            </div>
                            <div class="aysa-modal-footer">
                                <button class="aysa-btn aysa-btn-secondary" onclick="window.closeOrderDetailsModal()">Close</button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Automated SEO Tab -->
                    <div class="aysa-tab-pane" id="automated-seo-tab">
                        <div class="aysa-review-tabs">
                            <button class="review-tab active" data-tab="automated-seo">Automated SEO</button>
                        </div>
                        
                        <div class="review-content" id="automated-seo-reviews">
                            <div class="review-list" id="automated-seo-review-list">
                                <p>Loading pending automated SEO reviews...</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Queue Management Tab -->
                    <div class="aysa-tab-pane" id="queue-management-tab">
                        <div class="aysa-queue-section">
                            <div class="aysa-queue-header">
                                <h3>
                                    <span class="aysa-queue-icon">⚙️</span>
                                    Queue Management
                                </h3>
                                <p class="aysa-queue-description">Monitor and control the automation processing queue</p>
                            </div>
                            
                            <!-- Queue Statistics -->
                            <div class="aysa-queue-stats-container">
                                <h4>Queue Statistics (Last 24 Hours)</h4>
                                <div class="aysa-stats-grid">
                                    <div class="aysa-stat-card">
                                        <div class="aysa-stat-number" id="total-queue-jobs">--</div>
                                        <div class="aysa-stat-label">Total Jobs</div>
                                    </div>
                                    <div class="aysa-stat-card">
                                        <div class="aysa-stat-number" id="pending-queue-jobs">--</div>
                                        <div class="aysa-stat-label">Pending</div>
                                    </div>
                                    <div class="aysa-stat-card">
                                        <div class="aysa-stat-number" id="completed-queue-jobs">--</div>
                                        <div class="aysa-stat-label">Completed</div>
                                    </div>
                                    <div class="aysa-stat-card">
                                        <div class="aysa-stat-number" id="failed-queue-jobs">--</div>
                                        <div class="aysa-stat-label">Failed</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Queue Actions -->
                            <div class="aysa-queue-actions">
                                <button class="aysa-btn aysa-btn-primary" id="process-queue-now">
                                    <span class="dashicons dashicons-controls-play"></span>
                                    Process Queue Now
                                </button>
                                <button class="aysa-btn aysa-btn-secondary" id="refresh-queue-stats">
                                    <span class="dashicons dashicons-update"></span>
                                    Refresh Statistics
                                </button>
                            </div>
                            
                            <!-- Queue Status -->
                            <div class="aysa-queue-status" id="queue-status-info">
                                <div class="aysa-loading-spinner">
                                    <span class="dashicons dashicons-update aysa-spinning"></span>
                                    <span>Loading queue status...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Automation Settings Tab -->
                    <div class="aysa-tab-pane" id="automation-tab">
                        <div class="aysa-settings-section">
                            <div class="aysa-settings-header">
                                <h3>
                                    <span class="aysa-settings-icon">🔧</span>
                                    Automation Settings
                                </h3>
                                <p class="aysa-settings-description">Configure automation features and preferences</p>
                            </div>
                            
                            <div class="aysa-automation-cards">
                                <div class="aysa-automation-card">
                                    <div class="aysa-card-header">
                                        <h4>
                                            <span class="aysa-feature-icon">🎯</span>
                                            Domain Authority Tasks
                                        </h4>
                                        <div class="aysa-toggle-container">
                                            <label class="aysa-toggle-switch">
                                                <input type="checkbox" id="settings-domain-authority-toggle">
                                                <span class="aysa-toggle-slider"></span>
                                            </label>
                                            <span class="aysa-toggle-status" id="settings-domain-authority-status">Disabled</span>
                                        </div>
                                    </div>
                                    <div class="aysa-card-body">
                                        <p>Automatically analyze competitor domain authority and generate link building tasks.</p>
                                        <div class="aysa-automation-stats">
                                            <div class="aysa-stat-item">
                                                <span class="aysa-stat-label">Tasks Generated:</span>
                                                <span class="aysa-stat-value" id="settings-da-tasks-generated">--</span>
                                            </div>
                                            <div class="aysa-stat-item">
                                                <span class="aysa-stat-label">Acceptance Rate:</span>
                                                <span class="aysa-stat-value" id="settings-da-acceptance-rate">--</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Placeholder for future automation features -->
                                <div class="aysa-automation-card aysa-card-disabled">
                                    <div class="aysa-card-header">
                                        <h4>
                                            <span class="aysa-feature-icon">🔗</span>
                                            Keyword Association
                                        </h4>
                                        <div class="aysa-toggle-container">
                                            <label class="aysa-toggle-switch">
                                                <input type="checkbox" disabled>
                                                <span class="aysa-toggle-slider"></span>
                                            </label>
                                            <span class="aysa-toggle-status">Coming Soon</span>
                                        </div>
                                    </div>
                                    <div class="aysa-card-body">
                                        <p>Automatically associate keywords with relevant pages and products.</p>
                                    </div>
                                </div>
                                
                                <div class="aysa-automation-card aysa-card-disabled">
                                    <div class="aysa-card-header">
                                        <h4>
                                            <span class="aysa-feature-icon">📄</span>
                                            Content Optimization
                                        </h4>
                                        <div class="aysa-toggle-container">
                                            <label class="aysa-toggle-switch">
                                                <input type="checkbox" disabled>
                                                <span class="aysa-toggle-slider"></span>
                                            </label>
                                            <span class="aysa-toggle-status">Coming Soon</span>
                                        </div>
                                    </div>
                                    <div class="aysa-card-body">
                                        <p>Automatically optimize meta descriptions, titles, and content structure.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Banned Keywords Tab -->
                    <div class="aysa-tab-pane" id="banned-keywords-tab">
                        <div class="aysa-banned-keywords-section">
                            <div class="aysa-section-header">
                                <h3>
                                    <span class="aysa-tab-icon">🚫</span>
                                    Deleted Keywords
                                </h3>
                                <p class="aysa-section-description">Manage keywords that are deleted from keyword discovery and suggestions</p>
                </div>
                            
                            <div class="aysa-banned-keywords-controls">
                                <div class="aysa-controls-left">
                                    <button id="aysa-refresh-banned-keywords" class="aysa-btn aysa-btn-secondary">
                                        <span class="dashicons dashicons-update"></span>
                                        Refresh
                                    </button>
                                </div>
                                <div class="aysa-controls-right">
                                    <div class="aysa-search-box">
                                        <input type="text" id="aysa-banned-keywords-search" placeholder="Search deleted keywords..." />
                                        <span class="dashicons dashicons-search"></span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="aysa-banned-keywords-content">
                                <div class="aysa-table-responsive">
                                    <table class="aysa-banned-keywords-table">
                                        <thead>
                                            <tr>
                                                <th class="aysa-keyword-col">Keyword</th>
                                                <th class="aysa-banned-by-col">Banned By</th>
                                                <th class="aysa-banned-date-col">Date Banned</th>
                                                <th class="aysa-banned-reason-col">Reason</th>
                                                <th class="aysa-banned-actions-col">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="aysa-banned-keywords-tbody">
                                            <tr class="aysa-loading-row">
                                                <td colspan="5" class="aysa-loading-cell">
                                                    <div class="aysa-loading-container">
                                                        <span class="dashicons dashicons-update aysa-spinning"></span>
                                                        <span class="aysa-loading-text">Loading deleted keywords...</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                
                                <div class="aysa-banned-keywords-pagination">
                                    <div class="aysa-pagination-info">
                                        <span id="aysa-banned-keywords-count">0 deleted keywords</span>
                                    </div>
                                    <div class="aysa-pagination-controls">
                                        <button id="aysa-banned-prev-btn" class="aysa-pagination-btn" disabled>
                                            <span class="dashicons dashicons-arrow-left-alt2"></span>
                                            Previous
                                        </button>
                                        <div class="aysa-page-numbers" id="aysa-banned-page-numbers">
                                            <span class="aysa-page-number active">1</span>
                                        </div>
                                        <button id="aysa-banned-next-btn" class="aysa-pagination-btn" disabled>
                                            Next
                                            <span class="dashicons dashicons-arrow-right-alt2"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Technical Strategy Section - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Technical Strategy Adjustment</h2>
            <div class="aysa-info-box">
                <h3>Technical Monitoring and Optimization</h3>
                <p>Automated technical performance analysis and task generation for improvement</p>
            </div>
            
            <div class="aysa-tech-summary">
                <div class="aysa-tech-metric">
                    <div class="aysa-tech-header">
                        <span class="aysa-metric-icon aysa-red"><span class="dashicons dashicons-warning"></span></span>
                        <h4>Indexing Errors</h4>
                    </div>
                    <div class="aysa-tech-value">5</div>
                    <div class="aysa-tech-trend negative">+2 compared to last month</div>
                </div>
                
                <div class="aysa-tech-metric">
                    <div class="aysa-tech-header">
                        <span class="aysa-metric-icon aysa-orange"><span class="dashicons dashicons-performance"></span></span>
                        <h4>CWV Issues</h4>
                    </div>
                    <div class="aysa-tech-value">3</div>
                    <div class="aysa-tech-trend neutral">Unchanged</div>
                </div>
                
                <div class="aysa-tech-metric">
                    <div class="aysa-tech-header">
                        <span class="aysa-metric-icon aysa-purple"><span class="dashicons dashicons-admin-links"></span></span>
                        <h4>404 Links</h4>
                    </div>
                    <div class="aysa-tech-value">8</div>
                    <div class="aysa-tech-trend negative">+3 compared to last month</div>
                </div>
                
                <div class="aysa-tech-metric">
                    <div class="aysa-tech-header">
                        <span class="aysa-metric-icon aysa-blue"><span class="dashicons dashicons-update"></span></span>
                        <h4>Google Updates</h4>
                    </div>
                    <div class="aysa-tech-value">2</div>
                    <div class="aysa-tech-trend">New updates</div>
                </div>
            </div>
            
            <div class="aysa-tech-tasks">
                <h3 class="aysa-subsection-title">Generated Technical Tasks</h3>
                <div class="aysa-task-list">
                    <div class="aysa-task-item high-priority">
                        <div class="aysa-task-header">
                            <span class="aysa-priority-badge high">High Priority</span>
                            <span class="aysa-task-type">Core Web Vitals</span>
                        </div>
                        <h4 class="aysa-task-title">LCP Optimization on Main Page</h4>
                        <p class="aysa-task-description">Main element load time exceeds the recommended 2.5s threshold</p>
                        <div class="aysa-task-meta">
                            <span class="aysa-task-impact">Impact: +15 Performance points</span>
                            <span class="aysa-task-effort">Effort: Medium</span>
                        </div>
                        <div class="aysa-task-actions">
                            <button class="aysa-btn aysa-btn-primary">Start Optimization</button>
                            <button class="aysa-btn aysa-btn-secondary">View Details</button>
                        </div>
                    </div>
                    
                    <div class="aysa-task-item medium-priority">
                        <div class="aysa-task-header">
                            <span class="aysa-priority-badge medium">Medium Priority</span>
                            <span class="aysa-task-type">Indexing</span>
                        </div>
                        <h4 class="aysa-task-title">Update sitemap.xml</h4>
                        <p class="aysa-task-description">3 new pages are not included in sitemap. Update needed for optimal indexing.</p>
                        <div class="aysa-task-meta">
                            <span class="aysa-task-impact">Impact: Indexing Improvement</span>
                            <span class="aysa-task-effort">Effort: Low</span>
                        </div>
                        <div class="aysa-task-actions">
                            <button class="aysa-btn aysa-btn-primary">Update Sitemap</button>
                            <button class="aysa-btn aysa-btn-secondary">View Details</button>
                        </div>
                    </div>
                    
                    <div class="aysa-task-item low-priority">
                        <div class="aysa-task-header">
                            <span class="aysa-priority-badge low">Low Priority</span>
                            <span class="aysa-task-type">Links</span>
                        </div>
                        <h4 class="aysa-task-title">404 Link Redirection</h4>
                        <p class="aysa-task-description">8 404 links detected. Implementation of 301 redirects is recommended.</p>
                        <div class="aysa-task-meta">
                            <span class="aysa-task-impact">Impact: UX Improvement</span>
                            <span class="aysa-task-effort">Effort: Medium</span>
                        </div>
                        <div class="aysa-task-actions">
                            <button class="aysa-btn aysa-btn-primary">Configure Redirects</button>
                            <button class="aysa-btn aysa-btn-secondary">View Details</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        END COMMENTED SECTION -->

        <!-- Content Improvement Section - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Constant Content Improvement</h2>
            <div class="aysa-info-box">
                <h3>Content Analysis and Optimization</h3>
                <p>Monthly qualitative evaluation through semantic NLP scoring and user behavior analysis</p>
            </div>
            
            <div class="aysa-content-analysis">
                <div class="aysa-analysis-header">
                    <h3 class="aysa-subsection-title">Qualitative Analysis</h3>
                    <div class="aysa-analysis-filters">
                        <select class="aysa-select">
                            <option>Last month</option>
                            <option>Last 3 months</option>
                            <option>Last 6 months</option>
                        </select>
                    </div>
                </div>
                
                <div class="aysa-analysis-grid">
                    <div class="aysa-analysis-card">
                        <div class="aysa-analysis-score">
                            <svg viewBox="0 0 36 36" class="aysa-circular-chart">
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#eee"
                                    stroke-width="3"/>
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#34a853"
                                    stroke-width="3"
                                    stroke-dasharray="75, 100"/>
                                <text x="18" y="20.35" class="percentage">75%</text>
                            </svg>
                            <span class="aysa-score-label">NLP Score</span>
                        </div>
                        <div class="aysa-analysis-details">
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Clarity</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 85%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Relevance</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 70%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Originality</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 90%"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-analysis-card">
                        <div class="aysa-analysis-score">
                            <svg viewBox="0 0 36 36" class="aysa-circular-chart">
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#eee"
                                    stroke-width="3"/>
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#1a73e8"
                                    stroke-width="3"
                                    stroke-dasharray="65, 100"/>
                                <text x="18" y="20.35" class="percentage">65%</text>
                            </svg>
                            <span class="aysa-score-label">User Engagement</span>
                        </div>
                        <div class="aysa-analysis-details">
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Time on page</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 75%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Bounce rate</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 60%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Scroll depth</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 80%"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-analysis-card">
                        <div class="aysa-analysis-score">
                            <svg viewBox="0 0 36 36" class="aysa-circular-chart">
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#eee"
                                    stroke-width="3"/>
                                <path d="M18 2.0845
                                    a 15.9155 15.9155 0 0 1 0 31.831
                                    a 15.9155 15.9155 0 0 1 0 -31.831"
                                    fill="none"
                                    stroke="#e37400"
                                    stroke-width="3"
                                    stroke-dasharray="82, 100"/>
                                <text x="18" y="20.35" class="percentage">82%</text>
                            </svg>
                            <span class="aysa-score-label">Competitiveness</span>
                        </div>
                        <div class="aysa-analysis-details">
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Topic coverage</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 85%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Content length</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 90%"></div>
                                </div>
                            </div>
                            <div class="aysa-detail-item">
                                <span class="aysa-detail-label">Industry average</span>
                                <div class="aysa-progress-bar">
                                    <div class="aysa-progress" style="width: 70%"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="aysa-content-recommendations">
                <h3 class="aysa-subsection-title">AI Recommendations for Improvement</h3>
                <div class="aysa-recommendations-list">
                    <div class="aysa-recommendation-item">
                        <div class="aysa-recommendation-header">
                            <span class="aysa-recommendation-type">Paragraph Replacement</span>
                            <span class="aysa-page-url">/blog/seo-best-practices</span>
                        </div>
                        <div class="aysa-recommendation-content">
                            <div class="aysa-content-comparison">
                                <div class="aysa-current-content">
                                    <h4>Current Content</h4>
                                    <p>SEO is important for your website. Use keywords and optimize your content.</p>
                                </div>
                                <div class="aysa-suggested-content">
                                    <h4>AI Suggestion</h4>
                                    <p>Search engine optimization (SEO) is fundamental to your business's digital success. Implement a strategy based on keyword research and create valuable content that responds to user needs.</p>
                                </div>
                            </div>
                            <div class="aysa-recommendation-actions">
                                <button class="aysa-btn aysa-btn-success">Apply Change</button>
                                <button class="aysa-btn aysa-btn-secondary">Edit Manually</button>
                                <button class="aysa-btn aysa-btn-text">Ignore</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="aysa-recommendation-item">
                        <div class="aysa-recommendation-header">
                            <span class="aysa-recommendation-type">Content Extension</span>
                            <span class="aysa-page-url">/services/web-development</span>
                        </div>
                        <div class="aysa-recommendation-content">
                            <p class="aysa-recommendation-description">
                                The page has potential for extension. We suggest adding a section about modern web development technologies and their SEO benefits.
                            </p>
                            <div class="aysa-recommendation-actions">
                                <button class="aysa-btn aysa-btn-primary">Generate Content</button>
                                <button class="aysa-btn aysa-btn-secondary">View Suggestions</button>
                                <button class="aysa-btn aysa-btn-text">Ignore</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        END COMMENTED SECTION -->

        <!-- Off-Page Tactics Section - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Off-Page Strategy</h2>
            <div class="aysa-info-box">
                <h3>Link Building & Social Signals</h3>
                <p>Optimize your off-page SEO tactics</p>
            </div>
            
            <div class="aysa-metrics-grid">
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-blue"><span class="dashicons dashicons-admin-links"></span></span>
                    </div>
                    <div class="aysa-metric-name">Backlinks</div>
                    <div class="aysa-metric-value">245</div>
                </div>
                
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-green"><span class="dashicons dashicons-share"></span></span>
                    </div>
                    <div class="aysa-metric-name">Social Shares</div>
                    <div class="aysa-metric-value">1,234</div>
                </div>
                
                <div class="aysa-metric-card">
                    <div class="aysa-metric-header">
                        <span class="aysa-metric-icon aysa-purple"><span class="dashicons dashicons-groups"></span></span>
                    </div>
                    <div class="aysa-metric-name">Brand Mentions</div>
                    <div class="aysa-metric-value">567</div>
                </div>
            </div>
        </div>
        END COMMENTED SECTION -->

        <!-- Conversion Optimization Section - COMMENTED OUT (DUMMY DATA)
        <div class="aysa-panel">
            <h2 class="aysa-section-title">Conversion Rate Optimization</h2>
            <div class="aysa-info-box">
                <h3>Conversion Analysis</h3>
                <p>Improve your website's conversion rate</p>
            </div>
            
            <div class="aysa-funnel">
                <div class="aysa-funnel-step">
                    <div class="aysa-funnel-label">Visitors</div>
                    <div class="aysa-funnel-value">15,234</div>
                    <div class="aysa-funnel-arrow"></div>
                </div>
                <div class="aysa-funnel-step">
                    <div class="aysa-funnel-label">Engaged Users</div>
                    <div class="aysa-funnel-value">9,876</div>
                    <div class="aysa-funnel-arrow"></div>
                </div>
                <div class="aysa-funnel-step">
                    <div class="aysa-funnel-label">Leads</div>
                    <div class="aysa-funnel-value">487</div>
                    <div class="aysa-funnel-arrow"></div>
                </div>
                <div class="aysa-funnel-step">
                    <div class="aysa-funnel-label">Customers</div>
                    <div class="aysa-funnel-value">156</div>
                </div>
            </div>
            
            <div class="aysa-table-responsive">
                <table class="aysa-optimization-table">
                    <thead>
                        <tr>
                            <th>Page</th>
                            <th>Conversion Rate</th>
                            <th>Bounce Rate</th>
                            <th>Avg. Time</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Landing Page</td>
                            <td>3.2%</td>
                            <td>35%</td>
                            <td>2m 45s</td>
                            <td>
                                <button class="aysa-btn aysa-btn-primary">Optimize</button>
                                <button class="aysa-btn aysa-btn-secondary">Details</button>
                            </td>
                        </tr>
                        <tr>
                            <td>Product Page</td>
                            <td>4.5%</td>
                            <td>28%</td>
                            <td>3m 15s</td>
                            <td>
                                <button class="aysa-btn aysa-btn-primary">Optimize</button>
                                <button class="aysa-btn aysa-btn-secondary">Details</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        END COMMENTED SECTION -->

    </div>
</div>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

.aysa-info-box p {
    margin: 0;
    color: #5f6368;
    font-size: 13px;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

.aysa-competition.high {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-competition.medium {
    background-color: #fef7e0;
    color: #e37400;
}

.aysa-competition.low {
    background-color: #e6f4ea;
    color: #34a853;
}

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

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

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

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

/* Funnel Styles */
.aysa-funnel {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

.aysa-funnel-step {
    text-align: center;
    flex: 1;
    position: relative;
}

.aysa-funnel-step:not(:last-child)::after {
    content: '';
    position: absolute;
    top: 50%;
    right: -15px;
    width: 30px;
    height: 2px;
    background-color: #e0e0e0;
    transform: translateY(-50%);
}

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

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

/* Responsive Adjustments */
@media screen and (max-width: 1024px) {
    .aysa-metrics-grid {
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
    
    .aysa-funnel {
        flex-direction: column;
        gap: 20px;
    }
    
    .aysa-funnel-step:not(:last-child)::after {
        display: none;
    }
}

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

/* Add new styles for recommendations panel */
.aysa-recommendations-panel {
    margin-bottom: 30px;
}

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

.aysa-recommendations-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
}

.aysa-recommendation-card {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-recommendation-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

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

.aysa-recommendation-stats {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
}

.aysa-stat {
    text-align: center;
}

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

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

.aysa-btn-outline {
    width: 100%;
    background: none;
    border: 1px solid #1a73e8;
    color: #1a73e8;
}

.aysa-btn-outline:hover {
    background-color: #f8f9fa;
}

/* Keyword Summary Styles */
.aysa-keyword-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e0e0e0;
}

.aysa-summary-stat {
    text-align: center;
}

.aysa-summary-value {
    display: block;
    font-size: 28px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 5px;
}

.aysa-summary-label {
    font-size: 14px;
    color: #5f6368;
}

/* Action Tags */
.aysa-action-tag {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-action-tag.replace {
    background-color: #e8f0fe;
    color: #1a73e8;
}

.aysa-action-tag.add {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-action-tag.remove {
    background-color: #fce8e6;
    color: #ea4335;
}

/* Keyword Details */
.aysa-keyword-details {
    display: flex;
    flex-direction: column;
}

.aysa-keyword-text {
    font-weight: 500;
    margin-bottom: 4px;
}

.aysa-keyword-stats {
    font-size: 12px;
    color: #5f6368;
}

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

.aysa-impact.high {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-impact.medium {
    background-color: #fef7e0;
    color: #e37400;
}

.aysa-impact.low {
    background-color: #e8f0fe;
    color: #1a73e8;
}

/* Approval Buttons */
.aysa-approval-buttons {
    display: flex;
    gap: 8px;
}

.aysa-btn-success {
    background-color: #34a853;
    color: white;
}

.aysa-btn-danger {
    background-color: #ea4335;
    color: white;
}

/* Subsection Title */
.aysa-subsection-title {
    font-size: 16px;
    font-weight: 500;
    color: #202124;
    margin: 0 0 15px;
}

/* Technical Summary Styles */
.aysa-tech-summary {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.aysa-tech-metric {
    background: white;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e0e0e0;
}

.aysa-tech-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.aysa-tech-header h4 {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
    color: #202124;
}

.aysa-tech-value {
    font-size: 28px;
    font-weight: 500;
    color: #202124;
    margin-bottom: 5px;
}

.aysa-tech-trend {
    font-size: 12px;
    color: #5f6368;
}

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

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

/* Task List Styles */
.aysa-task-list {
    display: grid;
    gap: 20px;
}

.aysa-task-item {
    background: white;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #e0e0e0;
}

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

.aysa-priority-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 500;
}

.aysa-priority-badge.high {
    background-color: #fce8e6;
    color: #ea4335;
}

.aysa-priority-badge.medium {
    background-color: #fef7e0;
    color: #e37400;
}

.aysa-priority-badge.low {
    background-color: #e6f4ea;
    color: #34a853;
}

.aysa-task-type {
    font-size: 12px;
    color: #5f6368;
}

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

.aysa-task-description {
    margin: 0 0 15px;
    font-size: 14px;
    color: #5f6368;
}

.aysa-task-meta {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
    font-size: 12px;
    color: #5f6368;
}

.aysa-task-actions {
    display: flex;
    gap: 10px;
}

/* Task Priority Colors */
.aysa-task-item.high-priority {
    border-left: 4px solid #ea4335;
}

.aysa-task-item.medium-priority {
    border-left: 4px solid #e37400;
}

.aysa-task-item.low-priority {
    border-left: 4px solid #34a853;
}

/* Content Analysis Styles */
.aysa-content-analysis {
    margin-bottom: 30px;
}

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

.aysa-analysis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.aysa-analysis-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #e0e0e0;
}

.aysa-analysis-score {
    text-align: center;
    margin-bottom: 20px;
}

.aysa-circular-chart {
    width: 100px;
    height: 100px;
}

.aysa-circular-chart text {
    fill: #202124;
    font-size: 8px;
    text-anchor: middle;
}

.aysa-score-label {
    display: block;
    margin-top: 10px;
    font-size: 14px;
    color: #5f6368;
}

.aysa-analysis-details {
    display: grid;
    gap: 15px;
}

.aysa-detail-item {
    display: grid;
    gap: 5px;
}

.aysa-detail-label {
    font-size: 12px;
    color: #5f6368;
}

.aysa-progress-bar {
    height: 4px;
    background-color: #f1f3f4;
    border-radius: 2px;
    overflow: hidden;
}

.aysa-progress {
    height: 100%;
    background-color: #1a73e8;
    border-radius: 2px;
}

/* Content Recommendations Styles */
.aysa-content-recommendations {
    margin-top: 30px;
}

.aysa-recommendations-list {
    display: grid;
    gap: 20px;
}

.aysa-recommendation-item {
    background: white;
    border-radius: 8px;
    padding: 20px;
    border: 1px solid #e0e0e0;
}

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

.aysa-recommendation-type {
    font-weight: 500;
    color: #202124;
}

.aysa-page-url {
    font-size: 12px;
    color: #5f6368;
}

.aysa-content-comparison {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.aysa-current-content,
.aysa-suggested-content {
    padding: 15px;
    background: white;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
}

.aysa-current-content h4,
.aysa-suggested-content h4 {
    margin: 0 0 10px;
    font-size: 14px;
    font-weight: 500;
    color: #202124;
}

.aysa-current-content p,
.aysa-suggested-content p {
    margin: 0;
    font-size: 14px;
    color: #5f6368;
}

.aysa-recommendation-actions {
    display: flex;
    gap: 10px;
}

/* Select Styles */
.aysa-select {
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    background-color: white;
    color: #202124;
    font-size: 14px;
}

/* Responsive Adjustments */
@media screen and (max-width: 768px) {
    .aysa-content-comparison {
        grid-template-columns: 1fr;
    }
    
    .aysa-recommendation-actions {
        flex-wrap: wrap;
    }
    

}

/* Domain Authority Task Styles */
.aysa-domain-authority-section {
    padding: 20px 0;
}

.aysa-section-header {
    text-align: center;
    margin-bottom: 30px;
}

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

.aysa-section-header p {
    color: #5f6368;
    font-size: 16px;
    max-width: 600px;
    margin: 0 auto;
}

.aysa-task-groups {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 30px;
    margin-top: 30px;
}

.aysa-task-group {
    background: #fff;
    border: 1px solid #e8eaed;
    border-radius: 8px;
    overflow: hidden;
}

.aysa-task-group-header {
    background: linear-gradient(135deg, #f8f9ff 0%, #f1f3ff 100%);
    padding: 20px;
    border-bottom: 1px solid #e8eaed;
}

.aysa-task-group-header h4 {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 18px;
    color: #1a73e8;
}

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

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

.aysa-badge-auto {
    background: #e3f2fd;
    color: #1976d2;
    border: 1px solid #bbdefb;
}

.aysa-badge-manual {
    background: #fff3e0;
    color: #f57c00;
    border: 1px solid #ffcc02;
}

.aysa-badge-review {
    background: #ffebee;
    color: #d32f2f;
    border: 1px solid #ffcdd2;
}

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

.aysa-task-item {
    border-bottom: 1px solid #f1f3f4;
    transition: background-color 0.2s ease;
}

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

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

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

.aysa-task-checkbox {
    width: 18px;
    height: 18px;
    margin: 0;
}

.aysa-task-label {
    flex: 1;
    font-size: 14px;
    color: #202124;
    font-weight: 500;
}

.aysa-task-label.completed {
    text-decoration: line-through;
    color: #5f6368;
}

.aysa-task-progress-inline {
        width: 60px;
    height: 6px;
    background: #f1f3f4;
    border-radius: 3px;
    overflow: hidden;
}

.aysa-inline-progress-bar {
    height: 100%;
    transition: width 0.3s ease;
    border-radius: 3px;
}

.aysa-progress-text {
    font-size: 12px;
    color: #5f6368;
    min-width: 80px;
    text-align: right;
}

.aysa-task-actions {
    display: flex;
    gap: 8px;
}

.aysa-task-action-btn {
    padding: 6px 12px;
    font-size: 12px;
    border: 1px solid #dadce0;
    background: #fff;
    color: #1a73e8;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-task-action-btn:hover {
    background: #f1f3f4;
    border-color: #5f6368;
}

.aysa-delete-btn {
    background: none;
    border: none;
    color: #94a3b8;
    font-size: 16px;
    cursor: pointer;
    padding: 4px 6px;
    border-radius: 4px;
    transition: all 0.2s ease;
    flex-shrink: 0;
}

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

.aysa-no-tasks, .aysa-error-task {
    padding: 40px 20px;
    text-align: center;
    color: #5f6368;
    font-style: italic;
}

.aysa-error-task {
    color: #ea4335;
}

.aysa-loading-spinner {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 20px;
    color: #5f6368;
}

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

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

/* Review List Styles */
.aysa-review-list {
    padding: 0 20px 20px;
}

.aysa-review-item {
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-review-item h4 {
    margin: 0 0 10px 0;
    color: #202124;
    font-size: 16px;
    font-weight: 600;
}

.aysa-review-item p {
    margin: 8px 0;
    color: #5f6368;
    line-height: 1.5;
}

.aysa-review-item p strong {
    color: #202124;
}

.aysa-review-actions {
    display: flex;
    gap: 10px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #e8eaed;
}

.aysa-review-actions .button {
    min-width: 80px;
    text-align: center;
}

/* Action buttons like keyword discovery */
.aysa-action-btn {
    border: none;
    border-radius: 4px;
    padding: 6px 10px;
    font-size: 12px;
    cursor: pointer;
    color: white;
    width: 80px;
    text-align: center;
    background-color: #4285f4;
    transition: background-color 0.2s ease;
    position: relative;
    overflow: hidden;
}

.aysa-action-btn:hover {
    background-color: #1565c0;
}

/* Approve button - Green */
.approve-domain-authority.aysa-action-btn {
    background-color: #4caf50;
    margin-right: 8px;
}

.approve-domain-authority.aysa-action-btn:hover:not(:disabled) {
    background-color: #2e7d32;
}

.approve-domain-authority.aysa-action-btn:disabled {
    background-color: #9e9e9e;
    cursor: not-allowed;
}

/* Reject button - Red */
.reject-domain-authority.aysa-action-btn {
    background-color: #f44336;
}

.reject-domain-authority.aysa-action-btn:hover:not(:disabled) {
    background-color: #c62828;
}

.reject-domain-authority.aysa-action-btn:disabled {
    background-color: #9e9e9e;
    cursor: not-allowed;
}

/* Loading spinner for buttons */
.aysa-action-btn.button-loading {
    position: relative;
}

.aysa-action-btn.button-loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 12px;
    height: 12px;
    margin: -6px 0 0 -6px;
    border: 2px solid transparent;
    border-top: 2px solid white;
    border-radius: 50%;
    animation: button-spin 1s linear infinite;
}

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

/* Fade out animation for review items */
.review-item-removing {
    opacity: 0 !important;
    transform: translateX(-20px) scale(0.95) !important;
    max-height: 0 !important;
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    transition: all 0.3s ease !important;
    pointer-events: none !important;
    overflow: hidden !important;
}

/* Notification styles */
.aysa-notification {
    position: fixed;
    top: 32px;
    right: 20px;
    background: white;
    border-left: 4px solid #0073aa;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    padding: 12px 16px;
    border-radius: 4px;
    z-index: 9999;
    display: flex;
    align-items: center;
    gap: 8px;
        font-size: 14px;
    max-width: 350px;
    animation: slideInRight 0.3s ease;
}

.aysa-notification-success {
    border-left-color: #4caf50;
}

.aysa-notification-error {
    border-left-color: #f44336;
}

.aysa-notification-info {
    border-left-color: #2196f3;
}

.aysa-notification.fade-out {
    animation: slideOutRight 0.6s ease;
}

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

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

/* Orders Tab Styles */
.aysa-orders-section {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.aysa-orders-header {
    margin-bottom: 25px;
    border-bottom: 1px solid #f1f3f4;
    padding-bottom: 20px;
}

.aysa-orders-header h3 {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.aysa-orders-icon {
    font-size: 24px;
}

.aysa-orders-description {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-orders-filters {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 25px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.aysa-select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 14px;
    min-width: 150px;
}

.aysa-orders-table-container {
    overflow-x: auto;
    border: 1px solid #e1e5e9;
    border-radius: 8px;
}

.aysa-orders-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
}

.aysa-orders-table th {
    background: #f8f9fa;
    padding: 12px 16px;
    text-align: left;
    font-weight: 600;
    color: #333;
    border-bottom: 2px solid #e1e5e9;
    font-size: 13px;
}

.aysa-orders-table td {
    padding: 12px 16px;
    border-bottom: 1px solid #f1f3f4;
    font-size: 13px;
    vertical-align: middle;
}

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

.aysa-order-status {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.aysa-order-status.pending {
    background: #fff3cd;
    color: #856404;
}

.aysa-order-status.processing {
    background: #cce5ff;
    color: #004085;
}

.aysa-order-status.completed {
    background: #d4edda;
    color: #155724;
}

.aysa-order-status.error {
    background: #f8d7da;
    color: #721c24;
}

.aysa-order-progress {
    display: flex;
    align-items: center;
    gap: 8px;
}

.aysa-progress-bar {
    flex: 1;
    height: 6px;
    background: #e9ecef;
    border-radius: 3px;
    overflow: hidden;
}

.aysa-progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #4caf50, #2e7d32);
    transition: width 0.3s ease;
}

.aysa-progress-text {
    font-size: 11px;
    font-weight: 600;
    color: #666;
    min-width: 40px;
}

.aysa-empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #666;
}

.aysa-empty-icon {
    font-size: 48px;
    display: block;
        margin-bottom: 15px;
    }
    
.aysa-empty-state h4 {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #333;
}

.aysa-empty-state p {
    margin: 0;
    font-size: 14px;
}

.aysa-order-actions {
    display: flex;
    gap: 6px;
}

.aysa-order-action-btn {
    padding: 4px 8px;
    border: none;
    border-radius: 4px;
    font-size: 11px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.aysa-order-action-btn.view {
    background: #e3f2fd;
    color: #1976d2;
}

.aysa-order-action-btn.retry {
    background: #fff3e0;
    color: #f57c00;
}

.aysa-order-action-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* Order Details Modal */
.aysa-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.aysa-modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
}

.aysa-modal-content {
    position: relative;
    background: white;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
    max-width: 600px;
    width: 90%;
    max-height: 80%;
    overflow: hidden;
    animation: modalFadeIn 0.3s ease;
}

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

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

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

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

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

.aysa-modal-body {
    padding: 25px;
    max-height: calc(85vh - 140px);
    overflow-y: auto;
}

.aysa-modal-footer {
    padding: 15px 25px;
    border-top: 1px solid #e1e5e9;
    background: #f8f9fa;
    text-align: right;
}

.aysa-order-detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f1f3f4;
}

.aysa-order-detail-row:last-child {
    border-bottom: none;
}

.aysa-order-detail-label {
    font-weight: 600;
    color: #333;
    min-width: 150px;
}

.aysa-order-detail-value {
    color: #666;
    flex: 1;
    text-align: right;
}

.aysa-order-json-data {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    padding: 15px;
    margin-top: 15px;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    max-height: 200px;
    overflow-y: auto;
    white-space: pre-wrap;
}

.aysa-progress-detail {
    display: flex;
    align-items: center;
    gap: 10px;
}

.aysa-progress-detail .aysa-progress-bar {
    flex: 1;
    max-width: 150px;
}

/* Automated SEO Tab Styles */
.aysa-automated-seo-section,
.aysa-queue-section {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.aysa-seo-header,
.aysa-queue-header {
    margin-bottom: 25px;
    border-bottom: 1px solid #f1f3f4;
    padding-bottom: 20px;
}

.aysa-seo-header h3,
.aysa-queue-header h3 {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.aysa-seo-icon,
.aysa-queue-icon {
        font-size: 24px;
}

.aysa-seo-description,
.aysa-queue-description {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-automation-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.aysa-automation-card {
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.aysa-automation-card:hover {
    border-color: #4285f4;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.aysa-automation-card.aysa-card-disabled {
    opacity: 0.6;
    background: #f8f9fa;
}

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

.aysa-card-header h4 {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.aysa-feature-icon {
        font-size: 18px;
    }
    
.aysa-toggle-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.aysa-toggle-switch {
    position: relative;
    display: inline-block;
    width: 50px;
        height: 24px;
    }
    
.aysa-toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.aysa-toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.3s;
    border-radius: 24px;
}

.aysa-toggle-slider:before {
    position: absolute;
    content: "";
    height: 18px;
    width: 18px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.3s;
    border-radius: 50%;
}

.aysa-toggle-switch input:checked + .aysa-toggle-slider {
    background-color: #4caf50;
}

.aysa-toggle-switch input:checked + .aysa-toggle-slider:before {
    transform: translateX(26px);
}

.aysa-toggle-switch input:disabled + .aysa-toggle-slider {
    background-color: #e0e0e0;
    cursor: not-allowed;
}

.aysa-toggle-status {
    font-size: 12px;
    font-weight: 600;
    color: #666;
}

.aysa-card-body {
    padding: 20px;
}

.aysa-card-body p {
    margin: 0 0 15px 0;
    color: #666;
    line-height: 1.5;
}

.aysa-automation-stats {
    display: flex;
    gap: 20px;
}

.aysa-stat-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.aysa-stat-label {
    font-size: 12px;
    color: #888;
    font-weight: 500;
}

.aysa-stat-value {
        font-size: 14px;
    font-weight: 600;
    color: #333;
}

/* Queue Management Styles */
.aysa-queue-stats-container {
    margin-bottom: 25px;
}

.aysa-queue-stats-container h4 {
    margin: 0 0 15px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.aysa-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.aysa-stat-card {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    transition: all 0.3s ease;
}

.aysa-stat-card:hover {
    background: #e3f2fd;
    border-color: #4285f4;
}

.aysa-stat-number {
    display: block;
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}

.aysa-stat-label {
    font-size: 12px;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.aysa-queue-actions {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
}

.aysa-queue-status {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
}

/* Domain Authority Header with Toggle */
.aysa-header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
}

.aysa-header-text {
    flex: 1;
}

.aysa-automation-toggle-container {
    flex-shrink: 0;
}

.aysa-toggle-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
}

.aysa-toggle-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.aysa-toggle-label {
    font-size: 13px;
    font-weight: 600;
    color: #333;
}

.aysa-toggle-status {
    font-size: 11px;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

@media (max-width: 768px) {
    .aysa-header-content {
        flex-direction: column;
        align-items: stretch;
    }
    
    .aysa-automation-toggle-container {
        align-self: flex-end;
    }
}

/* Automated SEO Dashboard Styles - Original from automation dashboard */
.aysa-settings-section {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Original automation dashboard styles for reviews */
.automated-seo-review {
    border-left: 4px solid #00a32a;
}

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

.review-header h4 {
    margin: 0;
    font-size: 14px;
}

.review-actions {
    margin-top: 10px;
    display: flex;
    gap: 10px;
}

.aysa-settings-header {
    margin-bottom: 25px;
    border-bottom: 1px solid #f1f3f4;
    padding-bottom: 20px;
}

.aysa-settings-header h3 {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 8px 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.aysa-settings-icon {
    font-size: 24px;
}

.aysa-settings-description {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.aysa-automation-status {
    margin-bottom: 30px;
}

.aysa-automation-status h4 {
    margin: 0 0 15px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.aysa-status-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.aysa-status-card {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.aysa-status-card h5 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #333;
}

.status-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
}

.status-dot[data-status="enabled"] {
    background-color: #4caf50;
}

.status-dot[data-status="disabled"] {
    background-color: #f44336;
}

.status-text {
    font-size: 13px;
    font-weight: 500;
    color: #666;
}

.toggle-automation {
    align-self: flex-start;
    font-size: 12px;
    padding: 6px 12px;
}

.aysa-pending-reviews {
    margin-top: 30px;
}

.aysa-pending-reviews h4 {
    margin: 0 0 15px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

/* Original automation dashboard review styles */
.aysa-review-tabs {
    display: flex;
    gap: 5px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ddd;
}

.review-tab {
    padding: 10px 15px;
    background: #f1f1f1;
    border: 1px solid #ddd;
    border-bottom: none;
    cursor: pointer;
    border-radius: 4px 4px 0 0;
    font-size: 12px;
}

.review-tab:hover {
    background: #e1e1e1;
}

.review-tab.active {
    background: #007cba;
    color: white;
    border-color: #007cba;
}

.review-content {
    padding: 20px;
    background: #fff;
    border: 1px solid #ddd;
    border-top: none;
    border-radius: 0 0 4px 4px;
}

.aysa-task-group-description {
    margin: 5px 0 15px 0;
    color: #5f6368;
        font-size: 14px;
    font-style: italic;
}

/* Pending Reviews Section */
.aysa-pending-reviews-section {
    background: #fff;
    border: 1px solid #e1e5e9;
    border-radius: 12px;
    margin-bottom: 25px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.aysa-pending-reviews-header {
    padding: 20px 25px;
    border-bottom: 1px solid #f1f3f4;
    background: linear-gradient(135deg, #ffebee 0%, #fff3e0 100%);
    border-radius: 12px 12px 0 0;
}

.aysa-pending-reviews-header h4 {
    margin: 0 0 10px 0;
    color: #202124;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 10px;
}

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

.aysa-modal-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    max-width: 90vw;
    max-height: 90vh;
    overflow: auto;
}

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

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

.aysa-modal-footer {
    border-top: 1px solid #e5e7eb;
    background: #f9fafb;
    border-radius: 0 0 8px 8px;
}

.aysa-button-secondary {
    background: #f3f4f6;
    color: #374151;
    border: 1px solid #d1d5db;
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 500;
    transition: all 0.2s ease;
}

.aysa-button-secondary:hover {
    background: #e5e7eb;
    border-color: #9ca3af;
}

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

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

/* Tab Navigation Styles */
.aysa-tabs-nav {
    display: flex;
    border-bottom: 2px solid #e2e8f0;
    margin-bottom: 20px;
    gap: 4px;
}

.aysa-tab-btn {
    background: transparent;
    border: none;
    padding: 12px 20px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    color: #64748b;
    border-radius: 6px 6px 0 0;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    gap: 8px;
    position: relative;
}

.aysa-tab-btn:hover {
    background-color: #f8fafc;
    color: #334155;
}

.aysa-tab-btn.active {
    background-color: #1a73e8;
    color: white;
    box-shadow: 0 2px 4px rgba(26, 115, 232, 0.2);
}

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

.aysa-tab-icon {
    font-size: 16px;
}

/* Tab Content Styles */
.aysa-tabs-content {
    min-height: 200px;
}

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

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

/* Loading Task Styles */
.aysa-loading-task td {
    background-color: #f8fafc !important;
    color: #64748b !important;
    font-style: italic !important;
}

/* Banned Keywords Tab Styles */
.aysa-banned-keywords-section {
    padding: 20px;
}

.aysa-banned-keywords-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

.aysa-controls-left .aysa-btn {
    margin-right: 10px;
}

.aysa-search-box {
    position: relative;
    display: inline-block;
}

.aysa-search-box input {
    padding: 8px 35px 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    width: 250px;
}

.aysa-search-box .dashicons {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #666;
    pointer-events: none;
}

.aysa-banned-keywords-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.aysa-banned-keywords-table th,
.aysa-banned-keywords-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #eee;
}

.aysa-banned-keywords-table th {
    background: #f8f9fa;
    font-weight: 600;
    color: #333;
}

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

.aysa-banned-keywords-table .aysa-keyword-col {
    width: 25%;
}

.aysa-banned-keywords-table .aysa-banned-by-col {
    width: 20%;
}

.aysa-banned-keywords-table .aysa-banned-date-col {
    width: 20%;
}

.aysa-banned-keywords-table .aysa-banned-reason-col {
    width: 25%;
}

.aysa-banned-keywords-table .aysa-banned-actions-col {
    width: 10%;
    text-align: center;
}

.aysa-unban-btn {
    background: #28a745;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s ease;
}

.aysa-unban-btn:hover {
    background: #218838;
}

.aysa-unban-btn:disabled {
    background: #6c757d;
    cursor: not-allowed;
}

.aysa-banned-keywords-pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
}

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

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

.aysa-pagination-btn {
    background: #007cba;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 12px;
    cursor: pointer;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: background-color 0.2s ease;
}

.aysa-pagination-btn:hover:not(:disabled) {
    background: #005a87;
}

.aysa-pagination-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.aysa-page-numbers {
    display: flex;
    gap: 5px;
}

.aysa-page-number {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    background: white;
    transition: all 0.2s ease;
}

.aysa-page-number:hover {
    background: #f0f0f0;
}

.aysa-page-number.active {
    background: #007cba;
    color: white;
    border-color: #007cba;
}

.aysa-banned-keyword-text {
    font-weight: 600;
    color: #333;
}

.aysa-banned-date {
    color: #666;
    font-size: 13px;
}

.aysa-banned-reason {
    color: #555;
    font-style: italic;
}

.aysa-banned-by-name {
    color: #333;
    font-weight: 500;
}

.aysa-empty-state {
    text-align: center;
    padding: 40px;
    color: #666;
}

.aysa-empty-state .dashicons {
    font-size: 48px;
    color: #ccc;
    margin-bottom: 15px;
}

.aysa-empty-state h4 {
    margin: 0 0 10px 0;
    color: #333;
}

.aysa-empty-state p {
    margin: 0;
    font-size: 14px;
}
</style>

<script>
// Add ajaxurl for WordPress AJAX requests
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';

document.addEventListener('DOMContentLoaded', function() {
    // Test button removed - using only real automation generation
    
    // Add generate real review button event listener
    const generateButton = document.getElementById('generate-real-review');
    if (generateButton) {
        generateButton.addEventListener('click', generateRealReview);
    }
    
    // Check if specific tab should be active based on URL parameter
    const urlParams = new URLSearchParams(window.location.search);
    const activeTab = urlParams.get('tab');
    if (activeTab) {
        // Delay to ensure DOM is fully ready
        setTimeout(function() {
            // Activate specified tab
            document.querySelectorAll('.aysa-tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.aysa-tab-pane').forEach(pane => pane.classList.remove('active'));
            
            let targetBtn = null;
            let targetPane = null;
            
            if (activeTab === 'automation') {
                targetBtn = document.querySelector('[data-tab="automation"]');
                targetPane = document.getElementById('automation-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    loadAutomationContent();
                }
            } else if (activeTab === 'domain-authority') {
                targetBtn = document.querySelector('[data-tab="domain-authority"]');
                targetPane = document.getElementById('domain-authority-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    fetchAndInjectDomainAuthorityTasks();
                }
            } else if (activeTab === 'orders') {
                targetBtn = document.querySelector('[data-tab="orders"]');
                targetPane = document.getElementById('orders-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    loadOrders();
                }
            } else if (activeTab === 'banned-keywords') {
                targetBtn = document.querySelector('[data-tab="banned-keywords"]');
                targetPane = document.getElementById('banned-keywords-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    // Load banned keywords data with delay to ensure function is available
                    setTimeout(function() {
                        if (typeof loadBannedKeywords === 'function') {
                            loadBannedKeywords();
                        }
                    }, 200);
                }
            } else if (activeTab === 'automated-seo') {
                targetBtn = document.querySelector('[data-tab="automated-seo"]');
                targetPane = document.getElementById('automated-seo-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    loadAutomatedSeoData();
                }
            } else if (activeTab === 'queue-management') {
                targetBtn = document.querySelector('[data-tab="queue-management"]');
                targetPane = document.getElementById('queue-management-tab');
                if (targetBtn && targetPane) {
                    targetBtn.classList.add('active');
                    targetPane.classList.add('active');
                    loadQueueManagementData();
                }
            }
        }, 100);
    }
    
    function getProjectId() {
        const projectId = localStorage.getItem('aysa_project_id');
        if (projectId) {
            return parseInt(projectId, 10);
        }
        
        console.log('[AYSA] No localStorage project ID, fetching from API');
        let apiProjectId = null;
        const domain = window.location.hostname;
        const apiBaseUrl = '<?php echo esc_js(rtrim(class_exists('Aysa_API_Config') ? Aysa_API_Config::get_api_base_url() : 'https://api.aysa.ai', '/')); ?>';
        var xhr = new XMLHttpRequest();
        xhr.open('GET', apiBaseUrl + '/api/Project/getbydomain/' + domain, false);
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var resp = JSON.parse(xhr.responseText);
                    if (resp && resp.projectId) {
                        apiProjectId = resp.projectId;
                        localStorage.setItem('aysa_project_id', apiProjectId);
                    }
                } catch (e) {
                    console.error('[AYSA] Error parsing API response: ' + e.message);
                }
            }
        };
        xhr.send();
        return apiProjectId ? parseInt(apiProjectId, 10) : 0;
    }

    function fetchAndInjectDomainAuthorityTasks() {
        const projectId = getProjectId();
        if (!projectId) return;
        
        // Load pending reviews
        loadDomainAuthorityReviews();
        
        // Get both task lists
        const automatedTasksList = document.getElementById('automated-domain-authority-tasks');
        const manualTasksList = document.getElementById('manual-domain-authority-tasks');
        
        if (!automatedTasksList || !manualTasksList) return;
        
        // Fetch existing domain authority tasks from Research Tasks API
        fetch(`${apiBaseUrl}/api/ResearchTasks/ByProject/${projectId}`)
            .then(response => response.json())
            .then(tasks => {
                // Filter domain authority tasks (containing "links" and "authority")
                const domainAuthorityTasks = tasks.filter(task => 
                    task.title && 
                    task.title.toLowerCase().includes('links') && 
                    task.title.toLowerCase().includes('authority') &&
                    task.status !== 'deleted'
                );
                
                renderDomainAuthorityTasks(domainAuthorityTasks, automatedTasksList, manualTasksList);
                
                // Also try to generate new tasks based on competitor analysis
                generateDomainAuthorityTask(projectId);
            })
            .catch(err => {
                console.error('[AYSA] Error fetching domain authority tasks:', err);
                showTaskError(automatedTasksList);
                showTaskError(manualTasksList);
            });
    }
    
    function renderDomainAuthorityTasks(tasks, automatedTasksList, manualTasksList) {
        // Clear loading states
        automatedTasksList.innerHTML = '';
        manualTasksList.innerHTML = '';
        
        if (!tasks || tasks.length === 0) {
            automatedTasksList.innerHTML = '<li class="aysa-no-tasks">No AI generated domain authority tasks</li>';
            manualTasksList.innerHTML = '<li class="aysa-no-tasks">No manual domain authority tasks</li>';
                    return;
                }
                
        let automatedCount = 0;
        let manualCount = 0;
        
        tasks.forEach(task => {
            const taskElement = createDomainAuthorityTaskItem(task);
            
            // Separate by flag: isAi = automated, others = manual
            if (task.flag === 'isAi') {
                automatedTasksList.appendChild(taskElement);
                automatedCount++;
            } else {
                manualTasksList.appendChild(taskElement);
                manualCount++;
            }
        });
        
        // Add "no tasks" message if empty
        if (automatedCount === 0) {
            automatedTasksList.innerHTML = '<li class="aysa-no-tasks">No AI generated domain authority tasks</li>';
        }
        if (manualCount === 0) {
            manualTasksList.innerHTML = '<li class="aysa-no-tasks">No manual domain authority tasks</li>';
        }
    }
    
    function createDomainAuthorityTaskItem(task) {
        const li = document.createElement('li');
        li.className = 'aysa-task-item';
        li.dataset.taskId = task.id;
        li.dataset.taskFlag = task.flag;
        li.dataset.taskTitle = task.title;
        li.dataset.taskDescription = task.description || '';
        li.dataset.status = task.status;
        li.dataset.taskCreatedDate = task.createdDate;
        li.dataset.taskUpdatedDate = task.updatedDate || '';
        
        const isCompleted = task.status === 'done';
        // Only show 100% progress if task is actually done, not just based on API percent
        // This prevents showing 100% for tasks that haven't had any link purchases
        const progress = isCompleted ? 100 : (task.percent > 0 && task.percent < 100 ? task.percent : 0);
        const progressColor = isCompleted ? '#34a853' : (progress > 50 ? '#3b82f6' : '#f59e0b');
        
        li.innerHTML = `
            <div class="aysa-task-content">
                <input type="checkbox" id="task-${task.id}" class="aysa-task-checkbox" ${isCompleted ? 'checked' : ''}>
                <label for="task-${task.id}" class="aysa-task-label ${isCompleted ? 'completed' : ''}">${task.title}</label>
                <div class="aysa-task-progress-inline">
                    <div class="aysa-inline-progress-bar" style="width: ${progress}%; background-color: ${progressColor};"></div>
                </div>
                <span class="aysa-progress-text">${progress}% Complete</span>
                <div class="aysa-task-actions">
                    <button class="aysa-task-detail-btn" onclick="openDomainAuthorityTaskDetail('${task.id}')">Details</button>
                    <button class="aysa-delete-btn" onclick="deleteDomainAuthorityTask('${task.id}')">×</button>
                </div>
            </div>
        `;
        
        return li;
    }
    
    function generateDomainAuthorityTask(projectId) {
        // Temporarily disabled by product decision:
        // domain-authority avg endpoint will be redesigned later.
        // Keep this as no-op to avoid legacy external calls/noisy 404s.
        console.log('[AYSA] Domain authority auto-generation disabled (will be reworked later).');
        return;
    }
    
    function showTaskError(tasksList) {
        tasksList.innerHTML = '<li class="aysa-error-task">Error loading tasks</li>';
    }
    
    // Global variables for link purchase functionality
    let progressPollingInterval = null;
    let lastKnownProgress = null;
    
    // Global functions for domain authority task actions
    
    window.deleteDomainAuthorityTask = function(taskId) {
        // Mark task as deleted
        const taskElement = document.querySelector(`[data-task-id="${taskId}"]`);
        if (!taskElement) return;
        
        const taskLabel = taskElement.querySelector('.aysa-task-label').textContent;
        const taskFlag = taskElement.dataset.taskFlag;
        
        fetch(`${apiBaseUrl}/api/ResearchTasks/${taskId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                status: 'deleted',
                title: taskLabel,
                description: '',
                flag: taskFlag
            })
        }).then(() => {
            fetchAndInjectDomainAuthorityTasks();
        }).catch(err => {
            console.error('Error deleting task:', err);
        });
    };
    
    window.openDomainAuthorityTaskDetail = function(taskId) {
        const taskElement = document.querySelector(`[data-task-id="${taskId}"]`);
        if (!taskElement) return;
        
        const title = taskElement.dataset.taskTitle;
        const description = taskElement.dataset.taskDescription;
        const flag = taskElement.dataset.taskFlag;
        const status = taskElement.dataset.status;
        const createdDate = taskElement.dataset.taskCreatedDate;
        const updatedDate = taskElement.dataset.taskUpdatedDate;
        
        // Format dates
        const formatDate = (dateString) => {
            if (!dateString) return 'N/A';
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        };
        
        const modal = document.getElementById('aysa-task-detail-modal');
        if (!modal) return;
        
        // Set modal content
        const titleEl = document.getElementById('task-detail-title');
        const descEl = document.getElementById('task-detail-description');
        const typeEl = document.getElementById('task-detail-type');
        const statusEl = document.getElementById('task-detail-status');
        const createdEl = document.getElementById('task-detail-created');
        const updatedEl = document.getElementById('task-detail-updated');
        
        if (titleEl) titleEl.textContent = title;
        if (descEl) descEl.textContent = description || 'No description provided';
        if (typeEl) typeEl.textContent = flag === 'isAi' ? 'Automated Task' : 'Manual Task';
        if (statusEl) statusEl.textContent = status.charAt(0).toUpperCase() + status.slice(1).replace('-', ' ');
        if (createdEl) createdEl.textContent = formatDate(createdDate);
        if (updatedEl) updatedEl.textContent = formatDate(updatedDate);
        
        // Check if this is a domain authority task and show link purchase section
        const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
        const isDomainAuthorityTask = title && title.toLowerCase().includes('links') && 
                                     title.toLowerCase().includes('authority');
        
        if (isDomainAuthorityTask && linkPurchaseSection) {
            linkPurchaseSection.style.display = 'block';
            linkPurchaseSection.dataset.taskId = taskId;
            linkPurchaseSection.dataset.taskTitle = title;
            
            // Auto-check credits when modal opens
            setTimeout(() => {
                autoCheckCredits();
            }, 100);
        } else if (linkPurchaseSection) {
            linkPurchaseSection.style.display = 'none';
        }
        
        // Show modal
        modal.style.display = 'block';
        
        // Update price display when modal opens
        setTimeout(() => {
            updatePriceDisplay();
        }, 50);
        
        // Start auto-polling for progress updates if this is a domain authority task
        if (isDomainAuthorityTask) {
            setTimeout(() => {
                if (typeof startProgressPolling === 'function') {
                    startProgressPolling(taskId);
                }
            }, 100);
        }
    };
    
    // Progress polling functions - DISABLED AUTO-REFRESH
    function startProgressPolling(taskId) {
        // Clear any existing polling
        stopProgressPolling();
        
        console.log('[AYSA PROGRESS] Auto-refresh disabled - manual refresh only');
        
        // Only refresh immediately on modal open (no auto-polling)
        console.log('[AYSA MODAL] About to call loadLinkPurchaseStatus with preventAutoComplete=true');
        loadLinkPurchaseStatus(taskId, true, true);
    }
    
    function stopProgressPolling() {
        if (progressPollingInterval) {
            console.log('[AYSA PROGRESS] Stopping auto-refresh');
            clearInterval(progressPollingInterval);
            progressPollingInterval = null;
            lastKnownProgress = null; // Reset progress tracking
        }
    }
    
    // Link Purchase Functionality
    function loadLinkPurchaseStatus(taskId, silentRefresh = false, preventAutoComplete = false) {
        console.log(`[AYSA MODAL] loadLinkPurchaseStatus called with taskId=${taskId}, silentRefresh=${silentRefresh}, preventAutoComplete=${preventAutoComplete}`);
        
        const projectId = getProjectId();
        if (!projectId) return;
        
        const statusDiv = document.getElementById('aysa-purchase-status');
        if (statusDiv) {
            statusDiv.innerHTML = '<span style="color:#6b7280;">Loading status...</span>';
        }
        
        // Create FormData for the request
        const formData = new FormData();
        formData.append('action', 'aysa_get_link_purchase_status');
        formData.append('nonce', aysaLinkPurchaseNonce);
        formData.append('task_id', taskId);
        formData.append('project_id', projectId);
        
        fetch(ajaxurl + '?' + new URLSearchParams(formData))
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const status = data.data;
                    document.getElementById('aysa-links-quantity').value = status.links_requested || 1;
                    
                    // Update price display after setting quantity
                    updatePriceDisplay();
                    
                    // The progress is now updated directly in the ResearchTasks table via backend
                    // Refresh task list to get updated progress from API (silent if polling)
                    // But only if we're not preventing auto-completion (i.e., not just opening the modal)
                    if (typeof fetchAndInjectDomainAuthorityTasks === 'function' && !preventAutoComplete) {
                        if (!silentRefresh) {
                            console.log('[AYSA PROGRESS] Refreshing task list');
                        }
                        fetchAndInjectDomainAuthorityTasks();
                    } else if (preventAutoComplete) {
                        console.log('[AYSA PROGRESS] Task list refresh prevented (modal just opened)');
                    }
                    
                    // Check for progress changes and notify user
                    const currentProgress = status.links_purchased;
                    if (silentRefresh && lastKnownProgress !== null && currentProgress > lastKnownProgress) {
                        console.log(`[AYSA PROGRESS] Progress updated: ${lastKnownProgress} → ${currentProgress}`);
                        
                        // Progress notification disabled
                        // const progressNotification = document.createElement('div');
                        // progressNotification.style.cssText = `
                        //     position: fixed;
                        //     top: 20px;
                        //     right: 20px;
                        //     background: #10b981;
                        //     color: white;
                        //     padding: 12px 16px;
                        //     border-radius: 8px;
                        //     box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                        //     z-index: 10000;
                        //     font-size: 14px;
                        //     font-weight: 500;
                        // `;
                        // progressNotification.textContent = `🎉 Link purchased! Progress: ${currentProgress}/${status.links_requested}`;
                        // document.body.appendChild(progressNotification);
                        
                        // // Remove after 3 seconds
                        // setTimeout(() => {
                        //     if (progressNotification.parentNode) {
                        //         progressNotification.parentNode.removeChild(progressNotification);
                        //     }
                        // }, 3000);
                    }
                    lastKnownProgress = currentProgress;
                    
                    // Check if task should be marked as completed (all links purchased but status not 'done')
                    console.log(`[AYSA PROGRESS] Status check: ${status.links_purchased}/${status.links_requested} links, status: '${status.status}'`);
                    
                    // If link purchase status is 'completed', we need to update ResearchTask status to 'done'
                    // But only if we're not preventing auto-completion (i.e., not just opening the modal)
                    // AND only if there's actually a purchase request and links purchased
                    if (status.status === 'completed' && !preventAutoComplete && status.links_requested > 0 && status.links_purchased > 0) {
                        console.log('[AYSA PROGRESS] Link purchase is completed - updating ResearchTask status to done');
                        
                        // Get task ID from the link purchase section
                        const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
                        const taskId = linkPurchaseSection ? linkPurchaseSection.dataset.taskId : null;
                        
                        if (taskId) {
                            // Trigger status update to 'done' for ResearchTask
                            const statusFormData = new FormData();
                            statusFormData.append('action', 'aysa_fix_task_status');
                            statusFormData.append('task_id', taskId);
                            statusFormData.append('nonce', aysa_ajax.nonce);
                            
                            // Add task title and description from modal
                            const titleEl = document.getElementById('task-detail-title');
                            const descEl = document.getElementById('task-detail-description');
                            
                            if (titleEl && titleEl.textContent) {
                                statusFormData.append('task_title', titleEl.textContent.trim());
                            }
                            if (descEl && descEl.textContent) {
                                statusFormData.append('task_description', descEl.textContent.trim());
                            }
                            
                            fetch(aysa_ajax.ajax_url, {
                                method: 'POST',
                                body: statusFormData
                            })
                            .then(response => response.json())
                            .then(statusData => {
                                console.log('[AYSA PROGRESS] ResearchTask status update result:', statusData);
                                
                                if (statusData.success) {
                                    console.log('✅ ResearchTask status updated to done');
                                    
                                    // Research task notification disabled
                                    // const statusNotification = document.createElement('div');
                                    // statusNotification.style.cssText = `
                                    //     position: fixed;
                                    //     top: 20px;
                                    //     right: 20px;
                                    //     background: #10b981;
                                    //     color: white;
                                    //     padding: 12px 16px;
                                    //     border-radius: 8px;
                                    //     box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                                    //     z-index: 10000;
                                    //     font-size: 14px;
                                    //     font-weight: 500;
                                    // `;
                                    // statusNotification.textContent = '✅ Research task marked as completed!';
                                    // document.body.appendChild(statusNotification);
                                    
                                    // setTimeout(() => {
                                    //     if (statusNotification.parentNode) {
                                    //         statusNotification.parentNode.removeChild(statusNotification);
                                    //     }
                                    // }, 3000);
                                    
                                    // Refresh task list to show updated status
                                    if (typeof fetchAndInjectDomainAuthorityTasks === 'function') {
                                        fetchAndInjectDomainAuthorityTasks();
                                    }
                                } else {
                                    console.log('❌ Failed to update ResearchTask status:', statusData.data);
                                }
                            })
                            .catch(error => {
                                console.error('[AYSA PROGRESS] Error updating ResearchTask status:', error);
                            });
                        }
                    } else if (status.status === 'completed' && preventAutoComplete) {
                        console.log('[AYSA PROGRESS] Link purchase is completed but auto-completion is prevented (modal just opened)');
                    }
                    
                    if (status.links_purchased >= status.links_requested && status.status !== 'done' && status.status !== 'completed' && !preventAutoComplete && status.links_requested > 0 && status.links_purchased > 0) {
                        console.log('[AYSA PROGRESS] Task at 100% but status not done - triggering status update');
                        
                        // Get task ID from the link purchase section
                        const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
                        const taskId = linkPurchaseSection ? linkPurchaseSection.dataset.taskId : null;
                        
                        if (taskId) {
                            // Trigger status update to 'done'
                            const statusFormData = new FormData();
                            statusFormData.append('action', 'aysa_fix_task_status');
                            statusFormData.append('task_id', taskId);
                            statusFormData.append('nonce', aysa_ajax.nonce);
                            
                            fetch(aysa_ajax.ajax_url, {
                                method: 'POST',
                                body: statusFormData
                            })
                            .then(response => response.json())
                            .then(statusData => {
                                console.log('[AYSA PROGRESS] Status update result:', statusData);
                                
                                if (statusData.success) {
                                    console.log('✅ Task status updated to done');
                                    
                                    // Status notification disabled
                                    // const statusNotification = document.createElement('div');
                                    // statusNotification.style.cssText = `
                                    //     position: fixed;
                                    //     top: 20px;
                                    //     right: 20px;
                                    //     background: #10b981;
                                    //     color: white;
                                    //     padding: 12px 16px;
                                    //     border-radius: 8px;
                                    //     box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                                    //     z-index: 10000;
                                    //     font-size: 14px;
                                    //     font-weight: 500;
                                    // `;
                                    // statusNotification.textContent = '✅ Task marked as completed!';
                                    // document.body.appendChild(statusNotification);
                                    
                                    // setTimeout(() => {
                                    //     if (statusNotification.parentNode) {
                                    //         statusNotification.parentNode.removeChild(statusNotification);
                                    //     }
                                    // }, 3000);
                                    
                                    // Refresh task list to show updated status
                                    if (typeof fetchAndInjectDomainAuthorityTasks === 'function') {
                                        fetchAndInjectDomainAuthorityTasks();
                                    }
                                } else {
                                    console.log('❌ Failed to update task status:', statusData.data);
                                }
                            })
                            .catch(error => {
                                console.error('[AYSA PROGRESS] Error updating task status:', error);
                            });
                        }
                    } else if (status.links_purchased >= status.links_requested && status.status !== 'done' && status.status !== 'completed' && preventAutoComplete) {
                        console.log('[AYSA PROGRESS] Task is at 100% but auto-completion is prevented (modal just opened)');
                    }
                    
                    // Check if task is completed and stop polling
                    // Only stop polling if task is actually done or if links are genuinely purchased
                    if (status.status === 'done' || (status.links_purchased >= status.links_requested && status.links_requested > 0 && status.links_purchased > 0)) {
                        if (!silentRefresh) {
                            console.log('[AYSA PROGRESS] Task completed, stopping auto-refresh');
                        }
                        stopProgressPolling();
                        
                        // Completion notification disabled
                        // if (silentRefresh && !preventAutoComplete) {
                        //     const completionNotification = document.createElement('div');
                        //     completionNotification.style.cssText = `
                        //         position: fixed;
                        //         top: 20px;
                        //         right: 20px;
                        //         background: #059669;
                        //         color: white;
                        //         padding: 12px 16px;
                        //         border-radius: 8px;
                        //         box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                        //         z-index: 10000;
                        //         font-size: 14px;
                        //         font-weight: 500;
                        //     `;
                        //     completionNotification.textContent = `✅ Task completed! All ${status.links_requested} links purchased.`;
                        //     document.body.appendChild(completionNotification);
                        //     
                        //     setTimeout(() => {
                        //         if (completionNotification.parentNode) {
                        //             completionNotification.parentNode.removeChild(completionNotification);
                        //         }
                        //     }, 5000);
                        // } else if (silentRefresh && preventAutoComplete) {
                        //     console.log('[AYSA PROGRESS] Task appears completed but notification prevented (modal just opened)');
                        // }
                    }
                    
                    if (status.status === 'none') {
                        statusDiv.innerHTML = '<span style="color:#6b7280;">No purchase request found</span>';
                    } else {
                        const progress = status.links_purchased + '/' + status.links_requested;
                        let statusColor = '#6b7280';
                        let statusText = status.status;
                        
                        if (status.status === 'done') {
                            statusColor = '#10b981';
                            statusText = 'Completed';
                        } else if (status.status === 'completed') {
                            statusColor = '#10b981';
                            statusText = 'Completed';
                        } else if (status.status === 'processing') {
                            statusColor = '#f59e0b';
                            statusText = 'In Progress';
                        } else if (status.status === 'pending') {
                            statusColor = '#3b82f6';
                            statusText = 'Pending';
                        } else if (status.status === 'error') {
                            statusColor = '#ef4444';
                            statusText = 'Error';
                            
                            // Check for insufficient credits error details
                            if (status.error_details && status.error_details.response) {
                                try {
                                    const apiResponse = JSON.parse(status.error_details.response);
                                    if (apiResponse.message && apiResponse.message.toLowerCase().includes('insufficient credits')) {
                                        // Show user-friendly insufficient credits message
                                        const requiredCredits = apiResponse.requiredCredits ? (apiResponse.requiredCredits * 100) : 'N/A';
                                        const currentCredits = apiResponse.currentCredits ? (apiResponse.currentCredits * 100) : 'N/A';
                                        const currentTaskId = taskId; // Make taskId available in template
                                        
                                        statusDiv.innerHTML = `
                                            <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:16px;margin-top:8px;">
                                                <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                                                    <span style="color:#dc2626;font-weight:600;">⚠️ You've used all the credits included in your subscription.
          To continue, please add more credits or upgrade your plan.</span>
                            </div>
                                                <div style="color:#7f1d1d;font-size:14px;margin-bottom:12px;">
                                                    <strong>Links purchased:</strong> ${status.links_purchased}/${status.links_requested}<br>
                                                    <strong>Required:</strong> ${requiredCredits} credits<br>
                                                    <strong>Available:</strong> ${currentCredits} credits
                            </div>
                                                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                                                    <a href="https://app.aysa.ai/credits" target="_blank" style="background:#dc2626;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">Add Credits</a>
                                                    <a href="https://app.aysa.ai/credits" target="_blank" style="background:#6b7280;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">View Plans</a>
                                                    <button onclick="resetLinkPurchaseError('${currentTaskId}')" style="background:#059669;color:white;border:none;padding:8px 16px;border-radius:6px;font-size:14px;font-weight:500;cursor:pointer;">Reset Error</button>
                                                </div>
                                            </div>
                                        `;
                                        return; // Don't show the default status div
                                    }
                                } catch (e) {
                                    console.log('Could not parse error response:', e);
                                }
                            }
                        }
                        
                        // Auto-refresh indicator removed (manual refresh only)
                            
                        statusDiv.innerHTML = `
                            <div style="display:flex;align-items:center;gap:8px;">
                                <span style="color:${statusColor};font-weight:600;">Status: ${statusText}</span>
                                <span style="color:#374151;">Progress: ${progress} links</span>
                                ${autoRefreshIndicator}
                            </div>
                        `;
                    }
                } else {
                    statusDiv.innerHTML = '<span style="color:#ef4444;">Error loading status</span>';
                }
            })
            .catch(error => {
                console.error('Error loading link purchase status:', error);
                if (statusDiv) {
                    statusDiv.innerHTML = '<span style="color:#ef4444;">Error loading status</span>';
                }
            });
    }
    
    function saveLinkPurchaseRequest() {
        const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
        if (!linkPurchaseSection) return;
        
        const taskId = linkPurchaseSection.dataset.taskId;
        const taskTitle = linkPurchaseSection.dataset.taskTitle;
        const projectId = getProjectId();
        
        const linksQuantity = parseInt(document.getElementById('aysa-links-quantity').value) || 1;
        
        if (!taskId || !projectId || linksQuantity <= 0) {
            alert('Invalid parameters. Please check your input.');
            return;
        }
        
        // Check if button is disabled due to insufficient credits
        const saveBtn = document.getElementById('aysa-save-purchase-request');
        if (saveBtn && saveBtn.disabled && saveBtn.textContent === 'Insufficient Credits') {
            return; // Don't proceed if credits are insufficient
        }
        
        // Calculate required credits before proceeding
        const requiredCredits = calculateRequiredCredits(linksQuantity);
        
        // Check if user has sufficient credits one more time
        checkCreditsAndProceed(projectId, requiredCredits, function() {
            // This function will be called if credits are sufficient
            proceedWithPurchase(taskId, taskTitle, projectId, linksQuantity);
        });
    }
    
    function calculateRequiredCredits(linksQuantity) {
        // Fixed price: 500 credits per link regardless of domain authority
        const pricePerLinkCredits = 500;
        
        return linksQuantity * pricePerLinkCredits;
    }
    
    function checkCreditsAndProceed(projectId, requiredCredits, successCallback) {
        // Get current credits from API
        const apiUrl = `${apiBaseUrl}/api/AysaCredits/get-total-credits/${projectId}`;
        
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                const currentCredits = data.totalCredits || 0;
                
                if (currentCredits < requiredCredits) {
                    // Show insufficient credits error in modal
                    showInsufficientCreditsError(requiredCredits, currentCredits);
                } else {
                    // Proceed with purchase
                    successCallback();
                }
            })
            .catch(error => {
                console.error('Error checking credits:', error);
                alert('Error checking credits. Please try again.');
            });
    }
    
    function showInsufficientCreditsError(requiredCredits, currentCredits) {
        // Stop auto-polling when showing insufficient credits error
        if (typeof stopProgressPolling === 'function') {
            stopProgressPolling();
            console.log('[AYSA CREDITS] Stopped auto-polling due to insufficient credits');
        }
        
        // Find the purchase status div or create one
        let statusDiv = document.getElementById('aysa-purchase-status');
        if (!statusDiv) {
            const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
            statusDiv = document.createElement('div');
            statusDiv.id = 'aysa-purchase-status';
            linkPurchaseSection.appendChild(statusDiv);
        }
        
        statusDiv.innerHTML = `
            <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:16px;margin-top:8px;">
                <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">
                    <span style="color:#dc2626;font-weight:600;">⚠️ You've used all the credits included in your subscription.
To continue, please add more credits or upgrade your plan.</span>
                </div>
                <div style="color:#7f1d1d;font-size:14px;margin-bottom:12px;">
                    <strong>Required:</strong> ${requiredCredits} credits<br>
                    <strong>Available:</strong> ${currentCredits} credits
                </div>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="https://app.aysa.ai/credits" target="_blank" style="background:#dc2626;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">Add Credits</a>
                    <a href="https://app.aysa.ai/credits" target="_blank" style="background:#6b7280;color:white;padding:8px 16px;border-radius:6px;text-decoration:none;font-size:14px;font-weight:500;">View Plans</a>
                </div>
            </div>
        `;
    }
    
    function clearInsufficientCreditsError() {
        const statusDiv = document.getElementById('aysa-purchase-status');
        if (statusDiv) {
            statusDiv.innerHTML = '';
            
            // Restart auto-polling when clearing insufficient credits error
            const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
            const taskId = linkPurchaseSection ? linkPurchaseSection.dataset.taskId : null;
            
            if (taskId && typeof startProgressPolling === 'function') {
                startProgressPolling(taskId);
                console.log('[AYSA CREDITS] Restarted auto-polling after clearing insufficient credits error');
            }
        }
    }
    
    function autoCheckCredits() {
        const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
        if (!linkPurchaseSection || linkPurchaseSection.style.display === 'none') {
            return; // Don't check if modal is not visible
        }
        
        const projectId = getProjectId();
        const linksQuantity = parseInt(document.getElementById('aysa-links-quantity').value) || 1;
        
        if (!projectId || linksQuantity <= 0) {
            return;
        }
        
        // Calculate required credits
        const requiredCredits = calculateRequiredCredits(linksQuantity);
        
        // Get current credits and check
        const apiUrl = `${apiBaseUrl}/api/AysaCredits/get-total-credits/${projectId}`;
        
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                const currentCredits = data.totalCredits || 0;
                
                if (currentCredits < requiredCredits) {
                    // Show insufficient credits error
                    showInsufficientCreditsError(requiredCredits, currentCredits);
                    // Disable the save button
                    const saveBtn = document.getElementById('aysa-save-purchase-request');
                    if (saveBtn && !saveBtn.disabled) {
                        saveBtn.disabled = true;
                        saveBtn.textContent = 'Insufficient Credits';
                        saveBtn.style.background = '#9ca3af';
                        saveBtn.setAttribute('data-original-state', 'modified'); // Mark as modified
                    }
                    
                    // Disable the refresh button too
                    const refreshBtn = document.getElementById('aysa-refresh-purchase-status');
                    if (refreshBtn && !refreshBtn.disabled) {
                        refreshBtn.disabled = true;
                        refreshBtn.style.background = '#9ca3af';
                        refreshBtn.style.cursor = 'not-allowed';
                        refreshBtn.setAttribute('data-original-state', 'modified'); // Mark as modified
                    }
                } else {
                    // Clear error and enable button
                    clearInsufficientCreditsError();
                    const saveBtn = document.getElementById('aysa-save-purchase-request');
                    if (saveBtn && saveBtn.getAttribute('data-original-state') === 'modified') {
                        saveBtn.disabled = false;
                        saveBtn.textContent = 'Save Purchase Request';
                        saveBtn.style.background = '#10b981'; // Original green color
                        saveBtn.removeAttribute('data-original-state');
                    }
                    
                    // Re-enable the refresh button too
                    const refreshBtn = document.getElementById('aysa-refresh-purchase-status');
                    if (refreshBtn && refreshBtn.getAttribute('data-original-state') === 'modified') {
                        refreshBtn.disabled = false;
                        refreshBtn.style.background = '#6b7280'; // Original grey color for refresh button
                        refreshBtn.style.cursor = 'pointer';
                        refreshBtn.removeAttribute('data-original-state');
                    }
                }
            })
            .catch(error => {
                console.error('Error checking credits:', error);
            });
    }
    
    function proceedWithPurchase(taskId, taskTitle, projectId, linksQuantity) {
        const formData = new FormData();
        formData.append('action', 'aysa_save_link_purchase_request');
        formData.append('nonce', aysaLinkPurchaseNonce);
        formData.append('task_id', taskId);
        formData.append('project_id', projectId);
        formData.append('task_title', taskTitle);
        formData.append('links_requested', linksQuantity);
        
        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Link purchase request saved successfully! Links will be purchased automatically over time.');
                loadLinkPurchaseStatus(taskId, false, false); // Refresh status and allow auto-completion
            } else {
                alert('Error saving purchase request: ' + (data.data || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error saving purchase request:', error);
            alert('Error saving purchase request. Please try again.');
        })
        .finally(() => {
            const saveBtn = document.getElementById('aysa-save-purchase-request');
            if (saveBtn) {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save Purchase Request';
            }
        });
    }
    
    // Function to get base price based on domain authority (in Euro)
    function getBasePriceEuro(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; // DA 100
    }
    
    // Function to calculate price with VAT
    function calculatePriceWithVAT(basePrice, vat) {
        // Use the service type helper for consistent VAT calculation
        if (window.AysaServiceTypeHelper) {
            return window.AysaServiceTypeHelper.calculatePriceWithVAT(basePrice, vat);
        }
        // Fallback to original logic
        const vatAmount = basePrice * vat;
        return basePrice + vatAmount;
    }
    
    // Function to calculate and update price display
    function updatePriceDisplay() {
        const quantity = parseInt(document.getElementById('aysa-links-quantity').value) || 1;
        
        // Fixed price: 500 credits per link
        const pricePerLinkCredits = 500;
        const totalPriceCredits = quantity * pricePerLinkCredits;
        
        const priceElement = document.getElementById('aysa-price-amount');
        if (priceElement) {
            priceElement.textContent = totalPriceCredits;
        }
    }
    
    // Function to reset link purchase error
    window.resetLinkPurchaseError = function(taskId) {
        if (!confirm('Are you sure you want to reset this error and retry the purchase?')) {
            return;
        }
        
        const formData = new FormData();
        formData.append('action', 'aysa_reset_link_purchase_errors');
        formData.append('nonce', aysaLinkPurchaseNonce);
        
        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Error has been reset. The purchase will be retried automatically.');
                loadLinkPurchaseStatus(taskId, false, false); // Refresh status and allow auto-completion
            } else {
                alert('Failed to reset error: ' + (data.data || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Reset error failed:', error);
            alert('Failed to reset error. Check console for details.');
        });
    };

    function fetchAndInjectAssociationTasks() {
        const projectId = getProjectId();
        if (!projectId) return;
        
        const tasksList = document.querySelector('.aysa-association-tasks');
        if (!tasksList) return;

        // Temporarily disabled by product decision:
        // association count endpoint will be refactored later.
        const loadingTask = tasksList.querySelector('.aysa-loading-task');
        if (loadingTask) {
            loadingTask.remove();
        }
        tasksList.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px;">Association suggestions are temporarily disabled in this tab.</td></tr>';
        console.log('[AYSA] Association task auto-injection disabled (pending redesign).');
    }

    function initTabSwitching() {
        const tabButtons = document.querySelectorAll('.aysa-tab-btn');
        const tabPanes = document.querySelectorAll('.aysa-tab-pane');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', function() {
                const targetTab = this.getAttribute('data-tab');
                
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabPanes.forEach(pane => pane.classList.remove('active'));
                
                this.classList.add('active');
                const targetPane = document.getElementById(targetTab + '-tab');
                if (targetPane) {
                    targetPane.classList.add('active');
                }
                
                if (targetTab === 'domain-authority') {
                    fetchAndInjectDomainAuthorityTasks();
                } else if (targetTab === 'associations') {
                    fetchAndInjectAssociationTasks();
                } else if (targetTab === 'automation') {
                    loadAutomationContent();
                }
            });
        });
    }
    
    initTabSwitching();
    
    fetchAndInjectDomainAuthorityTasks();
    
    // Load automation states on initial load
    loadAutomationStates();
    
    // Auto-load automated SEO data immediately when script runs
    loadAutomatedSeoData();
    
    // Tab-specific event listeners
    document.addEventListener('click', function(e) {
        if (e.target.matches('[data-tab="automated-seo"]')) {
            loadAutomatedSeoData();
        }
        if (e.target.matches('[data-tab="queue-management"]')) {
            loadQueueManagementData();
        }
    });
    
    // Automation toggle event listeners (support all toggles including new ones)
    document.addEventListener('change', function(e) {
        if (e.target.id === 'da-automation-toggle' || 
            e.target.id === 'domain-authority-automation-toggle' ||
            e.target.id === 'settings-domain-authority-toggle') {
            const isEnabled = e.target.checked;
            toggleDomainAuthorityAutomation(isEnabled);
        }
    });
    
    // Original automation dashboard toggle functionality (for Settings tab)
    jQuery(document).on('click', '.toggle-automation', function() {
        var feature = jQuery(this).data('feature');
        var $card = jQuery(this).closest('.aysa-status-card');
        var $dot = $card.find('.status-dot');
        var $text = $card.find('.status-text');
        var enabled = $dot.attr('data-status') === 'enabled';
        
        console.log('[AYSA AUTOMATION] Toggle button clicked for feature: ' + feature + ', current status: ' + (enabled ? 'enabled' : 'disabled'));
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_toggle_automation',
                feature: feature,
                enabled: !enabled,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            beforeSend: function() {
                console.log('[AYSA AUTOMATION] Sending toggle request for feature: ' + feature + ', new status: ' + (!enabled ? 'enabled' : 'disabled'));
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Toggle response received: ' + JSON.stringify(response));
                if (response.success) {
                    if (response.data.enabled) {
                        $dot.attr('data-status', 'enabled');
                        $text.text('Enabled');
                        console.log('[AYSA AUTOMATION] UI updated to enabled for feature: ' + feature);
                    } else {
                        $dot.attr('data-status', 'disabled');
                        $text.text('Disabled');
                        console.log('[AYSA AUTOMATION] UI updated to disabled for feature: ' + feature);
                    }
                    
                    // Update all related toggles
                    updateAllToggles(feature, response.data.enabled);
                    
                    // Show notification
                    showNotification(
                        `${feature.replace('_', ' ')} ${response.data.enabled ? 'enabled' : 'disabled'}`, 
                        response.data.enabled ? 'success' : 'info'
                    );
                } else {
                    console.error('[AYSA AUTOMATION] Toggle failed for feature: ' + feature + ', error: ' + (response.data || 'Unknown error'));
                    showNotification('Failed to toggle automation: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error toggling feature: ' + feature + ', Error: ' + error + ', Status: ' + status);
                console.error('[AYSA AUTOMATION] Response text: ' + xhr.responseText);
                showNotification('Error toggling automation: ' + error, 'error');
            }
        });
    });
    
    // Queue management button listeners
    document.addEventListener('click', function(e) {
        if (e.target.id === 'process-queue-now' || e.target.closest('#process-queue-now')) {
            processQueueNow();
        }
        if (e.target.id === 'refresh-queue-stats' || e.target.closest('#refresh-queue-stats')) {
            loadQueueStatistics();
        }
    });
    
    // Orders tab event listeners
    document.addEventListener('click', function(e) {
        if (e.target.matches('[data-tab="orders"]')) {
            loadOrders();
        }
    });
    
            // Orders filter and refresh listeners
        const statusFilter = document.getElementById('aysa-orders-status-filter');
        if (statusFilter) {
            statusFilter.addEventListener('change', function() {
                loadOrders(this.value);
            });
        }
        
        const refreshBtn = document.getElementById('aysa-refresh-orders');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', function() {
                const filter = document.getElementById('aysa-orders-status-filter');
                loadOrders(filter ? filter.value : 'all');
            });
        }
        
        // Modal close on overlay click
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('aysa-modal-overlay')) {
                window.closeOrderDetailsModal();
            }
        });
        
        // Modal close on escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                window.closeOrderDetailsModal();
            }
        });
    
    // Handler for the approve domain authority task button
    document.addEventListener('click', function(e) {
        if (!e.target.classList.contains('approve-domain-authority-task')) return;
        
        const button = e.target;
        const projectId = getProjectId();
        const meanBacklinks = parseInt(button.getAttribute('data-mean-backlinks'));
        const meanAuthority = parseInt(button.getAttribute('data-mean-authority'));
        
        if (!projectId) {
            alert('Project ID not found');
            return;
        }
        
        const userId = getCookie('aysa_user_id');
        if (!userId) {
            alert('User ID not found. Please login again.');
            return;
        }
        
        button.disabled = true;
        button.textContent = 'Processing...';
        
        // Also disable the reject button
        const rejectButton = button.parentElement.querySelector('.aysa-btn-danger');
        if (rejectButton) {
            rejectButton.disabled = true;
        }
        
        Promise.all([
            getSeoSettings(projectId),
            getResearchTaskDetails(projectId)
        ])
            .then(function([seoSettings, taskData]) {
                console.log('SeoSettings:', seoSettings);
                console.log('TaskData:', taskData);
                
                const payload = {
                    ProjectId: projectId.toString(),
                    Keyword: "Domain Authority",
                    NumberOfLinksToBuy: meanBacklinks,
                    Country: seoSettings.country || "Romania",
                    Language: seoSettings.language || "ro",
                    MinDa: taskData.minDa || Math.max(20, meanAuthority - 10),
                    MaxDa: taskData.maxDa || Math.min(80, meanAuthority + 10),
                    UserId: parseInt(userId),
                    WordToLinks: [{
                        PublisherWebsite: `domain-authority-task-${projectId}`,
                        Keyword: "Domain Authority",
                        Url: `https://domain-authority-task-${projectId}.com`,
                        Title: `Domain Authority Improvement for Project ${projectId}`,
                        TypeOfLink: "NormalFollow",
                        Exclusivity: false,
                        MonthlyValue: meanBacklinks * 10,
                        DomainAuthority: meanAuthority,
                        TargetUrl: `https://domain-authority-task-${projectId}.com`
                    }]
                };
                
                console.log('Sending domain authority order:', payload);
                
                return fetch(`${apiBaseUrl}/api/order/process-order`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(payload)
                });
            })
            .then(response => response.json())
            .then(function(response) {
                console.log('Domain authority order response:', response);
                if (response && response.success) {
                    alert('Domain authority task approved and order placed successfully!');
                    button.textContent = 'Approved';
                    button.classList.remove('aysa-btn-success');
                    button.classList.add('aysa-btn-secondary');
                    button.disabled = true;
                    
                    // Remove the reject button
                    if (rejectButton) {
                        rejectButton.remove();
                    }
                } else {
                    let msg = response && response.message ? response.message : 'Unknown error!';
                    alert('Error: ' + msg);
                    button.disabled = false;
                    button.textContent = 'Approve';
                    if (rejectButton) {
                        rejectButton.disabled = false;
                    }
                }
            })
            .catch(function(error) {
                console.error('Error processing domain authority order:', error);
                alert('Error processing domain authority task. Please try again.');
                button.disabled = false;
                button.textContent = 'Approve';
                if (rejectButton) {
                    rejectButton.disabled = false;
                }
            });
    });
    
    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }
    
    function getSeoSettings(projectId) {
        return fetch(`${apiBaseUrl}/api/SeoSettings/ByProject/${projectId}`)
            .then(response => response.json());
    }
    
    function getResearchTaskDetails(projectId) {
        console.log('🔍 Starting getResearchTaskDetails for projectId:', projectId);
        
        // Get all research tasks to see what exists
        return fetch(`${apiBaseUrl}/api/ResearchTasks/ByProject/${projectId}`)
            .then(response => {
                console.log('📡 All ResearchTasks response status:', response.status);
                return response.json();
            })
            .then(allTasks => {
                console.log('📋 All ResearchTasks for project:', allTasks);
                
                // Look for domain-authority type first
                let domainAuthorityTasks = allTasks.filter(task => task.type === "domain-authority");
                console.log('🎯 Domain-authority tasks found:', domainAuthorityTasks);
                
                // If no domain-authority tasks, get the latest task
                let tasksToUse = domainAuthorityTasks.length > 0 ? domainAuthorityTasks : allTasks;
                
                if (tasksToUse && tasksToUse.length > 0) {
                    const latestTask = tasksToUse[0];
                    console.log('🎯 Using task:', latestTask);
                    console.log('🔗 Making call to TaskDetails for taskId:', latestTask.id);
                    
                    return fetch(`${apiBaseUrl}/api/ResearchTasks/TaskDetails/${latestTask.id}`)
                        .then(response => {
                            console.log('📡 TaskDetails response status:', response.status);
                            return response.json();
                        })
                        .then(taskDetails => {
                            console.log('📊 TaskDetails API Response:', taskDetails);
                            if (taskDetails && taskDetails.length > 0) {
                                const latestDetail = taskDetails[0];
                                console.log('✅ Latest TaskDetail found:', latestDetail);
                                return {
                                    taskId: latestTask.id,
                                    minDa: latestDetail.minDa || latestDetail.MinDa,
                                    maxDa: latestDetail.maxDa || latestDetail.MaxDa,
                                    keyword: latestDetail.keyword || latestDetail.Keyword
                                };
                            }
                            console.log('❌ No TaskDetails found in response');
                            return { taskId: latestTask.id, minDa: null, maxDa: null, keyword: null };
                        })
                        .catch((error) => {
                            console.error('❌ Error fetching TaskDetails:', error);
                            return { taskId: latestTask.id, minDa: null, maxDa: null, keyword: null };
                        });
                }
                console.log('❌ No ResearchTasks found');
                return { taskId: null, minDa: null, maxDa: null, keyword: null };
            })
            .catch((error) => {
                console.error('❌ Error fetching ResearchTasks:', error);
                return { taskId: null, minDa: null, maxDa: null, keyword: null };
            });
    }
    
    // Function to load Domain Authority reviews
    function loadDomainAuthorityReviews() {
        console.log('[AYSA] Loading domain authority reviews...');
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_domain_authority_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Domain authority reviews response:', response);
                if (response.success) {
                    renderDomainAuthorityReviews(response.data);
                } else {
                    console.error('[AYSA] Failed to load domain authority reviews:', response.data);
                    document.getElementById('domain-authority-pending-reviews').innerHTML = 
                        '<p style="color: #666; text-align: center; padding: 20px; font-style: italic;">No pending reviews at this time. Tasks with high confidence scores are automatically approved.</p>';
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] AJAX error loading domain authority reviews:', error);
                document.getElementById('domain-authority-pending-reviews').innerHTML = 
                    '<p style="color: #ea4335; text-align: center; padding: 20px;">Error loading reviews.</p>';
            }
        });
    }
    
    // Function to render Domain Authority reviews
    function renderDomainAuthorityReviews(reviews) {
        const reviewsContainer = document.getElementById('domain-authority-pending-reviews');
        const reviewsGroup = document.getElementById('pending-reviews-group');
        
        if (!reviewsContainer || !reviewsGroup) return;
        
        const reviewsArray = Object.keys(reviews);
        
        // Always show reviews group
        reviewsGroup.style.display = 'block';
        
        if (reviewsArray.length === 0) {
            reviewsContainer.innerHTML = '<p style="color: #666; text-align: center; padding: 20px; font-style: italic;">No pending reviews at this time. Tasks with high confidence scores are automatically approved.</p>';
            return;
        }
        
        let html = '';
        reviewsArray.forEach(function(projectId) {
            const review = reviews[projectId];
            html += `
                <div class="aysa-review-item">
                    <h4>Domain Authority Task</h4>
                    <p>${review.task_data.title || 'Domain Authority Optimization'}</p>
                    <p><strong>Confidence:</strong> ${Math.round(review.confidence_score * 100)}%</p>
                    <p><strong>Recommendation:</strong> ${review.recommendation || 'Review required'}</p>
                    <p><strong>Created:</strong> ${review.created_at ? new Date(review.created_at).toLocaleDateString() : 'Unknown'}</p>
                    <div class="aysa-review-actions">
                        <button class="aysa-action-btn approve-domain-authority" data-project-id="${projectId}">
                            Approve
                        </button>
                        <button class="aysa-action-btn reject-domain-authority" data-project-id="${projectId}">
                            Reject
                        </button>
                    </div>
                </div>
            `;
        });
        
        reviewsContainer.innerHTML = html;
        
        // Add event listeners for approve/reject buttons
        attachReviewEventListeners();
    }
    
    // Function to attach event listeners to review buttons
    function attachReviewEventListeners() {
        // Approve buttons
        document.querySelectorAll('.approve-domain-authority').forEach(button => {
            button.addEventListener('click', function() {
                const projectId = this.getAttribute('data-project-id');
                approveDomainAuthorityReview(projectId);
            });
        });
        
        // Reject buttons  
        document.querySelectorAll('.reject-domain-authority').forEach(button => {
            button.addEventListener('click', function() {
                const projectId = this.getAttribute('data-project-id');
                rejectDomainAuthorityReview(projectId);
            });
        });
    }
    
    // Function to approve a domain authority review
    function approveDomainAuthorityReview(projectId) {
        if (!confirm('Are you sure you want to approve this domain authority task?')) {
            return;
        }
        
        console.log('[AYSA] Approving domain authority review for project:', projectId);
        
        // Find the button and review item
        const button = document.querySelector(`[data-project-id="${projectId}"].approve-domain-authority`);
        const reviewItem = button.closest('.aysa-review-item');
        const rejectButton = reviewItem.querySelector('.reject-domain-authority');
        
        // Add loading state to button
        button.disabled = true;
        button.classList.add('button-loading');
        rejectButton.disabled = true;
        
        // Change button text and hide it during loading
        const originalText = button.innerHTML;
        button.style.color = 'transparent';
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST', 
            data: {
                action: 'aysa_approve_domain_authority_review',
                project_id: projectId,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Approve response:', response);
                if (response.success) {
                    // Add fade out animation to review item
                    reviewItem.classList.add('review-item-removing');
                    
                    // Show success message
                    showNotification('✅ Task approved and added to your task list!', 'success');
                    
                    // Remove review item after animation
                    setTimeout(() => {
                        reviewItem.remove();
                        
                        // Check if there are any remaining reviews
                        const remainingReviews = document.querySelectorAll('.aysa-review-item');
                        if (remainingReviews.length === 0) {
                            document.getElementById('domain-authority-pending-reviews').innerHTML = 
                                '<p style="color: #666; text-align: center; padding: 20px; font-style: italic;">No pending reviews at this time. Tasks with high confidence scores are automatically approved.</p>';
                        }
                        
                        // Immediately reload tasks to show the newly created task
                        if (typeof fetchAndInjectDomainAuthorityTasks === 'function') {
                            fetchAndInjectDomainAuthorityTasks();
                            // Show notification about new task appearing
                            setTimeout(() => {
                                showNotification('📋 New task appeared in AI Generated Tasks!', 'info');
                            }, 800);
                        }
                    }, 300); // Reduced from 500ms to 300ms for faster response
                } else {
                    // Reset button state on error
                    button.disabled = false;
                    button.classList.remove('button-loading');
                    button.style.color = '';
                    rejectButton.disabled = false;
                    
                    showNotification('Failed to approve review: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] AJAX error approving review:', error);
                
                // Reset button state on error
                button.disabled = false;
                button.classList.remove('button-loading');
                button.style.color = '';
                rejectButton.disabled = false;
                
                showNotification('Error approving review: ' + error, 'error');
            }
        });
    }
    
    // Function to load orders
    function loadOrders(statusFilter = 'all') {
        const projectId = getProjectId();
        if (!projectId) {
            console.error('[AYSA ORDERS] No project ID found');
            return;
        }
        
        console.log('[AYSA ORDERS] Loading orders for project:', projectId);
        
        // Show loading state
        const ordersList = document.getElementById('aysa-orders-list');
        const emptyState = document.getElementById('aysa-orders-empty');
        
        if (ordersList) {
            ordersList.innerHTML = `
                <tr class="aysa-loading-row">
                    <td colspan="9" style="text-align: center; padding: 40px;">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        Loading orders...
                    </td>
                </tr>
            `;
        }
        
        if (emptyState) {
            emptyState.style.display = 'none';
        }
        
        // Fetch orders via AJAX
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_link_orders',
                project_id: projectId,
                status_filter: statusFilter,
                nonce: '<?php echo wp_create_nonce('aysa_orders_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA ORDERS] Response:', response);
                if (response.success && response.data) {
                    renderOrders(response.data);
                } else {
                    showOrdersError('Failed to load orders: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA ORDERS] AJAX error:', error);
                showOrdersError('Error loading orders: ' + error);
            }
        });
    }
    
    // Function to render orders
    function renderOrders(orders) {
        const ordersList = document.getElementById('aysa-orders-list');
        const emptyState = document.getElementById('aysa-orders-empty');
        
        if (!orders || orders.length === 0) {
            ordersList.innerHTML = '';
            emptyState.style.display = 'block';
            return;
        }
        
        emptyState.style.display = 'none';
        
        let html = '';
        orders.forEach(order => {
            const progress = order.links_requested > 0 ? 
                Math.round((order.links_purchased / order.links_requested) * 100) : 0;
            
            const statusClass = order.status.toLowerCase();
            const createdDate = new Date(order.created_at).toLocaleDateString();
            const lastUpdate = order.updated_at ? 
                new Date(order.updated_at).toLocaleDateString() : 'Never';
            
            html += `
                <tr data-order-id="${order.id}">
                    <td><strong>#${order.id}</strong></td>
                    <td title="${order.task_title}">${order.task_title.length > 40 ? 
                        order.task_title.substring(0, 40) + '...' : order.task_title}</td>
                    <td>${order.links_requested}</td>
                    <td>${order.links_purchased}</td>
                    <td>
                        <div class="aysa-order-progress">
                            <div class="aysa-progress-bar">
                                <div class="aysa-progress-fill" style="width: ${progress}%"></div>
                            </div>
                            <span class="aysa-progress-text">${progress}%</span>
                        </div>
                    </td>
                    <td>
                        <span class="aysa-order-status ${statusClass}">${order.status}</span>
                    </td>
                    <td>${createdDate}</td>
                    <td>${lastUpdate}</td>
                    <td>
                        <div class="aysa-order-actions">
                            <button class="aysa-order-action-btn view" onclick="window.viewOrderDetails(${order.id})" title="View Details">
                                👁️
                            </button>
                            ${order.status === 'error' ? `
                                <button class="aysa-order-action-btn retry" onclick="window.retryOrder(${order.id})" title="Retry">
                                    🔄
                                </button>
                            ` : ''}
                        </div>
                    </td>
                </tr>
            `;
        });
        
        ordersList.innerHTML = html;
    }
    
    // Function to show orders error
    function showOrdersError(message) {
        const ordersList = document.getElementById('aysa-orders-list');
        ordersList.innerHTML = `
            <tr>
                <td colspan="9" style="text-align: center; padding: 40px; color: #dc3545;">
                    <span class="dashicons dashicons-warning"></span>
                    ${message}
                </td>
            </tr>
        `;
    }
    
    // Function to view order details - make it global
    window.viewOrderDetails = function(orderId) {
        console.log('[AYSA ORDERS] Viewing details for order:', orderId);
        
        // Find the order data from the current loaded orders
        const orderRow = document.querySelector(`tr[data-order-id="${orderId}"]`);
        if (!orderRow) {
            showNotification('Order not found', 'error');
            return;
        }
        
        // Get order details via AJAX
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_order_details',
                order_id: orderId,
                nonce: '<?php echo wp_create_nonce('aysa_orders_nonce'); ?>'
            },
            success: function(response) {
                if (response.success && response.data) {
                    window.openOrderDetailsModal(response.data);
                } else {
                    showNotification('Failed to load order details: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                showNotification('Error loading order details: ' + error, 'error');
            }
        });
    }
    
    // Function to open order details modal - make it global
    window.openOrderDetailsModal = function(order) {
        const modal = document.getElementById('aysa-order-details-modal');
        const title = document.getElementById('aysa-order-modal-title');
        const body = document.getElementById('aysa-order-modal-body');
        
        if (!modal || !title || !body) return;
        
        // Set modal title
        title.textContent = `Order #${order.id} Details`;
        
        // Calculate progress
        const progress = order.links_requested > 0 ? 
            Math.round((order.links_purchased / order.links_requested) * 100) : 0;
        
        // Format dates
        const createdDate = new Date(order.created_at).toLocaleString();
        const lastUpdate = order.updated_at ? 
            new Date(order.updated_at).toLocaleString() : 'Never';
        const lastAttempt = order.last_purchase_attempt ? 
            new Date(order.last_purchase_attempt).toLocaleString() : 'Never';
        
        // Generate modal content
        let orderDataHtml = '';
        if (order.order_data) {
            try {
                const orderData = typeof order.order_data === 'string' ? 
                    JSON.parse(order.order_data) : order.order_data;
                orderDataHtml = `
                    <div class="aysa-order-detail-row">
                        <span class="aysa-order-detail-label">API Response Data:</span>
                        <span class="aysa-order-detail-value"></span>
                    </div>
                    <div class="aysa-order-json-data">${JSON.stringify(orderData, null, 2)}</div>
                `;
            } catch (e) {
                orderDataHtml = `
                    <div class="aysa-order-detail-row">
                        <span class="aysa-order-detail-label">Raw Order Data:</span>
                        <span class="aysa-order-detail-value"></span>
                    </div>
                    <div class="aysa-order-json-data">${order.order_data}</div>
                `;
            }
        }
        
        body.innerHTML = `
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Order ID:</span>
                <span class="aysa-order-detail-value"><strong>#${order.id}</strong></span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Project ID:</span>
                <span class="aysa-order-detail-value">${order.project_id}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Task ID:</span>
                <span class="aysa-order-detail-value">${order.task_id}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Task Title:</span>
                <span class="aysa-order-detail-value">${order.task_title}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Target Keyword:</span>
                <span class="aysa-order-detail-value">${order.target_keyword || 'Domain Authority'}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Links Requested:</span>
                <span class="aysa-order-detail-value"><strong>${order.links_requested}</strong></span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Links Purchased:</span>
                <span class="aysa-order-detail-value"><strong>${order.links_purchased}</strong></span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Progress:</span>
                <span class="aysa-order-detail-value">
                    <div class="aysa-progress-detail">
                        <div class="aysa-progress-bar">
                            <div class="aysa-progress-fill" style="width: ${progress}%"></div>
                        </div>
                        <span>${progress}%</span>
                    </div>
                </span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Status:</span>
                <span class="aysa-order-detail-value">
                    <span class="aysa-order-status ${order.status.toLowerCase()}">${order.status.toUpperCase()}</span>
                </span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Created:</span>
                <span class="aysa-order-detail-value">${createdDate}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Last Updated:</span>
                <span class="aysa-order-detail-value">${lastUpdate}</span>
            </div>
            <div class="aysa-order-detail-row">
                <span class="aysa-order-detail-label">Last Purchase Attempt:</span>
                <span class="aysa-order-detail-value">${lastAttempt}</span>
            </div>
            ${orderDataHtml}
        `;
        
        // Show modal
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
    }
    
    // Function to close order details modal - make it global
    window.closeOrderDetailsModal = function() {
        const modal = document.getElementById('aysa-order-details-modal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = ''; // Restore scrolling
        }
    }
    
    // Function to retry failed order - make it global
    window.retryOrder = function(orderId) {
        if (!confirm('Are you sure you want to retry this order?')) {
            return;
        }
        
        console.log('[AYSA ORDERS] Retrying order:', orderId);
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_retry_link_order',
                order_id: orderId,
                nonce: '<?php echo wp_create_nonce('aysa_orders_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    showNotification('Order retry initiated successfully!', 'success');
                    loadOrders(); // Refresh the orders list
                } else {
                    showNotification('Failed to retry order: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                showNotification('Error retrying order: ' + error, 'error');
            }
        });
    }
    
    // Function to load Automated SEO data
    function loadAutomatedSeoData() {
        console.log('[AYSA] Loading Automated SEO data');
        
        // Load automated SEO reviews directly
        loadAutomatedSeoReviews();
    }
    
    // Function to load Queue Management data
    function loadQueueManagementData() {
        console.log('[AYSA] Loading Queue Management data');
        
        // Load queue statistics
        loadQueueStatistics();
    }
    
    // Function to load automation states
    function loadAutomationStates() {
        // Load automation status from backend
        loadAutomationStatus();
    }
    
    // Function to load automation statistics
    function loadAutomationStats() {
        // Mock data for now - in real implementation, load from API
        document.getElementById('da-tasks-generated').textContent = '12';
        document.getElementById('da-acceptance-rate').textContent = '85%';
    }
    
    // Function to load queue statistics (ported from automation dashboard)
    function loadQueueStatistics() {
        console.log('[AYSA AUTOMATION] Loading queue statistics...');
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_automation_status',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Queue statistics response: ' + JSON.stringify(response));
                if (response.success && response.data.queue_stats) {
                    var stats = response.data.queue_stats;
                    
                    var totalJobs = (stats.total || 0) + (stats.domain_authority_total || 0);
                    var pendingJobs = (stats.pending || 0) + (stats.domain_authority_pending || 0);
                    var completedJobs = (stats.completed || 0) + (stats.domain_authority_completed || 0);
                    var failedJobs = (stats.failed || 0) + (stats.domain_authority_failed || 0);
                    
                    jQuery('#total-queue-jobs').text(totalJobs);
                    jQuery('#pending-queue-jobs').text(pendingJobs);
                    jQuery('#completed-queue-jobs').text(completedJobs);
                    jQuery('#failed-queue-jobs').text(failedJobs);
                    
                    console.log('[AYSA AUTOMATION] Queue statistics updated - Total: ' + totalJobs + ', Pending: ' + pendingJobs + ', Completed: ' + completedJobs + ', Failed: ' + failedJobs);
                    
                    updateQueueStatistics({
                        total: totalJobs,
                        pending: pendingJobs,
                        completed: completedJobs,
                        failed: failedJobs
                    });
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load queue statistics: ' + (response.data || 'Unknown error'));
                    showQueueError('Failed to load queue statistics');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading queue statistics: ' + error + ', Status: ' + status);
                console.error('[AYSA AUTOMATION] Response text: ' + xhr.responseText);
                showQueueError('Error loading queue statistics: ' + error);
            }
        });
    }
    
    // Function to update queue statistics
    function updateQueueStatistics(stats) {
        document.getElementById('total-queue-jobs').textContent = stats.total || '--';
        document.getElementById('pending-queue-jobs').textContent = stats.pending || '--';
        document.getElementById('completed-queue-jobs').textContent = stats.completed || '--';
        document.getElementById('failed-queue-jobs').textContent = stats.failed || '--';
        
        // Update queue status
        const statusInfo = document.getElementById('queue-status-info');
        if (statusInfo) {
            statusInfo.innerHTML = `
                <div class="aysa-queue-status-good">
                    <span class="dashicons dashicons-yes-alt"></span>
                    Queue is running normally
                </div>
            `;
        }
    }
    
    // Function to show queue error
    function showQueueError(message) {
        document.getElementById('total-queue-jobs').textContent = '--';
        document.getElementById('pending-queue-jobs').textContent = '--';
        document.getElementById('completed-queue-jobs').textContent = '--';
        document.getElementById('failed-queue-jobs').textContent = '--';
        
        const statusInfo = document.getElementById('queue-status-info');
        if (statusInfo) {
            statusInfo.innerHTML = `
                <div class="aysa-queue-status-error">
                    <span class="dashicons dashicons-warning"></span>
                    ${message}
                </div>
            `;
        }
    }
    
    // Function to toggle Domain Authority automation
    function toggleDomainAuthorityAutomation(isEnabled) {
        console.log('[AYSA] Toggling Domain Authority automation:', isEnabled);
        
        // Update all toggles using the centralized function
        updateAllToggles('domain_authority_automation', isEnabled);
        
        // Show notification
        showNotification(
            `Domain Authority automation ${isEnabled ? 'enabled' : 'disabled'}`, 
            isEnabled ? 'success' : 'info'
        );
        
        // Send to backend to persist setting
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_toggle_automation',
                feature: 'domain_authority_automation',
                enabled: isEnabled,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Automation toggle saved:', response);
                if (response.success) {
                    // Update the status card too
                    const $card = jQuery('#aysa-domain-authority-status');
                    const $dot = $card.find('.status-dot');
                    const $text = $card.find('.status-text');
                    
                    if (response.data.enabled) {
                        $dot.attr('data-status', 'enabled');
                        $text.text('Enabled');
                    } else {
                        $dot.attr('data-status', 'disabled');
                        $text.text('Disabled');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] Error saving automation toggle:', error);
                showNotification('Error saving automation setting: ' + error, 'error');
            }
        });
    }
    
    // Function to process queue now (ported from automation dashboard)
    function processQueueNow() {
        console.log('[AYSA] Processing queue now');
        
        const button = document.getElementById('process-queue-now');
        if (button) {
            button.disabled = true;
            button.innerHTML = '<span class="dashicons dashicons-update aysa-spinning"></span> Processing...';
        }
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_process_automation_queue',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Process queue response:', response);
                if (response.success) {
                    showNotification('Queue processing initiated successfully!', 'success');
                    if (response.data && response.data.message) {
                        showNotification(response.data.message, 'info');
                    }
                    // Refresh statistics after processing
                    setTimeout(() => {
                        loadQueueStatistics();
                    }, 2000);
                } else {
                    showNotification('Failed to process queue: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] Process queue error:', error);
                showNotification('Error processing queue: ' + error, 'error');
            },
            complete: function() {
                if (button) {
                    button.disabled = false;
                    button.innerHTML = '<span class="dashicons dashicons-controls-play"></span> Process Queue Now';
                }
            }
        });
    }
    
    // Port automation functions from automation dashboard
    function loadAutomationStatus() {
        console.log('[AYSA AUTOMATION] Loading automation status...');
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_automation_status',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Status response received: ' + JSON.stringify(response));
                if (response.success) {
                    var config = response.data.config;
                    console.log('[AYSA AUTOMATION] Processing config with ' + Object.keys(config).length + ' features');
                    
                    Object.keys(config).forEach(function(feature) {
                        var cardId;
                        if (feature === 'domain_authority_automation') {
                            cardId = '#aysa-domain-authority-status';
                        } else {
                            cardId = '#aysa-' + feature.replace('_', '-') + '-status';
                        }
                        var $card = jQuery(cardId);
                        var $dot = $card.find('.status-dot');
                        var $text = $card.find('.status-text');
                        
                        console.log('[AYSA AUTOMATION] Updating feature: ' + feature + ', card: ' + cardId + ', enabled: ' + config[feature]);
                        
                        if (config[feature]) {
                            $dot.attr('data-status', 'enabled');
                            $text.text('Enabled');
                        } else {
                            $dot.attr('data-status', 'disabled');
                            $text.text('Disabled');
                        }
                        
                        // Update all related toggles
                        updateAllToggles(feature, config[feature]);
                    });
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load automation status: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading status: ' + error + ', Status: ' + status);
                console.error('[AYSA AUTOMATION] Response text: ' + xhr.responseText);
            }
        });
    }
    
    function loadAutomatedSeoReviews() {
        console.log('[AYSA AUTOMATION] Loading automated SEO reviews');
        jQuery('#automated-seo-review-list').html('<p>Loading pending automated SEO reviews...</p>');
        
        // Load dotnet reviews - same as in automation dashboard
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_dotnet_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] .NET Core task reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderAutomatedSeoReviews(response.data);
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load .NET Core task reviews: ' + (response.data || 'Unknown error'));
                    jQuery('#automated-seo-review-list').html('<p>No pending automated SEO reviews at this time.</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading .NET Core task reviews: ' + error + ', Status: ' + status);
                jQuery('#automated-seo-review-list').html('<p>Error loading automated SEO reviews. Please try again.</p>');
            }
        });
    }
    
    function renderAutomatedSeoReviews(reviews) {
        console.log('[AYSA AUTOMATION] Rendering automated SEO reviews:', reviews);
        
        if (!reviews || reviews.length === 0) {
            jQuery('#automated-seo-review-list').html('<p>No pending automated SEO reviews at this time.</p>');
            return;
        }
        
        var html = '';
        reviews.forEach(function(review) {
            html += `
                <div class="automated-seo-review" style="padding: 15px; margin-bottom: 15px; background: #f9f9f9; border-radius: 4px;">
                    <div class="review-header">
                        <h4>${review.title || 'Automated SEO Task'}</h4>
                        <small>ID: ${review.id || 'N/A'}</small>
                    </div>
                    <p><strong>Description:</strong> ${review.description || 'No description available'}</p>
                    <p><strong>Confidence:</strong> ${review.confidence || 'N/A'}%</p>
                    <p><strong>Created:</strong> ${review.created_at || 'N/A'}</p>
                    <div class="review-actions">
                        <button class="button button-primary" onclick="approveAutomatedSeoReview(${review.id})">Approve</button>
                        <button class="button" onclick="rejectAutomatedSeoReview(${review.id})">Reject</button>
                    </div>
                </div>
            `;
        });
        
                jQuery('#automated-seo-review-list').html(html);
    }
    
    // Global functions for automated SEO review actions
    window.approveAutomatedSeoReview = function(reviewId) {
        console.log('[AYSA AUTOMATION] Approving automated SEO review:', reviewId);
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_approve_automated_seo_review',
                review_id: reviewId,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Approve response:', response);
                if (response.success) {
                    showNotification('Automated SEO review approved successfully!', 'success');
                    loadAutomatedSeoReviews(); // Reload reviews
                } else {
                    showNotification('Failed to approve review: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] Error approving review:', error);
                showNotification('Error approving review: ' + error, 'error');
            }
        });
    }
    
    window.rejectAutomatedSeoReview = function(reviewId) {
        console.log('[AYSA AUTOMATION] Rejecting automated SEO review:', reviewId);
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_reject_automated_seo_review',
                review_id: reviewId,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Reject response:', response);
                if (response.success) {
                    showNotification('Automated SEO review rejected.', 'info');
                    loadAutomatedSeoReviews(); // Reload reviews
                } else {
                    showNotification('Failed to reject review: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] Error rejecting review:', error);
                showNotification('Error rejecting review: ' + error, 'error');
            }
        });
    }

    function updateAllToggles(feature, enabled) {
        if (feature === 'domain_authority_automation') {
            // Update all domain authority toggles
            const toggles = [
                { toggle: 'da-automation-toggle', status: 'da-automation-status' },
                { toggle: 'domain-authority-automation-toggle', status: 'domain-authority-status-text' },
                { toggle: 'settings-domain-authority-toggle', status: 'settings-domain-authority-status' }
            ];
            
            toggles.forEach(function(item) {
                const toggle = document.getElementById(item.toggle);
                const status = document.getElementById(item.status);
                if (toggle) toggle.checked = enabled;
                if (status) status.textContent = enabled ? 'Enabled' : 'Disabled';
            });
            
            // Update localStorage
            localStorage.setItem('aysa_domain_authority_automation', enabled.toString());
        }
    }

    // Function to show notifications - DISABLED
    function showNotification(message, type = 'info') {
        // All notifications disabled - only console log for debugging
        console.log(`[AYSA NOTIFICATION] ${type.toUpperCase()}: ${message}`);
        
        // Original notification code disabled:
        // const notification = document.createElement('div');
        // notification.className = `aysa-notification aysa-notification-${type}`;
        // 
        // // Add icon based on type
        // let iconClass = '';
        // switch(type) {
        //     case 'success':
        //         iconClass = 'dashicons-yes';
        //         break;
        //     case 'error':
        //         iconClass = 'dashicons-no';
        //         break;
        //     case 'loading':
        //         iconClass = 'dashicons-update aysa-spinning';
        //         break;
        //     default:
        //         iconClass = 'dashicons-info';
        // }
        // 
        // notification.innerHTML = `
        //     <span class="dashicons ${iconClass}"></span>
        //     <span>${message}</span>
        // `;
        // 
        // // Add to page
        // document.body.appendChild(notification);
        // 
        // // Remove after 3 seconds with fade out animation
        // setTimeout(() => {
        //     notification.classList.add('fade-out');
        //     setTimeout(() => {
        //         notification.remove();
        //     }, 600);
        // }, 3000);
    }

    // Function to reject a domain authority review
    function rejectDomainAuthorityReview(projectId) {
        if (!confirm('Are you sure you want to reject this domain authority task?')) {
            return;
        }
        
        console.log('[AYSA] Rejecting domain authority review for project:', projectId);
        
        // Find the button and review item
        const button = document.querySelector(`[data-project-id="${projectId}"].reject-domain-authority`);
        const reviewItem = button.closest('.aysa-review-item');
        const approveButton = reviewItem.querySelector('.approve-domain-authority');
        
        // Add loading state to button
        button.disabled = true;
        button.classList.add('button-loading');
        approveButton.disabled = true;
        
        // Change button text and hide it during loading
        const originalText = button.innerHTML;
        button.style.color = 'transparent';
        
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_reject_domain_authority_review', 
                project_id: projectId,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Reject response:', response);
                if (response.success) {
                    // Add fade out animation to review item
                    reviewItem.classList.add('review-item-removing');
                    
                    // Show success message
                    showNotification('❌ Task rejected and removed from queue!', 'success');
                    
                    // Remove review item after animation
                    setTimeout(() => {
                        reviewItem.remove();
                        
                        // Check if there are any remaining reviews
                        const remainingReviews = document.querySelectorAll('.aysa-review-item');
                        if (remainingReviews.length === 0) {
                            document.getElementById('domain-authority-pending-reviews').innerHTML = 
                                '<p style="color: #666; text-align: center; padding: 20px; font-style: italic;">No pending reviews at this time. Tasks with high confidence scores are automatically approved.</p>';
                        }
                    }, 300); // Reduced from 500ms to 300ms for faster response
                } else {
                    // Reset button state on error
                    button.disabled = false;
                    button.classList.remove('button-loading');
                    button.style.color = '';
                    approveButton.disabled = false;
                    
                    showNotification('Failed to reject review: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] AJAX error rejecting review:', error);
                
                // Reset button state on error
                button.disabled = false;
                button.classList.remove('button-loading');
                button.style.color = '';
                approveButton.disabled = false;
                
                showNotification('Error rejecting review: ' + error, 'error');
            }
        });
    }
    
    // Function to generate a real review through automation simulation
    function generateRealReview() {
        const projectId = getProjectId();
        if (!projectId) {
            alert('No project ID found. Please ensure you have an active project.');
            return;
        }
        
        console.log('[AYSA] Generating real review through automation simulation...');
        
        // Show loading state
        if (typeof showNotification === 'function') {
            showNotification('Running automation analysis... This will generate a real domain authority task.', 'info');
        }
        
        // Simulate the automation process by calling the domain authority processor
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_simulate_domain_authority_task',
                project_id: projectId,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA] Simulation response:', response);
                if (response.success) {
                    if (response.data.queued_for_review) {
                        // Task was queued for review - reload reviews
                        loadDomainAuthorityReviews();
                        if (typeof showNotification === 'function') {
                            showNotification('Domain authority task generated and queued for review due to low confidence score!', 'success');
                        }
                    } else {
                        // Task was auto-approved - refresh task list
                        if (typeof fetchAndInjectDomainAuthorityTasks === 'function') {
                            fetchAndInjectDomainAuthorityTasks();
                        }
                        if (typeof showNotification === 'function') {
                            showNotification('Domain authority task generated and auto-approved due to high confidence score!', 'success');
                        }
                    }
                } else {
                    console.error('[AYSA] Failed to generate review:', response.data);
                    if (typeof showNotification === 'function') {
                        showNotification('Failed to generate task: ' + (response.data || 'Unknown error'), 'error');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA] AJAX error generating review:', error);
                if (typeof showNotification === 'function') {
                    showNotification('Error generating task: ' + error, 'error');
                }
            }
        });
    }
    
    // Function to load automation content (now Settings tab)
    function loadAutomationContent() {
        console.log('[AYSA] Loading automation settings content');
        
        // Load automation status and settings
        loadAutomationStatus();
        loadSettingsStats();
    }
    
    function loadSettingsStats() {
        // Load stats for settings tab
        console.log('[AYSA] Loading settings stats');
        
        const settingsStatsElements = [
            'settings-da-tasks-generated',
            'settings-da-acceptance-rate'
        ];
        
        settingsStatsElements.forEach(function(elementId) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = '--';
            }
        });
        
        // Mock data for now - in real implementation, load from API
        setTimeout(function() {
            const generated = document.getElementById('settings-da-tasks-generated');
            const acceptance = document.getElementById('settings-da-acceptance-rate');
            if (generated) generated.textContent = '12';
            if (acceptance) acceptance.textContent = '85%';
        }, 500);
    }
    // Create task detail modal if it doesn't exist
    if (document.getElementById('aysa-task-detail-modal') === null) {
        const detailModalHtml = `
        <div id="aysa-task-detail-modal" class="aysa-modal" style="display:none;">
            <div class="aysa-modal-content" style="max-width:600px;max-height:85vh;">
                <div class="aysa-modal-header" style="background:#2563eb;color:white;">
                    <h3 style="color:white;">Task Details</h3>
                    <button class="aysa-modal-close-detail" style="color:white;background:none;border:none;font-size:24px;float:right;">&times;</button>
                </div>
                <div class="aysa-modal-body" style="padding:24px;max-height:calc(85vh - 140px);overflow-y:auto;">
                    <div class="aysa-detail-group" style="margin-bottom:16px;">
                        <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Title:</label>
                        <p id="task-detail-title" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
                    </div>
                    <div class="aysa-detail-group" style="margin-bottom:16px;">
                        <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Description:</label>
                        <p id="task-detail-description" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;min-height:60px;"></p>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;">
                        <div class="aysa-detail-group">
                            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Type:</label>
                            <p id="task-detail-type" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
                        </div>
                        <div class="aysa-detail-group">
                            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Status:</label>
                            <p id="task-detail-status" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid #e2e8f0;"></p>
                        </div>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                        <div class="aysa-detail-group">
                            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Created:</label>
                            <p id="task-detail-created" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid:#e2e8f0;font-size:12px;"></p>
                        </div>
                        <div class="aysa-detail-group">
                            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Updated:</label>
                            <p id="task-detail-updated" style="margin:0;color:#475569;background:#f8fafc;padding:8px 12px;border-radius:4px;border:1px solid:#e2e8f0;font-size:12px;"></p>
                        </div>
                    </div>
                    
                    <!-- Link Purchase Section (only for domain authority tasks) -->
                    <div id="aysa-link-purchase-section" style="display:none;margin-top:20px;padding:16px;background:#f0f9ff;border:1px solid #0ea5e9;border-radius:8px;">
                        <h4 style="margin:0 0 12px 0;color:#0369a1;font-size:16px;">🛒 Purchase Links for Domain Authority</h4>
                        <div style="margin-bottom:12px;">
                            <label style="font-weight:600;color:#334155;display:block;margin-bottom:4px;">Number of links to purchase:</label>
                            <div style="display:flex;align-items:center;gap:12px;margin-bottom:8px;">
                            <input type="number" id="aysa-links-quantity" min="1" max="100" value="1" style="width:100px;padding:6px 8px;border:1px solid #cbd5e1;border-radius:4px;">
                                <div id="aysa-price-display" style="background:#e6f7ea;color:#0f7729;padding:6px 12px;border-radius:6px;font-weight:600;font-size:14px;border:1px solid #a7f3d0;">
                                    💰 <span id="aysa-price-amount">10</span> credits
                                </div>
                            </div>
                            <span style="font-size:12px;color:#64748b;">Links will be purchased automatically over time</span>
                        </div>
                        <div id="aysa-purchase-status" style="margin-bottom:12px;font-size:14px;color:#374151;"></div>
                        <div style="display:flex;gap:8px;">
                            <button id="aysa-save-purchase-request" style="background:#10b981;color:white;border:none;border-radius:6px;padding:8px 16px;font-weight:500;cursor:pointer;">Save Purchase Request</button>
                            <button id="aysa-refresh-purchase-status" style="background:#6b7280;color:white;border:none;border-radius:6px;padding:8px 16px;font-weight:500;cursor:pointer;">Refresh Status</button>
                        </div>
                    </div>
                </div>
                <div class="aysa-modal-footer" style="padding:16px;text-align:right;">
                    <button id="aysa-task-detail-close" class="aysa-button-secondary">Close</button>
                </div>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', detailModalHtml);
        
        // Add modal event listeners
        const modal = document.getElementById('aysa-task-detail-modal');
        const closeBtn = modal.querySelector('.aysa-modal-close-detail');
        const footerCloseBtn = document.getElementById('aysa-task-detail-close');
        
        closeBtn.addEventListener('click', () => modal.style.display = 'none');
        footerCloseBtn.addEventListener('click', () => modal.style.display = 'none');
        
        // Close modal when clicking outside
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
        
        // Add event listeners for link purchase functionality
        document.addEventListener('click', function(e) {
            if (e.target && e.target.id === 'aysa-save-purchase-request') {
                saveLinkPurchaseRequest();
            }
            
            if (e.target && e.target.id === 'aysa-refresh-purchase-status') {
                const linkPurchaseSection = document.getElementById('aysa-link-purchase-section');
                if (linkPurchaseSection && linkPurchaseSection.dataset.taskId) {
                    // Check if there's an insufficient credits error before refreshing
                    const statusDiv = document.getElementById('aysa-purchase-status');
                    const hasInsufficientCreditsError = statusDiv && statusDiv.innerHTML.includes('You\'ve used all the credits included in your subscription');
                    
                    if (hasInsufficientCreditsError) {
                        console.log('[AYSA CREDITS] Blocked manual refresh due to insufficient credits error');
                        return; // Don't refresh if there's an insufficient credits error
                    }
                    
                    // Manual refresh - allow auto-completion if conditions are met
                    loadLinkPurchaseStatus(linkPurchaseSection.dataset.taskId, false, false);
                }
            }
            });
        
        // Add event listener for quantity input to update price
        document.addEventListener('input', function(e) {
            if (e.target && e.target.id === 'aysa-links-quantity') {
                updatePriceDisplay();
                autoCheckCredits();
            }
        });
        
        // Also listen for change event (when user uses up/down arrows)
        document.addEventListener('change', function(e) {
            if (e.target && e.target.id === 'aysa-links-quantity') {
                updatePriceDisplay();
                autoCheckCredits();
            }
        });
    }
    
    // Banned Keywords Tab Functionality
    let bannedKeywordsCurrentPage = 1;
    let bannedKeywordsPerPage = 20;
    let bannedKeywordsTotal = 0;
    
    // Initialize banned keywords tab when it becomes active
    document.addEventListener('click', function(e) {
        if (e.target.matches('[data-tab="banned-keywords"]')) {
            loadBannedKeywords();
        }
    });
    
    // Load banned keywords
    function loadBannedKeywords(page = 1) {
        bannedKeywordsCurrentPage = page;
        const tbody = document.getElementById('aysa-banned-keywords-tbody');
        
        // Show loading state
        tbody.innerHTML = `
            <tr class="aysa-loading-row">
                <td colspan="5" class="aysa-loading-cell">
                    <div class="aysa-loading-container">
                        <span class="dashicons dashicons-update aysa-spinning"></span>
                        <span class="aysa-loading-text">Loading banned keywords...</span>
                    </div>
                </td>
            </tr>
        `;
        
        // Calculate offset
        const offset = (page - 1) * bannedKeywordsPerPage;
        
        // Make AJAX request
        jQuery.ajax({
            url: ajaxurl,
            type: 'GET',
            data: {
                action: 'aysa_get_banned_keywords',
                project_id: getProjectId() || 0,
                limit: bannedKeywordsPerPage,
                offset: offset,
                nonce: '<?php echo wp_create_nonce('aysa_banned_keywords_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    displayBannedKeywords(response.data.keywords);
                    updateBannedKeywordsPagination(response.data.total);
                } else {
                    showBannedKeywordsError(response.data || 'Failed to load deleted keywords');
                }
            },
            error: function(xhr, status, error) {
                console.error('Load deleted keywords error:', error);
                showBannedKeywordsError('Error loading deleted keywords: ' + error);
            }
        });
    }
    
    // Display banned keywords in table
    function displayBannedKeywords(keywords) {
        const tbody = document.getElementById('aysa-banned-keywords-tbody');
        
        if (!keywords || keywords.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="aysa-empty-state">
                        <div class="dashicons dashicons-warning"></div>
                                                                <h4>No deleted keywords found</h4>
                                        <p>You haven't deleted any keywords yet. Deleted keywords will appear here when you delete them from keyword discovery.</p>
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = keywords.map(keyword => {
            const bannedDate = new Date(keyword.created_at).toLocaleDateString();
            const bannedBy = keyword.banned_by_name || 'Unknown';
            const reason = keyword.banned_reason || 'No reason provided';
            
            return `
                <tr data-keyword-id="${keyword.id}">
                    <td class="aysa-keyword-col">
                        <span class="aysa-banned-keyword-text">${keyword.keyword}</span>
                    </td>
                    <td class="aysa-banned-by-col">
                        <span class="aysa-banned-by-name">${bannedBy}</span>
                    </td>
                    <td class="aysa-banned-date-col">
                        <span class="aysa-banned-date">${bannedDate}</span>
                    </td>
                    <td class="aysa-banned-reason-col">
                        <span class="aysa-banned-reason">${reason}</span>
                    </td>
                    <td class="aysa-banned-actions-col">
                                                                <button class="aysa-unban-btn" data-keyword="${keyword.keyword}" title="Restore this keyword">
                                            Restore
                                        </button>
                    </td>
                </tr>
            `;
        }).join('');
        
        // Add unban event listeners
        tbody.querySelectorAll('.aysa-unban-btn').forEach(btn => {
            btn.addEventListener('click', handleUnbanKeyword);
        });
    }
    
    // Handle unban keyword
    function handleUnbanKeyword(e) {
        const btn = e.target;
        const keyword = btn.dataset.keyword;
        const row = btn.closest('tr');
        
        if (!confirm(`Are you sure you want to restore the keyword "${keyword}"?\n\nThis will allow it to appear in keyword discovery again.`)) {
            return;
        }
        
        // Disable button and show loading
        btn.disabled = true;
        btn.textContent = 'Restoring...';
        
        // Make AJAX request
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_unban_keyword',
                keyword: keyword,
                project_id: getProjectId() || 0,
                nonce: '<?php echo wp_create_nonce('aysa_banned_keywords_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    showNotification(`Keyword "${keyword}" has been restored successfully`, 'success');
                    
                    // Update cache if it exists (for keyword discovery page)
                    if (window.bannedKeywordsCache) {
                        const index = window.bannedKeywordsCache.indexOf(keyword.toLowerCase().trim());
                        if (index > -1) {
                            window.bannedKeywordsCache.splice(index, 1);
                        }
                    }
                    
                    // Remove row with animation
                    row.style.transition = 'opacity 0.3s ease';
                    row.style.opacity = '0';
                    setTimeout(() => {
                        loadBannedKeywords(bannedKeywordsCurrentPage); // Reload current page
                    }, 300);
                } else {
                    showNotification(response.data || 'Failed to restore keyword', 'error');
                    
                    // Restore button state
                    btn.disabled = false;
                    btn.textContent = 'Restore';
                }
            },
            error: function(xhr, status, error) {
                console.error('Restore keyword error:', error);
                showNotification('Error restoring keyword: ' + error, 'error');
                
                // Restore button state
                btn.disabled = false;
                btn.textContent = 'Restore';
            }
        });
    }
    
    // Update pagination
    function updateBannedKeywordsPagination(total) {
        bannedKeywordsTotal = total;
        const totalPages = Math.ceil(total / bannedKeywordsPerPage);
        
        // Update count
        document.getElementById('aysa-banned-keywords-count').textContent = 
            `${total} banned keyword${total !== 1 ? 's' : ''}`;
        
        // Update pagination buttons
        const prevBtn = document.getElementById('aysa-banned-prev-btn');
        const nextBtn = document.getElementById('aysa-banned-next-btn');
        
        prevBtn.disabled = bannedKeywordsCurrentPage <= 1;
        nextBtn.disabled = bannedKeywordsCurrentPage >= totalPages;
        
        // Update page numbers
        const pageNumbers = document.getElementById('aysa-banned-page-numbers');
        pageNumbers.innerHTML = generatePageNumbers(bannedKeywordsCurrentPage, totalPages);
        
        // Add click handlers to page numbers
        pageNumbers.querySelectorAll('.aysa-page-number').forEach(pageBtn => {
            pageBtn.addEventListener('click', function() {
                const page = parseInt(this.textContent);
                if (page !== bannedKeywordsCurrentPage) {
                    loadBannedKeywords(page);
                }
            });
        });
    }
    
    // Generate page numbers HTML
    function generatePageNumbers(currentPage, totalPages) {
        let pages = [];
        const maxVisible = 5;
        
        if (totalPages <= maxVisible) {
            for (let i = 1; i <= totalPages; i++) {
                pages.push(i);
            }
        } else {
            pages.push(1);
            if (currentPage > 3) pages.push('...');
            
            const start = Math.max(2, currentPage - 1);
            const end = Math.min(totalPages - 1, currentPage + 1);
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            
            if (currentPage < totalPages - 2) pages.push('...');
            pages.push(totalPages);
        }
        
        return pages.map(page => {
            if (page === '...') {
                return '<span class="aysa-page-ellipsis">...</span>';
            }
            const isActive = page === currentPage ? ' active' : '';
            return `<span class="aysa-page-number${isActive}">${page}</span>`;
        }).join('');
    }
    
    // Show error in banned keywords table
    function showBannedKeywordsError(message) {
        const tbody = document.getElementById('aysa-banned-keywords-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="5" class="aysa-empty-state">
                    <div class="dashicons dashicons-warning" style="color: #dc3545;"></div>
                    <h4>Error loading banned keywords</h4>
                    <p>${message}</p>
                </td>
            </tr>
        `;
    }
    
    // Refresh button handler
    document.getElementById('aysa-refresh-banned-keywords').addEventListener('click', function() {
        loadBannedKeywords(bannedKeywordsCurrentPage);
    });
    
    // Search functionality
    let searchTimeout;
    document.getElementById('aysa-banned-keywords-search').addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            // TODO: Implement search functionality
            console.log('Search:', this.value);
        }, 500);
    });
    
    // Pagination handlers
    document.getElementById('aysa-banned-prev-btn').addEventListener('click', function() {
        if (bannedKeywordsCurrentPage > 1) {
            loadBannedKeywords(bannedKeywordsCurrentPage - 1);
        }
    });
    
    document.getElementById('aysa-banned-next-btn').addEventListener('click', function() {
        const totalPages = Math.ceil(bannedKeywordsTotal / bannedKeywordsPerPage);
        if (bannedKeywordsCurrentPage < totalPages) {
            loadBannedKeywords(bannedKeywordsCurrentPage + 1);
        }
    });
    
    // Auto-activate banned keywords tab if user came from keyword discovery
    // This runs at the end to ensure all functions are available
    function activateBannedKeywordsTab() {
        const tabButtons = document.querySelectorAll('.aysa-tab-btn');
        const tabPanes = document.querySelectorAll('.aysa-tab-pane');
        const bannedKeywordsTab = document.querySelector('[data-tab="banned-keywords"]');
        
        if (bannedKeywordsTab) {
            // Remove active class from all tabs
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // Activate banned keywords tab
            bannedKeywordsTab.classList.add('active');
            const targetPane = document.getElementById('banned-keywords-tab');
            if (targetPane) {
                targetPane.classList.add('active');
            }
            
            // Load banned keywords data
            loadBannedKeywords();
        }
    }
    
    // Check localStorage for auto-activation (URL parameters are handled above)
    setTimeout(function() {
        if (typeof(Storage) !== "undefined") {
            const autoActivateTab = localStorage.getItem('aysa_auto_activate_tab');
            if (autoActivateTab === 'banned-keywords') {
                activateBannedKeywordsTab();
                localStorage.removeItem('aysa_auto_activate_tab');
            }
        }
        
        // Also check URL hash as fallback
        if (window.location.hash === '#banned-keywords') {
            activateBannedKeywordsTab();
        }
    }, 500); // Wait for all initialization to complete
});
</script>                                                                                
