<?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 (!defined('WPINC')) {
    die;
}

?>

<style>
.task-type {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: bold;
    text-transform: uppercase;
    margin-left: 10px;
}

.task-type.automated {
    background-color: #e3f2fd;
    color: #1976d2;
    border: 1px solid #bbdefb;
}

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

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

.progress-bar {
    background-color: #f0f0f0;
    border-radius: 4px;
    height: 8px;
    overflow: hidden;
    margin: 5px 0;
}

.progress-fill {
    background-color: #007cba;
    height: 100%;
    transition: width 0.3s ease;
}

.progress-text {
    font-size: 12px;
    color: #666;
    margin-left: 5px;
}

.backend-task-item {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 10px;
    background: #fff;
}

.review-item {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 10px;
    background: #fff;
}

.domain-authority-review {
    border-left: 4px solid #007cba;
}

.dotnet-task-review {
    border-left: 4px solid #00a32a;
}
</style>

<div class="wrap">
    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
    
    <div class="aysa-automation-dashboard">
        

                        <p class="description">This will manually trigger the SEO generation cron and show results.</p>
                    </td>
                </tr>
                <!-- COMMENTED OUT: Test functions without backend implementation -->
                <!-- 
                <tr>
                    <th scope="row">Test Timeout</th>
                    <td>
                        <button type="button" class="button button-secondary" id="test-timeout-handling">
                            ⏱️ Test Timeout Handling
                        </button>
                        <p class="description">Test the timeout configuration for different API types.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Performance Stats</th>
                    <td>
                        <button type="button" class="button button-secondary" id="get-performance-stats">
                            📊 Get Performance Stats
                        </button>
                        <p class="description">View performance statistics for job processing.</p>
                    </td>
                </tr>
                -->
            </table>
            
            <div id="test-results" style="margin-top: 20px;"></div>
        </div>
        
        <!-- Automation Status Overview -->
        <div class="aysa-automation-status">
            <h2>Automation Status</h2>
            <div class="aysa-status-cards">
                <!-- COMMENTED OUT: These automation features are not fully implemented -->
                <!-- 
                <div class="aysa-status-card" id="aysa-image-status">
                    <h3>Image Optimization</h3>
                    <div class="status-indicator">
                        <span class="status-dot" data-status="disabled"></span>
                        <span class="status-text">Disabled</span>
                    </div>
                    <button class="button toggle-automation" data-feature="image_optimization">Toggle</button>
                </div>
                
                <div class="aysa-status-card" id="aysa-redirect-status">
                    <h3>Redirect Creation</h3>
                    <div class="status-indicator">
                        <span class="status-dot" data-status="disabled"></span>
                        <span class="status-text">Disabled</span>
                    </div>
                    <button class="button toggle-automation" data-feature="redirect_creation">Toggle</button>
                </div>
                
                <div class="aysa-status-card" id="aysa-meta-status">
                    <h3>Meta Generation</h3>
                    <div class="status-indicator">
                        <span class="status-dot" data-status="disabled"></span>
                        <span class="status-text">Disabled</span>
                    </div>
                    <button class="button toggle-automation" data-feature="meta_generation">Toggle</button>
                </div>
                
                <div class="aysa-status-card" id="aysa-keyword-status">
                    <h3>Keyword Assignment</h3>
                    <div class="status-indicator">
                        <span class="status-dot" data-status="disabled"></span>
                        <span class="status-text">Disabled</span>
                    </div>
                    <button class="button toggle-automation" data-feature="keyword_assignment">Toggle</button>
                </div>
                -->
                
                <div class="aysa-status-card" id="aysa-domain-authority-status">
                    <h3>Domain Authority Tasks</h3>
                    <div class="status-indicator">
                        <span class="status-dot" data-status="disabled"></span>
                        <span class="status-text">Disabled</span>
                    </div>
                    <button class="button toggle-automation" data-feature="domain_authority_automation">Toggle</button>
                </div>
            </div>
        </div>
        
        <!-- Queue Statistics -->
        <div class="aysa-queue-stats">
            <h2>Queue Statistics (Last 24 Hours)</h2>
            <div class="aysa-stats-grid">
                <div class="stat-item">
                    <span class="stat-number" id="total-jobs">0</span>
                    <span class="stat-label">Total Jobs</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number" id="pending-jobs">0</span>
                    <span class="stat-label">Pending</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number" id="completed-jobs">0</span>
                    <span class="stat-label">Completed</span>
                </div>
                <div class="stat-item">
                    <span class="stat-number" id="failed-jobs">0</span>
                    <span class="stat-label">Failed</span>
                </div>
            </div>
            <button class="button button-primary" id="process-queue">Process Queue Now</button>
        </div>
        
        <!-- Pending Reviews -->
        <div class="aysa-pending-reviews">
            <h2>Pending Reviews</h2>
            
            <!-- COMMENTED OUT: Bulk Actions - Complex implementation with timeout issues -->
            <!-- 
            <div class="aysa-bulk-actions" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 4px;">
                <h3 style="margin: 0 0 10px 0; font-size: 16px;">Bulk Actions</h3>
                <div style="display: flex; gap: 10px; align-items: center;">
                    <button class="button button-primary" id="approve-all-reviews" style="background: #46b450; border-color: #46b450;">
                        <span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>
                        Approve All Pending Reviews
                    </button>
                    <span id="bulk-status" style="font-size: 12px; color: #666;"></span>
                </div>
            </div>
            -->
            
            <div class="aysa-review-tabs">
                <!-- COMMENTED OUT: No real data for these review types -->
                <!-- <button class="review-tab" data-tab="images">Images</button> -->
                <!-- <button class="review-tab" data-tab="redirects">Redirects</button> -->
                <!-- <button class="review-tab" data-tab="meta">Meta Tags</button> -->
                <!-- <button class="review-tab" data-tab="keywords">Keywords</button> -->
                <!-- <button class="review-tab" data-tab="domain-authority">Domain Authority</button> -->
                <button class="review-tab active" data-tab="automated-seo">Automated SEO</button>
            </div>
            
            <!-- COMMENTED OUT: Non-functional review sections -->
            <!-- 
            <div class="review-content" id="images-reviews">
                <div class="review-list" id="image-review-list">
                    <p>Loading pending image reviews...</p>
                </div>
            </div>
            
            <div class="review-content" id="redirects-reviews" style="display: none;">
                <div class="review-list" id="redirect-review-list">
                    <p>Loading pending redirect reviews...</p>
                </div>
            </div>
            
            <div class="review-content" id="meta-reviews" style="display: none;">
                <div class="review-list" id="meta-review-list">
                    <p>Loading pending meta reviews...</p>
                </div>
            </div>
            
            <div class="review-content" id="keywords-reviews" style="display: none;">
                <div class="review-list" id="keyword-review-list">
                    <p>Loading pending keyword reviews...</p>
                </div>
            </div>
            -->
            
            <!-- MOVED TO Domain Authority Tasks in Adjustment & Improvement -->
            <!-- 
            <div class="review-content" id="domain-authority-reviews">
                <div class="review-list" id="domain-authority-review-list">
                    <p>Loading pending domain authority reviews...</p>
                </div>
            </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>
        
        <!-- Active Tasks from Backend - COMMENTED OUT: No backend implementation -->
        <!-- 
        <div class="aysa-backend-tasks">
            <h2>Active Tasks</h2>
            <div class="backend-tasks-list" id="backend-tasks-list">
                <p>Loading tasks from backend...</p>
            </div>
        </div>

        <div class="aysa-task-history">
            <h2>Task History</h2>
            <div class="task-history-controls">
                <button class="button" id="refresh-history">Refresh History</button>
                <select id="history-filter">
                    <option value="all">All Completed</option>
                    <option value="today">Today</option>
                    <option value="week">This Week</option>
                    <option value="month">This Month</option>
                </select>
            </div>
            <div class="task-history-list" id="task-history-list">
                <p>Loading completed tasks...</p>
            </div>
        </div>

        <div class="aysa-scheduled-tasks">
            <h2>Scheduled Tasks</h2>
            <div class="scheduled-tasks-list" id="scheduled-tasks-list">
                <p>Loading scheduled tasks...</p>
            </div>
        </div>
        -->
        

    </div>
