// Track loading states for sections
let sectionLoadingStates = {
    'scheduling': false,
    'general': false,
    'performance': false,
    'advanced': false
};

function showSectionLoading(sectionId) {
    const section = document.querySelector(`[onclick="toggleSection('${sectionId}')"]`).parentElement;
    if (section) {
        const contentArea = section.querySelector('.vmpfence-scan-option-content');
        if (contentArea && !contentArea.querySelector('.vmpfence-loading-indicator')) {
            const loadingDiv = document.createElement('div');
            loadingDiv.className = 'vmpfence-loading-indicator';
            loadingDiv.innerHTML = '<div class="vmpfence-spinner"></div><span>Loading section data...</span>';
            contentArea.appendChild(loadingDiv);
        }
    }
}

function hideSectionLoading(sectionId) {
    const section = document.querySelector(`[onclick="toggleSection('${sectionId}')"]`).parentElement;
    if (section) {
        const loadingIndicator = section.querySelector('.vmpfence-loading-indicator');
        if (loadingIndicator) {
            loadingIndicator.remove();
        }
    }
}

function toggleSection(sectionId) {
    const arrow = document.getElementById(sectionId + '-arrow');
    const section = document.querySelector(`[onclick="toggleSection('${sectionId}')"]`).parentElement;
    
    if (section.classList.contains('vmpfence-section-expanded')) {
        // Collapsing
        section.classList.remove('vmpfence-section-expanded');
        // Reset arrow to right (0 degrees)
        arrow.style.transform = 'rotate(0deg)';
    } else {
        // Expanding
        section.classList.add('vmpfence-section-expanded');
        // Rotate arrow down (90 degrees)
        arrow.style.transform = 'rotate(90deg)';
        
        // Show loading indicator if section data hasn't been fully loaded
        if (!sectionLoadingStates[sectionId]) {
            showSectionLoading(sectionId);
            
            // The section will be marked as loaded by the main initialization process
            // Check periodically if it's been loaded
            const checkLoaded = setInterval(() => {
                if (sectionLoadingStates[sectionId]) {
                    hideSectionLoading(sectionId);
                    clearInterval(checkLoaded);
                }
            }, 250);
            
            // Failsafe: remove loading indicator after 5 seconds even if state doesn't update
            setTimeout(() => {
                hideSectionLoading(sectionId);
                sectionLoadingStates[sectionId] = true;
                clearInterval(checkLoaded);
            }, 5000);
        }
    }
}

