/**
 * Batch Processing JavaScript for Content Performance Analyzer
 *
 * @package ContentPerformanceAnalyzer
 * @since 1.0.0
 */

(function($) {
    'use strict';
    
    var batchProcessor = {
        isRunning: false,
        statusInterval: null,
        passiveInterval: null,

        init: function() {
            this.bindEvents();
            this.checkInitialStatus();
            this.startPassiveWatch();
        },

        // The URL Status table is server-rendered, so when background cron
        // finishes pending URLs the page goes stale (fresh stat cards via
        // AJAX, old table rows). Watch quietly and reload once everything
        // pending has completed.
        startPassiveWatch: function() {
            var self = this;
            var polls = 0;

            this.getStatus(function(initial) {
                var pendingWork = (initial.data.pending || 0) + (initial.data.in_progress || 0);
                if (pendingWork === 0 || initial.data.is_running) {
                    return; // Nothing outstanding, or active-run monitoring handles it.
                }

                self.passiveInterval = setInterval(function() {
                    polls++;
                    if (polls > 100 || self.isRunning) { // ~5 minutes, or a manual run took over
                        clearInterval(self.passiveInterval);
                        self.passiveInterval = null;
                        return;
                    }
                    self.getStatus(function(response) {
                        self.updateStatusDisplay(response.data);
                        if (!response.data.is_running && (response.data.pending || 0) === 0 && (response.data.in_progress || 0) === 0) {
                            clearInterval(self.passiveInterval);
                            self.passiveInterval = null;
                            location.reload();
                        }
                    });
                }, 3000);
            });
        },
        
        bindEvents: function() {
            $('#cpanalyzer-start-batch').on('click', this.startBatch.bind(this));
            $('#cpanalyzer-rescan-all').on('click', this.rescanAll.bind(this));
            $('#cpanalyzer-cancel-batch').on('click', this.cancelBatch.bind(this));
            $('#cpanalyzer-refresh-status').on('click', this.refreshStatus.bind(this));
            $('.cpanalyzer-retry-url').on('click', this.retryUrl.bind(this));
        },
        
        checkInitialStatus: function() {
            this.getStatus(function(response) {
                if (response.data.is_running) {
                    batchProcessor.showProgress();
                    batchProcessor.startStatusMonitoring();
                }
            });
        },
        
        startBatch: function(e) {
            e.preventDefault();
            
            var $button = $(e.currentTarget);
            $button.prop('disabled', true);
            
            $.ajax({
                url: cpanalyzer_batch.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_start_batch_process',
                    nonce: cpanalyzer_batch.batch_nonce
                },
                success: function(response) {
                    if (response.success) {
                        batchProcessor.showMessage(cpanalyzer_batch.strings.starting, 'info');
                        batchProcessor.showProgress();
                        batchProcessor.startStatusMonitoring();
                    } else {
                        batchProcessor.showMessage(response.data.message || cpanalyzer_batch.strings.error, 'error');
                    }
                },
                error: function() {
                    batchProcessor.showMessage(cpanalyzer_batch.strings.error, 'error');
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        },
        
        rescanAll: function(e) {
            e.preventDefault();
            
            if (!confirm(cpanalyzer_batch.strings.confirm_rescan)) {
                return;
            }
            
            var $button = $(e.currentTarget);
            $button.prop('disabled', true);
            
            $.ajax({
                url: cpanalyzer_batch.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_rescan_all_urls',
                    nonce: cpanalyzer_batch.batch_nonce
                },
                success: function(response) {
                    if (response.success) {
                        batchProcessor.showMessage(response.data.message, 'success');
                        batchProcessor.showProgress();
                        batchProcessor.startStatusMonitoring();
                        
                        // Reload page after 2 seconds to show updated status
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        batchProcessor.showMessage(response.data.message || cpanalyzer_batch.strings.error, 'error');
                    }
                },
                error: function() {
                    batchProcessor.showMessage(cpanalyzer_batch.strings.error, 'error');
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        },
        
        cancelBatch: function(e) {
            e.preventDefault();
            
            var $button = $(e.currentTarget);
            $button.prop('disabled', true);
            
            $.ajax({
                url: cpanalyzer_batch.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_cancel_batch',
                    nonce: cpanalyzer_batch.batch_nonce
                },
                success: function(response) {
                    if (response.success) {
                        batchProcessor.hideProgress();
                        batchProcessor.stopStatusMonitoring();
                        batchProcessor.showMessage(response.data.message, 'info');
                        
                        // Reload page after 1 second
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    }
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        },
        
        refreshStatus: function(e) {
            e.preventDefault();

            // Full reload so the URL Status table refreshes along with the
            // stat cards — updating only the cards left the two contradicting
            // each other.
            location.reload();
        },
        
        retryUrl: function(e) {
            e.preventDefault();
            
            var $button = $(e.currentTarget);
            var urlId = $button.data('url-id');
            
            $button.prop('disabled', true);
            
            $.ajax({
                url: cpanalyzer_batch.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_retry_failed_url',
                    nonce: cpanalyzer_batch.batch_nonce,
                    url_id: urlId
                },
                success: function(response) {
                    if (response.success) {
                        batchProcessor.showMessage(response.data.message, 'success');
                        
                        // Update button text and style
                        $button.text('Queued').removeClass('button-small').addClass('button-disabled');
                        
                        // Start monitoring if not already running
                        if (!batchProcessor.isRunning) {
                            batchProcessor.startStatusMonitoring();
                        }
                    } else {
                        batchProcessor.showMessage(response.data.message || 'Retry failed', 'error');
                        $button.prop('disabled', false);
                    }
                }
            });
        },
        
        startStatusMonitoring: function() {
            if (this.statusInterval) {
                return;
            }
            
            this.isRunning = true;
            $('#cpanalyzer-start-batch').hide();
            $('#cpanalyzer-cancel-batch').show();
            
            // Update status every 3 seconds
            this.statusInterval = setInterval(function() {
                batchProcessor.getStatus(function(response) {
                    batchProcessor.updateStatusDisplay(response.data);
                    
                    // Check if processing is complete
                    if (!response.data.is_running && response.data.pending === 0) {
                        batchProcessor.processingComplete();
                    }
                });
            }, 3000);
        },
        
        stopStatusMonitoring: function() {
            if (this.statusInterval) {
                clearInterval(this.statusInterval);
                this.statusInterval = null;
            }
            
            this.isRunning = false;
            $('#cpanalyzer-start-batch').show();
            $('#cpanalyzer-cancel-batch').hide();
        },
        
        getStatus: function(callback) {
            $.ajax({
                url: cpanalyzer_batch.ajax_url,
                type: 'POST',
                data: {
                    action: 'cpanalyzer_get_batch_status',
                    nonce: cpanalyzer_batch.batch_nonce
                },
                success: callback,
                error: function() {
                    console.error('Failed to get batch status');
                }
            });
        },
        
        updateStatusDisplay: function(data) {
            // Update statistics
            $('.cpanalyzer-stat-card').each(function() {
                var $card = $(this);
                var label = $card.find('.cpanalyzer-stat-label').text().toLowerCase();
                
                if (label.includes('total')) {
                    $card.find('.cpanalyzer-stat-value').text(data.total);
                } else if (label.includes('pending')) {
                    $card.find('.cpanalyzer-stat-value').text(data.pending);
                } else if (label.includes('progress')) {
                    $card.find('.cpanalyzer-stat-value').text(data.in_progress);
                } else if (label.includes('completed')) {
                    $card.find('.cpanalyzer-stat-value').text(data.success);
                } else if (label.includes('failed')) {
                    $card.find('.cpanalyzer-stat-value').text(data.failed);
                }
            });
            
            // Progress bar removed - statistics cards provide accurate progress info
        },
        
        processingComplete: function() {
            this.stopStatusMonitoring();
            this.hideProgress();
            this.showMessage(cpanalyzer_batch.strings.completed, 'success');
            
            // Reload page after 2 seconds to show final results
            setTimeout(function() {
                location.reload();
            }, 2000);
        },
        
        showProgress: function() {
            // Progress bar removed - no action needed
        },
        
        hideProgress: function() {
            // Progress bar removed - no action needed
        },
        
        showMessage: function(message, type) {
            // Remove existing messages
            $('.cpanalyzer-batch-message').remove();
            
            var alertClass = 'notice-info';
            if (type === 'success') alertClass = 'notice-success';
            if (type === 'error') alertClass = 'notice-error';
            
            var $message = $('<div class="notice ' + alertClass + ' cpanalyzer-batch-message is-dismissible">' +
                '<p>' + message + '</p>' +
                '</div>');
            
            $('.cpanalyzer-batch-controls').prepend($message);
            
            // Auto-hide after 5 seconds
            setTimeout(function() {
                $message.fadeOut(function() {
                    $(this).remove();
                });
            }, 5000);
        }
    };
    
    // Initialize on document ready
    $(document).ready(function() {
        if ($('.cpanalyzer-batch-controls').length > 0) {
            batchProcessor.init();
        }
    });
    
})(jQuery);