</div>

<style>
.aysa-automation-dashboard {
    max-width: 1200px;
}

.aysa-automation-dashboard h2 {
    margin-top: 30px;
    margin-bottom: 15px;
}

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

.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-status-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.aysa-status-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    text-align: center;
}

.aysa-status-card h3 {
    margin: 0 0 15px 0;
    font-size: 16px;
}

.status-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
}

.status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 8px;
}

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

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

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

.stat-item {
    text-align: center;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 4px;
}

.stat-number {
    display: block;
    font-size: 32px;
    font-weight: bold;
    color: #0073aa;
}

.stat-label {
    display: block;
    font-size: 14px;
    color: #666;
    margin-top: 5px;
}

.aysa-review-tabs {
    margin-bottom: 20px;
}

.review-tab {
    background: #f1f1f1;
    border: 1px solid #ccd0d4;
    padding: 10px 20px;
    margin-right: 5px;
    cursor: pointer;
}

.review-tab.active {
    background: #0073aa;
    color: white;
}

.review-content {
    background: #fff;
    border: 1px solid #ccd0d4;
    padding: 20px;
    min-height: 200px;
}

.review-item {
    border-bottom: 1px solid #eee;
    padding: 15px 0;
}

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

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

.review-actions .button {
    margin-right: 10px;
}

.scheduled-task {
    background: #f9f9f9;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 10px;
    border-radius: 4px;
}

.task-status {
    font-weight: bold;
}

.task-status.enabled {
    color: #46b450;
}

.task-status.disabled {
    color: #dc3232;
}

.aysa-backend-tasks, .aysa-task-history {
    margin-top: 30px;
}

.task-history-controls {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    align-items: center;
}

.backend-task-item, .history-task-item {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.task-info h4 {
    margin: 0 0 5px 0;
    font-size: 16px;
}

.task-info p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.task-meta {
    text-align: right;
    font-size: 12px;
    color: #999;
}

.task-status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 3px;
    font-size: 11px;
    font-weight: bold;
    text-transform: uppercase;
}

.task-status-badge.in-progress {
    background: #fff3cd;
    color: #856404;
}

.task-status-badge.done {
    background: #d4edda;
    color: #155724;
}

.task-status-badge.deleted {
    background: #f8d7da;
    color: #721c24;
}

.task-progress {
    width: 100%;
    height: 6px;
    background: #f0f0f0;
    border-radius: 3px;
    margin: 8px 0;
    overflow: hidden;
}

.task-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #4CAF50, #45a049);
    transition: width 0.3s ease;
}

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

.task-actions .button {
    padding: 4px 8px;
    font-size: 12px;
}
</style>

