/**
 * VMPFence Scan Options JavaScript
 * 
 */

(function($) {
    'use strict';

    /**
     * VMPFence Scan Options Object
     */
    window.VMPFenceScanOptions = {
        
        // Store initial page state for cancel functionality
        initialState: {
            scanType: null,
            schedule_mode: null,
            options: {}
        },
        
        /**
         * Initialize scan options functionality
         */
        init: function() {
            this.loadCurrentConfiguration();
            this.bindEvents();
            this.bindSchedulingEvents();
            
            // Initialize schedule preview if scheduling is enabled
            if ($('.vmpfence-toggle-enabled.active').length) {
                this.updateSchedulePreview();
            }
            
        },
        
        /**
         * Load current saved configuration on page load
         */
        loadCurrentConfiguration: function() {
            var self = this;
            
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_load_current_config',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        // Apply current saved configuration to UI
                        self.applyScanConfiguration(response.data.config, response.data.scan_type);
                        
                        // Now capture the loaded state as initial state
                        self.captureInitialState();
                    } else {
                        console.warn('VMPFence: Could not load current configuration, using defaults');
                        // Fallback: capture whatever is on the page as initial state
                        self.captureInitialState();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('VMPFence: Error loading current configuration', error);
                    // Fallback: capture whatever is on the page as initial state
                    self.captureInitialState();
                }
            });
        },
        
        /**
         * Capture the initial page state for cancel functionality
         */
        captureInitialState: function() {
            // Get currently selected scan type
            var $selectedScanType = $('input[name="scan_type[]"]:checked');
            if ($selectedScanType.length) {
                this.initialState.scanType = $selectedScanType.val();
            } else {
                this.initialState.scanType = 'standard'; // fallback
            }
            
            // Get currently selected schedule mode (updated field name)
            var $selectedScheduleMode = $('input[name="schedule_mode"]:checked');
            if ($selectedScheduleMode.length) {
                this.initialState.schedule_mode = $selectedScheduleMode.val();
            } else {
                this.initialState.schedule_mode = 'auto'; // fallback
            }
            
            // Capture all current option states
            var self = this;
            
            // Capture checkboxes (excluding scan_type which we handled above)
            $('input[type="checkbox"]').not('input[name="scan_type[]"]').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    self.initialState.options[name] = $(this).is(':checked') ? 1 : 0;
                }
            });
            
            // Capture number inputs
            $('input[type="number"]').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    var value = $(this).val();
                    self.initialState.options[name] = value !== '' ? parseInt(value) : 0;
                }
            });
            
            // Capture textarea values
            $('textarea').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    self.initialState.options[name] = $(this).val().trim();
                }
            });
        },

        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Task 1: Restore defaults button
            $('.vmpfence-btn-restore').on('click', this.restoreDefaults.bind(this));
            
            // Cancel changes button
            $('.vmpfence-btn-cancel').on('click', this.cancelChanges.bind(this));
            
            // Save changes button
            $('.vmpfence-btn-save').on('click', this.saveChanges.bind(this));
            
            // Task 2: Scan type selection (limited, standard, high sensitivity)
            $('input[name="scan_type[]"]:not(#scan-custom)').on('change', this.handleScanTypeChange.bind(this));
        },

        /**
         * Task 1: Restore defaults button functionality
         * Resets to default values with standard scan type
         */
        restoreDefaults: function(e) {
            e.preventDefault();
            var self = this;
            
            // Show loading state
            var $btn = $(e.currentTarget);
            var originalText = $btn.text();
            $btn.text('RESTORING...').prop('disabled', true);
            
            // AJAX call to restore defaults
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_restore_defaults',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        // Apply standard configuration to UI
                        self.applyScanConfiguration(response.data.config, 'standard');
                        
                        // Show success message with reload
                        VMPFenceNotifications.showSuccess(response.data.message + ' - Page will reload in 2 seconds...', 3000);
                        
                        // Reload page after 2 seconds
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        VMPFenceNotifications.showError(response.data.message || 'Failed to restore defaults', 5000);
                    }
                },
                error: function(xhr, status, error) {
                    VMPFenceNotifications.showError('AJAX error: ' + error, 6000);
                    console.error('VMPFence: Restore defaults error', error);
                },
                complete: function() {
                    $btn.text(originalText).prop('disabled', false);
                }
            });
        },

        /**
         * Handle scheduling mode change (auto/manual)
         */
        handleSchedulingModeChange: function() {
            var selectedMode = $('input[name="schedule_mode"]:checked').val();
            var $manualConfig = $('#manual-schedule-config');
            
            if (selectedMode === 'manual') {
                $manualConfig.slideDown(300);
                this.updateSchedulePreview();
            } else {
                $manualConfig.slideUp(300);
                this.updateSchedulePreview();
            }
        },

        /**
         * Handle manual schedule pattern change
         */
        handleManualScheduleChange: function() {
            var pattern = $('#manual-schedule-pattern').val();
            
            var $customGrid = $('#custom-schedule-grid');
            var $startTimeConfig = $('#start-time-config');
            
            if (pattern === 'custom') {
                $customGrid.slideDown(300);
                $startTimeConfig.hide();
            } else {
                $customGrid.slideUp(300);
                $startTimeConfig.show();
            }

            // Update pattern description and preview
            this.updateManualPatternDescription();
            this.updateSchedulePreview();
        },

        /**
         * Update manual pattern description
         */
        updateManualPatternDescription: function() {
            var self = this;
            var pattern = $('#manual-schedule-pattern').val();
            var startHour = $('#schedule-start-hour').val() || 2;
            var $description = $('#manual-pattern-description');

            if (!$description.length) {
                return; // Description element doesn't exist
            }

            // Show loading
            $description.html('<em>Loading description...</em>');

            // Get pattern description
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_pattern_description',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val(),
                    pattern: pattern,
                    start_hour: parseInt(startHour)
                },
                success: function(response) {
                    if (response.success) {
                        $description.html(response.data.description);
                    } else {
                        $description.html('<em>Could not load description</em>');
                    }
                },
                error: function() {
                    $description.html('<em>Error loading description</em>');
                }
            });
        },

        /**
         * Update schedule preview
         */
        updateSchedulePreview: function() {
            var self = this;
            var $previewContent = $('#schedule-preview-content');
            
            // Show loading state
            $previewContent.html('<div class="vmpfence-loading">Generating preview...</div>');
            
            // Collect current scheduling configuration
            var scheduleData = this.getScheduleConfiguration();
            // AJAX call to generate preview
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_preview_schedule',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val(),
                    schedule_data: scheduleData
                },
                success: function(response) {
                    if (response.success) {
                        self.displaySchedulePreview(response.data);
                    } else {
                        console.error('VMPFence: Preview failed:', response.data);
                        $previewContent.html('<div class="vmpfence-error">Could not generate preview: ' + (response.data.message || 'Unknown error') + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('VMPFence: Preview AJAX error:', status, error);
                    $previewContent.html('<div class="vmpfence-error">Preview error: ' + error + '</div>');
                    console.error('VMPFence: Schedule preview error', error);
                }
            });
        },

        /**
         * Update current schedule (shows actual saved times from database)
         */
        updateCurrentSchedule: function() {
            var self = this;
            var $currentContent = $('#current-schedule-content');
            
            // Show loading state
            $currentContent.html('<div class="vmpfence-loading">Loading current schedule...</div>');
            
            // AJAX call to get current saved schedule
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_current_schedule',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val()
                },
                success: function(response) {
                    if (response.success) {
                        self.displayCurrentSchedule(response.data);
                    } else {
                        $currentContent.html('<div class="vmpfence-error">Could not load current schedule: ' + (response.data.message || 'Unknown error') + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    $currentContent.html('<div class="vmpfence-error">Current schedule error: ' + error + '</div>');
                    console.error('VMPFence: Current schedule error', error);
                }
            });
        },

        /**
         * Get current schedule configuration
         */
        getScheduleConfiguration: function() {
            // Read individual form values with logging
            var enabled = $('.vmpfence-toggle-enabled').hasClass('active');
            var mode = $('input[name="schedule_mode"]:checked').val() || 'auto';
            var pattern = $('#manual-schedule-pattern').val() || 'once_daily';
            var startHour = $('#schedule-start-hour').val() || 2;
            var timezone = $('#schedule-timezone').val() || 'UTC';
            var randomOffset = $('#random-offset').is(':checked');
            
            var config = {
                enabled: enabled,
                mode: mode,
                pattern: pattern,
                start_hour: startHour,
                timezone: timezone,
                random_offset: randomOffset,
                custom_schedule: {}
            };
            
            // Get custom schedule grid if applicable
            if (config.pattern === 'custom') {
                var totalChecked = 0;
                
                for (var day = 0; day < 7; day++) {
                    config.custom_schedule[day] = {};
                    for (var hour = 0; hour < 24; hour++) {
                        var $checkbox = $('#schedule-' + day + '-' + hour);
                        var isChecked = $checkbox.is(':checked');
                        config.custom_schedule[day][hour] = isChecked ? 1 : 0;
                        if (isChecked) totalChecked++;
                    }
                }
            }
            return config;
        },

        /**
         * Display schedule preview
         */
        displaySchedulePreview: function(previewData) {
            var $content = $('#schedule-preview-content');
            var html = '';
            
            if (!previewData.upcoming_scans || previewData.upcoming_scans.length === 0) {
                html = '<div class="vmpfence-no-scans">No scans scheduled. Enable scheduling to see upcoming scan times.</div>';
            } else {
                html = '<div class="vmpfence-upcoming-scans">';
                html += '<h5>Next ' + Math.min(5, previewData.upcoming_scans.length) + ' Scans:</h5>';
                html += '<ul class="vmpfence-scan-list">';
                
                for (var i = 0; i < Math.min(5, previewData.upcoming_scans.length); i++) {
                    var scan = previewData.upcoming_scans[i];
                    html += '<li class="vmpfence-scan-item">';
                    html += '<span class="vmpfence-scan-time">' + scan.formatted_time + '</span>';
                    html += '<span class="vmpfence-scan-relative">(' + scan.relative_time + ')</span>';
                    html += '</li>';
                }
                
                html += '</ul>';
                html += '</div>';
            }
            
            $content.html(html);
            this.updateScheduleStatus(previewData);
        },

        /**
         * Display current schedule (actual saved times)
         */
        displayCurrentSchedule: function(scheduleData) {
            var $content = $('#current-schedule-content');
            var html = '';
            
            if (!scheduleData.upcoming_scans || scheduleData.upcoming_scans.length === 0) {
                html = '<div class="vmpfence-no-scans">No saved schedule found. Click "Save Changes" to generate actual schedule.</div>';
            } else {
                html = '<div class="vmpfence-current-scans">';
                html += '<h5>Next ' + Math.min(10, scheduleData.upcoming_scans.length) + ' Actual Scans:</h5>';
                
                if (scheduleData.random_offset_enabled) {
                    html += '<p class="vmpfence-offset-notice"><strong>Random Offset:</strong> Enabled - times include random delay</p>';
                } else {
                    html += '<p class="vmpfence-offset-notice"><strong>Random Offset:</strong> Disabled - exact times</p>';
                }
                
                html += '<ul class="vmpfence-scan-list">';
                
                for (var i = 0; i < Math.min(10, scheduleData.upcoming_scans.length); i++) {
                    var scan = scheduleData.upcoming_scans[i];
                    html += '<li class="vmpfence-scan-item">';
                    html += '<span class="vmpfence-scan-time">' + scan.formatted_time + '</span>';
                    html += '<span class="vmpfence-scan-relative">(' + scan.relative_time + ')</span>';
                    html += '</li>';
                }
                
                html += '</ul>';
                
                if (scheduleData.total_scheduled > 10) {
                    html += '<p class="vmpfence-more-scans">...and ' + (scheduleData.total_scheduled - 10) + ' more scans scheduled</p>';
                }
                
                html += '</div>';
            }
            
            $content.html(html);
        },

        /**
         * Update schedule status display
         */
        updateScheduleStatus: function(statusData) {
            if (statusData.next_scan) {
                $('#next-scan-time').text(statusData.next_scan.formatted_time || 'Not scheduled');
            }
            $('#current-schedule-mode').text(statusData.mode || 'Automatic');
            if (statusData.last_update) {
                $('#last-schedule-update').text(statusData.last_update || 'Never');
            }
        },

        /**
         * Handle custom schedule grid controls
         */
        initCustomScheduleControls: function() {
            var self = this;
            
            // Select All button
            $('#select-all-hours').on('click', function() {
                $('.vmpfence-schedule-checkbox').prop('checked', true);
                self.updateSchedulePreview();
            });
            
            // Clear All button
            $('#clear-all-hours').on('click', function() {
                $('.vmpfence-schedule-checkbox').prop('checked', false);
                self.updateSchedulePreview();
            });
            
            // Business Hours (9 AM - 5 PM, Mon-Fri)
            $('#select-business-hours').on('click', function() {
                $('.vmpfence-schedule-checkbox').prop('checked', false);
                for (var day = 1; day <= 5; day++) { // Mon-Fri
                    for (var hour = 9; hour <= 17; hour++) { // 9 AM - 5 PM
                        $('#schedule-' + day + '-' + hour).prop('checked', true);
                    }
                }
                self.updateSchedulePreview();
            });
            
            // Night Hours (10 PM - 6 AM)
            $('#select-night-hours').on('click', function() {
                $('.vmpfence-schedule-checkbox').prop('checked', false);
                for (var day = 0; day < 7; day++) {
                    // 10 PM - 11 PM
                    for (var hour = 22; hour <= 23; hour++) {
                        $('#schedule-' + day + '-' + hour).prop('checked', true);
                    }
                    // 12 AM - 6 AM
                    for (var hour = 0; hour <= 6; hour++) {
                        $('#schedule-' + day + '-' + hour).prop('checked', true);
                    }
                }
                self.updateSchedulePreview();
            });
            
            // Individual checkbox changes
            $('.vmpfence-schedule-checkbox').on('change', function() {
                self.updateSchedulePreview();
            });
        },

        /**
         * Bind enhanced event handlers for scheduling
         */
        bindSchedulingEvents: function() {
            var self = this;
            
            // Schedule mode change
            $('input[name="schedule_mode"]').on('change', this.handleSchedulingModeChange.bind(this));
            
            // Manual schedule pattern change
            $('#manual-schedule-pattern').on('change', this.handleManualScheduleChange.bind(this));
            
            // Other schedule option changes
            $('#schedule-start-hour, #schedule-timezone').on('change', function() {
                var field = $(this).attr('id');
                var newValue = $(this).val();
                self.updateManualPatternDescription();
                self.updateSchedulePreview();
            });
            
            $('#random-offset').on('change', function() {
                var isChecked = $(this).is(':checked');
                self.updateSchedulePreview();
            });
            
            // Refresh preview button
            $('#refresh-schedule-preview').on('click', function() {
                self.updateSchedulePreview();
            });
            
            // Toggle buttons for enabling/disabling scheduling
            $('.vmpfence-toggle-btn').on('click', function() {
                var $this = $(this);
                var value = $this.data('value');
                
                // Update active state
                $this.siblings().removeClass('active');
                $this.addClass('active');
                
                // Update preview when scheduling is toggled
                if ($this.closest('.vmpfence-schedule-toggle-section').length) {
                    self.updateSchedulePreview();
                }
            });
            
            // Initialize custom schedule controls
            this.initCustomScheduleControls();
        },

        /**
         * Cancel changes - revert to initial page load state
         */
        cancelChanges: function(e) {
            e.preventDefault();
            var self = this;
            
            // Show loading state
            var $btn = $(e.currentTarget);
            var originalText = $btn.text();
            $btn.text('CANCELLING...').prop('disabled', true);
            
            try {
                // Revert to initial scan type
                $('input[name="scan_type[]"]').prop('checked', false);
                $('.vmpfence-scan-type-card').removeClass('vmpfence-scan-type-selected');
                
                // Map scan types to their actual HTML IDs
                var scanTypeIdMap = {
                    'limited': '#scan-limited',
                    'standard': '#scan-standard',
                    'high_sensitivity': '#scan-high',
                    'custom': '#scan-custom'
                };
                
                var scanTypeId = scanTypeIdMap[self.initialState.scanType] || '#scan-standard';
                $(scanTypeId).prop('checked', true);
                $(scanTypeId).closest('.vmpfence-scan-type-card').addClass('vmpfence-scan-type-selected');
                
                // Revert schedule type
                $('input[name="schedule_type"]').prop('checked', false);
                var scheduleTypeId = '#schedule-' + (self.initialState.schedule_type || 'auto');
                $(scheduleTypeId).prop('checked', true);
                
                // Revert all option checkboxes to initial state
                $.each(self.initialState.options, function(optionName, value) {
                    var $field = $('input[name="' + optionName + '"], textarea[name="' + optionName + '"]');
                    if ($field.length) {
                        if ($field.attr('type') === 'checkbox') {
                            $field.prop('checked', value == 1);
                        } else if ($field.is('textarea') || $field.attr('type') === 'number') {
                            $field.val(value);
                        }
                    }
                });
                
                // Update scan type info cards
                self.updateScanTypeCards(self.initialState.scanType);
                
                // Reputation percentage recalculated on page reload
                
                // Show success message
                VMPFenceNotifications.showSuccess('Changes cancelled - reverted to initial state', 3000);      
            } catch (error) {
                VMPFenceNotifications.showError('Error cancelling changes: ' + error.message, 5000);
                console.error('VMPFence: Cancel changes error', error);
            }
            
            // Always restore button state
            $btn.text(originalText).prop('disabled', false);
        },

        /**
         * Save changes - save all current form data to database
         */
        saveChanges: function(e) {
            e.preventDefault();
            var self = this;
            
            // Show loading state
            var $btn = $(e.currentTarget);
            var originalText = $btn.text();
            $btn.text('SAVING...').prop('disabled', true);
            
            try {
                // Collect all form data
                var formData = this.collectFormData();

                // Validate form data
                if (!this.validateFormData(formData)) {
                    throw new Error('Form validation failed');
                }
                
                // AJAX call to save configuration
                $.ajax({
                    url: vmpfence_ajax.ajax_url || ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_save_changes',
                        nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val(),
                        form_data: formData
                    },
                    success: function(response) {
                        if (response.success) {
                            // Update initial state with saved data
                            self.updateInitialStateAfterSave(formData);
                            
                            // Show success message with reload
                            VMPFenceNotifications.showSuccess(response.data.message + ' - Page will reload in 2 seconds...', 3000);
                            
                            // Reload page after 2 seconds
                            setTimeout(function() {
                                location.reload();
                            }, 2000);
                        } else {
                            VMPFenceNotifications.showError(response.data.message || 'Failed to save settings', 5000);
                        }
                    },
                    error: function(xhr, status, error) {
                        VMPFenceNotifications.showError('AJAX error: ' + error, 6000);
                        console.error('VMPFence: Save changes error', error);
                    },
                    complete: function() {
                        $btn.text(originalText).prop('disabled', false);
                    }
                });
                
            } catch (error) {
                VMPFenceNotifications.showError('Error preparing data: ' + error.message, 6000);
                console.error('VMPFence: Save changes error', error);
                $btn.text(originalText).prop('disabled', false);
            }
        },

        /**
         * Collect all form data from the page
         */
        collectFormData: function() {
            var formData = {};
            
            // Get selected scan type
            var $selectedScanType = $('input[name="scan_type[]"]:checked');
            formData.scanType = $selectedScanType.length ? $selectedScanType.val() : 'standard';
            
            // Get schedule mode (updated field name)
            var $selectedScheduleMode = $('input[name="schedule_mode"]:checked');
            formData.schedule_mode = $selectedScheduleMode.length ? $selectedScheduleMode.val() : 'auto';
            
            // Get toggle button state for scheduledScansEnabled
            var $activeToggle = $('.vmpfence-toggle-btn.active');
            if ($activeToggle.length) {
                formData.scheduledScansEnabled = $activeToggle.attr('data-value') === 'enabled' ? 1 : 0;
            } else {
                formData.scheduledScansEnabled = 1; // Default to enabled
            }

            // Get manual scheduling options
            formData.manual_schedule_pattern = $('#manual-schedule-pattern').val() || 'once_daily';
            formData.schedule_start_hour = $('#schedule-start-hour').val() || 2;
            formData.schedule_timezone = $('#schedule-timezone').val() || 'UTC';
            formData.random_offset = $('#random-offset').is(':checked') ? 1 : 0;

            // Get custom schedule grid
            formData.custom_schedule = {};
            var totalCheckedBoxes = 0;
            
            for (var day = 0; day < 7; day++) {
                formData.custom_schedule[day] = {};
                for (var hour = 0; hour < 24; hour++) {
                    var $checkbox = $('#schedule-' + day + '-' + hour);
                    var isChecked = $checkbox.is(':checked');
                    formData.custom_schedule[day][hour] = isChecked ? 1 : 0;
                    
                    if (isChecked) {
                        totalCheckedBoxes++;
                    }
                    
                }
            }
            
            // Get all other checkbox options (excluding scan_type which we handled above)
            $('input[type="checkbox"]').not('input[name="scan_type[]"]').not('.vmpfence-schedule-checkbox').not('#random-offset').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    formData[name] = $(this).is(':checked') ? 1 : 0;
                }
            });
            
            // Get all number inputs
            $('input[type="number"]').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    var value = $(this).val();
                    formData[name] = value !== '' ? parseInt(value) : 0;
                }
            });
            
            // Get all textarea values
            $('textarea').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    formData[name] = $(this).val().trim();
                }
            });
            
            // Get all select values
            $('select').each(function() {
                var name = $(this).attr('name');
                if (name) {
                    formData[name] = $(this).val();
                }
            });
            return formData;
        },

        /**
         * Validate form data before saving
         */
        validateFormData: function(formData) {
            // Ensure scan type is valid
            var validScanTypes = ['limited', 'standard', 'high_sensitivity', 'custom'];
            if (!validScanTypes.includes(formData.scanType)) {
                VMPFenceNotifications.showError('Invalid scan type selected', 5000);
                return false;
            }
            
            // Ensure schedule mode is valid (updated field name)
            var validScheduleModes = ['auto', 'manual'];
            if (!validScheduleModes.includes(formData.schedule_mode)) {
                VMPFenceNotifications.showError('Invalid schedule mode selected', 5000);
                return false;
            }
            
            // Validate scheduling-specific fields
            if (formData.schedule_mode === 'manual') {
                var validPatterns = ['once_daily', 'twice_daily', 'every_other_day', 'weekdays', 'weekends', 'odd_days_weekends', 'custom'];
                if (!validPatterns.includes(formData.manual_schedule_pattern)) {
                    VMPFenceNotifications.showError('Invalid schedule pattern selected', 5000);
                    return false;
                }
                
                // Validate start hour
                var startHour = parseInt(formData.schedule_start_hour);
                if (isNaN(startHour) || startHour < 0 || startHour > 23) {
                    VMPFenceNotifications.showError('Start hour must be between 0 and 23', 5000);
                    return false;
                }
            }
            
            // Validate number fields are positive
            var numberFields = ['scan_maxIssues', 'scan_maxDuration', 'maxMem', 'scan_maxExecTime'];
            for (var i = 0; i < numberFields.length; i++) {
                var field = numberFields[i];
                if (formData[field] !== undefined && formData[field] < 0) {
                    VMPFenceNotifications.showError('Numeric values must be positive', 5000);
                    return false;
                }
            }
            
            return true;
        },

        /**
         * Update initial state after successful save
         */
        updateInitialStateAfterSave: function(savedData) {
            // Update scan type
            this.initialState.scanType = savedData.scanType;
            
            // Update schedule mode (updated field name)
            this.initialState.schedule_mode = savedData.schedule_mode;
            
            // Update all options
            this.initialState.options = {};
            for (var key in savedData) {
                if (key !== 'scanType' && key !== 'schedule_mode') {
                    this.initialState.options[key] = savedData[key];
                }
            }
        },

        /**
         * Task 2: Handle scan type changes (limited, standard, high sensitivity)
         * Loads appropriate configuration and updates checkmarks in real-time
         */
        handleScanTypeChange: function(e) {
            var $checkbox = $(e.currentTarget);
            var scanType = $checkbox.val();
            var self = this;
            
            if (!$checkbox.is(':checked')) {
                return; // Skip if unchecked
            }
            
            // Uncheck other scan types (radio behavior)
            $('input[name="scan_type[]"]:not(#scan-custom)').not($checkbox).prop('checked', false);
            $('.vmpfence-scan-type-card').removeClass('vmpfence-scan-type-selected');
            $checkbox.closest('.vmpfence-scan-type-card').addClass('vmpfence-scan-type-selected');
            
            // Load scan type configuration via AJAX
            this.loadScanTypeConfiguration(scanType);
        },

        /**
         * Task 2 Helper: Load scan type configuration from server
         */
        loadScanTypeConfiguration: function(scanType) {
            var self = this;
            // Show loading indicator
            VMPFenceNotifications.showInfo('Loading ' + scanType + ' configuration preview...', 4000);
            
            $.ajax({
                url: vmpfence_ajax.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_load_scan_type',
                    nonce: vmpfence_ajax.nonce || $('#vmpfence_scan_options_nonce').val(),
                    scan_type: scanType
                },
                success: function(response) {
                    if (response.success) {
                        // Apply the configuration to UI checkboxes
                        self.applyScanConfiguration(response.data.config, scanType);
                        
                        // Update card displays
                        self.updateScanTypeCards(scanType);
                        VMPFenceNotifications.showSuccess(response.data.message, 3000);
                    } else {
                        VMPFenceNotifications.showError(response.data.message || 'Failed to load scan type configuration', 5000);
                    }
                },
                error: function(xhr, status, error) {
                    VMPFenceNotifications.showError('Failed to load scan type configuration', 5000);
                    console.error('VMPFence: Load scan type error', error);
                }
            });
        },

        /**
         * Helper: Apply scan configuration to form checkboxes
         */
        applyScanConfiguration: function(config, scanType) {
            var self = this;
            
            // Apply all field values based on configuration
            $.each(config, function(optionName, value) {
                // Handle checkboxes
                var $checkbox = $('input[name="' + optionName + '"][type="checkbox"]');
                if ($checkbox.length) {
                    $checkbox.prop('checked', value == 1);
                }
                
                // Handle number inputs
                var $numberInput = $('input[name="' + optionName + '"][type="number"]');
                if ($numberInput.length) {
                    $numberInput.val(value);
                }
                
                // Handle textareas
                var $textarea = $('textarea[name="' + optionName + '"]');
                if ($textarea.length) {
                    $textarea.val(value);
                }
                
                // Handle select dropdowns
                var $select = $('select[name="' + optionName + '"]');
                if ($select.length) {
                    $select.val(value);
                }
                
                // Handle radio buttons for schedule_mode (updated field name)
                if (optionName === 'schedMode' || optionName === 'schedule_mode') {
                    $('input[name="schedule_mode"]').prop('checked', false);
                    $('#schedule-' + value).prop('checked', true);
                    
                    // Trigger change event to show/hide manual options
                    $('input[name="schedule_mode"]:checked').trigger('change');
                }
                
                // Handle specific scheduling fields
                if (optionName === 'manualScanType' || optionName === 'manual_schedule_pattern') {
                    $('#manual-schedule-pattern').val(value).trigger('change');
                }
                
                if (optionName === 'schedStartHour' || optionName === 'schedule_start_hour') {
                    $('#schedule-start-hour').val(value);
                }
                
                if (optionName === 'scheduleTimezone') {
                    $('#schedule-timezone').val(value);
                }
                
                if (optionName === 'randomOffset') {
                    $('#random-offset').prop('checked', value == 1);
                }
                
                // Handle custom schedule grid
                if (optionName === 'scanSched' && value && typeof value === 'object') {
                    var totalToApply = 0;
                    var totalApplied = 0;
                    var totalFound = 0;
                    
                    // Count how many should be checked
                    for (var day = 0; day < 7; day++) {
                        if (value[day]) {
                            for (var hour = 0; hour < 24; hour++) {
                                if (value[day][hour] == 1) {
                                    totalToApply++;
                                }
                            }
                        }
                    }
                    // Apply the values
                    for (var day = 0; day < 7; day++) {
                        if (value[day]) {
                            for (var hour = 0; hour < 24; hour++) {
                                var $checkbox = $('#schedule-' + day + '-' + hour);
                                totalFound++;
                                
                                if (value[day][hour] == 1) {
                                    $checkbox.prop('checked', true);
                                    totalApplied++;
                                } else {
                                    $checkbox.prop('checked', false);
                                }
                            }
                        }
                    }                
                    
                    // Verify the result
                    var actualChecked = $('.vmpfence-schedule-checkbox:checked').length;

                    if (actualChecked !== totalToApply) {
                        console.warn('VMPFence: Mismatch! Expected', totalToApply, 'but found', actualChecked, 'checked');
                    }
                }
                
                // Handle scheduledScansEnabled toggle
                if (optionName === 'scheduledScansEnabled') {
                    $('.vmpfence-toggle-btn').removeClass('active');
                    if (value == 1) {
                        $('.vmpfence-toggle-enabled').addClass('active');
                    } else {
                        $('.vmpfence-toggle-disabled').addClass('active');
                    }
                }
            });
            
            // Ensure correct scan type is selected
            $('input[name="scan_type[]"]').prop('checked', false);
            $('.vmpfence-scan-type-card').removeClass('vmpfence-scan-type-selected');
            
            // Map scan types to their actual HTML IDs
            var scanTypeIdMap = {
                'limited': '#scan-limited',
                'standard': '#scan-standard',
                'high_sensitivity': '#scan-high',
                'custom': '#scan-custom'
            };
            
            var scanTypeId = scanTypeIdMap[scanType] || '#scan-standard';
            $(scanTypeId).prop('checked', true);
            $(scanTypeId).closest('.vmpfence-scan-type-card').addClass('vmpfence-scan-type-selected');
            
            // Reputation percentage recalculated on page reload
        },

        /**
         * Helper: Update scan type info cards
         * Uses same calculation logic as PHP VMPFence_Scanner_Status::get_scan_type_card_status()
         * Formula: 30% Premium Signatures + 11% Premium Reputation (3 checks) + 59% Scan Options (15 options)
         */
        updateScanTypeCards: function(scanType) {
            var cardInfo = {
                'limited': {
                    title: 'Scan Type: Limited',
                    description: 'Limited detection capability'
                },
                'standard': {
                    title: 'Scan Type: Standard',
                    description: 'Standard detection capability'
                },
                'high_sensitivity': {
                    title: 'Scan Type: High Sensitivity',
                    description: 'High sensitivity detection'
                }
            };
            
            var info = cardInfo[scanType] || cardInfo['standard'];
            
            // Update the main scan type card
            $('.vmpfence-options-card-info h3').first().text(info.title);
            $('.vmpfence-options-card-info p').first().text(info.description);
            
            // Calculate percentage dynamically based on current form values
            var progressValue = this.calculateScanTypePercentage();
            
            // Get the progress element
            var progressElement = document.getElementById('scan-types-progress');
            var textElement = document.getElementById('scan-types-text');
            
            if (progressElement && textElement) {
                // Update stroke-dasharray (progress bar fill)
                progressElement.style.strokeDasharray = progressValue + ',100';
                
                // Determine color based on percentage (matching PHP logic)
                var color = '#dc3545'; // Red default
                if (progressValue >= 80) {
                    color = '#28a745'; // Green
                } else if (progressValue >= 60) {
                    color = '#17a2b8'; // Blue
                } else if (progressValue >= 40) {
                    color = '#ffc107'; // Yellow
                }
                
                // Update stroke color
                progressElement.setAttribute('stroke', color);
                
                // Update percentage text
                textElement.textContent = progressValue + '%';
            }
        },

        /**
         * Calculate scan type percentage using same logic as PHP
         * Formula: 30% Premium + 11% Reputation (3 checks) + 59% Options (15 checks)
         */
        calculateScanTypePercentage: function() {
            var score = 0.0;
            
            // Component 1: Premium Scan Signatures (30%)
            // Check if premium by reading malware signatures percentage (100% = premium, 70% = free)
            var malwareText = $('#malware-signatures-text').text();
            var isPremium = malwareText === '100%';
            if (isPremium) {
                score += 0.30;
            }
            
            // Component 2: Premium Reputation Checks (11% total: 3.67% each for 3 checks)
            var reputationChecks = ['spamvertizeCheck', 'checkSpamIP', 'scansEnabled_checkGSB'];
            var reputationEnabled = 0;
            
            if (isPremium) {
                for (var i = 0; i < reputationChecks.length; i++) {
                    if ($('input[name="' + reputationChecks[i] + '"]').is(':checked')) {
                        score += 0.0367;
                        reputationEnabled++;
                    }
                }
                
                // Adjust for rounding (0.0367 * 3 = 0.1101, need exactly 0.11)
                if (reputationEnabled === 3) {
                    score -= 0.0001;
                }
            }
            
            // Component 3: Regular Scan Options (59% total: 3.93% each for 15 options)
            var regularOptions = [
                'scansEnabled_checkHowGetIPs',
                'scansEnabled_checkReadableConfig',
                'scansEnabled_suspectedFiles',
                'scansEnabled_core',
                'scansEnabled_coreUnknown',
                'scansEnabled_malware',
                'scansEnabled_fileContents',
                'scansEnabled_fileContentsGSB',
                'scansEnabled_posts',
                'scansEnabled_comments',
                'scansEnabled_suspiciousOptions',
                'scansEnabled_oldVersions',
                'scansEnabled_suspiciousAdminUsers',
                'scansEnabled_passwds',
                'scansEnabled_diskSpace'
            ];
            
            var optionsEnabled = 0;
            for (var i = 0; i < regularOptions.length; i++) {
                if ($('input[name="' + regularOptions[i] + '"]').is(':checked')) {
                    score += 0.0393;
                    optionsEnabled++;
                }
            }
            
            // Adjust for rounding (0.0393 * 15 = 0.5895, need exactly 0.59)
            if (optionsEnabled === 15) {
                score += 0.0005;
            }
            
            // Return as percentage (0-100)
            return Math.round(score * 100);
        },


    };

    // Initialize when document is ready
    $(document).ready(function() {
        // Only initialize on scan options page
        if ($('.vmpfence-options-content').length > 0) {
            VMPFenceScanOptions.init();
        }
    });

})(jQuery);