// Handle scan type selection with checkboxes (only one can be selected)
document.addEventListener('DOMContentLoaded', function() {
    const scanTypeCards = document.querySelectorAll('.vmpfence-scan-type-card:not(.vmpfence-custom-scan-card)');
    const checkboxButtons = document.querySelectorAll('input[name="scan_type[]"]:not(#scan-custom)');
    const customScanCard = document.querySelector('.vmpfence-custom-scan-card');
    const customCheckbox = document.getElementById('scan-custom');
    
    checkboxButtons.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            if (this.checked) {
                // Uncheck all other checkboxes except this one
                checkboxButtons.forEach(function(otherCheckbox) {
                    if (otherCheckbox !== checkbox) {
                        otherCheckbox.checked = false;
                        otherCheckbox.closest('.vmpfence-scan-type-card').classList.remove('vmpfence-scan-type-selected');
                    }
                });
                
                // Check this one and add selected class
                this.closest('.vmpfence-scan-type-card').classList.add('vmpfence-scan-type-selected');
                
                // Uncheck custom scan when user selects a predefined option
                customCheckbox.checked = false;
                customScanCard.classList.remove('vmpfence-scan-type-selected');
                
                // Update only the scan type card with new percentage
                updateScanTypeOnly();
            } else {
                this.closest('.vmpfence-scan-type-card').classList.remove('vmpfence-scan-type-selected');
            }
        });
    });
    
    // Make regular cards clickable to toggle checkbox (but not custom scan)
    scanTypeCards.forEach(function(card) {
        card.addEventListener('click', function(e) {
            // Only trigger if clicking on the card, not on the checkbox or label
            if (e.target.type !== 'checkbox' && e.target.tagName !== 'LABEL') {
                const checkbox = card.querySelector('input[type="checkbox"]');
                checkbox.checked = !checkbox.checked;
                checkbox.dispatchEvent(new Event('change'));
            }
        });
    });
    
    // Function to auto-select Custom Scan when options are changed
    window.selectCustomScan = function() {
        // Uncheck all regular scan types
        checkboxButtons.forEach(function(checkbox) {
            checkbox.checked = false;
            checkbox.closest('.vmpfence-scan-type-card').classList.remove('vmpfence-scan-type-selected');
        });
        
        // Select custom scan
        customCheckbox.checked = true;
        customScanCard.classList.add('vmpfence-scan-type-selected');
    };

    // Handle toggle buttons for schedule settings
    const toggleButtons = document.querySelectorAll('.vmpfence-toggle-btn');
    toggleButtons.forEach(function(button) {
        button.addEventListener('click', function() {
            // Remove active class from siblings
            const siblings = this.parentElement.querySelectorAll('.vmpfence-toggle-btn');
            siblings.forEach(function(sibling) {
                sibling.classList.remove('active');
            });
            
            // Add active class to clicked button
            this.classList.add('active');
        });
    });

    // Handle radio button changes
    const radioButtons = document.querySelectorAll('input[name="schedule_type"]');
    radioButtons.forEach(function(radio) {
        radio.addEventListener('change', function() {
            // Just handle the radio button selection, no scan type changes
        });
    });

    // Handle URL hash fragments to auto-expand sections
    if (window.location.hash) {
        const hash = window.location.hash.substring(1); // Remove the #
        
        if (hash === 'advanced-content') {
            // Expand the Advanced Scan Options section
            const advancedSection = document.querySelector(`[onclick="toggleSection('advanced')"]`).parentElement;
            const advancedArrow = document.getElementById('advanced-arrow');
            
            if (advancedSection && !advancedSection.classList.contains('vmpfence-section-expanded')) {
                advancedSection.classList.add('vmpfence-section-expanded');
                if (advancedArrow) {
                    advancedArrow.style.transform = 'rotate(90deg)';
                }
            }
            
            // Scroll to the section after a brief delay to ensure it's expanded
            setTimeout(() => {
                const targetElement = document.getElementById('advanced-content');
                if (targetElement) {
                    targetElement.scrollIntoView({ 
                        behavior: 'smooth', 
                        block: 'start' 
                    });
                }
            }, 100);
        } else if (hash === 'general-content') {
            // Expand the General Options section
            const generalSection = document.querySelector(`[onclick="toggleSection('general')"]`).parentElement;
            const generalArrow = document.getElementById('general-arrow');
            
            if (generalSection && !generalSection.classList.contains('vmpfence-section-expanded')) {
                generalSection.classList.add('vmpfence-section-expanded');
                if (generalArrow) {
                    generalArrow.style.transform = 'rotate(90deg)';
                }
            }
            
            // Scroll to the section after a brief delay to ensure it's expanded
            setTimeout(() => {
                const targetElement = document.getElementById('general-content');
                if (targetElement) {
                    targetElement.scrollIntoView({ 
                        behavior: 'smooth', 
                        block: 'start' 
                    });
                }
            }, 100);
        }
    }
    
    // Wait for both DOM and jQuery to be ready
    function waitForDependencies() {
        
        if (typeof window.jQuery !== 'undefined') {
            // Use jQuery's ready function to ensure DOM is ready
            window.jQuery(document).ready(function($) {
                // Initialize page-wide loading state
                initializePageLoading();
                
                // Load all configurations in sequence
                setTimeout(function() {
                    loadAllConfigurations();
                }, 500); // Brief delay to show loading states
            });
        } else {
            setTimeout(waitForDependencies, 100);
        }
    }
    
    /**
     * Initialize page loading state management
     */
    function initializePageLoading() {
        
        // Reset all section loading states
        sectionLoadingStates = {
            'scheduling': false,
            'general': false,
            'performance': false,
            'advanced': false
        };
        
        // If any sections are already expanded, show loading for them
        ['scheduling', 'general', 'performance', 'advanced'].forEach(sectionId => {
            const section = document.querySelector(`[onclick="toggleSection('${sectionId}')"]`);
            if (section && section.parentElement.classList.contains('vmpfence-section-expanded')) {
                showSectionLoading(sectionId);
            }
        });
    }
    
    /**
     * Load all page configurations and update loading states
     */
    function loadAllConfigurations() {
        
        // Load configuration data
        loadSecurityScores();
        updateReputationPercentageDynamic();
        
        // Mark all sections as loaded after data is retrieved
        setTimeout(function() {
            ['scheduling', 'general', 'performance', 'advanced'].forEach(sectionId => {
                sectionLoadingStates[sectionId] = true;
                hideSectionLoading(sectionId);
            });
        }, 1500); // Allow time for AJAX calls to complete
    }
    
    // Start checking for dependencies
    waitForDependencies();
    
    // Update reputation percentage on window load
    window.addEventListener('load', function() {
        setTimeout(function() {
            if (window.updateReputationPercentageDynamic) {
                updateReputationPercentageDynamic();
            }
        }, 500);
    });

    /**
     * Load and display reputation percentage - standalone implementation
     */
    function loadReputationPercentageStandalone() {
        
        // Use jQuery from window object to avoid conflicts
        const $ = window.jQuery;
        
        // Verify AJAX object is available
        if (typeof vmpfence_options_ajax === 'undefined') {
            return;
        }
        
        $.ajax({
            url: vmpfence_options_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_reputation_percentage',
                nonce: vmpfence_options_ajax.nonce
            },
            success: function(response) {
                if (response.success && response.data && typeof response.data.percentage !== 'undefined') {
                    updateReputationCardStandalone(response.data.percentage);
                }
            },
            error: function(xhr, status, error) {
                // Handle error silently
            }
        });
    }
    
    /**
     * Update the reputation check card with calculated percentage
     * Using correct 4-tier color scheme: ≥80% green, ≥60% blue, ≥40% yellow, <40% red
     */
    function updateReputationCardStandalone(percentage) {
        const $ = window.jQuery;
        
        // Target the third vmpfence-options-card (reputation card)
        const $reputationCards = $('.vmpfence-options-card');
        if ($reputationCards.length < 3) return;
        
        const $reputationCard = $reputationCards.eq(2);
        const $progressBar = $reputationCard.find('.vmpfence-circle-progress-bar');
        const $percentageText = $reputationCard.find('.vmpfence-circle-text');
        
        if ($progressBar.length === 0 || $percentageText.length === 0) return;
        
        // Update percentage text
        $percentageText.text(percentage + '%');
        
        // Update progress bar
        $progressBar.attr('stroke-dasharray', percentage + ',100');
        
        // Update color based on 4-tier system (matches PHP calculation)
        let color = '#dc3545'; // Red for <40%
        if (percentage >= 80) {
            color = '#28a745'; // Green
        } else if (percentage >= 60) {
            color = '#17a2b8'; // Blue
        } else if (percentage >= 40) {
            color = '#ffc107'; // Yellow
        }
        
        $progressBar.attr('stroke', color);
    }
    
    /**
     * Calculate and update reputation percentage based on checkbox states
     * Formula: 33% + 33% + 33% = 99%, rounds to 100%
     */
    function updateReputationPercentageDynamic() {
        const $ = window.jQuery;
        if (!$) return;
        
        // Get checkbox states
        const checkGSB = $('input[name="scansEnabled_checkGSB"]').is(':checked');
        const spamvertizeCheck = $('input[name="spamvertizeCheck"]').is(':checked');
        const checkSpamIP = $('input[name="checkSpamIP"]').is(':checked');
        
        // Calculate percentage: 33% per check
        let percentage = 0;
        if (checkGSB) percentage += 33;
        if (spamvertizeCheck) percentage += 33;
        if (checkSpamIP) percentage += 33;
        
        // Round 99 to 100 (when all three enabled)
        if (percentage == 99) {
            percentage = 100;
        }
        
        // Update the card
        updateReputationCardStandalone(percentage);
    }
    
    // Make function globally available
    window.updateReputationPercentageDynamic = updateReputationPercentageDynamic;
    
    /**
     * Load security scores (scan types and malware signatures)
     */
    function loadSecurityScores() {
        
        if (typeof window.jQuery === 'undefined') {
            return;
        }
        
        window.jQuery.ajax({
            url: vmpfence_options_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_security_scores',
                nonce: vmpfence_options_ajax.security_nonce  // Use security_nonce for this action
            },
            success: function(response) {
                if (response.success) {
                    // Scan type now calculated in PHP (30% premium + 11% reputation + 59% options)
                    // Malware signatures now calculated in PHP (70% free + 30% premium)
                    
                    updateScanTypeTitle(response.data.scan_type_name);
                }
            },
            error: function(xhr, status, error) {
                // Handle error silently
            }
        });
    }

    /**
     * Update security score circle
     */
    function updateSecurityScoreCircle(textElementId, progressElementId, percentage) {
        
        // Update text
        const textElement = document.getElementById(textElementId);
        if (textElement) {
            textElement.textContent = percentage + '%';
        }
        
        // Update circle progress
        const progressElement = document.getElementById(progressElementId);
        if (progressElement) {
            const circumference = 2 * Math.PI * 15.91549431;
            const offset = circumference - (percentage / 100) * circumference;
            progressElement.style.strokeDasharray = percentage + ',100';
            
            // Color coding
            let newColor = '';
            if (percentage < 60) {
                newColor = '#f44336'; // Red
            } else if (percentage < 85) {
                newColor = '#ff9800'; // Orange
            } else {
                newColor = '#4CAF50'; // Green
            }
            
            progressElement.setAttribute('stroke', newColor);
        }
    }
    
    /**
     * Update scan type title
     */
    function updateScanTypeTitle(scanTypeName) {
        const titleElement = document.getElementById('scan-types-title');
        if (titleElement) {
            titleElement.textContent = 'Scan Type: ' + scanTypeName;
        }
    }
    
    /**
     * Update only the scan type card when scan type selection changes
     */
    function updateScanTypeOnly() {
        
        if (typeof window.jQuery === 'undefined') {
            return;
        }
        
        // Get currently selected scan type
        let selectedScanType = '';
        const scanTypeCheckboxes = document.querySelectorAll('input[name="scan_type[]"]:checked');
        
        if (scanTypeCheckboxes.length > 0) {
            selectedScanType = scanTypeCheckboxes[0].value;
        }
        
        
        window.jQuery.ajax({
            url: vmpfence_options_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_get_scan_type_percentage',
                nonce: vmpfence_options_ajax.nonce,
                selected_scan_type: selectedScanType
            },
            success: function(response) {
                if (response.success) {
                    // Scan type percentage now calculated in PHP (30% premium + 11% reputation + 59% options)
                    updateScanTypeTitle(response.data.scan_type_name);
                    const descElement = document.getElementById('scan-types-description');
                    if (descElement) {
                        descElement.textContent = response.data.scan_type_description;
                    }
                }
            },
            error: function(error) {
                // Handle error silently
            }
        });
    }
    
    // Make function globally available
    window.updateScanTypeOnly = updateScanTypeOnly;
    
    // Make functions globally available
    window.loadSecurityScores = loadSecurityScores;
    
    // Wait for scan-options.js to finish loading configuration
    setTimeout(function() {
        loadSecurityScores();
    }, 1000); // 1 second delay should be enough
});
