/**
 * FormShield IP Whitelist JavaScript
 * 
 * Handles all IP whitelist functionality including:
 * - Saving whitelist settings
 * - Adding/removing IP addresses
 * - Testing IP addresses
 * - Form validation
 * - User feedback
 * 
 * @since 1.0.3-beta
 */
jQuery(document).ready(function($) {
    const DEBUG = false;
    
    const FormShieldIPWhitelist = {
        init: function() {
            this.setupEventListeners();
            this.initializeWhitelist();
        },
        
        setupEventListeners: function() {
            // Save whitelist
            $('.save-whitelist').on('click', (e) => {
                e.preventDefault();
                this.saveWhitelist();
            });
            
            // Add IP button
            $('.add-ip-btn').on('click', (e) => {
                e.preventDefault();
                this.showAddIPModal();
            });
            
            // Test IP button
            $('.test-ip-btn').on('click', (e) => {
                e.preventDefault();
                this.showTestIPModal();
            });
            
            // Remove IP buttons
            $(document).on('click', '.remove-ip-btn', (e) => {
                e.preventDefault();
                const ip = $(e.target).data('ip');
                this.removeIP(ip);
            });
            
            // IP input validation
            $('#whitelist-ips').on('input', (e) => {
                this.validateIPList($(e.target).val());
            });
        },
        
        initializeWhitelist: function() {
            // Load current whitelist
            this.loadWhitelist();
            
            // Update statistics
            this.updateStatistics();
        },
        
        saveWhitelist: function() {
            const button = $('.save-whitelist');
            const originalText = button.text();
            
            // Disable button and show loading
            button.prop('disabled', true).text('Saving...');
            
            // Collect form data
            const formData = {
                whitelist_ips: $('#whitelist-ips').val(),
                whitelist_enabled: $('#whitelist-enabled').is(':checked'),
                nonce: formshieldData.nonce
            };
            
            
            // Send AJAX request
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formshield_save_whitelist',
                    ...formData
                },
                success: (response) => {
                    if (response.success) {
                        this.showSuccess(response.data.message);
                        this.loadWhitelist();
                        this.updateStatistics();
                    } else {
                        this.showError('Failed to save whitelist: ' + response.data);
                        if (DEBUG) console.error('FormShield: Save failed:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    this.showError('Error saving whitelist: ' + error);
                    if (DEBUG) console.error('FormShield: AJAX error:', error);
                },
                complete: () => {
                    // Re-enable button
                    button.prop('disabled', false).text(originalText);
                }
            });
        },
        
        addIP: function(ip) {
            if (!this.validateSingleIP(ip)) {
                this.showError('Invalid IP address: ' + ip);
                return;
            }
            
            
            // Send AJAX request
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formshield_add_ip_to_whitelist',
                    ip: ip,
                    nonce: formshieldData.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showSuccess(response.data.message);
                        this.loadWhitelist();
                        this.updateStatistics();
                    } else {
                        this.showError('Failed to add IP: ' + response.data);
                        if (DEBUG) console.error('FormShield: Add IP failed:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    this.showError('Error adding IP: ' + error);
                    if (DEBUG) console.error('FormShield: Add IP error:', error);
                }
            });
        },
        
        removeIP: function(ip) {
            if (confirm('Are you sure you want to remove IP address: ' + ip + '?')) {
                
                // Send AJAX request
                $.ajax({
                    url: formshieldData.ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'formshield_remove_ip_from_whitelist',
                        ip: ip,
                        nonce: formshieldData.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            this.showSuccess(response.data.message);
                            this.loadWhitelist();
                            this.updateStatistics();
                        } else {
                            this.showError('Failed to remove IP: ' + response.data);
                            if (DEBUG) console.error('FormShield: Remove IP failed:', response.data);
                        }
                    },
                    error: (xhr, status, error) => {
                        this.showError('Error removing IP: ' + error);
                        if (DEBUG) console.error('FormShield: Remove IP error:', error);
                    }
                });
            }
        },
        
        testIP: function(ip) {
            if (!this.validateSingleIP(ip)) {
                this.showError('Invalid IP address: ' + ip);
                return;
            }
            
            
            // Send AJAX request
            $.ajax({
                url: formshieldData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'formsh_test_ip',
                    ip: ip,
                    nonce: formshieldData.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.showSuccess('Valid IP address: ' + ip);
                    } else {
                        this.showError('Invalid IP address: ' + ip);
                        if (DEBUG) console.error('FormShield: IP test failed:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    this.showError('Error testing IP: ' + error);
                    if (DEBUG) console.error('FormShield: IP test error:', error);
                }
            });
        },
        
        validateSingleIP: function(ip) {
            // Basic IP validation
            const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
            const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
            const cidrRegex = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/;
            const wildcardRegex = /^(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)$/;
            
            return ipv4Regex.test(ip) || ipv6Regex.test(ip) || cidrRegex.test(ip) || wildcardRegex.test(ip);
        },
        
        validateIPList: function(ipList) {
            const lines = ipList.split('\n');
            let validCount = 0;
            let invalidCount = 0;
            
            lines.forEach(line => {
                const ip = line.trim();
                if (ip && this.validateSingleIP(ip)) {
                    validCount++;
                } else if (ip) {
                    invalidCount++;
                }
            });
            
            // Update validation display
            this.updateValidationDisplay(validCount, invalidCount);
        },
        
        updateValidationDisplay: function(validCount, invalidCount) {
            const container = $('.whitelist-validation');
            
            if (container.length === 0) {
                $('.whitelist-management').append('<div class="whitelist-validation"></div>');
            }
            
            const validation = $('.whitelist-validation');
            validation.html(`
                <div class="validation-summary">
                    <span class="valid-count">✅ Valid IPs: ${validCount}</span>
                    <span class="invalid-count">❌ Invalid IPs: ${invalidCount}</span>
                </div>
            `);
        },
        
        loadWhitelist: function() {
            // This would typically load from the server
            // For now, we'll just update the display
            this.updateWhitelistDisplay();
        },
        
        updateWhitelistDisplay: function() {
            const textarea = $('#whitelist-ips');
            const currentIPs = textarea.val().split('\n').filter(ip => ip.trim());
            
            // Update the display with current IPs
            if (currentIPs.length > 0) {
                this.updateStatistics();
            }
        },
        
        updateStatistics: function() {
            const textarea = $('#whitelist-ips');
            const currentIPs = textarea.val().split('\n').filter(ip => ip.trim());
            const enabled = $('#whitelist-enabled').is(':checked');
            
            const statsContainer = $('.whitelist-stats');
            if (statsContainer.length === 0) {
                $('.whitelist-management').append('<div class="whitelist-stats"></div>');
            }
            
            const stats = $('.whitelist-stats');
            stats.html(`
                <div class="stats-summary">
                    <span class="status ${enabled ? 'enabled' : 'disabled'}">
                        ${enabled ? '🟢 Enabled' : '🔴 Disabled'}
                    </span>
                    <span class="total-ips">📊 Total IPs: ${currentIPs.length}</span>
                    <span class="last-updated">🕒 Last Updated: ${new Date().toLocaleString()}</span>
                </div>
            `);
        },
        
        showAddIPModal: function() {
            const ip = prompt('Enter IP address to add:');
            if (ip && ip.trim()) {
                this.addIP(ip.trim());
            }
        },
        
        showTestIPModal: function() {
            const ip = prompt('Enter IP address to test:');
            if (ip && ip.trim()) {
                this.testIP(ip.trim());
            }
        },
        
        showSuccess: function(message) {
            this.showMessage(message, 'success');
        },
        
        showError: function(message) {
            this.showMessage(message, 'error');
        },
        
        showMessage: function(message, type) {
            // Remove existing messages
            $('.formshield-message').remove();
            
            // Create message element
            const messageElement = $('<div>', {
                class: `formshield-message ${type}`,
                text: message
            });
            
            // Add to page
            $('.whitelist-management').prepend(messageElement);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                messageElement.fadeOut('slow', function() {
                    $(this).remove();
                });
            }, 5000);
        }
    };
    
    // Initialize IP Whitelist
    FormShieldIPWhitelist.init();
});
