/**
 * Aysa Automation Controls JavaScript
 * Handles the suggest-then-automate workflow and quality assurance features
 */

jQuery(document).ready(function($) {
    
    console.log('🚀 [DEBUG] aysa-automation-controls.js loaded successfully');
    console.log('🚀 [DEBUG] aysaAutomation object:', typeof aysaAutomation !== 'undefined' ? aysaAutomation : 'NOT FOUND');

    const automationAjaxUrl = (typeof ajaxurl !== 'undefined' && ajaxurl)
        ? ajaxurl
        : ((typeof aysaAutomation !== 'undefined' && aysaAutomation.ajax_url) ? aysaAutomation.ajax_url : '/wp-admin/admin-ajax.php');
    const automationNonce = (typeof aysaAutomation !== 'undefined' && aysaAutomation.nonce)
        ? aysaAutomation.nonce
        : ((typeof aysaParams !== 'undefined' && aysaParams.ajax_nonce) ? aysaParams.ajax_nonce : '');
    
    initializeAutomationControls();
    
    initializeAuditLog();
    
    initializeConfidenceControls();
    
    function initializeAutomationControls() {
        $('.aysa-automation-features input[id$="-suggestions"]').on('change', function() {
            const featureType = $(this).attr('id').replace('-suggestions', '').replace('aysa-', '');
            const isEnabled = $(this).is(':checked');
            const automationToggle = $(`#aysa-${featureType}-automation`);
            const statusBadge = $(`#${featureType}-status`);
            
            if (isEnabled) {
                statusBadge.removeClass('aysa-status-disabled')
                          .addClass('aysa-status-suggest')
                          .text('Suggest Mode');
                
                loadFeatureStats(featureType);
            } else {
                statusBadge.removeClass('aysa-status-suggest aysa-status-auto')
                          .addClass('aysa-status-disabled')
                          .text('Disabled');
                
                automationToggle.prop('checked', false).prop('disabled', true);
                
                clearFeatureStats(featureType);
            }
            
            saveAutomationSetting(`${featureType}_suggestions`, isEnabled);
        });
        
        $('.aysa-automation-features input[id$="-automation"]').on('change', function() {
            const featureType = $(this).attr('id').replace('-automation', '').replace('aysa-', '');
            const isEnabled = $(this).is(':checked');
            const statusBadge = $(`#${featureType}-status`);
            
            if (isEnabled) {
                checkAcceptanceRate(featureType).then(function(meetsThreshold) {
                    if (meetsThreshold) {
                        statusBadge.removeClass('aysa-status-suggest')
                                  .addClass('aysa-status-auto')
                                  .text('Auto Mode');
                        
                        saveAutomationSetting(`${featureType}_automation`, true);
                        
                        showNotification('Automation enabled successfully', 'success');
                    } else {
                        $(this).prop('checked', false);
                        
                        showNotification('Automation requires 85%+ acceptance rate', 'warning');
                    }
                });
            } else {
                statusBadge.removeClass('aysa-status-auto')
                          .addClass('aysa-status-suggest')
                          .text('Suggest Mode');
                
                saveAutomationSetting(`${featureType}_automation`, false);
            }
        });
        
        loadAllFeatureStats();
    }
    
    function initializeAuditLog() {
        $('#view-audit-log').on('click', function() {
            openAuditLogModal();
        });
        
        $(document).on('change', '#audit-log-filters select, #audit-log-filters input', function() {
            loadAuditLog();
        });
        
        $(document).on('click', '.aysa-rollback-btn', function() {
            const logId = $(this).data('log-id');
            rollbackChange(logId);
        });
    }
    
    function initializeConfidenceControls() {
        $('.aysa-range').on('input', function() {
            const value = $(this).val();
            const percentage = Math.round(value * 100);
            $(this).siblings('.aysa-range-display').find('.aysa-range-value').text(percentage + '%');
        });
        
        $('#save-qa-settings').on('click', function() {
            saveQASettings();
        });
    }
    
    function loadFeatureStats(featureType) {
        $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_get_feature_stats',
                nonce: automationNonce,
                feature_type: featureType
            },
            success: function(response) {
                if (response.success) {
                    updateFeatureStats(featureType, response.data);
                    
                    const acceptanceRate = response.data.acceptance_rate;
                    const automationToggle = $(`#aysa-${featureType}-automation`);
                    
                    if (acceptanceRate >= 85) {
                        automationToggle.prop('disabled', false);
                    }
                }
            }
        });
    }
    
    function loadAllFeatureStats() {
        ['image', 'redirect', 'meta'].forEach(function(featureType) {
            const suggestionsEnabled = $(`#aysa-${featureType}-suggestions`).is(':checked');
            if (suggestionsEnabled) {
                loadFeatureStats(featureType);
            }
        });
    }
    
    function updateFeatureStats(featureType, stats) {
        $(`#${featureType}-acceptance`).text(stats.acceptance_rate + '%');
        $(`#${featureType}-suggestions-count`).text(stats.suggestions_count);
    }
    
    function clearFeatureStats(featureType) {
        $(`#${featureType}-acceptance`).text('--');
        $(`#${featureType}-suggestions-count`).text('--');
    }
    
    function checkAcceptanceRate(featureType) {
        return $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_check_acceptance_rate',
                nonce: automationNonce,
                feature_type: featureType
            }
        }).then(function(response) {
            if (response.success) {
                return response.data.meets_threshold;
            }
            return false;
        });
    }
    
    function saveAutomationSetting(settingName, value) {
        $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_save_automation_setting',
                nonce: automationNonce,
                setting_name: settingName,
                setting_value: value
            },
            success: function(response) {
                if (!response.success) {
                    console.error('Failed to save automation setting:', response.data);
                }
            }
        });
    }
    
    function openAuditLogModal() {
        if ($('#aysa-audit-log-modal').length === 0) {
            createAuditLogModal();
        }
        
        loadAuditLog();
        
        $('#aysa-audit-log-modal').show();
    }
    
    function createAuditLogModal() {
        const modalHtml = `
            <div id="aysa-audit-log-modal" class="aysa-modal" style="display: none;">
                <div class="aysa-modal-content">
                    <div class="aysa-modal-header">
                        <h3>Automation Audit Log</h3>
                        <span class="aysa-modal-close">&times;</span>
                    </div>
                    <div class="aysa-modal-body">
                        <div id="audit-log-filters" class="aysa-filters">
                            <select id="filter-action-type">
                                <option value="">All Actions</option>
                                <option value="image_optimization">Image Optimization</option>
                                <option value="redirect_creation">Redirect Creation</option>
                                <option value="meta_generation">Meta Generation</option>
                                <option value="rollback">Rollback</option>
                            </select>
                            <select id="filter-automation-type">
                                <option value="">All Types</option>
                                <option value="1">Automated</option>
                                <option value="0">Manual</option>
                            </select>
                            <input type="date" id="filter-date-from" placeholder="From Date">
                            <input type="date" id="filter-date-to" placeholder="To Date">
                        </div>
                        <div id="audit-log-content">
                            <div class="aysa-loading">Loading audit log...</div>
                        </div>
                        <div id="audit-log-pagination"></div>
                    </div>
                </div>
            </div>
        `;
        
        $('body').append(modalHtml);
        
        $('.aysa-modal-close').on('click', function() {
            $('#aysa-audit-log-modal').hide();
        });
        
        $(window).on('click', function(event) {
            if (event.target.id === 'aysa-audit-log-modal') {
                $('#aysa-audit-log-modal').hide();
            }
        });
    }
    
    function loadAuditLog(page = 1) {
        const filters = {
            action_type: $('#filter-action-type').val(),
            is_automated: $('#filter-automation-type').val(),
            date_from: $('#filter-date-from').val(),
            date_to: $('#filter-date-to').val()
        };
        
        $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_get_audit_log',
                nonce: automationNonce,
                page: page,
                per_page: 20,
                filters: filters
            },
            success: function(response) {
                if (response.success) {
                    renderAuditLog(response.data.logs);
                    renderPagination(response.data.page, response.data.per_page, response.data.total);
                } else {
                    $('#audit-log-content').html('<div class="aysa-error">Failed to load audit log</div>');
                }
            },
            error: function() {
                $('#audit-log-content').html('<div class="aysa-error">Error loading audit log</div>');
            }
        });
    }
    
    function renderAuditLog(logs) {
        if (logs.length === 0) {
            $('#audit-log-content').html('<div class="aysa-no-data">No audit log entries found</div>');
            return;
        }
        
        let html = '<table class="aysa-audit-table">';
        html += '<thead><tr>';
        html += '<th>Date</th>';
        html += '<th>Action</th>';
        html += '<th>Object</th>';
        html += '<th>Type</th>';
        html += '<th>Confidence</th>';
        html += '<th>Actions</th>';
        html += '</tr></thead><tbody>';
        
        logs.forEach(function(log) {
            html += '<tr>';
            html += `<td>${formatDate(log.created_at)}</td>`;
            html += `<td>${formatActionType(log.action_type)}</td>`;
            html += `<td>${log.object_type} #${log.object_id}</td>`;
            html += `<td>${log.is_automated ? '<span class="aysa-icon-robot">🤖</span> Auto' : '<span class="aysa-icon-hand">✋</span> Manual'}</td>`;
            html += `<td>${log.confidence_score ? Math.round(log.confidence_score * 100) + '%' : '--'}</td>`;
            html += '<td>';
            if (log.can_rollback) {
                html += `<button class="aysa-rollback-btn aysa-btn-small" data-log-id="${log.id}">Rollback</button>`;
            }
            html += '</td>';
            html += '</tr>';
        });
        
        html += '</tbody></table>';
        $('#audit-log-content').html(html);
    }
    
    function rollbackChange(logId) {
        if (!confirm('Are you sure you want to rollback this change? This action cannot be undone.')) {
            return;
        }
        
        $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_rollback_change',
                nonce: automationNonce,
                log_id: logId
            },
            success: function(response) {
                if (response.success) {
                    showNotification('Change rolled back successfully', 'success');
                    loadAuditLog(); // Reload audit log
                } else {
                    showNotification('Failed to rollback change: ' + response.data, 'error');
                }
            },
            error: function() {
                showNotification('Error rolling back change', 'error');
            }
        });
    }
    
    function saveQASettings() {
        const settings = {
            auto_approve_threshold: $('#aysa-auto-approve-threshold').val(),
            suggest_threshold: $('#aysa-suggest-threshold').val(),
            manual_review_threshold: $('#aysa-manual-review-threshold').val(),
            enable_audit_log: $('#aysa-enable-audit-log').is(':checked'),
            enable_rollback: $('#aysa-enable-rollback').is(':checked'),
            require_confirmation: $('#aysa-require-confirmation').is(':checked')
        };
        
        $.ajax({
            url: automationAjaxUrl,
            type: 'POST',
            data: {
                action: 'aysa_save_qa_settings',
                nonce: automationNonce,
                settings: settings
            },
            success: function(response) {
                if (response.success) {
                    showNotification('QA settings saved successfully', 'success');
                } else {
                    showNotification('Failed to save QA settings', 'error');
                }
            },
            error: function() {
                showNotification('Error saving QA settings', 'error');
            }
        });
    }
    
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
    
    function formatActionType(actionType) {
        const types = {
            'image_optimization': 'Image Optimization',
            'redirect_creation': 'Redirect Creation',
            'meta_generation': 'Meta Generation',
            'rollback': 'Rollback'
        };
        return types[actionType] || actionType;
    }
    
    function showNotification(message, type) {
        const notificationClass = type === 'success' ? 'aysa-notice-success' : 
                                 type === 'error' ? 'aysa-notice-error' : 'aysa-notice-warning';
        
        const notification = $(`<div class="aysa-notice ${notificationClass}">${message}</div>`);
        
        $('.aysa-automation-features').prepend(notification);
        
        setTimeout(function() {
            notification.fadeOut(function() {
                $(this).remove();
            });
        }, 3000);
    }

    // SEO Generation Automation Controls
    $('#test-seo-generation').on('click', function() {
        const $btn = $(this);
        const originalText = $btn.text();
        
        $btn.prop('disabled', true).text('Testing...');
        
        $.ajax({
            url: aysaParams.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_test_seo_generation',
                nonce: aysaParams.nonce
            },
            success: function(response) {
                if (response.success) {
                    showNotification('SEO generation test completed successfully!', 'success');
                    updateSeoGenerationStatus();
                } else {
                    showNotification('SEO generation test failed: ' + (response.data?.message || 'Unknown error'), 'error');
                }
            },
            error: function() {
                showNotification('Failed to test SEO generation. Please try again.', 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    $('#get-seo-status').on('click', function() {
        updateSeoGenerationStatus();
    });
    
    $('#manual-seo-generation').on('click', function() {
        $('#manual-seo-form').toggle();
    });
    
    $('#submit-manual-seo').on('click', function() {
        const entityId = $('#manual-entity-id').val();
        const entityType = $('#manual-entity-type').val();
        const keyword = $('#manual-keyword').val();
        
        if (!entityId || !entityType || !keyword) {
            showNotification('Please fill in all fields.', 'error');
            return;
        }
        
        const $btn = $(this);
        const originalText = $btn.text();
        
        $btn.prop('disabled', true).text('Generating...');
        
        $.ajax({
            url: aysaParams.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_manual_seo_generation',
                entity_id: entityId,
                entity_type: entityType,
                keyword: keyword,
                nonce: aysaParams.nonce
            },
            success: function(response) {
                if (response.success) {
                    showNotification('Manual SEO generation completed successfully!', 'success');
                    $('#manual-seo-form').hide();
                    $('#manual-entity-id, #manual-entity-type, #manual-keyword').val('');
                    updateSeoGenerationStatus();
                } else {
                    showNotification('Manual SEO generation failed: ' + (response.data?.message || 'Unknown error'), 'error');
                }
            },
            error: function() {
                showNotification('Failed to generate SEO. Please try again.', 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    function updateSeoGenerationStatus() {
        const $status = $('#seo-generation-status');
        $status.html('<p>Loading status...</p>');
        
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_seo_generation_status',
                nonce: aysaAutomation.nonce
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    let statusHtml = '<div class="aysa-status-grid">';
                    
                    statusHtml += '<div class="aysa-status-item">';
                    statusHtml += '<strong>Status:</strong> ' + (data.enabled ? 'Enabled' : 'Disabled');
                    statusHtml += '</div>';
                    
                    if (data.next_run) {
                        statusHtml += '<div class="aysa-status-item">';
                        statusHtml += '<strong>Next Run:</strong> ' + data.next_run;
                        statusHtml += '</div>';
                    }
                    
                    if (data.queue_stats) {
                        statusHtml += '<div class="aysa-status-item">';
                        statusHtml += '<strong>Queue:</strong> ' + data.queue_stats.pending + ' pending, ' + data.queue_stats.completed + ' completed';
                        statusHtml += '</div>';
                    }
                    
                    statusHtml += '<div class="aysa-status-item">';
                    statusHtml += '<strong>Pending Reviews:</strong> ' + data.pending_reviews;
                    statusHtml += '</div>';
                    
                    statusHtml += '</div>';
                    
                    // Add processing jobs section if there are any
                    if (data.queue_stats && data.queue_stats.processing > 0) {
                        statusHtml += '<div class="aysa-processing-jobs">';
                        statusHtml += '<h4>Currently Processing Jobs</h4>';
                        statusHtml += '<p>There are ' + data.queue_stats.processing + ' jobs currently being processed.</p>';
                        statusHtml += '<button type="button" class="button button-secondary" id="refresh-processing-jobs">Refresh Processing Status</button>';
                        statusHtml += '</div>';
                    }
                    
                    $status.html(statusHtml);
                    
                    // Set up refresh button for processing jobs
                    $('#refresh-processing-jobs').on('click', function() {
                        updateProcessingJobs();
                    });
                    
                } else {
                    $status.html('<p>Failed to load status.</p>');
                }
            },
            error: function() {
                $status.html('<p>Failed to load status. Please try again.</p>');
            }
        });
    }
    
    function updateProcessingJobs() {
        const $status = $('#seo-generation-status');
        
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_processing_stats',
                nonce: aysaAutomation.nonce
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    let jobsHtml = '<div class="aysa-processing-jobs">';
                    jobsHtml += '<h4>Processing Jobs</h4>';
                    
                    if (data.processing_jobs && data.processing_jobs.length > 0) {
                        jobsHtml += '<div class="aysa-jobs-list">';
                        
                        data.processing_jobs.forEach(function(job) {
                            const jobData = JSON.parse(job.job_data || '{}');
                            const elapsed = job.started_at ? Math.floor((new Date() - new Date(job.started_at)) / 1000) : 0;
                            
                            jobsHtml += '<div class="aysa-job-item">';
                            jobsHtml += '<div class="aysa-job-header">';
                            jobsHtml += '<strong>Job #' + job.id + '</strong> - ' + (jobData.entity_type || 'Unknown');
                            jobsHtml += '<span class="aysa-job-time">Elapsed: ' + formatTime(elapsed) + '</span>';
                            jobsHtml += '</div>';
                            jobsHtml += '<div class="aysa-job-details">';
                            jobsHtml += '<span>Entity ID: ' + (jobData.entity_id || 'N/A') + '</span>';
                            jobsHtml += '<span>Keyword: ' + (jobData.keyword || 'N/A') + '</span>';
                            jobsHtml += '</div>';
                            jobsHtml += '<div class="aysa-job-progress">';
                            jobsHtml += '<div class="aysa-progress-bar">';
                            jobsHtml += '<div class="aysa-progress-fill" style="width: 50%;"></div>'; // Placeholder
                            jobsHtml += '</div>';
                            jobsHtml += '<span class="aysa-progress-text">Processing...</span>';
                            jobsHtml += '</div>';
                            jobsHtml += '</div>';
                        });
                        
                        jobsHtml += '</div>';
                        
                        // Start progress polling for these jobs
                        startProgressPolling(data.processing_jobs.map(job => job.id));
                        
                    } else {
                        jobsHtml += '<p>No jobs currently processing.</p>';
                    }
                    
                    jobsHtml += '<button type="button" class="button button-secondary" id="refresh-processing-jobs">Refresh</button>';
                    jobsHtml += '</div>';
                    
                    // Replace or add the processing jobs section
                    let $existingJobs = $('.aysa-processing-jobs');
                    if ($existingJobs.length) {
                        $existingJobs.replaceWith(jobsHtml);
                    } else {
                        $status.append(jobsHtml);
                    }
                    
                    // Re-attach event handler
                    $('#refresh-processing-jobs').on('click', function() {
                        updateProcessingJobs();
                    });
                    
                } else {
                    showNotification('Failed to load processing jobs.', 'error');
                }
            },
            error: function() {
                showNotification('Failed to load processing jobs. Please try again.', 'error');
            }
        });
    }
    
    function startProgressPolling(jobIds) {
        // Clear any existing polling
        if (window.aysaProgressPolling) {
            clearInterval(window.aysaProgressPolling);
        }
        
        // Poll every 5 seconds for job progress
        window.aysaProgressPolling = setInterval(function() {
            jobIds.forEach(function(jobId) {
                updateJobProgress(jobId);
            });
        }, 5000);
        
        // Stop polling after 10 minutes
        setTimeout(function() {
            if (window.aysaProgressPolling) {
                clearInterval(window.aysaProgressPolling);
                window.aysaProgressPolling = null;
            }
        }, 600000); // 10 minutes
    }
    
    function updateJobProgress(jobId) {
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_job_progress',
                job_id: jobId,
                nonce: aysaAutomation.nonce
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    const $jobItem = $('.aysa-job-item').filter(function() {
                        return $(this).find('.aysa-job-header strong').text().includes('Job #' + jobId);
                    });
                    
                    if ($jobItem.length) {
                        const progress = data.progress;
                        
                        // Update progress bar
                        $jobItem.find('.aysa-progress-fill').css('width', progress.percentage + '%');
                        $jobItem.find('.aysa-progress-text').text(progress.current_step);
                        
                        // Update status based on completion
                        if (data.status === 'completed') {
                            $jobItem.addClass('aysa-job-completed');
                            $jobItem.find('.aysa-progress-text').text('Completed successfully');
                        } else if (data.status === 'failed') {
                            $jobItem.addClass('aysa-job-failed');
                            $jobItem.find('.aysa-progress-text').text('Failed: ' + (data.error_message || 'Unknown error'));
                        }
                    }
                }
            }
        });
    }
    
    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return minutes + 'm ' + remainingSeconds + 's';
    }
    
    // Tab content loading functionality
    
    function loadTabContent(tabName) {
        console.log('[AYSA AUTOMATION CONTROLS] Loading tab content for:', tabName);
        
        const selector = '#' + tabName + '-reviews .review-list';
        console.log('[AYSA AUTOMATION CONTROLS] Looking for selector:', selector);
        
        const $content = $(selector);
        console.log('[AYSA AUTOMATION CONTROLS] Content element found:', $content.length > 0);
        console.log('[AYSA AUTOMATION CONTROLS] Content element:', $content);
        
        if ($content.length === 0) {
            console.error('[AYSA AUTOMATION CONTROLS] Content element not found! Available elements:');
            console.log('[AYSA AUTOMATION CONTROLS] #' + tabName + '-reviews exists:', $('#' + tabName + '-reviews').length > 0);
            console.log('[AYSA AUTOMATION CONTROLS] .review-list elements:', $('.review-list').length);
            console.log('[AYSA AUTOMATION CONTROLS] All review-list IDs:', $('.review-list').map(function() { return this.id; }).get());
            return;
        }
        
        // Show loading message
        $content.html('<p>Loading pending ' + tabName + ' reviews...</p>');
        
        // Load content based on tab type
        switch(tabName) {
            case 'automated-seo':
                loadAutomatedSeoReviews($content);
                break;
            case 'images':
                loadImageReviews($content);
                break;
            case 'redirects':
                loadRedirectReviews($content);
                break;
            case 'meta':
                loadMetaReviews($content);
                break;
            case 'keywords':
                loadKeywordReviews($content);
                break;
            case 'domain-authority':
                loadDomainAuthorityReviews($content);
                break;
        }
    }
    
    function loadAutomatedSeoReviews($content) {
        console.log('[AYSA AUTOMATION CONTROLS] Loading automated SEO reviews...');
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_pending_automated_seo_reviews',
                nonce: aysaAutomation.nonce
            },
            success: function(response) {
                console.log('[AYSA AUTOMATION CONTROLS] Response received:', response);
                
                if (response.success && response.data) {
                    console.log('[AYSA AUTOMATION CONTROLS] Response data type:', typeof response.data);
                    console.log('[AYSA AUTOMATION CONTROLS] Response data keys:', Object.keys(response.data));
                    
                    // Check if we have any reviews
                    if (Object.keys(response.data).length > 0) {
                        let html = '<div class="aysa-review-list">';
                        
                        // Iterate through the object (not array)
                        Object.keys(response.data).forEach(function(reviewId) {
                            const review = response.data[reviewId];
                            console.log('[AYSA AUTOMATION CONTROLS] Processing review:', reviewId, review);
                            
                            html += '<div class="review-item automated-seo-review">';
                            html += '<div class="review-header">';
                            html += '<h4>Automated SEO Review</h4>';
                            html += '<span class="task-type automated">Automated SEO</span>';
                            html += '</div>';
                            html += '<p><strong>Review ID:</strong> ' + reviewId + '</p>';
                            if (review.title) {
                                html += '<p><strong>Entity:</strong> ' + review.title + ' (' + review.entity_type + ')</p>';
                            } else {
                                html += '<p><strong>Entity:</strong> ' + review.entity_type + ' #' + review.entity_id + '</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>Status:</strong> ' + (review.status || 'pending') + '</p>';
                            html += '<p><strong>Created:</strong> ' + (review.created_at || 'Unknown') + '</p>';
                            html += '<div class="review-actions">';
                            html += '<button class="button button-primary approve-review" data-id="' + reviewId + '">Approve</button>';
                            html += '<button class="button button-secondary reject-review" data-id="' + reviewId + '">Reject</button>';
                            html += '</div>';
                            html += '</div>';
                        });
                        
                        html += '</div>';
                        console.log('[AYSA AUTOMATION CONTROLS] Generated HTML length:', html.length);
                        $content.html(html);
                    } else {
                        console.log('[AYSA AUTOMATION CONTROLS] No reviews found');
                        $content.html('<p>No pending automated SEO reviews found.</p>');
                    }
                } else {
                    console.error('[AYSA AUTOMATION CONTROLS] Failed to load reviews:', response.data);
                    $content.html('<p>Error loading automated SEO reviews: ' + (response.data || 'Unknown error') + '</p>');
                }
            },
            error: function(xhr, status, error) {
                console.error('[AYSA AUTOMATION CONTROLS] AJAX error:', error);
                console.error('[AYSA AUTOMATION CONTROLS] XHR status:', xhr.status);
                console.error('[AYSA AUTOMATION CONTROLS] Response text:', xhr.responseText);
                $content.html('<p>Error loading automated SEO reviews.</p>');
            }
        });
    }
    
    function loadImageReviews($content) {
        $content.html('<p>Image reviews functionality not implemented yet.</p>');
    }
    
    function loadRedirectReviews($content) {
        $content.html('<p>Redirect reviews functionality not implemented yet.</p>');
    }
    
    function loadMetaReviews($content) {
        $content.html('<p>Meta reviews functionality not implemented yet.</p>');
    }
    
    function loadKeywordReviews($content) {
        $content.html('<p>Keyword reviews functionality not implemented yet.</p>');
    }
    
    function loadDomainAuthorityReviews($content) {
        $content.html('<p>Domain authority reviews functionality not implemented yet.</p>');
    }

    // Debug: Check if everything is loaded correctly
    console.log('AYSA DEBUG: aysa-automation-controls.js loaded');
    console.log('AYSA DEBUG: jQuery available:', typeof $ !== 'undefined');
    console.log('AYSA DEBUG: aysaAutomation object:', typeof aysaAutomation !== 'undefined' ? aysaAutomation : 'NOT AVAILABLE');
    
    // Check DOM elements after document ready
    $(document).ready(function() {
        console.log('AYSA DEBUG: Document ready fired');
        console.log('AYSA DEBUG: Test button exists:', $('#test-cron-system').length > 0);
        console.log('AYSA DEBUG: Test results div exists:', $('#test-results').length > 0);
        console.log('AYSA DEBUG: All buttons with test-cron-system:', $('[id*="test-cron-system"]').length);
        
        // Try to find the button by different selectors
        console.log('AYSA DEBUG: Button by ID:', document.getElementById('test-cron-system'));
        console.log('AYSA DEBUG: Button by querySelector:', document.querySelector('#test-cron-system'));
    });

    // Test cron system - with debugging
    console.log('AYSA DEBUG: Attempting to attach click handler to #test-cron-system');
    
    // Try multiple ways to attach the handler
    $(document).on('click', '#test-cron-system', function() {
        console.log('AYSA DEBUG: Test cron system button clicked via document delegation!');
    });
    
    $('#test-cron-system').on('click', function() {
        console.log('AYSA DEBUG: Test cron system button clicked!');
        
        const $btn = $(this);
        const $results = $('#test-results');
        
        console.log('AYSA DEBUG: Button element:', $btn);
        console.log('AYSA DEBUG: Results element:', $results);
        console.log('AYSA DEBUG: aysaAutomation object:', aysaAutomation);
        
        $btn.prop('disabled', true).text('Testing...');
        $results.html('<div class="aysa-loading">Testing cron system...</div>');
        
        console.log('AYSA DEBUG: Starting AJAX request...');
        
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_test_seo_generation',
                nonce: aysaAutomation.nonce
            },
            beforeSend: function(xhr) {
                console.log('AYSA DEBUG: AJAX request starting...');
                console.log('AYSA DEBUG: URL:', aysaAutomation.ajax_url);
                console.log('AYSA DEBUG: Data:', {
                    action: 'aysa_test_seo_generation',
                    nonce: aysaAutomation.nonce
                });
            },
            success: function(response) {
                console.log('AYSA DEBUG: AJAX success response:', response);
                if (response.success) {
                    let resultHtml = '<div class="aysa-success-indicator">✅ Cron system test completed successfully!</div>';
                    
                    // Add debug information if available
                    if (response.data && response.data.debug_info && Array.isArray(response.data.debug_info)) {
                        resultHtml += '<div style="margin-top: 15px;"><h4>Debug Information:</h4>';
                        resultHtml += '<div style="background: #f1f1f1; padding: 10px; border-radius: 4px; font-family: monospace; font-size: 12px; max-height: 400px; overflow-y: auto;">';
                        
                        response.data.debug_info.forEach(function(line, index) {
                            // Add some styling based on content
                            let lineClass = '';
                            if (line.includes('❌')) lineClass = 'style="color: #d63638;"';
                            else if (line.includes('✅')) lineClass = 'style="color: #00a32a;"';
                            else if (line.includes('🎯') || line.includes('🔍')) lineClass = 'style="color: #135e96;"';
                            else if (line.includes('📊')) lineClass = 'style="color: #8c8f94;"';
                            
                            resultHtml += '<div ' + lineClass + '>' + (index + 1) + '. ' + line + '</div>';
                        });
                        
                        resultHtml += '</div></div>';
                    }
                    
                    $results.html(resultHtml);
                    
                    // Update status
                    updateSeoGenerationStatus();
                } else {
                    $results.html('<div class="aysa-error-indicator">❌ Test failed: ' + (response.data || 'Unknown error') + '</div>');
                }
            },
            error: function(xhr, status, error) {
                console.log('AYSA DEBUG: AJAX error occurred:');
                console.log('AYSA DEBUG: XHR:', xhr);
                console.log('AYSA DEBUG: Status:', status);
                console.log('AYSA DEBUG: Error:', error);
                console.log('AYSA DEBUG: Response text:', xhr.responseText);
                
                $results.html('<div class="aysa-error-indicator">❌ Test failed: Network error (' + error + ')<br>Check console for details</div>');
            },
            complete: function() {
                console.log('AYSA DEBUG: AJAX request completed');
                $btn.prop('disabled', false).text('🚀 Test Cron System');
            }
        });
    });
    
    // Test timeout handling
    $('#test-timeout-handling').on('click', function() {
        const $btn = $(this);
        const $results = $('#test-results');
        
        $btn.prop('disabled', true).text('Testing...');
        $results.html('<div class="aysa-loading">Testing timeout configuration...</div>');
        
        // Test different timeout scenarios
        const timeoutTests = [
            { type: 'seo-optimized-content', expected: 180 },
            { type: 'second-keyword', expected: 120 },
            { type: 'product-or-category-title', expected: 90 },
            { type: 'meta-title', expected: 60 }
        ];
        
        let resultsHtml = '<div class="aysa-info">⏱️ Timeout Configuration Test Results:</div>';
        resultsHtml += '<div class="aysa-stats-grid">';
        
        timeoutTests.forEach(function(test) {
            resultsHtml += '<div class="aysa-stat-item">';
            resultsHtml += '<div class="aysa-stat-value">' + test.expected + 's</div>';
            resultsHtml += '<div class="aysa-stat-label">' + test.type + '</div>';
            resultsHtml += '</div>';
        });
        
        resultsHtml += '</div>';
        resultsHtml += '<div class="aysa-success-indicator">✅ All timeout configurations are properly set!</div>';
        
        $results.html(resultsHtml);
        $btn.prop('disabled', false).text('⏱️ Test Timeout Handling');
    });
    
    // Get performance stats
    $('#get-performance-stats').on('click', function() {
        const $btn = $(this);
        const $results = $('#test-results');
        
        $btn.prop('disabled', true).text('Loading...');
        $results.html('<div class="aysa-loading">Loading performance statistics...</div>');
        
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_processing_stats',
                nonce: aysaAutomation.nonce
            },
            success: function(response) {
                if (response.success) {
                    const data = response.data;
                    let resultsHtml = '<div class="aysa-info">📊 Performance Statistics:</div>';
                    
                    if (data.performance_stats && Object.keys(data.performance_stats).length > 0) {
                        resultsHtml += '<div class="aysa-stats-grid">';
                        
                        Object.keys(data.performance_stats).forEach(function(processor) {
                            const stats = data.performance_stats[processor];
                            resultsHtml += '<div class="aysa-stat-item">';
                            resultsHtml += '<div class="aysa-stat-value">' + stats.average + 's</div>';
                            resultsHtml += '<div class="aysa-stat-label">' + processor + ' (avg)</div>';
                            resultsHtml += '<div style="font-size: 10px; color: #666;">Min: ' + stats.min + 's | Max: ' + stats.max + 's | Count: ' + stats.count + '</div>';
                            resultsHtml += '</div>';
                        });
                        
                        resultsHtml += '</div>';
                    } else {
                        resultsHtml += '<div class="aysa-warning">⚠️ No performance data available yet</div>';
                    }
                    
                    if (data.processing_jobs && data.processing_jobs.length > 0) {
                        resultsHtml += '<div class="aysa-info">🔄 Currently Processing: ' + data.total_processing + ' jobs</div>';
                    }
                    
                    $results.html(resultsHtml);
                } else {
                    $results.html('<div class="aysa-error-indicator">❌ Failed to load performance stats</div>');
                }
            },
            error: function() {
                $results.html('<div class="aysa-error-indicator">❌ Failed to load performance stats: Network error</div>');
            },
            complete: function() {
                $btn.prop('disabled', false).text('📊 Get Performance Stats');
            }
        });
    });
    
    // Test if buttons exist
    console.log('🚀 [DEBUG] Looking for approve/reject buttons...');
    console.log('🚀 [DEBUG] Approve buttons found:', $('.aysa-btn-approve-automated').length);
    console.log('🚀 [DEBUG] Reject buttons found:', $('.aysa-btn-reject-automated').length);
    
    // Check if buttons are loaded dynamically
    console.log('🚀 [DEBUG] Checking for dynamic button loading...');
    console.log('🚀 [DEBUG] All buttons with "approve" in class:', $('[class*="approve"]').length);
    console.log('🚀 [DEBUG] All buttons with "reject" in class:', $('[class*="reject"]').length);
    console.log('🚀 [DEBUG] All buttons in page:', $('button').length);
    
    // Check if we're in the right tab
    console.log('🚀 [DEBUG] Current active tab:', $('.review-tab.active').text());
    console.log('🚀 [DEBUG] Automated SEO tab exists:', $('.review-tab[data-tab="automated-seo"]').length);
    
    // Set up observer to detect when buttons are added dynamically
    console.log('🚀 [DEBUG] Setting up MutationObserver for dynamic buttons...');
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                const approveButtons = document.querySelectorAll('.aysa-btn-approve-automated');
                const rejectButtons = document.querySelectorAll('.aysa-btn-reject-automated');
                
                if (approveButtons.length > 0 || rejectButtons.length > 0) {
                    console.log('🚀 [DEBUG] Buttons detected dynamically!');
                    console.log('🚀 [DEBUG] Approve buttons found:', approveButtons.length);
                    console.log('🚀 [DEBUG] Reject buttons found:', rejectButtons.length);
                    
                    // Re-attach event handlers if needed
                    console.log('🚀 [DEBUG] Re-attaching event handlers...');
                }
            }
        });
    });
    
    // Start observing
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
    
    console.log('🚀 [DEBUG] MutationObserver started');
    
    // Main tab switching handler
    $(document).on('click', '.review-tab', function() {
        const tab = $(this).data('tab');
        console.log('🚀 [DEBUG] Tab clicked with data-tab:', tab);
        
        // Remove active class from all tabs and content
        $('.review-tab').removeClass('active');
        $('.review-content').hide();
        
        // Add active class to clicked tab and show corresponding content
        $(this).addClass('active');
        $('#' + tab + '-reviews').show();
        
        console.log('🚀 [DEBUG] Tab switched to:', tab);
        console.log('🚀 [DEBUG] Content shown for:', '#' + tab + '-reviews');
        
        // Load content for the selected tab
        console.log('🚀 [DEBUG] About to call loadTabContent for:', tab);
        loadTabContent(tab);
    });
    
    // Event handlers for automated SEO review buttons
    $(document).on('click', '.approve-review', function() {
        const $reviewItem = $(this).closest('.review-item');
        const reviewId = $(this).data('id');
        const entityInfo = $reviewItem.find('h4').text().trim();
        
        console.log('📋 [DEBUG] Approve button clicked for review ID:', reviewId);
        
        // Validate required data
        if (!reviewId) {
            console.error('❌ [ERROR] Review ID is missing from button data');
            alert('Review ID is missing. Cannot approve review.');
            return;
        }
        
        // Show loading state
        $(this).prop('disabled', true).text('Approving...');
        
        const requestData = {
            action: 'aysa_approve_automated_review',
            review_id: reviewId,
            nonce: aysaAutomation.nonce
        };
        
        console.log('📤 [DEBUG] Sending approval request:', requestData);
        
        // Make AJAX call to approve
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: requestData,
            beforeSend: function() {
                console.log('🚀 [DEBUG] AJAX request starting...');
            },
            success: function(response) {
                console.log('✅ [DEBUG] AJAX success response:', response);
                
                if (response.success) {
                    console.log('✅ [DEBUG] Server returned success, data:', response.data);
                    
                    // Remove from pending reviews table
                    $reviewItem.remove();
                    
                    // Show success message
                    alert('✅ SEO changes applied for "' + entityInfo + '"');
                } else {
                    console.error('❌ [ERROR] Server returned failure for approval:', response.data);
                    alert('❌ Failed to approve review: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('💥 [FATAL ERROR] Approval AJAX request failed:');
                console.error('📊 [ERROR] XHR status:', xhr.status);
                console.error('📊 [ERROR] Status text:', status);
                console.error('📊 [ERROR] Error message:', error);
                console.error('📊 [ERROR] Response text:', xhr.responseText);
                alert('❌ Failed to approve review. Please try again.');
            },
            complete: function() {
                // Reset button state
                $reviewItem.find('.approve-review').prop('disabled', false).text('Approve');
            }
        });
    });
    
    $(document).on('click', '.reject-review', function() {
        const $reviewItem = $(this).closest('.review-item');
        const reviewId = $(this).data('id');
        const entityInfo = $reviewItem.find('h4').text().trim();
        
        console.log('📋 [DEBUG] Reject button clicked for review ID:', reviewId);
        console.log('📋 [DEBUG] Entity info:', entityInfo);
        
        // Validate required data
        if (!reviewId) {
            console.error('❌ [ERROR] Review ID is missing from button data');
            alert('Review ID is missing. Cannot reject review.');
            return;
        }
        
        // Show loading state
        $(this).prop('disabled', true).text('Rejecting...');
        console.log('🚀 [DEBUG] Button disabled, sending AJAX request...');
        
        const requestData = {
            action: 'aysa_reject_automated_review',
            review_id: reviewId,
            nonce: aysaAutomation.nonce
        };
        
        console.log('📤 [DEBUG] Sending rejection request:', requestData);
        
        // Make AJAX call to reject
        $.ajax({
            url: aysaAutomation.ajax_url,
            type: 'POST',
            data: requestData,
            beforeSend: function() {
                console.log('🚀 [DEBUG] AJAX request starting for reject...');
            },
            success: function(response) {
                console.log('✅ [DEBUG] Reject response:', response);
                console.log('✅ [DEBUG] Response success:', response.success);
                console.log('✅ [DEBUG] Response data:', response.data);
                
                if (response.success) {
                    // Remove from pending reviews table
                    $reviewItem.remove();
                    
                    // Show success message
                    alert('✅ SEO suggestions rejected for "' + entityInfo + '"');
                } else {
                    console.error('❌ [ERROR] Failed to reject review:', response.data);
                    alert('❌ Failed to reject review: ' + (response.data || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                console.error('💥 [FATAL ERROR] Reject AJAX request failed:');
                console.error('📊 [ERROR] XHR status:', xhr.status);
                console.error('📊 [ERROR] Status text:', status);
                console.error('📊 [ERROR] Error message:', error);
                console.error('📊 [ERROR] Response text:', xhr.responseText);
                alert('❌ Failed to reject review. Please try again.');
            },
            complete: function() {
                // Reset button state
                $reviewItem.find('.reject-review').prop('disabled', false).text('Reject');
            }
        });
    });
    
    // Event handlers for preview buttons
    $(document).on('click', '.aysa-btn-preview', function() {
        const $row = $(this).closest('tr');
        const reviewData = $row.data('review-data');
        const keyword = $row.data('keyword');
        const associationId = $row.data('association-id');
        
        console.log('📋 [DEBUG] Preview button clicked:', {
            reviewData: reviewData,
            keyword: keyword,
            associationId: associationId
        });
        
        if (reviewData && reviewData.seo_data) {
            try {
                const seoData = JSON.parse(reviewData.seo_data);
                showSEOPreviewModal(associationId, keyword, seoData);
            } catch (e) {
                console.error('❌ [ERROR] Failed to parse SEO data:', e);
                alert('❌ Failed to load preview data');
            }
        } else {
            alert('❌ No preview data available');
        }
    });
    
    // Function to show SEO preview modal
    function showSEOPreviewModal(associationId, keyword, seoData) {
        console.log('🔍 [DEBUG] showSEOPreviewModal called with:', {
            associationId: associationId,
            keyword: keyword,
            seoData: seoData
        });
        
        // Build preview sections based on available data
        let previewSections = '';
        
        // Define field mappings for better display names
        const fieldMappings = {
            'metaTitle': 'Meta Title',
            'metaDescription': 'Meta Description', 
            'metaKeywords': 'Meta Keywords',
            'secondKeyword': 'Secondary Keywords',
            'entityTitle': 'Entity Title',
            'entityContent': 'Entity Content',
            'shortProductDescription': 'Short Description',
            'permalink': 'Permalink'
        };
        
        // Loop through all available fields in seoData
        for (const [key, value] of Object.entries(seoData)) {
            if (value && value !== '' && value !== null && value !== undefined) {
                const displayName = fieldMappings[key] || key.charAt(0).toUpperCase() + key.slice(1);
                
                if (key === 'entityContent' || key === 'metaDescription') {
                    // Handle long content fields with scroll
                    previewSections += `
                        <div class="aysa-preview-section">
                            <h3>${displayName}</h3>
                            <div class="aysa-preview-suggested">
                                <strong>Generated:</strong> <div class="aysa-content-preview">${value}</div>
                            </div>
                        </div>
                    `;
                } else {
                    // Handle regular text fields
                    previewSections += `
                        <div class="aysa-preview-section">
                            <h3>${displayName}</h3>
                            <div class="aysa-preview-suggested">
                                <strong>Generated:</strong> <span>${value}</span>
                            </div>
                        </div>
                    `;
                }
            }
        }
        
        const modalHtml = `
            <div id="aysa-seo-preview-modal" class="aysa-modal">
                <div class="aysa-modal-content">
                    <div class="aysa-modal-header">
                        <h2 class="aysa-modal-title">SEO Preview for "${keyword}"</h2>
                        <span class="aysa-modal-close">&times;</span>
                    </div>
                    <div class="aysa-modal-body">
                        ${previewSections || '<p>No SEO data available for preview.</p>'}
                    </div>
                    <div class="aysa-modal-footer">
                        <button class="aysa-btn aysa-btn-secondary" id="aysa-preview-close-btn">Close</button>
                    </div>
                </div>
            </div>
        `;
        
        // Add modal to page
        $('body').append(modalHtml);
        
        // Show modal
        $('#aysa-seo-preview-modal').show();
        
        // Close modal handlers
        $('#aysa-seo-preview-modal .aysa-modal-close, #aysa-preview-close-btn').on('click', function() {
            $('#aysa-seo-preview-modal').remove();
        });
        
        // Close on outside click
        $('#aysa-seo-preview-modal').on('click', function(e) {
            if (e.target === this) {
                $('#aysa-seo-preview-modal').remove();
            }
        });
    }
});
