// Subscription Form Validation Script
// Pushpvatika Florist - Daily Flower Subscription

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('subscriptionForm');
    const submitBtn = document.getElementById('submitBtn');

    if (!form || !submitBtn) {
        return;
    }

    // ========================================
    // TOUCHED STATE
    // ========================================
    // A field only shows an error once the visitor has left it (blur), or once
    // they have tried to submit. Before that, validators still run so the form
    // knows whether it is valid — they just do not paint anything red.
    const touched = Object.create(null);
    let submitAttempted = false;

    function markTouched(fieldName) {
        touched[fieldName] = true;
    }

    function shouldShowErrors(fieldName) {
        return submitAttempted || touched[fieldName] === true;
    }

    // ========================================
    // DATE RULE — must match api/submit-subscription.php
    // ========================================
    // Earliest allowed start date is today. Midnight-anchored so the time of day
    // the visitor happens to be browsing can never shift the rule, and so a date
    // picked as "today" is never rejected for being a few hours in the past.
    function earliestStartDate() {
        const earliest = new Date();
        earliest.setHours(0, 0, 0, 0);
        return earliest;
    }

    function toDateInputValue(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    function parseDateInputValue(value) {
        const parts = String(value).split('-');
        if (parts.length !== 3) {
            return null;
        }
        const parsed = new Date(Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
        parsed.setHours(0, 0, 0, 0);
        return isNaN(parsed.getTime()) ? null : parsed;
    }

    const startDateInput = document.getElementById('startDate');
    const minStartDate = earliestStartDate();
    startDateInput.min = toDateInputValue(minStartDate);

    const minStartDateLabel = minStartDate.toLocaleDateString('en-IN', {
        day: '2-digit',
        month: 'short',
        year: 'numeric'
    });

    // Helper hint so the rule is visible before the visitor hits it.
    (function renderDateHint() {
        const group = startDateInput.closest('.form-group');
        if (!group) {
            return;
        }
        // Do not duplicate a hint that already exists in the markup.
        let hint = group.querySelector('small');
        if (!hint) {
            hint = document.createElement('small');
            group.appendChild(hint);
        }
        hint.textContent = `You can start today — earliest start date is ${minStartDateLabel}`;
    }());

    // ========================================
    // REAL-TIME VALIDATION FOR EACH FIELD
    // ========================================

    // Name validation
    const nameInput = document.getElementById('fullName');
    nameInput.addEventListener('input', function () {
        validateName(this);
        checkFormValidity();
    });
    nameInput.addEventListener('blur', function () {
        markTouched('fullName');
        validateName(this);
    });

    // Accepts letters from any script (Gujarati, Devanagari, Latin, ...) plus
    // the punctuation real names carry: "Dr. Mehta", "R.K. Shah", "D'Souza".
    const NAME_PATTERN = /^[\p{L}\p{M}][\p{L}\p{M}\s.'\-]{1,99}$/u;

    function validateName(input) {
        const value = input.value.trim();
        const errorSpan = document.getElementById('nameError');

        if (value.length === 0) {
            return fail(input, errorSpan, 'fullName', 'Name is required');
        }
        if (value.length < 3) {
            return fail(input, errorSpan, 'fullName', 'Name must be at least 3 characters');
        }
        if (!NAME_PATTERN.test(value)) {
            return fail(input, errorSpan, 'fullName', 'Please enter your name');
        }
        return pass(input, errorSpan, 'fullName');
    }

    // Phone validation
    const phoneInput = document.getElementById('phone');
    phoneInput.addEventListener('input', function () {
        // Allow only numbers
        this.value = this.value.replace(/[^0-9]/g, '');
        validatePhone(this);
        checkFormValidity();
    });
    phoneInput.addEventListener('blur', function () {
        markTouched('phone');
        validatePhone(this);
    });

    function validatePhone(input) {
        const value = input.value;
        const errorSpan = document.getElementById('phoneError');

        if (value.length === 0) {
            return fail(input, errorSpan, 'phone', 'Phone number is required');
        }
        if (value.length !== 10) {
            return fail(input, errorSpan, 'phone', 'Phone number must be 10 digits');
        }
        if (!/^[6-9][0-9]{9}$/.test(value)) {
            return fail(input, errorSpan, 'phone', 'Invalid phone number format (must start with 6-9)');
        }
        return pass(input, errorSpan, 'phone');
    }

    // WhatsApp validation (optional field — only validated when the user typed something).
    // Previously unvalidated in JS while carrying a native `pattern`, so a non-Indian
    // number blocked submission with no message anywhere on the page.
    const whatsappInput = document.getElementById('whatsapp');
    if (whatsappInput) {
        whatsappInput.addEventListener('input', function () {
            validateWhatsapp(this);
            checkFormValidity();
        });
        whatsappInput.addEventListener('blur', function () {
            markTouched('whatsapp');
            validateWhatsapp(this);
        });
    }

    function validateWhatsapp(input) {
        if (!input) {
            return true;
        }
        const errorSpan = document.getElementById('whatsappError');
        const raw = input.value.trim();

        if (raw.length === 0) {
            return pass(input, errorSpan, 'whatsapp'); // optional
        }
        // Accept the ways Indians actually type it: +91 98765 43210, 091-98765 43210, 9876543210
        const national = raw.replace(/[\s\-()]/g, '').replace(/^(\+91|91|0)/, '');
        if (!/^[6-9][0-9]{9}$/.test(national)) {
            return fail(input, errorSpan, 'whatsapp',
                'Enter a 10-digit Indian mobile number, or leave this blank');
        }
        return pass(input, errorSpan, 'whatsapp');
    }

    // Email validation
    const emailInput = document.getElementById('email');
    emailInput.addEventListener('input', function () {
        validateEmail(this);
        checkFormValidity();
    });
    emailInput.addEventListener('blur', function () {
        markTouched('email');
        validateEmail(this);
    });

    function validateEmail(input) {
        const value = input.value.trim();
        const errorSpan = document.getElementById('emailError');
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (value.length === 0) {
            return fail(input, errorSpan, 'email', 'Email is required');
        }
        if (!emailRegex.test(value)) {
            return fail(input, errorSpan, 'email', 'Please enter a valid email address');
        }
        return pass(input, errorSpan, 'email');
    }

    // Address validation
    const addressInput = document.getElementById('address');
    addressInput.addEventListener('input', function () {
        validateAddress(this);
        checkFormValidity();
    });
    addressInput.addEventListener('blur', function () {
        markTouched('address');
        validateAddress(this);
    });

    function validateAddress(input) {
        const value = input.value.trim();
        const errorSpan = document.getElementById('addressError');

        if (value.length === 0) {
            return fail(input, errorSpan, 'address', 'Address is required');
        }
        if (value.length < 20) {
            return fail(input, errorSpan, 'address', 'Please provide complete address (min 20 characters)');
        }
        return pass(input, errorSpan, 'address');
    }

    // City validation
    const cityInput = document.getElementById('city');
    cityInput.addEventListener('input', function () {
        validateCity(this);
        checkFormValidity();
    });
    cityInput.addEventListener('blur', function () {
        markTouched('city');
        validateCity(this);
    });

    function validateCity(input) {
        const value = input.value.trim();
        const errorSpan = document.getElementById('cityError');

        if (value.length === 0) {
            return fail(input, errorSpan, 'city', 'City is required');
        }
        return pass(input, errorSpan, 'city');
    }

    // PIN code validation
    const pincodeInput = document.getElementById('pincode');
    pincodeInput.addEventListener('input', function () {
        this.value = this.value.replace(/[^0-9]/g, '');
        validatePincode(this);
        checkFormValidity();
    });
    pincodeInput.addEventListener('blur', function () {
        markTouched('pincode');
        validatePincode(this);
    });

    function validatePincode(input) {
        const value = input.value;
        const errorSpan = document.getElementById('pincodeError');

        if (value.length === 0) {
            return fail(input, errorSpan, 'pincode', 'PIN code is required');
        }
        if (value.length !== 6) {
            return fail(input, errorSpan, 'pincode', 'PIN code must be 6 digits');
        }
        return pass(input, errorSpan, 'pincode');
    }

    // Plan selection
    const planSelect = document.getElementById('plan');
    planSelect.addEventListener('change', function () {
        markTouched('plan');
        validatePlan(this);
        updateOrderSummary();
        checkFormValidity();
    });
    planSelect.addEventListener('blur', function () {
        markTouched('plan');
        validatePlan(this);
    });

    function validatePlan(select) {
        const errorSpan = document.getElementById('planError');

        if (select.value === '') {
            return fail(select, errorSpan, 'plan', 'Please select a plan');
        }
        return pass(select, errorSpan, 'plan');
    }

    // Date validation
    const dateInput = startDateInput;
    dateInput.addEventListener('change', function () {
        markTouched('startDate');
        validateDate(this);
        updateOrderSummary();
        checkFormValidity();
    });
    dateInput.addEventListener('blur', function () {
        markTouched('startDate');
        validateDate(this);
    });

    function validateDate(input) {
        const errorSpan = document.getElementById('dateError');

        if (!input.value) {
            return fail(input, errorSpan, 'startDate', 'Please select start date');
        }

        const selectedDate = parseDateInputValue(input.value);
        if (!selectedDate) {
            return fail(input, errorSpan, 'startDate', 'Please select a valid start date');
        }

        if (selectedDate < minStartDate) {
            return fail(
                input,
                errorSpan,
                'startDate',
                `Please choose today or a later date (earliest is ${minStartDateLabel})`
            );
        }

        return pass(input, errorSpan, 'startDate');
    }

    // Terms checkbox
    const termsCheckbox = document.getElementById('terms');
    termsCheckbox.addEventListener('change', function () {
        markTouched('terms');
        validateTerms(this);
        checkFormValidity();
    });
    termsCheckbox.addEventListener('blur', function () {
        markTouched('terms');
        validateTerms(this);
    });

    function validateTerms(checkbox) {
        const errorSpan = document.getElementById('termsError');

        if (!checkbox.checked) {
            return fail(checkbox, errorSpan, 'terms', 'You must agree to terms & conditions');
        }
        return pass(checkbox, errorSpan, 'terms');
    }

    // Character counter for special instructions
    const specialInstructions = document.getElementById('specialInstructions');
    const charCount = document.getElementById('charCount');
    if (specialInstructions && charCount) {
        specialInstructions.addEventListener('input', function () {
            const used = this.value.length;
            charCount.textContent = `${used}/300 characters`;
            charCount.style.color = used > 300 ? '#ef4444' : 'var(--color-text-secondary)';
        });
    }

    // ========================================
    // UPDATE ORDER SUMMARY
    // ========================================
    function selectedPlanPrice() {
        const option = planSelect.options[planSelect.selectedIndex];
        return option ? option.getAttribute('data-price') : null;
    }

    function updateOrderSummary() {
        const option = planSelect.options[planSelect.selectedIndex];
        const planText = option ? option.text : '';
        const price = selectedPlanPrice();
        const startDate = dateInput.value ? parseDateInputValue(dateInput.value) : null;

        setText('summaryPlan', planSelect.value ? planText : '-');
        setText('summaryPrice', price ? `₹${price}` : '₹0');
        setText('summaryTotal', price ? `₹${price}` : '₹0');
        setText('summaryDate', startDate
            ? startDate.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' })
            : '-');
    }

    function setText(id, value) {
        const el = document.getElementById(id);
        if (el) {
            el.textContent = value;
        }
    }

    // ========================================
    // HELPER FUNCTIONS
    // ========================================
    function fail(input, errorSpan, fieldName, message) {
        if (shouldShowErrors(fieldName)) {
            showError(input, errorSpan, message);
        } else {
            clearFieldState(input, errorSpan);
        }
        return false;
    }

    function pass(input, errorSpan, fieldName) {
        if (shouldShowErrors(fieldName) || hasValue(input)) {
            showSuccess(input, errorSpan);
        } else {
            clearFieldState(input, errorSpan);
        }
        return true;
    }

    function hasValue(input) {
        if (input.type === 'checkbox') {
            return input.checked;
        }
        return String(input.value || '').trim().length > 0;
    }

    function showError(input, errorSpan, message) {
        input.classList.add('error');
        input.classList.remove('success');
        input.setAttribute('aria-invalid', 'true');
        if (errorSpan) {
            errorSpan.textContent = message;
            errorSpan.style.display = 'block';
        }
    }

    function showSuccess(input, errorSpan) {
        input.classList.remove('error');
        input.classList.add('success');
        input.removeAttribute('aria-invalid');
        if (errorSpan) {
            errorSpan.textContent = '';
            errorSpan.style.display = 'none';
        }
    }

    function clearFieldState(input, errorSpan) {
        input.classList.remove('error');
        input.classList.remove('success');
        input.removeAttribute('aria-invalid');
        if (errorSpan) {
            errorSpan.textContent = '';
            errorSpan.style.display = 'none';
        }
    }

    // ========================================
    // CHECK OVERALL FORM VALIDITY
    // ========================================
    // Always computes validity. Whether anything is painted red is decided by
    // the touched/submitAttempted gate inside fail()/pass().
    const FIELD_VALIDATORS = [
        { input: nameInput, validate: validateName },
        { input: phoneInput, validate: validatePhone },
        { input: emailInput, validate: validateEmail },
        { input: addressInput, validate: validateAddress },
        { input: cityInput, validate: validateCity },
        { input: pincodeInput, validate: validatePincode },
        { input: whatsappInput, validate: validateWhatsapp },
        { input: planSelect, validate: validatePlan },
        { input: dateInput, validate: validateDate },
        { input: termsCheckbox, validate: validateTerms }
    ];

    function checkFormValidity() {
        let allValid = true;

        FIELD_VALIDATORS.forEach(function (field) {
            if (!field.validate(field.input)) {
                allValid = false;
            }
        });

        return allValid;
    }

    function firstInvalidField() {
        for (let i = 0; i < FIELD_VALIDATORS.length; i++) {
            if (!FIELD_VALIDATORS[i].validate(FIELD_VALIDATORS[i].input)) {
                return FIELD_VALIDATORS[i].input;
            }
        }
        return null;
    }

    // ========================================
    // MESSAGING
    // ========================================
    function notify(message, type) {
        if (typeof window.showNotification === 'function') {
            window.showNotification(message, type);
            return;
        }
        // Last-resort fallback if script.js did not load.
        window.alert(message);
    }

    // ========================================
    // FORM SUBMISSION
    // ========================================
    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        // From here on every field is fair game for error display.
        submitAttempted = true;

        if (!checkFormValidity()) {
            const invalidField = firstInvalidField();
            if (invalidField) {
                invalidField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                invalidField.focus({ preventScroll: true });
            }
            notify('Please complete the highlighted fields before submitting.', 'error');
            return;
        }

        // Show loading state
        const originalBtnText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing Your Subscription...';
        submitBtn.disabled = true;

        function restoreSubmitButton() {
            submitBtn.innerHTML = originalBtnText;
            submitBtn.disabled = false;
        }

        // Collect form data
        const formData = new FormData(form);
        const subscriptionData = {
            fullName: formData.get('fullName'),
            phone: formData.get('phone'),
            email: formData.get('email'),
            whatsapp: formData.get('whatsapp') || '',
            address: formData.get('address'),
            city: formData.get('city'),
            pincode: formData.get('pincode'),
            landmark: formData.get('landmark') || '',
            plan: formData.get('plan'),
            startDate: formData.get('startDate'),
            specialInstructions: formData.get('specialInstructions') || '',
            terms: formData.get('terms') === 'on',
            promoEmails: formData.get('promoEmails') === 'on'
        };

        try {
            const response = await fetch('/api/subscription', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(subscriptionData)
            });

            const result = await response.json();

            if (result && result.success) {
                renderSuccess(result.data || {});

                // Hide form, show success message
                form.style.display = 'none';
                const successMessage = document.getElementById('successMessage');
                if (successMessage) {
                    successMessage.style.display = 'flex';
                }

                window.scrollTo({ top: 0, behavior: 'smooth' });

                // Track conversion (if using analytics)
                if (typeof gtag !== 'undefined') {
                    gtag('event', 'subscription_complete', {
                        event_category: 'subscription',
                        event_label: subscriptionData.plan,
                        value: selectedPlanPrice()
                    });
                }
            } else {
                // The form is deliberately NOT reset — the visitor's details stay put.
                notify((result && result.message) || 'We could not submit your subscription. Please try again.', 'error');
                restoreSubmitButton();
            }
        } catch (error) {
            console.error('Subscription submission failed:', error);
            notify(
                "We couldn't submit your subscription. Your details are still here — please try again, or call 9879991799.",
                'error'
            );
            restoreSubmitButton();
        }
    });

    // ========================================
    // SUCCESS SCREEN
    // ========================================
    // The static shell is built with innerHTML; every server-supplied value is
    // written with textContent so nothing from the response can become markup.
    function renderSuccess(data) {
        const successContent = document.querySelector('.success-content');
        if (!successContent) {
            return;
        }

        successContent.innerHTML = `
            <div class="success-icon-wrapper">
                <i class="fas fa-check-circle"></i>
            </div>

            <h2>Subscription Confirmed!</h2>

            <p style="font-size: 1.15rem; color: var(--color-text-secondary); margin: 1rem 0 2rem 0;">
                Thank you, <strong data-field="customerName" style="color: var(--primary-600);"></strong>, for choosing Pushpvatika Florist!
            </p>

            <div class="success-details">
                <p>
                    <strong>Order ID:</strong>
                    <span class="order-id" id="orderId" data-field="orderId"></span>
                </p>
                <p>
                    <strong>Selected Plan:</strong>
                    <span data-field="plan"></span>
                </p>
                <p>
                    <strong>Delivery Starts:</strong>
                    <span data-field="startDate"></span>
                </p>
                <p>
                    <strong>Status:</strong>
                    <span style="color: #10b981; font-weight: 600;">Confirmed</span>
                </p>
            </div>

            <div class="success-note">
                <i class="fas fa-phone-volume"></i>
                <strong>Next Steps:</strong> Our team will contact you within 2 hours to confirm your delivery schedule and address details.
            </div>

            <div class="success-buttons">
                <button type="button" class="btn btn-primary" data-action="new-subscription">
                    <i class="fas fa-plus"></i> New Subscription
                </button>
                <button type="button" class="btn btn-secondary" data-action="go-home">
                    <i class="fas fa-home"></i> Back to Home
                </button>
            </div>

            <p style="margin-top: 2rem; font-size: 0.9rem; color: var(--color-text-secondary);">
                <i class="fas fa-shield-halved" style="color: #10b981;"></i>
                Your subscription details have been securely saved
            </p>
        `;

        fillField(successContent, 'customerName', data.customerName || 'there');
        fillField(successContent, 'orderId', data.orderId || '-');
        fillField(successContent, 'plan', data.plan ? `${data.plan} Plan` : '-');
        fillField(successContent, 'startDate', data.startDate || '-');

        const newSubscriptionBtn = successContent.querySelector('[data-action="new-subscription"]');
        if (newSubscriptionBtn) {
            newSubscriptionBtn.addEventListener('click', function () {
                window.location.reload();
            });
        }

        const homeBtn = successContent.querySelector('[data-action="go-home"]');
        if (homeBtn) {
            homeBtn.addEventListener('click', function () {
                window.location.href = '/';
            });
        }
    }

    function fillField(root, field, value) {
        const el = root.querySelector(`[data-field="${field}"]`);
        if (el) {
            el.textContent = String(value);
        }
    }

    // ========================================
    // INITIAL SETUP
    // ========================================
    // The submit button stays enabled at all times. A disabled button that
    // never explains itself is worse than a button that tells you what is
    // missing when you press it.
    submitBtn.disabled = false;
    submitBtn.removeAttribute('disabled');
    submitBtn.style.opacity = '';
    submitBtn.style.cursor = '';

    updateOrderSummary();
});
