/**
 * Site Content Analyzer JavaScript
 * Handles content scanning, sync confirmation, and progress tracking
 */

jQuery(document).ready(function($) {
    'use strict';

    // Initialize the Site Content Analyzer
    const SiteContentAnalyzer = {
        progressInterval: null,
        isScanning: false,

        init() {
            this.bindEvents();
            this.loadInitialData();
        },

        bindEvents() {
            // Sync Now button click
            $(document).on('click', '#start-content-sync', this.showSyncConfirmation.bind(this));
            
            // Reset Scan button click
            $(document).on('click', '#reset-content-scan', this.resetScan.bind(this));
            
            // View Log button click
            $(document).on('click', '#view-scan-log', this.showScanLog.bind(this));
            
            // Modal close events for custom scan log modal
            $(document).on('click', '.blog82ai-modal-close', function(e) {
                $(this).closest('.blog82ai-modal').hide();
            });

            // Close modal when clicking outside (for scan log modal)
            $(document).on('click', '.blog82ai-modal', function(e) {
                if (e.target === this) {
                    $(this).hide();
                }
            });

            // Confirmation dialog buttons are handled by the reusable modal system

            // Auto-refresh progress when page loads if scan is in progress
            this.checkScanStatus();
        },

        loadInitialData() {
            // Load current scan overview data
            this.updateScanOverview();
        },

        showSyncConfirmation() {
            // Use the reusable modal system for confirmation
            const title = "Start Content Analysis?";
            const message = `This will scan all your published posts and send the content data to our API for analysis. The process may take several minutes depending on the number of posts.

What will be analyzed:
• Post titles, content, and excerpts
• Publication dates and categories  
• Yoast SEO meta data (if available)
• Focus keywords and SEO scores

Your content will be securely transmitted to our servers for fingerprinting and analysis. No content will be stored permanently - only content fingerprints for duplication detection.`;

            Blog82AI_Modal.showConfirm(
                title,
                message,
                () => {
                    // User confirmed - start the sync
                    this.startContentSync();
                },
                () => {
                    // User cancelled - do nothing
                }
            );
        },

        hideSyncConfirmation() {
            // No longer needed since we use the reusable modal
            Blog82AI_Modal.closeConfirm();
        },

        async resetScan() {
            // Use the reusable modal system for confirmation
            Blog82AI_Modal.showConfirm(
                'Reset Scan Process',
                'Are you sure you want to reset the scan process? This will clear the current progress and stop any running scans.',
                async () => {
                    // User confirmed - proceed with reset
                    try {
                        // Show loading state
                        $('#reset-content-scan').prop('disabled', true).html('<i class="dashicons dashicons-update-alt"></i> Resetting...');
                        Blog82AI_Modal.showLoading('Resetting scan process...');
                        
                        const response = await $.ajax({
                            url: blogibotAjax.ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'blogibot_reset_scan',
                                nonce: blogibotAjax.nonces.content_scan
                            }
                        });

                        Blog82AI_Modal.closeLoading();

                        if (response.success) {
                            Blog82AI_Modal.showSuccess('Reset Complete', 'Scan process reset successfully! The page will refresh shortly.');
                            
                            // Stop progress tracking
                            clearInterval(this.progressInterval);
                            this.isScanning = false;
                            
                            // Reset UI
                            $('.sync-progress').hide();
                            $('.status-badge').removeClass('status-running status-completed')
                                             .addClass('status-pending')
                                             .html('<i class="dashicons dashicons-clock"></i> Not Started');
                            
                            $('#start-content-sync').prop('disabled', false)
                                                   .html('<i class="dashicons dashicons-cloud-upload"></i> Sync Now');
                            
                            $('.progress-fill').css('width', '0%');
                            $('.progress-text').text('No scan in progress');
                            
                            // Reload the page to refresh all data
                            setTimeout(() => {
                                window.location.reload();
                            }, 2000);
                            
                        } else {
                            throw new Error(response.data.message || 'Failed to reset scan');
                        }

                    } catch (error) {
                        console.error('Reset error:', error);
                        Blog82AI_Modal.closeLoading();
                        Blog82AI_Modal.showError('Reset Failed', 'Error resetting scan: ' + error.message);
                        
                        $('#reset-content-scan').prop('disabled', false).html('<i class="dashicons dashicons-image-rotate"></i> Reset');
                    }
                },
                () => {
                    // User cancelled - do nothing
                }
            );
        },

        async startContentSync() {
            try {
                // Disable the sync button and show loading
                $('#start-content-sync').prop('disabled', true).html('<i class="dashicons dashicons-update-alt"></i> Starting...');
                
                // Show loading modal
                Blog82AI_Modal.showLoading('Starting content analysis...');
                
                // Start the scan
                const response = await $.ajax({
                    url: blogibotAjax.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'blogibot_start_content_scan',
                        nonce: blogibotAjax.nonces.content_scan
                    }
                });

                // Close loading modal
                Blog82AI_Modal.closeLoading();

                if (response.success) {
                    // Show success message
                    Blog82AI_Modal.showSuccess('Content Analysis Started', 'Content analysis started successfully! Processing will begin now...');
                    
                    this.isScanning = true;
                    this.currentScanId = response.data.scan_id;
                    this.currentPage = 1;
                    
                    // Start direct batch processing (no polling, just process batches via AJAX)
                    this.updateScanningUI();
                    this.processBatch();
                } else {
                    throw new Error(response.data.message || 'Failed to start content scan');
                }

            } catch (error) {
                console.error('Sync error:', error);
                
                // Close loading modal and show error
                Blog82AI_Modal.closeLoading();
                Blog82AI_Modal.showError('Sync Failed', 'Error: ' + error.message);
                
                // Re-enable the sync button
                $('#start-content-sync').prop('disabled', false).html('<i class="dashicons dashicons-cloud-upload"></i> Sync Now');
            }
        },

        async processBatch() {
            if (!this.isScanning) {
                return;
            }

            try {
                const response = await $.ajax({
                    url: blogibotAjax.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'blogibot_process_batch',
                        nonce: blogibotAjax.nonces.content_scan,
                        scan_id: this.currentScanId,
                        page: this.currentPage
                    }
                });

                if (response.success) {
                    const progress = response.data.progress;
                    
                    // Update progress bar immediately
                    $('.progress-fill').css('width', progress.percentage + '%');
                    $('.progress-text').text(`Processed ${progress.posts_processed} of ${progress.total_posts} posts (${progress.percentage}%)`);
                    
                    // If there are more batches, process next one
                    if (response.data.has_more) {
                        this.currentPage = response.data.next_page;
                        // Small delay to prevent overwhelming the server
                        setTimeout(() => {
                            this.processBatch();
                        }, 500);
                    } else {
                        // Scan completed!
                        this.onScanCompleted(progress);
                    }
                } else {
                    throw new Error(response.data.message || 'Batch processing failed');
                }

            } catch (error) {
                console.error('Batch processing error:', error);
                this.onScanError({
                    message: 'Batch processing error: ' + error.message
                });
            }
        },

        startProgressTracking() {
            // This method is no longer used (kept for backward compatibility)
            // We now process batches directly via AJAX instead of polling
            this.updateScanningUI();
        },

        updateScanningUI() {
            // Show the progress bar container
            $('.sync-progress').show();
            
            // Update the status badge
            $('.status-badge').removeClass('status-completed status-pending')
                             .addClass('status-running')
                             .html('<span class="spinner"></span> Scanning in progress...');
            
            // Update sync button
            $('#start-content-sync').prop('disabled', true)
                                   .html('<i class="dashicons dashicons-update-alt"></i> Scanning...');
        },

        async updateProgress() {
            try {
                const response = await $.ajax({
                    url: blogibotAjax.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'blogibot_get_scan_progress',
                        nonce: blogibotAjax.nonces.content_scan
                    }
                });

                if (response.success) {
                    const progress = response.data.data;
                    
                    // Update progress bar
                    $('.progress-fill').css('width', progress.percentage + '%');
                    $('.progress-text').text(progress.message);
                    
                    // Update status badge
                    if (progress.status === 'completed') {
                        this.onScanCompleted(progress);
                    } else if (progress.status === 'error') {
                        this.onScanError(progress);
                    } else {
                        // Update scanning status
                        $('.status-badge .spinner').show();
                    }
                } else {
                    console.error('Failed to get progress:', response.data.message);
                }

            } catch (error) {
                console.error('Progress update error:', error);
            }
        },

        onScanCompleted(progress) {
            // Stop progress tracking
            clearInterval(this.progressInterval);
            this.isScanning = false;
            
            // Hide progress bar
            $('.sync-progress').hide();
            
            // Update UI
            $('.status-badge').removeClass('status-running')
                             .addClass('status-completed')
                             .html('<i class="dashicons dashicons-yes-alt"></i> Completed');
            
            $('#start-content-sync').prop('disabled', false)
                                   .html('<i class="dashicons dashicons-cloud-upload"></i> Sync Now');
            
            // Show success message with modal
            Blog82AI_Modal.showSuccess(
                'Scan Completed',
                `Content scan completed successfully! Processed ${progress.posts_processed} posts. The page will refresh to show updated data.`,
                true
            );
            
            // Update the overview data
            setTimeout(() => {
                this.updateScanOverview();
                window.location.reload();
            }, 3000);
        },

        onScanError(progress) {
            // Stop progress tracking
            clearInterval(this.progressInterval);
            this.isScanning = false;
            
            // Hide progress bar
            $('.sync-progress').hide();
            
            // Update UI
            $('.status-badge').removeClass('status-running')
                             .addClass('status-pending')
                             .html('<i class="dashicons dashicons-warning"></i> Error');
            
            $('#start-content-sync').prop('disabled', false)
                                   .html('<i class="dashicons dashicons-cloud-upload"></i> Retry Sync');
            
            // Show error message with modal
            Blog82AI_Modal.showError(
                'Scan Failed',
                'Content scan failed: ' + (progress.error || 'Unknown error occurred. Please try again.')
            );
        },

        async checkScanStatus() {
            try {
                const response = await $.ajax({
                    url: blogibotAjax.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'blogibot_get_scan_progress',
                        nonce: blogibotAjax.nonces.content_scan
                    }
                });

                if (response.success) {
                    const progress = response.data.data;
                    
                    if (progress.status === 'in_progress') {
                        this.isScanning = true;
                        this.startProgressTracking();
                    }
                }

            } catch (error) {
                console.error('Status check error:', error);
            }
        },

        async showScanLog() {
            try {
                // Show loading
                Blog82AI_Modal.showLoading('Loading scan log...');
                
                const response = await $.ajax({
                    url: blogibotAjax.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'blogibot_get_scan_log',
                        nonce: blogibotAjax.nonces.content_scan
                    }
                });

                Blog82AI_Modal.closeLoading();

                if (response.success) {
                    const logData = response.data.data;
                    
                    // Create a custom modal for the log using the same structure as the reusable system
                    const logModalHtml = `
                        <div id="scan-log-modal" class="blog82ai-modal" style="display: block;">
                            <div class="blog82ai-modal-content">
                                <div class="blog82ai-modal-header">
                                    <h3><i class="dashicons dashicons-list-view"></i> Content Scan Log</h3>
                                    <span class="blog82ai-modal-close" onclick="document.getElementById('scan-log-modal').style.display='none'">&times;</span>
                                </div>
                                <div class="blog82ai-modal-body">
                                    ${logData.log_html}
                                </div>
                            </div>
                        </div>
                    `;
                    
                    // Remove any existing log modal and add new one
                    $('#scan-log-modal').remove();
                    $('body').append(logModalHtml);

                    // Add click outside to close
                    $(document).off('click.scanLogModal').on('click.scanLogModal', '#scan-log-modal', function(e) {
                        if (e.target === this) {
                            $(this).hide();
                        }
                    });
                    
                } else {
                    throw new Error(response.data.message || 'Failed to load scan log');
                }

            } catch (error) {
                console.error('Log loading error:', error);
                Blog82AI_Modal.closeLoading();
                Blog82AI_Modal.showError('Load Failed', 'Error loading scan log: ' + error.message);
            }
        },

        async updateScanOverview() {
            // This would typically fetch updated metrics from the server
            // For now, we'll just update the display based on stored options
            try {
                // Try to compute a fallback progress from server-rendered metrics
                // so small sites see immediate progress even if AJAX returns 0.
                const metrics = document.querySelectorAll('.blog82ai-metric-item');
                let postsFound = null, postsAnalyzed = null;
                metrics.forEach(item => {
                    const label = (item.querySelector('.blog82ai-metric-label') || {}).textContent || '';
                    const valueNode = item.querySelector('.blog82ai-metric-value');
                    const valueText = valueNode ? valueNode.textContent.trim().replace(/,/g, '') : '';
                    if (/Total Posts/i.test(label)) {
                        postsFound = parseInt(valueText) || postsFound;
                    }
                    if (/Posts Analyzed/i.test(label)) {
                        postsAnalyzed = parseInt(valueText) || postsAnalyzed;
                    }
                });

                if (postsFound !== null && postsAnalyzed !== null && postsFound > 0) {
                    const pct = Math.round((postsAnalyzed / postsFound) * 100 * 10) / 10; // one decimal
                    const progressFill = document.querySelector('.progress-fill');
                    const progressText = document.querySelector('.progress-text');
                    if (progressFill) progressFill.style.width = pct + '%';
                    if (progressText) progressText.textContent = `Processed ${postsAnalyzed} of ${postsFound} posts (${pct}%)`;
                }
            } catch (error) {
                console.error('Overview update error:', error);
            }
        },

        showToast(message, type = 'info') {
            if (typeof toastr !== 'undefined') {
                // Configure toastr
                toastr.options = {
                    closeButton: true,
                    debug: false,
                    newestOnTop: true,
                    progressBar: true,
                    positionClass: 'toast-top-right',
                    preventDuplicates: false,
                    onclick: null,
                    showDuration: '300',
                    hideDuration: '1000',
                    timeOut: '5000',
                    extendedTimeOut: '1000',
                    showEasing: 'swing',
                    hideEasing: 'linear',
                    showMethod: 'fadeIn',
                    hideMethod: 'fadeOut'
                };

                // Show toast based on type
                switch (type) {
                    case 'success':
                        toastr.success(message);
                        break;
                    case 'error':
                        toastr.error(message);
                        break;
                    case 'warning':
                        toastr.warning(message);
                        break;
                    case 'info':
                    default:
                        toastr.info(message);
                        break;
                }
            }
        }
    };

    // Initialize the analyzer
    SiteContentAnalyzer.init();

    // Make it globally accessible for debugging
    window.SiteContentAnalyzer = SiteContentAnalyzer;
});
