document.addEventListener('DOMContentLoaded', function() {
    const checkoutForm = document.getElementById('checkoutForm');
    const paymentMethodSelect = document.getElementById('payment_method');
    const paymentDetailsContainer = document.getElementById('payment_details');
    
    paymentMethodSelect.addEventListener('change', function() {
        showPaymentDetails(this.value);
    });
    
    function showPaymentDetails(paymentMethod) {
        paymentDetailsContainer.innerHTML = '';
        
        if (paymentMethod === 'card') {
            paymentDetailsContainer.innerHTML = `
                <div class="checkout-form-group">
                    <label for="card_number">Card Number *</label>
                    <input type="text" id="card_number" name="card_number" 
                           placeholder="1234 5678 9012 3456" maxlength="19" required>
                </div>
                <div class="checkout-form-row">
                    <div class="checkout-form-group">
                        <label for="expiry_date">Expiry Date *</label>
                        <input type="text" id="expiry_date" name="expiry_date" 
                               placeholder="MM/YY" maxlength="5" required>
                    </div>
                    <div class="checkout-form-group">
                        <label for="cvv">CVV *</label>
                        <input type="text" id="cvv" name="cvv" 
                               placeholder="123" maxlength="4" required>
                    </div>
                </div>
                <div class="checkout-form-group">
                    <label for="card_holder_name">Card Holder Name *</label>
                    <input type="text" id="card_holder_name" name="card_holder_name" 
                           placeholder="Name as on card" required>
                </div>
            `;
            
            const cardNumberInput = document.getElementById('card_number');
            cardNumberInput.addEventListener('input', formatCardNumber);
            
            const expiryInput = document.getElementById('expiry_date');
            expiryInput.addEventListener('input', formatExpiryDate);
            
            const cvvInput = document.getElementById('cvv');
            cvvInput.addEventListener('input', function() {
                this.value = this.value.replace(/\D/g, '');
            });
            
        } else if (paymentMethod === 'online') {
            paymentDetailsContainer.innerHTML = `
                <div class="checkout-form-group">
                    <label for="online_method">Select Online Payment Method *</label>
                    <select id="online_method" name="online_method" required>
                        <option value="">Choose payment method</option>
                        <option value="stc_pay">STC Pay</option>
                        <option value="apple_pay">Apple Pay</option>
                        <option value="mada">Mada</option>
                        <option value="visa">Visa</option>
                        <option value="mastercard">Mastercard</option>
                    </select>
                </div>
                <div class="payment-info">
                    <p><i class="fas fa-shield-alt"></i> Your payment is secured with 256-bit SSL encryption</p>
                    <p><i class="fas fa-mobile-alt"></i> You will be redirected to complete the payment</p>
                </div>
            `;
        } else if (paymentMethod === 'cash') {
            paymentDetailsContainer.innerHTML = `
                <div class="payment-info cash-info">
                    <h4><i class="fas fa-money-bill-wave"></i> Cash on Delivery</h4>
                    <p><i class="fas fa-truck"></i> Pay when your order is delivered</p>
                    <p><i class="fas fa-calculator"></i> Exact change is appreciated</p>
                    <p><i class="fas fa-receipt"></i> Receipt will be provided upon payment</p>
                </div>
            `;
        }
    }
    
    function formatCardNumber(e) {
        let value = e.target.value.replace(/\s/g, '').replace(/\D/g, '');
        let formattedValue = value.replace(/(.{4})/g, '$1 ').trim();
        if (formattedValue.length > 19) {
            formattedValue = formattedValue.substring(0, 19);
        }
        e.target.value = formattedValue;
    }
    
    function formatExpiryDate(e) {
        let value = e.target.value.replace(/\D/g, '');
        if (value.length >= 2) {
            value = value.substring(0, 2) + '/' + value.substring(2, 4);
        }
        e.target.value = value;
    }
    
    checkoutForm.addEventListener('submit', function(e) {
        const requiredFields = ['customer_name', 'customer_phone', 'customer_address', 'payment_method'];
        let isValid = true;
        
        requiredFields.forEach(field => {
            const input = document.getElementById(field);
            if (!input.value.trim()) {
                input.style.borderColor = '#dc3545';
                isValid = false;
            } else {
                input.style.borderColor = '#e1e5e9';
            }
        });
        
        const paymentMethod = paymentMethodSelect.value;
        
        if (paymentMethod === 'card') {
            const cardFields = ['card_number', 'expiry_date', 'cvv', 'card_holder_name'];
            cardFields.forEach(field => {
                const input = document.getElementById(field);
                if (input && !input.value.trim()) {
                    input.style.borderColor = '#dc3545';
                    isValid = false;
                } else if (input) {
                    input.style.borderColor = '#e1e5e9';
                }
            });
            
            const cardNumber = document.getElementById('card_number');
            if (cardNumber && cardNumber.value.replace(/\s/g, '').length < 13) {
                cardNumber.style.borderColor = '#dc3545';
                isValid = false;
            }
            
            const expiryDate = document.getElementById('expiry_date');
            if (expiryDate && !/^\d{2}\/\d{2}$/.test(expiryDate.value)) {
                expiryDate.style.borderColor = '#dc3545';
                isValid = false;
            }
            
            const cvv = document.getElementById('cvv');
            if (cvv && (cvv.value.length < 3 || cvv.value.length > 4)) {
                cvv.style.borderColor = '#dc3545';
                isValid = false;
            }
            
        } else if (paymentMethod === 'online') {
            const onlineMethod = document.getElementById('online_method');
            if (onlineMethod && !onlineMethod.value) {
                onlineMethod.style.borderColor = '#dc3545';
                isValid = false;
            } else if (onlineMethod) {
                onlineMethod.style.borderColor = '#e1e5e9';
            }
        }
        
        const phoneInput = document.getElementById('customer_phone');
        const phonePattern = /^[0-9+\-\s()]+$/;
        if (phoneInput && !phonePattern.test(phoneInput.value)) {
            phoneInput.style.borderColor = '#dc3545';
            isValid = false;
        }
        
        if (!isValid) {
            e.preventDefault();
            
            let errorDiv = document.querySelector('.validation-error');
            if (!errorDiv) {
                errorDiv = document.createElement('div');
                errorDiv.className = 'error-message validation-error';
                errorDiv.innerHTML = 'Please fill in all required fields correctly.';
                checkoutForm.insertBefore(errorDiv, checkoutForm.firstChild);
            }
            
            errorDiv.scrollIntoView({ behavior: 'smooth' });
            
            setTimeout(() => {
                if (errorDiv.parentNode) {
                    errorDiv.parentNode.removeChild(errorDiv);
                }
            }, 5000);
        }
    });
    
    if (paymentMethodSelect.value) {
        showPaymentDetails(paymentMethodSelect.value);
    }
    
    const subChk = document.getElementById('use_subscription');
    const delInfo = document.querySelector('.checkout-delivery-info');
    
    if (subChk && delInfo) {
        subChk.addEventListener('change', function() {
            if (this.checked) {
                delInfo.innerHTML = `
                    <p style="margin: 0; color: #4caf50; font-size: 0.9rem; font-weight: 600;">
                        <i class="fas fa-crown" style="color: #ffd700;"></i> <strong>Express Delivery Selected!</strong><br>
                        • Order delivered within 24 hours<br>
                        • Priority processing<br>
                        • Premium service included
                    </p>
                    <p style="margin: 0.5rem 0 0 0; color: #4caf50; font-weight: 600; font-size: 0.9rem;">
                        <i class="fas fa-check-circle"></i> Express delivery confirmed!
                    </p>
                `;
            } else {
                delInfo.innerHTML = `
                    <p style="margin: 0; color: #666; font-size: 0.9rem;">
                        <strong>Delivery calculated based on selected services:</strong><br>
                        • Standard services: 1-3 business days<br>
                        • Express services: 24 hours<br>
                        • Specialized services: 2-4 business days<br>
                        • Carpets & large items: 2-5 business days
                    </p>
                    <p style="margin: 0.5rem 0 0 0; color: #00aaff; font-weight: 600; font-size: 0.9rem;">
                        Delivery date confirmed after processing.
                    </p>
                `;
            }
        });
    }
    const submitButton = document.querySelector('.btn-checkout');
    checkoutForm.addEventListener('submit', function() {
        if (submitButton) {
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            submitButton.disabled = true;
        }
    });
});