<script>
jQuery(document).ready(function($) {
    
    // Load functions with working backends
    loadAutomationStatus();
    loadQueueStatistics();
    loadPendingReviews();
    
    // COMMENTED OUT: Functions without backend implementation
    // loadScheduledTasks();
    // loadBackendTasks();
    // loadTaskHistory();
    
    $('.toggle-automation').on('click', function() {
        var feature = $(this).data('feature');
        var $card = $(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'));
        
        $.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);
                    }
                } else {
                    console.error('[AYSA AUTOMATION] Toggle failed for feature: ' + feature + ', error: ' + (response.data || 'Unknown 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);
            }
        });
    });
    
    $('#process-queue').on('click', function() {
        var $button = $(this);
        $button.prop('disabled', true).text('Processing...');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_process_automation_queue',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    loadQueueStatistics();
                }
                $button.prop('disabled', false).text('Process Queue Now');
            }
        });
    });
    
    // Tab handling is now done in aysa-automation-controls.js
    
    function loadAutomationStatus() {
        console.log('[AYSA AUTOMATION] Loading automation status...');
        $.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 = $(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');
                        }
                    });
                    console.log('[AYSA AUTOMATION] Automation status UI updated successfully');
                } 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 automation status: ' + error + ', Status: ' + status);
                console.error('[AYSA AUTOMATION] Response text: ' + xhr.responseText);
            }
        });
    }
    
    function loadQueueStatistics() {
        console.log('[AYSA AUTOMATION] Loading queue statistics...');
        $.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);
                    
                    $('#total-jobs').text(totalJobs);
                    $('#pending-jobs').text(pendingJobs);
                    $('#completed-jobs').text(completedJobs);
                    $('#failed-jobs').text(failedJobs);
                    
                    console.log('[AYSA AUTOMATION] Queue statistics updated - Total: ' + totalJobs + ', Pending: ' + pendingJobs + ', Completed: ' + completedJobs + ', Failed: ' + failedJobs);
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load queue statistics: ' + (response.data || 'Unknown error'));
                }
            },
            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);
            }
        });
    }
    
    function loadPendingReviews() {
        console.log('[AYSA AUTOMATION] Loading all pending reviews');
        
        // MOVED TO Domain Authority Tasks in Adjustment & Improvement
        // Domain authority reviews are now handled in the Domain Authority Tasks tab
        /*
        $.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 AUTOMATION] Domain authority reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderPendingReviews(response.data, 'domain-authority');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load domain authority reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading domain authority reviews: ' + error + ', Status: ' + status);
            }
        });
        */
        
        // Load dotnet reviews
        $.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) {
                    renderPendingReviews(response.data, 'dotnet-tasks');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load .NET Core task reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading .NET Core task reviews: ' + error + ', Status: ' + status);
            }
        });
        
        // Load image reviews
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_image_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Image reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderPendingReviews(response.data, 'images');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load image reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading image reviews: ' + error + ', Status: ' + status);
            }
        });
        
        // Load meta reviews
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_meta_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Meta reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderPendingReviews(response.data, 'meta');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load meta reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading meta reviews: ' + error + ', Status: ' + status);
            }
        });
        
        // Load keyword reviews
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_keyword_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Keyword reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderPendingReviews(response.data, 'keywords');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load keyword reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading keyword reviews: ' + error + ', Status: ' + status);
            }
        });
        
        // Load redirect reviews
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_redirect_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Redirect reviews response: ' + JSON.stringify(response));
                if (response.success) {
                    renderPendingReviews(response.data, 'redirects');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load redirect reviews: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading redirect reviews: ' + error + ', Status: ' + status);
            }
        });
        
        // Load automated SEO reviews
        console.log('[AYSA AUTOMATION] Starting to load automated SEO reviews...');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_automated_seo_reviews',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Automated SEO reviews AJAX success');
                console.log('[AYSA AUTOMATION] Response type:', typeof response);
                console.log('[AYSA AUTOMATION] Response success:', response.success);
                console.log('[AYSA AUTOMATION] Response data type:', typeof response.data);
                console.log('[AYSA AUTOMATION] Response data length:', response.data ? Object.keys(response.data).length : 'N/A');
                console.log('[AYSA AUTOMATION] Full response:', JSON.stringify(response));
                
                if (response.success) {
                    console.log('[AYSA AUTOMATION] Response successful, calling renderPendingReviews');
                    if (response.data && Object.keys(response.data).length > 0) {
                        console.log('[AYSA AUTOMATION] Found ' + Object.keys(response.data).length + ' automated SEO reviews');
                        console.log('[AYSA AUTOMATION] Review IDs:', Object.keys(response.data));
                    } else {
                        console.log('[AYSA AUTOMATION] No automated SEO reviews found in response');
                    }
                    renderPendingReviews(response.data, 'automated-seo');
                } else {
                    console.error('[AYSA AUTOMATION] Failed to load automated SEO reviews: ' + (response.data || 'Unknown error'));
                    $('#automated-seo-review-list').html('<p>Error loading automated SEO reviews: ' + (response.data || 'Unknown error') + '</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error loading automated SEO reviews');
                console.error('[AYSA AUTOMATION] XHR status:', xhr.status);
                console.error('[AYSA AUTOMATION] XHR response:', xhr.responseText);
                console.error('[AYSA AUTOMATION] Status:', status);
                console.error('[AYSA AUTOMATION] Error:', error);
                $('#automated-seo-review-list').html('<p>AJAX error loading automated SEO reviews. Check console for details.</p>');
            }
        });
    }
    
    function renderPendingReviews(reviews, reviewType) {
        console.log('[AYSA AUTOMATION] Rendering pending reviews for type: ' + reviewType);
        var html = '';
        
        if (reviewType === 'domain-authority') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' domain authority reviews');
            Object.keys(reviews).forEach(function(projectId) {
                var review = reviews[projectId];
                html += '<div class="review-item domain-authority-review">';
                html += '<h4>Domain Authority Task</h4>';
                html += '<p>' + (review.task_data.title || 'Domain Authority Optimization') + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-domain-authority" data-project-id="' + projectId + '">Approve</button>';
                html += '<button class="button reject-domain-authority" data-project-id="' + projectId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#domain-authority-review-list').html(html || '<p>No pending domain authority reviews.</p>');
        } else if (reviewType === 'dotnet-tasks') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' .NET Core task reviews');
            Object.keys(reviews).forEach(function(taskId) {
                var review = reviews[taskId];
                var task = review.task_data;
                html += '<div class="review-item dotnet-task-review">';
                html += '<h4>.NET Core Task</h4>';
                html += '<p>' + (task.title || 'Untitled Task') + '</p>';
                html += '<p>' + (task.description || 'No description') + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Type:</strong> ' + (review.task_type || 'dotnet_core_task') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-dotnet-task" data-task-id="' + taskId + '">Approve</button>';
                html += '<button class="button reject-dotnet-task" data-task-id="' + taskId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#dotnet-task-review-list').html(html || '<p>No pending .NET Core task reviews.</p>');
        } else if (reviewType === 'images') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' image reviews');
            Object.keys(reviews).forEach(function(attachmentId) {
                var review = reviews[attachmentId];
                html += '<div class="review-item">';
                html += '<h4>Image Review</h4>';
                html += '<p>Attachment ID: ' + attachmentId + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-image-review" data-attachment-id="' + attachmentId + '">Approve</button>';
                html += '<button class="button reject-image-review" data-attachment-id="' + attachmentId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#image-review-list').html(html || '<p>No pending image reviews.</p>');
        } else if (reviewType === 'meta') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' meta reviews');
            Object.keys(reviews).forEach(function(postId) {
                var review = reviews[postId];
                html += '<div class="review-item">';
                html += '<h4>Meta Review</h4>';
                html += '<p>Post ID: ' + postId + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-meta-review" data-post-id="' + postId + '">Approve</button>';
                html += '<button class="button reject-meta-review" data-post-id="' + postId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#meta-review-list').html(html || '<p>No pending meta reviews.</p>');
        } else if (reviewType === 'keywords') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' keyword reviews');
            Object.keys(reviews).forEach(function(termId) {
                var review = reviews[termId];
                html += '<div class="review-item">';
                html += '<h4>Keyword Review</h4>';
                html += '<p>Term ID: ' + termId + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-keyword-review" data-term-id="' + termId + '">Approve</button>';
                html += '<button class="button reject-keyword-review" data-term-id="' + termId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#keyword-review-list').html(html || '<p>No pending keyword reviews.</p>');
        } else if (reviewType === 'redirects') {
            console.log('[AYSA AUTOMATION] Processing ' + Object.keys(reviews).length + ' redirect reviews');
            Object.keys(reviews).forEach(function(reviewKey) {
                var review = reviews[reviewKey];
                html += '<div class="review-item">';
                html += '<h4>Redirect Review</h4>';
                html += '<p>Review Key: ' + reviewKey + '</p>';
                html += '<p><strong>Confidence:</strong> ' + Math.round(review.confidence_score * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-redirect-review" data-review-key="' + reviewKey + '">Approve</button>';
                html += '<button class="button reject-redirect-review" data-review-key="' + reviewKey + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            $('#redirect-review-list').html(html || '<p>No pending redirect reviews.</p>');
        } else if (reviewType === 'automated-seo') {
            console.log('[AYSA AUTOMATION] Processing automated SEO reviews');
            console.log('[AYSA AUTOMATION] Reviews object type:', typeof reviews);
            console.log('[AYSA AUTOMATION] Reviews is array:', Array.isArray(reviews));
            console.log('[AYSA AUTOMATION] Reviews keys:', Object.keys(reviews));
            console.log('[AYSA AUTOMATION] Number of reviews:', Object.keys(reviews).length);
            
            if (Object.keys(reviews).length === 0) {
                console.log('[AYSA AUTOMATION] No automated SEO reviews to process');
                $('#automated-seo-review-list').html('<p>No pending automated SEO reviews.</p>');
                return;
            }
            
            Object.keys(reviews).forEach(function(reviewId, index) {
                var review = reviews[reviewId];
                console.log('[AYSA AUTOMATION] Processing review ' + (index + 1) + '/' + Object.keys(reviews).length);
                console.log('[AYSA AUTOMATION] Review ID:', reviewId);
                console.log('[AYSA AUTOMATION] Review object:', review);
                console.log('[AYSA AUTOMATION] Review confidence_score:', review.confidence_score);
                console.log('[AYSA AUTOMATION] Review recommendation:', review.recommendation);
                
                html += '<div class="review-item automated-seo-review">';
                html += '<h4>Automated SEO Review</h4>';
                html += '<p><strong>Review ID:</strong> ' + reviewId + '</p>';
                if (review.title) {
                    html += '<p><strong>Entity:</strong> ' + review.title + ' (' + review.entity_type + ')</p>';
                }
                if (review.keyword) {
                    html += '<p><strong>Keyword:</strong> ' + review.keyword + '</p>';
                }
                html += '<p><strong>Confidence:</strong> ' + Math.round((review.confidence_score || 0) * 100) + '%</p>';
                html += '<p><strong>Recommendation:</strong> ' + (review.recommendation || 'Review required') + '</p>';
                html += '<p><strong>Created:</strong> ' + (review.created_at || 'Unknown') + '</p>';
                html += '<div class="review-actions">';
                html += '<button class="button button-primary approve-automated-seo-review" data-review-id="' + reviewId + '">Approve</button>';
                html += '<button class="button reject-automated-seo-review" data-review-id="' + reviewId + '">Reject</button>';
                html += '</div>';
                html += '</div>';
            });
            
            console.log('[AYSA AUTOMATION] Generated HTML length:', html.length);
            console.log('[AYSA AUTOMATION] Generated HTML preview:', html.substring(0, 200) + '...');
            
            $('#automated-seo-review-list').html(html || '<p>No pending automated SEO reviews.</p>');
            
            console.log('[AYSA AUTOMATION] HTML inserted into #automated-seo-review-list');
            console.log('[AYSA AUTOMATION] Element exists:', $('#automated-seo-review-list').length > 0);
            console.log('[AYSA AUTOMATION] Element content length:', $('#automated-seo-review-list').html().length);
        }
        
        console.log('[AYSA AUTOMATION] Pending reviews UI updated for type: ' + reviewType);
    }
    
    $(document).on('click', '.approve-domain-authority', function() {
            var projectId = $(this).data('project-id');
            console.log('[AYSA DOMAIN AUTHORITY] Approving review for project: ' + projectId);
            $.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 DOMAIN AUTHORITY] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA DOMAIN AUTHORITY] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA DOMAIN AUTHORITY] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA DOMAIN AUTHORITY] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });
        
        $(document).on('click', '.reject-domain-authority', function() {
            var projectId = $(this).data('project-id');
            console.log('[AYSA DOMAIN AUTHORITY] Rejecting review for project: ' + projectId);
            $.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 DOMAIN AUTHORITY] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA DOMAIN AUTHORITY] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA DOMAIN AUTHORITY] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA DOMAIN AUTHORITY] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });
        
        $(document).on('click', '.approve-dotnet-task', function() {
            var taskId = $(this).data('task-id');
            console.log('[AYSA AUTOMATION] Approving .NET Core task: ' + taskId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_dotnet_task',
                    task_id: taskId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA AUTOMATION] Approve .NET Core task response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA AUTOMATION] .NET Core task approved successfully');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA AUTOMATION] Failed to approve .NET Core task: ' + response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA AUTOMATION] AJAX error approving .NET Core task: ' + error);
                }
            });
        });
        
        $(document).on('click', '.reject-dotnet-task', function() {
            var taskId = $(this).data('task-id');
            console.log('[AYSA AUTOMATION] Rejecting .NET Core task: ' + taskId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_dotnet_task',
                    task_id: taskId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA AUTOMATION] Reject .NET Core task response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA AUTOMATION] .NET Core task rejected successfully');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA AUTOMATION] Failed to reject .NET Core task: ' + response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA AUTOMATION] AJAX error rejecting .NET Core task: ' + error);
                }
            });
        });

        $(document).on('click', '.approve-image-review', function() {
            var attachmentId = $(this).data('attachment-id');
            console.log('[AYSA IMAGE REVIEW] Approving review for attachment: ' + attachmentId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_image_review',
                    attachment_id: attachmentId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA IMAGE REVIEW] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA IMAGE REVIEW] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA IMAGE REVIEW] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA IMAGE REVIEW] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.reject-image-review', function() {
            var attachmentId = $(this).data('attachment-id');
            console.log('[AYSA IMAGE REVIEW] Rejecting review for attachment: ' + attachmentId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_image_review',
                    attachment_id: attachmentId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA IMAGE REVIEW] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA IMAGE REVIEW] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA IMAGE REVIEW] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA IMAGE REVIEW] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.approve-meta-review', function() {
            var postId = $(this).data('post-id');
            console.log('[AYSA META REVIEW] Approving review for post: ' + postId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_meta_review',
                    post_id: postId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA META REVIEW] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA META REVIEW] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA META REVIEW] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA META REVIEW] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.reject-meta-review', function() {
            var postId = $(this).data('post-id');
            console.log('[AYSA META REVIEW] Rejecting review for post: ' + postId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_meta_review',
                    post_id: postId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA META REVIEW] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA META REVIEW] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA META REVIEW] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA META REVIEW] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.approve-keyword-review', function() {
            var termId = $(this).data('term-id');
            console.log('[AYSA KEYWORD REVIEW] Approving review for term: ' + termId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_keyword_review',
                    term_id: termId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA KEYWORD REVIEW] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA KEYWORD REVIEW] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA KEYWORD REVIEW] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA KEYWORD REVIEW] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.reject-keyword-review', function() {
            var termId = $(this).data('term-id');
            console.log('[AYSA KEYWORD REVIEW] Rejecting review for term: ' + termId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_keyword_review',
                    term_id: termId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA KEYWORD REVIEW] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA KEYWORD REVIEW] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA KEYWORD REVIEW] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA KEYWORD REVIEW] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.approve-redirect-review', function() {
            var reviewKey = $(this).data('review-key');
            console.log('[AYSA REDIRECT REVIEW] Approving review for key: ' + reviewKey);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_redirect_review',
                    review_key: reviewKey,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA REDIRECT REVIEW] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA REDIRECT REVIEW] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA REDIRECT REVIEW] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA REDIRECT REVIEW] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });

        $(document).on('click', '.reject-redirect-review', function() {
            var reviewKey = $(this).data('review-key');
            console.log('[AYSA REDIRECT REVIEW] Rejecting review for key: ' + reviewKey);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_redirect_review',
                    review_key: reviewKey,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA REDIRECT REVIEW] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA REDIRECT REVIEW] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA REDIRECT REVIEW] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA REDIRECT REVIEW] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });
        
        $(document).on('click', '.approve-automated-seo-review', function() {
            var reviewId = $(this).data('review-id');
            console.log('[AYSA AUTOMATED SEO REVIEW] Approving review for ID: ' + reviewId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_approve_automated_review',
                    review_id: reviewId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA AUTOMATED SEO REVIEW] Approve response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA AUTOMATED SEO REVIEW] Review approved successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA AUTOMATED SEO REVIEW] Failed to approve review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA AUTOMATED SEO REVIEW] AJAX error approving review: ' + error + ', Status: ' + status);
                }
            });
        });
        
        $(document).on('click', '.reject-automated-seo-review', function() {
            var reviewId = $(this).data('review-id');
            console.log('[AYSA AUTOMATED SEO REVIEW] Rejecting review for ID: ' + reviewId);
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_reject_automated_review',
                    review_id: reviewId,
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    console.log('[AYSA AUTOMATED SEO REVIEW] Reject response: ' + JSON.stringify(response));
                    if (response.success) {
                        console.log('[AYSA AUTOMATED SEO REVIEW] Review rejected successfully, refreshing UI');
                        loadPendingReviews();
                        loadQueueStatistics();
                    } else {
                        console.error('[AYSA AUTOMATED SEO REVIEW] Failed to reject review: ' + (response.data || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AYSA AUTOMATED SEO REVIEW] AJAX error rejecting review: ' + error + ', Status: ' + status);
                }
            });
        });
    }
    
    // COMMENTED OUT: No backend implementation for scheduled tasks
    /*
    function loadScheduledTasks() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_get_scheduled_tasks',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    var tasks = response.data;
                    var html = '';
                    
                    Object.keys(tasks).forEach(function(taskId) {
                        var task = tasks[taskId];
                        html += '<div class="scheduled-task">';
                        html += '<h4>' + task.name + '</h4>';
                        html += '<p>' + task.description + '</p>';
                        html += '<p><strong>Status:</strong> <span class="task-status ' + (task.enabled ? 'enabled' : 'disabled') + '">' + (task.enabled ? 'Enabled' : 'Disabled') + '</span></p>';
                        if (task.next_run) {
                            html += '<p><strong>Next Run:</strong> ' + task.next_run + '</p>';
                        }
                        html += '</div>';
                    });
                    
                    $('#scheduled-tasks-list').html(html);
                }
            }
        });
    }
    */
    
    function getProjectId() {
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && parseInt(projectId, 10) > 0) {
            return parseInt(projectId, 10);
        }
        
        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('Error parsing API response: ' + e.message);
                }
            }
        };
        xhr.send();
        return apiProjectId ? parseInt(apiProjectId, 10) : 0;
    }
    
    // COMMENTED OUT: Complex backend task loading without proper integration
    /*
    function loadBackendTasks() {
        const automationConfig = window.aysa_params?.automation_config || window.aysaAutomationConfig || {};
        if (!automationConfig.domain_authority_automation) {
            console.log('[AYSA AUTOMATION] Backend task loading skipped - automation disabled');
            $('#backend-tasks-list').html('<p>Automation is disabled. Enable automation to load tasks.</p>');
            return;
        }
        
        const projectId = getProjectId();
        if (!projectId) {
            $('#backend-tasks-list').html('<p>No project ID found. Please configure your project.</p>');
            return;
        }
        
        console.log('[AYSA AUTOMATION] Loading backend tasks for project:', projectId);
        const apiBase = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`;
        
        fetch(`${apiBase}/ByProject/${projectId}`)
            .then(response => {
                console.log('[AYSA AUTOMATION] Backend tasks API response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(tasks => {
                console.log('[AYSA AUTOMATION] Received tasks from backend:', tasks.length);
                const allTasks = tasks.filter(task => task.status !== 'deleted');
                console.log('[AYSA AUTOMATION] All valid tasks filtered:', allTasks.length);
                
                const automationConfig = { confidence_threshold: 0.7 }; // Default threshold
                
                const activeTasks = [];
                const pendingTasks = [];
                
                allTasks.forEach(task => {
                    if (task.status === 'done') {
                        return;
                    }
                    
                    const confidenceScore = calculateTaskConfidence(task);
                    
                    console.log(`[AYSA AUTOMATION] Routing task "${task.title}" to pending reviews (research & analysis task - bypassing confidence threshold of ${automationConfig.confidence_threshold})`);
                    console.log(`[AYSA AUTOMATION] Task "${task.title}" confidence score: ${confidenceScore} (threshold bypassed)`);
                    addToPendingReviews(task, confidenceScore);
                });
                
                console.log('[AYSA AUTOMATION] Active tasks after confidence filtering:', activeTasks.length);
                renderBackendTasks(activeTasks);
                loadPendingReviews(); // Refresh pending reviews display
            })
            .catch(error => {
                console.error('[AYSA AUTOMATION] Error loading backend tasks:', error);
                $('#backend-tasks-list').html(`<p>Error loading tasks from backend: ${error.message}</p>`);
            });
    }
    
    function renderBackendTasks(tasks) {
        let html = '';
        
        if (tasks.length === 0) {
            html = '<p>No active tasks found.</p>';
        } else {
            tasks.forEach(task => {
                const progress = calculateTaskProgress(task);
                const isAutomated = task.isAi || task.automated || false;
                const automationIcon = isAutomated ? '🤖' : '✍️';
                const automationText = isAutomated ? 'AUTOMATED' : 'MANUAL';
                const automationClass = isAutomated ? 'automated' : 'manual';
                
                html += `
                    <div class="backend-task-item" data-task-id="${task.id}">
                        <div class="task-info">
                            <div class="task-header">
                                <h4>${task.title}</h4>
                                <span class="task-type ${automationClass}">${automationIcon} ${automationText}</span>
                            </div>
                            <p>${task.description || 'No description'}</p>
                            <div class="task-progress">
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: ${progress}%"></div>
                                </div>
                                <span class="progress-text">${progress}%</span>
                            </div>
                        </div>
                        <div class="task-meta">
                            <span class="task-status-badge ${task.status}">${task.status.replace('_', ' ')}</span>
                            <div>Created: ${formatDate(task.createdDate)}</div>
                            <div class="task-actions">
                                <button class="button button-small" onclick="viewTaskDetails('${task.id}')">Details</button>
                            </div>
                        </div>
                    </div>
                `;
            });
        }
        
        $('#backend-tasks-list').html(html);
    }
    */
    
    // COMMENTED OUT: No backend implementation for task history
    /*
    function loadTaskHistory() {
        const projectId = getProjectId();
        if (!projectId) {
            $('#task-history-list').html('<p>No project ID found. Please configure your project.</p>');
            return;
        }
        
        console.log('[AYSA AUTOMATION] Loading task history for project:', projectId);
        const apiBase = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`;
        
        fetch(`${apiBase}/ByProject/${projectId}`)
            .then(response => {
                console.log('[AYSA AUTOMATION] Task history API response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                return response.json();
            })
            .then(tasks => {
                console.log('[AYSA AUTOMATION] Total tasks received for history:', tasks.length);
                const completedTasks = tasks.filter(task => task.status === 'done');
                console.log('[AYSA AUTOMATION] Completed tasks filtered:', completedTasks.length);
                renderTaskHistory(completedTasks);
            })
            .catch(error => {
                console.error('[AYSA AUTOMATION] Error loading task history:', error);
                $('#task-history-list').html(`<p>Error loading task history: ${error.message}</p>`);
            });
    }
    
    function renderTaskHistory(tasks) {
        let html = '';
        
        if (tasks.length === 0) {
            html = '<p>No completed tasks found.</p>';
        } else {
            tasks.forEach(task => {
                html += `
                    <div class="history-task-item" data-task-id="${task.id}">
                        <div class="task-info">
                            <h4>${task.title}</h4>
                            <p>${task.description || 'No description'}</p>
                            <div class="task-progress">
                                <div class="task-progress-bar" style="width: 100%"></div>
                            </div>
                        </div>
                        <div class="task-meta">
                            <span class="task-status-badge done">Completed</span>
                            <div>Completed: ${formatDate(task.updatedDate || task.createdDate)}</div>
                            <div class="task-actions">
                                <button class="button button-small" onclick="viewTaskDetails('${task.id}')">Details</button>
                                <button class="button button-small" onclick="reactivateTask('${task.id}')">Reactivate</button>
                            </div>
                        </div>
                    </div>
                `;
            });
        }
        
        $('#task-history-list').html(html);
    }
    */
    
    function calculateTaskProgress(task) {
        if (task.status === 'done') return 100;
        if (task.status === 'in_progress') {
            const createdDate = new Date(task.createdDate);
            const now = new Date();
            const hoursSinceCreated = (now - createdDate) / (1000 * 60 * 60);
            
            let progress = Math.min(hoursSinceCreated * 10, 90);
            return Math.max(progress, 10);
        }
        return 0;
    }
    
    function calculateTaskConfidence(task) {
        let confidence = 0.5; // Base confidence
        
        if (task.status === 'done') confidence += 0.3;
        
        if (task.description && task.description.length > 10) confidence += 0.1;
        
        if (task.isAi) confidence += 0.2;
        
        if (task.status === 'in_progress') confidence += 0.1;
        
        return Math.min(confidence, 1.0);
    }
    
    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
    
    function addToPendingReviews(task, confidenceScore) {
        const reviewData = {
            task_id: task.id,
            task_data: task,
            confidence_score: confidenceScore,
            task_type: 'dotnet_core_task',
            created_at: new Date().toISOString()
        };
        
        console.log('[AYSA AUTOMATION] Adding task to pending reviews:', task.title);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_add_pending_review',
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>',
                review_data: reviewData
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION] Task added to pending reviews:', response);
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] Error adding task to pending reviews:', error);
            }
        });
    }
    
    function addTaskToAutomationQueue(task) {
        console.log('[AYSA AUTOMATION] Adding task to automation queue:', task.title);
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_add_task_to_queue',
                task_id: task.id,
                task_data: JSON.stringify(task),
                processor: 'association_processor',
                priority: 5,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    console.log('[AYSA AUTOMATION] Task added to queue successfully:', task.title);
                } else {
                    console.error('[AYSA AUTOMATION] Failed to add task to queue:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error adding task to queue:', error);
            }
        });
    }
    
    $('#refresh-history').on('click', function() {
        loadTaskHistory();
    });
    
    $('#history-filter').on('change', function() {
        const filter = $(this).val();
        filterTaskHistory(filter);
    });
    
    function filterTaskHistory(filter) {
        const now = new Date();
        const items = $('.history-task-item');
        
        items.each(function() {
            const taskId = $(this).data('task-id');
            const dateText = $(this).find('.task-meta div:contains("Completed:")').text();
            const taskDate = new Date(dateText.replace('Completed: ', ''));
            
            let show = true;
            
            switch(filter) {
                case 'today':
                    show = taskDate.toDateString() === now.toDateString();
                    break;
                case 'week':
                    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    show = taskDate >= weekAgo;
                    break;
                case 'month':
                    const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                    show = taskDate >= monthAgo;
                    break;
                default:
                    show = true;
            }
            
            $(this).toggle(show);
        });
    }
    
    window.viewTaskDetails = function(taskId) {
        alert('Task details for ID: ' + taskId + '\n(This would open a detailed view)');
    };
    
    window.addToAutomationQueue = function(taskId) {
        const taskItem = $(`.backend-task-item[data-task-id="${taskId}"]`);
        const taskTitle = taskItem.find('h4').text();
        
        console.log('[AYSA AUTOMATION] Manually adding task to queue:', taskTitle);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_add_task_to_queue',
                task_id: taskId,
                task_title: taskTitle,
                processor: 'association_processor',
                priority: 3,
                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    alert('Task added to automation queue: ' + taskTitle);
                    loadQueueStatistics();
                    console.log('[AYSA AUTOMATION] Task manually added to queue successfully');
                } else {
                    alert('Failed to add task to queue: ' + (response.data || 'Unknown error'));
                    console.error('[AYSA AUTOMATION] Failed to manually add task to queue:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION] AJAX error manually adding task to queue:', error);
                alert('Error adding task to queue: ' + error);
            }
        });
    };
    
    window.reactivateTask = function(taskId) {
        const apiBase = `${window.AYSA_API_BASE || 'https://api.aysa.ai'}/api/ResearchTasks`;
        
        // First get the current task to preserve its flag
        fetch(`${apiBase}/ByProject/${getProjectId()}`)
            .then(response => response.json())
            .then(tasks => {
                const task = tasks.find(t => t.id === taskId);
                const taskFlag = task ? task.flag : 'isHuman'; // Default to isHuman if not found
                
                return fetch(`${apiBase}/${taskId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        status: 'in_progress',
                        flag: taskFlag  // ✅ FIXED: Preserve original flag (isAi/isHuman)
                    })
                });
            })
            .then(response => response.json())
            .then(() => {
                alert('Task reactivated successfully');
                loadBackendTasks();
                loadTaskHistory();
            })
            .catch(error => {
                console.error('Error reactivating task:', error);
                alert('Failed to reactivate task');
            });
    };
    
    // COMMENTED OUT: Bulk approve functionality - too complex and prone to timeouts
    /*
    $('#approve-all-reviews').on('click', function() {
        const $button = $(this);
        const $status = $('#bulk-status');
        
        if (!confirm('Are you sure you want to approve ALL pending reviews? This action cannot be undone.')) {
            return;
        }
        
        $button.prop('disabled', true).text('Processing...');
        $status.text('Starting bulk approval process...');
        
        // Collect all pending reviews from different types
        const allReviews = {
            domain_authority: [],
            dotnet_tasks: [],
            automated_seo: [],
            image_reviews: [],
            meta_reviews: [],
            keyword_reviews: [],
            redirect_reviews: []
        };
        
        let totalReviews = 0;
        let processedReviews = 0;
        let successCount = 0;
        let errorCount = 0;
        
        // Function to update status
        function updateStatus(message) {
            $status.text(message);
            console.log('[AYSA BULK APPROVE] ' + message);
        }
        
        // Function to process reviews
        function processReviews() {
            updateStatus(`Processing ${processedReviews}/${totalReviews} reviews...`);
            
            if (processedReviews >= totalReviews) {
                // All done
                const message = `Bulk approval completed! Success: ${successCount}, Errors: ${errorCount}`;
                updateStatus(message);
                $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                
                // Refresh the UI
                loadPendingReviews();
                loadQueueStatistics();
                
                // Show final notification
                if (errorCount === 0) {
                    alert('All reviews approved successfully!');
                } else {
                    alert(`Bulk approval completed with ${errorCount} errors. Check the status for details.`);
                }
                return;
            }
            
            // Process next review
            const reviewType = Object.keys(allReviews)[Math.floor(processedReviews / 10)]; // Distribute across types
            const reviews = allReviews[reviewType];
            const reviewIndex = processedReviews % reviews.length;
            
            if (reviewIndex < reviews.length) {
                const review = reviews[reviewIndex];
                approveSingleReview(reviewType, review)
                    .then(() => {
                        successCount++;
                        processedReviews++;
                        processReviews();
                    })
                    .catch((error) => {
                        errorCount++;
                        processedReviews++;
                        console.error('[AYSA BULK APPROVE] Error approving review:', error);
                        processReviews();
                    });
            } else {
                processedReviews++;
                processReviews();
            }
        }
        
        // Function to approve a single review
        function approveSingleReview(reviewType, review) {
            return new Promise((resolve, reject) => {
                let action = '';
                let data = {};
                
                switch(reviewType) {
                    case 'domain_authority':
                        action = 'aysa_approve_domain_authority_review';
                        data = { review_id: review.project_id };
                        break;
                    case 'dotnet_tasks':
                        action = 'aysa_approve_dotnet_task';
                        data = { task_id: review.task_id };
                        break;
                    case 'automated_seo':
                        action = 'aysa_approve_automated_review';
                        data = { review_id: review.review_id };
                        break;
                    case 'image_reviews':
                        action = 'aysa_approve_image_review';
                        data = { attachment_id: review.attachment_id };
                        break;
                    case 'meta_reviews':
                        action = 'aysa_approve_meta_review';
                        data = { post_id: review.post_id };
                        break;
                    case 'keyword_reviews':
                        action = 'aysa_approve_keyword_review';
                        data = { term_id: review.term_id, selected_keyword: review.suggested_keywords[0].keyword };
                        break;
                    case 'redirect_reviews':
                        action = 'aysa_approve_redirect_review';
                        data = { review_key: review.review_key, selected_target_url: review.suggestions[0].url };
                        break;
                }
                
                if (!action) {
                    reject(new Error('Unknown review type: ' + reviewType));
                    return;
                }
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: action,
                        nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>',
                        ...data
                    },
                    success: function(response) {
                        if (response.success) {
                            resolve(response);
                        } else {
                            reject(new Error(response.data || 'Unknown error'));
                        }
                    },
                    error: function(xhr, status, error) {
                        reject(new Error(error));
                    }
                });
            });
        }
        
        // Load all pending reviews first
        updateStatus('Loading all pending reviews...');
        
        // Load domain authority reviews
        $.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) {
                if (response.success) {
                    Object.keys(response.data).forEach(projectId => {
                        allReviews.domain_authority.push({
                            project_id: projectId,
                            ...response.data[projectId]
                        });
                    });
                }
                
                // Load dotnet reviews
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'aysa_get_pending_dotnet_reviews',
                        nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            Object.keys(response.data).forEach(taskId => {
                                allReviews.dotnet_tasks.push({
                                    task_id: taskId,
                                    ...response.data[taskId]
                                });
                            });
                        }
                        
                        // Load automated SEO reviews
                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'aysa_get_pending_automated_seo_reviews',
                                nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                            },
                            success: function(response) {
                                if (response.success) {
                                    response.data.forEach(review => {
                                        allReviews.automated_seo.push({
                                            review_id: review.id,
                                            ...review
                                        });
                                    });
                                }
                                
                                // Load other review types
                                loadOtherReviewTypes();
                            },
                            error: function() {
                                loadOtherReviewTypes();
                            }
                        });
                    },
                    error: function() {
                        loadOtherReviewTypes();
                    }
                });
            },
            error: function() {
                loadOtherReviewTypes();
            }
        });
        
        function loadOtherReviewTypes() {
            // Load image reviews
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_get_pending_image_reviews',
                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        Object.keys(response.data).forEach(attachmentId => {
                            allReviews.image_reviews.push({
                                attachment_id: attachmentId,
                                ...response.data[attachmentId]
                            });
                        });
                    }
                    
                    // Load meta reviews
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'aysa_get_pending_meta_reviews',
                            nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                Object.keys(response.data).forEach(postId => {
                                    allReviews.meta_reviews.push({
                                        post_id: postId,
                                        ...response.data[postId]
                                    });
                                });
                            }
                            
                            // Load keyword reviews
                            $.ajax({
                                url: ajaxurl,
                                type: 'POST',
                                data: {
                                    action: 'aysa_get_pending_keyword_reviews',
                                    nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                                },
                                success: function(response) {
                                    if (response.success) {
                                        Object.keys(response.data).forEach(termId => {
                                            allReviews.keyword_reviews.push({
                                                term_id: termId,
                                                ...response.data[termId]
                                            });
                                        });
                                    }
                                    
                                    // Load redirect reviews
                                    $.ajax({
                                        url: ajaxurl,
                                        type: 'POST',
                                        data: {
                                            action: 'aysa_get_pending_redirect_reviews',
                                            nonce: '<?php echo wp_create_nonce('aysa_automation_nonce'); ?>'
                                        },
                                        success: function(response) {
                                            if (response.success) {
                                                Object.keys(response.data).forEach(reviewKey => {
                                                    allReviews.redirect_reviews.push({
                                                        review_key: reviewKey,
                                                        ...response.data[reviewKey]
                                                    });
                                                });
                                            }
                                            
                                            // Calculate total and start processing
                                            totalReviews = Object.values(allReviews).reduce((sum, reviews) => sum + reviews.length, 0);
                                            updateStatus(`Found ${totalReviews} pending reviews to approve`);
                                            
                                            if (totalReviews === 0) {
                                                updateStatus('No pending reviews found');
                                                $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                                                return;
                                            }
                                            
                                            // Start processing
                                            processReviews();
                                        },
                                        error: function() {
                                            // Continue with processing even if redirect reviews fail to load
                                            totalReviews = Object.values(allReviews).reduce((sum, reviews) => sum + reviews.length, 0);
                                            updateStatus(`Found ${totalReviews} pending reviews to approve`);
                                            
                                            if (totalReviews === 0) {
                                                updateStatus('No pending reviews found');
                                                $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                                                return;
                                            }
                                            
                                            processReviews();
                                        }
                                    });
                                },
                                error: function() {
                                    // Continue with processing even if keyword reviews fail to load
                                    totalReviews = Object.values(allReviews).reduce((sum, reviews) => sum + reviews.length, 0);
                                    updateStatus(`Found ${totalReviews} pending reviews to approve`);
                                    
                                    if (totalReviews === 0) {
                                        updateStatus('No pending reviews found');
                                        $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                                        return;
                                    }
                                    
                                    processReviews();
                                }
                            });
                        },
                        error: function() {
                            // Continue with processing even if meta reviews fail to load
                            totalReviews = Object.values(allReviews).reduce((sum, reviews) => sum + reviews.length, 0);
                            updateStatus(`Found ${totalReviews} pending reviews to approve`);
                            
                            if (totalReviews === 0) {
                                updateStatus('No pending reviews found');
                                $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                                return;
                            }
                            
                            processReviews();
                        }
                    });
                },
                error: function() {
                    // Continue with processing even if image reviews fail to load
                    totalReviews = Object.values(allReviews).reduce((sum, reviews) => sum + reviews.length, 0);
                    updateStatus(`Found ${totalReviews} pending reviews to approve`);
                    
                    if (totalReviews === 0) {
                        updateStatus('No pending reviews found');
                        $button.prop('disabled', false).html('<span class="dashicons dashicons-yes-alt" style="margin-right: 5px;"></span>Approve All Pending Reviews');
                        return;
                    }
                    
                    processReviews();
                }
            });
        }
    });
    */
    

});
</script>
