/**
 * VMPFence Admin JavaScript
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.2 Added pause overlay functionality, dynamic update intervals
 * @since 2.2.4 scan.js now owns the scan page UI, admin.js will not bind scan buttons or progress updates if on scan page
 */

(function($) {
    'use strict';

    /**
     * Main VMPFence Admin Object
     */
    window.VMPFenceAdmin = {
        
        /**
         * Check if live updates should be paused (window not focused)
         * @returns {boolean} True if updates should pause
         */
        shouldPauseLiveUpdates: function() {
            // Check if pause setting is enabled (default: enabled)
            var pauseEnabled = typeof vmpfence_admin !== 'undefined' && vmpfence_admin.pause_live_updates === '1';
            if (!pauseEnabled) {
                return false; // Setting disabled, never pause
            }
            // Check if document has focus
            return !document.hasFocus();
        },
        
        /**
         * Show pause overlay when window loses focus
         */
        showPauseOverlay: function() {
            // Only show if pause setting is enabled
            var pauseEnabled = typeof vmpfence_admin !== 'undefined' && vmpfence_admin.pause_live_updates === '1';
            if (!pauseEnabled) {
                return;
            }
            
            // Create overlay if it doesn't exist
            if (!$('#vmpfence-pause-overlay').length) {
                var overlay = $('<div id="vmpfence-pause-overlay">' +
                    '<div class="vmpfence-pause-message">' +
                    '<svg width="20" height="20" viewBox="0 0 20 20" fill="none">' +
                    '<rect x="6" y="4" width="3" height="12" rx="1" fill="currentColor"/>' +
                    '<rect x="11" y="4" width="3" height="12" rx="1" fill="currentColor"/>' +
                    '</svg>' +
                    '<span>Live updates paused</span>' +
                    '</div>' +
                    '</div>');
                $('body').append(overlay);
            }
            
            // Show overlay with fade-in
            $('#vmpfence-pause-overlay').fadeIn(300);
        },
        
        /**
         * Hide pause overlay when window regains focus
         */
        hidePauseOverlay: function() {
            $('#vmpfence-pause-overlay').fadeOut(300);
        },
        
        /**
         * Initialize admin functionality
         * @since 2.0.0 -- Added brute force settings initialization
         */
        init: function() {
            this.bindEvents();
            this.initTooltips();
            this.initToggleSwitches();
            this.initProgressBars();
            this.loadDashboardData();
        },

        /**
         * Bind event handlers
         */
        bindEvents: function() {
            var self = this;
            
            // Window focus/blur events for pause overlay
            $(window).on('blur', function() {
                self.showPauseOverlay();
            });
            $(window).on('focus', function() {
                self.hidePauseOverlay();
            });
            
            // Navigation tabs
            $('.vmpfence-nav-tabs .nav-tab').on('click', this.handleTabClick);
            
            // Form submissions
            $('.vmpfence-form').on('submit', this.handleFormSubmit);
            
            // AJAX buttons
            $('.vmpfence-ajax-button').on('click', this.handleAjaxButton);
            
            // Scan buttons — only bind if scan.js is NOT loaded (scan.js owns the scan page)
            // Detect scan page by checking for .vmpfence-btn-start-scan (exists only on scan.php)
            if (!$('.vmpfence-btn-start-scan').length) {
                $('#vmpfence-start-scan').on('click', this.startScan);
                $('#vmpfence-stop-scan').on('click', this.stopScan);
            }
            
            // Settings toggles
            $('.vmpfence-toggle input').on('change', this.handleToggleChange);
            
            // Bulk actions
            $('#vmpfence-bulk-action').on('click', this.handleBulkAction);
            
            // Search and filters
            $('#vmpfence-search').on('input', this.debounce(this.handleSearch, 300));
            $('.vmpfence-filter').on('change', this.handleFilterChange);
            
            // Modal dialogs
            $('.vmpfence-modal-trigger').on('click', this.openModal);
            $('.vmpfence-modal-close').on('click', this.closeModal);
            
            // File uploads
            $('.vmpfence-file-upload').on('change', this.handleFileUpload);
        },

        /**
         * Handle tab navigation
         */
        handleTabClick: function(e) {
            e.preventDefault();
            
            var $tab = $(this);
            var target = $tab.attr('href');
            
            // Update active tab
            $('.vmpfence-nav-tabs .nav-tab').removeClass('nav-tab-active');
            $tab.addClass('nav-tab-active');
            
            // Show/hide content
            $('.vmpfence-tab-content').hide();
            $(target).show();
            
            // Update URL without reload
            if (history.pushState) {
                history.pushState(null, null, $tab.attr('href'));
            }
            
            // Trigger tab change event
            $(document).trigger('vmpfence:tab:changed', [target]);
        },

        /**
         * Handle form submissions
         */
        handleFormSubmit: function(e) {
            var $form = $(this);
            var $submitButton = $form.find('[type="submit"]');
            var originalText = $submitButton.val() || $submitButton.text();
            
            // Show loading state
            $submitButton.prop('disabled', true);
            $submitButton.val(vmpfence_admin.i18n.saving || 'Saving...');
            
            // Add spinner
            if (!$form.find('.vmpfence-spinner').length) {
                $submitButton.after('<span class="vmpfence-spinner"></span>');
            }
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: $form.serialize() + '&action=vmpfence_save_settings&nonce=' + vmpfence_admin.nonce,
                success: function(response) {
                    if (response.success) {
                        VMPFenceAdmin.showNotice('success', response.data.message || vmpfence_admin.i18n.saved);
                        
                        // Trigger settings saved event
                        $(document).trigger('vmpfence:settings:saved', [response.data]);
                    } else {
                        VMPFenceAdmin.showNotice('error', response.data.message || vmpfence_admin.i18n.error);
                    }
                },
                error: function() {
                    VMPFenceAdmin.showNotice('error', vmpfence_admin.i18n.ajax_error);
                },
                complete: function() {
                    // Restore button state
                    $submitButton.prop('disabled', false);
                    $submitButton.val(originalText);
                    $form.find('.vmpfence-spinner').remove();
                }
            });
            
            e.preventDefault();
        },

        /**
         * Handle AJAX button clicks
         */
        handleAjaxButton: function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var action = $button.data('action');
            var confirm_message = $button.data('confirm');
            
            if (confirm_message && !confirm(confirm_message)) {
                return;
            }
            
            var originalText = $button.text();
            $button.prop('disabled', true);
            $button.text(vmpfence_admin.i18n.processing || 'Processing...');
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_' + action,
                    nonce: vmpfence_admin.nonce,
                    data: $button.data()
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceAdmin.showNotice('success', response.data.message);
                        
                        // Handle specific actions
                        if (action === 'delete_threat' || action === 'quarantine_file') {
                            $button.closest('tr').fadeOut();
                        }
                        
                        // Trigger action completed event
                        $(document).trigger('vmpfence:action:completed', [action, response.data]);
                    } else {
                        VMPFenceAdmin.showNotice('error', response.data.message || vmpfence_admin.i18n.error);
                    }
                },
                error: function() {
                    VMPFenceAdmin.showNotice('error', vmpfence_admin.i18n.ajax_error);
                },
                complete: function() {
                    $button.prop('disabled', false);
                    $button.text(originalText);
                }
            });
        },

        /**
         * Start security scan
         */
        startScan: function(e) {
            e.preventDefault();

            // scan.js owns the scan-page UI — bail out if on scan page
            if ($('.vmpfence-btn-start-scan').length) {
                return;
            }
            
            var $button = $(this);
            var scanType = $('#scan-type').val() || 'full';
            
            $button.prop('disabled', true);
            $button.text(vmpfence_admin.i18n.starting_scan || 'Starting Scan...');
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_start_scan',
                    scan_type: scanType,
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceAdmin.showNotice('success', response.data.message);
                        VMPFenceAdmin.startScanProgress(response.data.scan_id);
                        
                        // Show scan progress section
                        $('#vmpfence-scan-progress').show();
                        $('#vmpfence-stop-scan').show();
                        $button.hide();
                    } else {
                        VMPFenceAdmin.showNotice('error', response.data.message);
                        $button.prop('disabled', false);
                        $button.text(vmpfence_admin.i18n.start_scan || 'Start Scan');
                    }
                },
                error: function() {
                    VMPFenceAdmin.showNotice('error', vmpfence_admin.i18n.ajax_error);
                    $button.prop('disabled', false);
                    $button.text(vmpfence_admin.i18n.start_scan || 'Start Scan');
                }
            });
        },

        /**
         * Stop security scan
         */
        stopScan: function(e) {
            e.preventDefault();

            // scan.js owns the scan-page UI — bail out if on scan page
            if ($('.vmpfence-btn-start-scan').length) {
                return;
            }
            
            var $button = $(this);
            
            if (!confirm(vmpfence_admin.i18n.confirm_stop_scan || 'Are you sure you want to stop the scan?')) {
                return;
            }
            
            $button.prop('disabled', true);
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_stop_scan',
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceAdmin.showNotice('success', response.data.message);
                        VMPFenceAdmin.stopScanProgress();
                    } else {
                        VMPFenceAdmin.showNotice('error', response.data.message);
                    }
                },
                complete: function() {
                    $button.prop('disabled', false);
                }
            });
        },

        /**
         * Start scan progress monitoring
         */
        startScanProgress: function(scanId) {
            // scan.js owns the scan-page UI — bail out if on scan page
            if ($('.vmpfence-btn-start-scan').length) {
                return;
            }

            // Get update interval from settings (default 10 seconds, converted to milliseconds)
            var updateInterval = (typeof vmpfence_admin !== 'undefined' && vmpfence_admin.update_interval) 
                ? parseInt(vmpfence_admin.update_interval) * 1000 
                : 10000;
            
            // console.log('[Scan Progress] Starting monitoring (' + (updateInterval / 1000) + ' second interval)');
            
            this.scanProgressInterval = setInterval(function() {
                VMPFenceAdmin.updateScanProgress(scanId);
            }, updateInterval);
        },

        /**
         * Update scan progress
         */
        updateScanProgress: function(scanId) {
            // scan.js owns the scan-page UI — bail out if on scan page
            if ($('.vmpfence-btn-start-scan').length) {
                return;
            }

            // Pause if window loses focus
            if (this.shouldPauseLiveUpdates()) {
                return;
            }
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_scan_progress',
                    scan_id: scanId,
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        var data = response.data;
                        
                        // Update progress bar
                        $('#scan-progress-bar').css('width', data.progress + '%');
                        $('#scan-progress-text').text(data.progress + '%');
                        
                        // Update status text
                        $('#scan-status-text').text(data.status_text);
                        
                        // Update file count
                        $('#scan-files-scanned').text(data.files_scanned);
                        $('#scan-threats-found').text(data.threats_found);
                        
                        // Check if scan is complete
                        if (data.status === 'completed' || data.status === 'failed') {
                            VMPFenceAdmin.stopScanProgress();
                            
                            if (data.status === 'completed') {
                                VMPFenceAdmin.showNotice('success', vmpfence_admin.i18n.scan_completed);
                            } else {
                                VMPFenceAdmin.showNotice('error', vmpfence_admin.i18n.scan_failed);
                            }
                            
                            // Reload scan results
                            VMPFenceAdmin.loadScanResults();
                        }
                    }
                }
            });
        },

        /**
         * Stop scan progress monitoring
         */
        stopScanProgress: function() {
            // scan.js owns the scan-page UI — bail out if on scan page
            if ($('.vmpfence-btn-start-scan').length) {
                return;
            }

            if (this.scanProgressInterval) {
                clearInterval(this.scanProgressInterval);
                this.scanProgressInterval = null;
            }
            
            $('#vmpfence-scan-progress').hide();
            $('#vmpfence-stop-scan').hide();
            // Defense-in-depth: target inner button if it exists, never destroy child elements
            var $wrapper = $('#vmpfence-start-scan');
            var $innerBtn = $wrapper.find('button');
            if ($innerBtn.length) {
                $innerBtn.show().prop('disabled', false).text(vmpfence_admin.i18n.start_scan || 'Start Scan');
            } else {
                $wrapper.show().prop('disabled', false).text(vmpfence_admin.i18n.start_scan || 'Start Scan');
            }
        },

        /**
         * Handle toggle switch changes
         */
        handleToggleChange: function() {
            var $toggle = $(this);
            var setting = $toggle.attr('name');
            var value = $toggle.is(':checked') ? 1 : 0;
            
            // Show saving indicator
            var $indicator = $toggle.closest('.vmpfence-form-field').find('.vmpfence-saving-indicator');
            if (!$indicator.length) {
                $indicator = $('<span class="vmpfence-saving-indicator vmpfence-spinner"></span>');
                $toggle.closest('.vmpfence-toggle').after($indicator);
            }
            $indicator.show();
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_update_setting',
                    setting: setting,
                    value: value,
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Trigger setting changed event
                        $(document).trigger('vmpfence:setting:changed', [setting, value]);
                    } else {
                        // Revert toggle on error
                        $toggle.prop('checked', !$toggle.is(':checked'));
                        VMPFenceAdmin.showNotice('error', response.data.message);
                    }
                },
                error: function() {
                    // Revert toggle on error
                    $toggle.prop('checked', !$toggle.is(':checked'));
                    VMPFenceAdmin.showNotice('error', vmpfence_admin.i18n.ajax_error);
                },
                complete: function() {
                    $indicator.hide();
                }
            });
        },

        /**
         * Handle search functionality
         */
        handleSearch: function() {
            var query = $(this).val();
            var searchType = $(this).data('search-type') || 'threats';
            
            VMPFenceAdmin.performSearch(searchType, query);
        },

        /**
         * Perform search request
         */
        performSearch: function(type, query) {
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_search',
                    search_type: type,
                    query: query,
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Update results table
                        $('#vmpfence-' + type + '-table tbody').html(response.data.html);
                        
                        // Update pagination if present
                        if (response.data.pagination) {
                            $('.vmpfence-pagination').html(response.data.pagination);
                        }
                    }
                }
            });
        },

        /**
         * Load dashboard data
         */
        loadDashboardData: function() {
            // console.log('[Dashboard Stats] loadDashboardData called, checking for dashboard element...');
            if ($('#vmpfence-dashboard').length) {
                // console.log('[Dashboard Stats] Dashboard element found, initializing auto-refresh');
                this.updateDashboardStats();
                
                // Get update interval from settings (default 10 seconds, converted to milliseconds)
                var updateInterval = (typeof vmpfence_admin !== 'undefined' && vmpfence_admin.update_interval) 
                    ? parseInt(vmpfence_admin.update_interval) * 1000 
                    : 10000;
                
                // console.log('[Dashboard Stats] Using ' + (updateInterval / 1000) + ' second interval');
                
                // Set up auto-refresh
                setInterval(function() {
                    VMPFenceAdmin.updateDashboardStats();
                }, updateInterval);
            } else {
                // console.log('[Dashboard Stats] Dashboard element not found (#vmpfence-dashboard), checking for alternative...');
                // Alternative check: Look for dashboard-specific elements
                if ($('.vmpfence-dashboard-grid').length || $('.vmpfence-protection-banner').length) {
                    // console.log('[Dashboard Stats] Dashboard detected via alternative selector, initializing auto-refresh');
                    this.updateDashboardStats();
                    
                    // Get update interval from settings (default 10 seconds, converted to milliseconds)
                    var updateInterval = (typeof vmpfence_admin !== 'undefined' && vmpfence_admin.update_interval) 
                        ? parseInt(vmpfence_admin.update_interval) * 1000 
                        : 10000;
                    
                    // console.log('[Dashboard Stats] Using ' + (updateInterval / 1000) + ' second interval');
                    
                    // Set up auto-refresh
                    setInterval(function() {
                        VMPFenceAdmin.updateDashboardStats();
                    }, updateInterval);
                } else {
                    // console.log('[Dashboard Stats] Not on dashboard page, skipping auto-refresh');
                }
            }
        },

        /**
         * Update dashboard statistics
         */
        updateDashboardStats: function() {
            // Pause if window loses focus
            if (this.shouldPauseLiveUpdates()) {
                // console.log('[Dashboard Stats] Auto-refresh paused (window not focused)');
                return;
            }
            
            // console.log('[Dashboard Stats] Fetching updated statistics...');
            
            $.ajax({
                url: vmpfence_admin.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_dashboard_stats',
                    nonce: vmpfence_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // console.log('[Dashboard Stats] Successfully fetched stats:', response.data);
                        var stats = response.data;
                        
                        // Update stat numbers
                        $('#stat-threats-detected .vmpfence-stat-number').text(stats.threats_detected);
                        $('#stat-scans-completed .vmpfence-stat-number').text(stats.scans_completed);
                        $('#stat-blocked-attempts .vmpfence-stat-number').text(stats.blocked_attempts);
                        $('#stat-uptime .vmpfence-stat-number').text(stats.uptime);
                        
                        // Update status indicator
                        $('#vmpfence-status-indicator')
                            .removeClass('healthy warning critical')
                            .addClass(stats.overall_status);
                    } else {
                        // console.log('[Dashboard Stats] Error fetching stats:', response.data);
                    }
                },
                error: function(xhr, status, error) {
                    console.log('[Dashboard Stats] AJAX error:', error);
                }
            });
        },

        /**
         * Show admin notice
         */
        showNotice: function(type, message, dismissible) {
            dismissible = dismissible !== false;
            
            var noticeClass = 'notice notice-' + type;
            if (dismissible) {
                noticeClass += ' is-dismissible';
            }
            
            var $notice = $('<div class="' + noticeClass + '"><p>' + message + '</p></div>');
            
            $('.vmpfence-admin-wrap').prepend($notice);
            
            // Auto-dismiss after 5 seconds for success messages
            if (type === 'success' && dismissible) {
                setTimeout(function() {
                    $notice.fadeOut(function() {
                        $notice.remove();
                    });
                }, 5000);
            }
            
            // Handle dismiss button
            if (dismissible) {
                $notice.on('click', '.notice-dismiss', function() {
                    $notice.fadeOut(function() {
                        $notice.remove();
                    });
                });
            }
        },

        /**
         * Initialize tooltips
         */
        initTooltips: function() {
            if ($.fn.tooltip) {
                $('.vmpfence-tooltip').tooltip({
                    position: { my: "left+15 center", at: "right center" }
                });
            }
        },

        /**
         * Initialize toggle switches
         */
        initToggleSwitches: function() {
            $('.vmpfence-toggle input').each(function() {
                var $input = $(this);
                var $slider = $input.siblings('.vmpfence-toggle-slider');
                
                // Add accessibility attributes
                $input.attr('role', 'switch');
                $input.attr('aria-checked', $input.is(':checked'));
                
                $input.on('change', function() {
                    $input.attr('aria-checked', $input.is(':checked'));
                });
            });
        },

        /**
         * Initialize progress bars
         */
        initProgressBars: function() {
            $('.vmpfence-progress').each(function() {
                var $progress = $(this);
                var value = $progress.data('value') || 0;
                
                $progress.find('.vmpfence-progress-bar').css('width', value + '%');
            });
        },

        /**
         * Utility function for debouncing
         */
        debounce: function(func, wait, immediate) {
            var timeout;
            return function() {
                var context = this, args = arguments;
                var later = function() {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        },

        /**
         * Open modal dialog
         */
        openModal: function(e) {
            e.preventDefault();
            
            var modalId = $(this).data('modal');
            var $modal = $('#' + modalId);
            
            if ($modal.length) {
                $modal.show();
                $('body').addClass('vmpfence-modal-open');
                
                // Focus first input
                $modal.find('input, select, textarea').first().focus();
            }
        },

        /**
         * Close modal dialog
         */
        closeModal: function(e) {
            e.preventDefault();
            
            var $modal = $(this).closest('.vmpfence-modal');
            $modal.hide();
            $('body').removeClass('vmpfence-modal-open');
        },

        /**
         * Handle file uploads
         */
        handleFileUpload: function() {
            var $input = $(this);
            var files = this.files;
            var $preview = $input.siblings('.vmpfence-file-preview');
            
            if (files.length > 0) {
                var fileNames = Array.from(files).map(function(file) {
                    return file.name;
                }).join(', ');
                
                if (!$preview.length) {
                    $preview = $('<div class="vmpfence-file-preview"></div>');
                    $input.after($preview);
                }
                
                $preview.text(fileNames);
            }
        }
    };

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        VMPFenceAdmin.init();
        
        // Handle initial tab from URL hash
        if (window.location.hash) {
            var $targetTab = $('.vmpfence-nav-tabs a[href="' + window.location.hash + '"]');
            if ($targetTab.length) {
                $targetTab.trigger('click');
            }
        }
    });

    /**
     * Handle browser back/forward navigation
     */
    $(window).on('popstate', function() {
        if (window.location.hash) {
            var $targetTab = $('.vmpfence-nav-tabs a[href="' + window.location.hash + '"]');
            if ($targetTab.length) {
                $targetTab.trigger('click');
            }
        }
    });

})(jQuery);
