// Localize AJAX configuration for settings page
var ajaxConfig = {
    url: formshieldSettings.ajaxUrl,
    autoSaveNonce: formshieldSettings.autoSaveNonce
};

// Use localized strings
var formshieldStrings = formshieldSettings.strings;
var savedSettings = formshieldSettings.savedSettings;

// Auto-save functionality - settings are saved automatically when changed
document.addEventListener('DOMContentLoaded', function() {
    // Add event listeners for auto-save
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.addEventListener('change', function() {
            autoSaveSetting(this);
        });
    });
    
    // Show/hide report frequency options based on periodic reports checkbox
    const periodicReportsCheckbox = document.getElementById('periodic_reports');
    const reportFrequencyGroup = document.getElementById('report_frequency_group');
    
    function toggleReportFrequency() {
        const reportFrequencySelect = document.getElementById('report_frequency');
        if (periodicReportsCheckbox.checked) {
            reportFrequencyGroup.style.opacity = '1';
            reportFrequencySelect.disabled = false;
        } else {
            reportFrequencyGroup.style.opacity = '0.5';
            reportFrequencySelect.disabled = true;
        }
    }
    
    // Initial state - set based on periodic reports checkbox
    toggleReportFrequency();
    
    // Add event listener for checkbox change
    periodicReportsCheckbox.addEventListener('change', toggleReportFrequency);
});

function autoSaveSetting(element) {
    const settingName = element.name || element.id || element.className;
    const settingValue = element.type === 'checkbox' ? element.checked : element.value;
    
    // Check if ajaxConfig is available
    if (!ajaxConfig || !ajaxConfig.url) {
        return;
    }
    
    // Prepare data for AJAX
    const data = {
        action: 'formshield_auto_save_setting',
        setting_name: settingName,
        setting_value: settingValue,
        nonce: ajaxConfig.autoSaveNonce
    };
    
    // Send AJAX request
    fetch(ajaxConfig.url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showAutoSaveIndicator();
        }
    })
    .catch(error => {
        console.error('Auto-save error:', error);
    });
}

function showAutoSaveIndicator() {
    // Show a more visible indicator that setting was saved
    const indicator = document.createElement('div');
    indicator.style.cssText = `
        position: fixed;
        top: 32px;
        right: 32px;
        background: #2563EB;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        z-index: 99999;
        opacity: 0;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
        border: 2px solid #1d4ed8;
    `;
    indicator.textContent = formshieldStrings.settingSaved;
    document.body.appendChild(indicator);
    
    // Fade in
    setTimeout(() => {
        indicator.style.opacity = '1';
        indicator.style.transform = 'translateY(0)';
    }, 10);
    
    // Fade out and remove after 3 seconds
    setTimeout(() => {
        indicator.style.opacity = '0';
        indicator.style.transform = 'translateY(-10px)';
        setTimeout(() => {
            if (document.body.contains(indicator)) {
                document.body.removeChild(indicator);
            }
        }, 300);
    }, 3000);
}

// Email Settings Functions
function sendTestEmail() {
    const adminEmail = document.querySelector('input[type="email"]').value;
    if (!adminEmail.trim()) {
        alert(formshieldStrings.pleaseEnterValidEmail);
        return;
    }
    if (!isValidEmail(adminEmail)) {
        alert(formshieldStrings.pleaseEnterValidEmailFormat);
        return;
    }
    // Send real test email via AJAX
    fetch(ajaxConfig.url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'formsh_test_email',
            email: adminEmail,
            nonce: ajaxConfig.autoSaveNonce
        })
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert(formshieldStrings.testEmailSent.replace('%s', adminEmail));
        } else {
            alert('Failed to send test email: ' + (result.data || 'Unknown error'));
        }
    })
    .catch(error => {
        alert('Error sending test email: ' + error.message);
    });
}

function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// IP Whitelist Functions
function saveWhitelist() {
    const whitelistIPs = document.getElementById('whitelist-ips').value;
    const whitelistEnabled = document.getElementById('whitelist-enabled').checked;
    if (!whitelistEnabled) {
        alert(formshieldStrings.ipWhitelistDisabled);
        return;
    }
    if (!whitelistIPs.trim()) {
        alert(formshieldStrings.pleaseEnterAtLeastOneIP);
        return;
    }
    // Validate IPs before saving
    const ipList = whitelistIPs.split('\n').filter(ip => ip.trim());
    const invalidIPs = [];
    for (const ip of ipList) {
        if (!isValidIP(ip.trim())) {
            invalidIPs.push(ip.trim());
        }
    }
    if (invalidIPs.length > 0) {
        alert(formshieldStrings.invalidIPsFound.replace('%s', invalidIPs.join('\n')));
        return;
    }
    alert(formshieldStrings.ipWhitelistSaved);
}

function validateIPs() {
    const whitelistIPs = document.getElementById('whitelist-ips').value;
    if (!whitelistIPs.trim()) {
        alert(formshieldStrings.noIPsToValidate);
        return;
    }
    const ipList = whitelistIPs.split('\n').filter(ip => ip.trim());
    const validIPs = [];
    const invalidIPs = [];
    for (const ip of ipList) {
        if (isValidIP(ip.trim())) {
            validIPs.push(ip.trim());
        } else {
            invalidIPs.push(ip.trim());
        }
    }
    let message = formshieldStrings.validationResults;
    message += formshieldStrings.validIPs.replace('%d', validIPs.length).replace('%s', validIPs.join('\n'));
    if (invalidIPs.length > 0) {
        message += formshieldStrings.invalidIPs.replace('%d', invalidIPs.length).replace('%s', invalidIPs.join('\n'));
        message += formshieldStrings.pleaseFixInvalidIPs;
    } else {
        message += formshieldStrings.allIPsValid;
    }
    alert(message);
}

function clearWhitelist() {
    if (confirm(formshieldStrings.confirmClearWhitelist)) {
        document.getElementById('whitelist-ips').value = '';
        document.getElementById('whitelist-enabled').checked = false;
        alert(formshieldStrings.ipWhitelistCleared);
    }
}

function isValidIP(ip) {
    // IPv4 validation
    const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
    if (ipv4Regex.test(ip)) {
        const parts = ip.split('.');
        return parts.every(part => {
            const num = parseInt(part);
            return num >= 0 && num <= 255;
        });
    }
    
    // IPv4 CIDR validation
    const ipv4CidrRegex = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/;
    if (ipv4CidrRegex.test(ip)) {
        const [ipPart, cidrPart] = ip.split('/');
        const cidr = parseInt(cidrPart);
        if (cidr < 0 || cidr > 32) return false;
        const parts = ipPart.split('.');
        return parts.every(part => {
            const num = parseInt(part);
            return num >= 0 && num <= 255;
        });
    }
    
    // IPv6 validation (basic)
    const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
    if (ipv6Regex.test(ip)) return true;
    
    // IPv6 CIDR validation (basic)
    const ipv6CidrRegex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/\d{1,3}$/;
    if (ipv6CidrRegex.test(ip)) {
        const [, cidrPart] = ip.split('/');
        const cidr = parseInt(cidrPart);
        return cidr >= 0 && cidr <= 128;
    }
    
    // IPv6 compressed format (::)
    if (ip.includes('::')) {
        const parts = ip.split('::');
        if (parts.length !== 2) return false;
        const leftParts = parts[0].split(':').filter(p => p);
        const rightParts = parts[1].split(':').filter(p => p);
        
        return (leftParts.length + rightParts.length) <= 8;
    }
    
    return false;
}
