// Enhanced Contact Form Submission with Validation
document.getElementById('contactForm').addEventListener('submit', async function (e) {
    e.preventDefault();

    // Get form data
    const formData = new FormData(this);
    const data = Object.fromEntries(formData);

    // Client-side validation
    const errors = validateContactForm(data);

    if (Object.keys(errors).length > 0) {
        displayValidationErrors(errors);
        return;
    }

    // Show loading state
    const submitButton = this.querySelector('button[type="submit"]');
    const originalButtonText = submitButton.innerHTML;
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';

    try {
        // Submit to API
        const response = await fetch('/api/contact', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'X-Requested-With': 'XMLHttpRequest',
            },
            body: new URLSearchParams(data)
        });

        const result = await response.json();

        if (result.success) {
            // Success
            showNotification(result.message, 'success');
            this.reset();

            // Optionally redirect to thank you page
            // window.location.href = 'thank-you.html';
        } else {
            // The API always returns a single flat `message` string and never a
            // per-field `errors` object — this branch is kept for parity with
            // the legacy front end, but the flat-message path below is what
            // actually surfaces the error in practice.
            if (result.errors) {
                displayValidationErrors(result.errors);
            } else {
                showNotification(result.message, 'error');
            }
        }
    } catch (error) {
        console.error('Error:', error);
        showNotification('An error occurred. Please try again or call us at 9879991799.', 'error');
    } finally {
        // Reset button state
        submitButton.disabled = false;
        submitButton.innerHTML = originalButtonText;
    }
});

// Accepts 9876543210, 09876543210, 919876543210, +91 98765 43210, +91-98765-43210
function isValidPhone(value) {
    const cleaned = String(value || '').replace(/[\s\-().]/g, '');
    const national = cleaned.replace(/^(\+91|91|0)/, '');
    return /^[6-9][0-9]{9}$/.test(national);
}

// One validator per field, so submit and blur can share the exact same rules
const fieldValidators = {
    name: value => (!value || value.trim().length < 2)
        ? 'Please enter your full name' : null,
    phone: value => !isValidPhone(value)
        ? 'Please enter a valid 10-digit mobile number, e.g. 9876543210' : null,
    email: value => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value || '')
        ? 'Please enter a valid email address' : null,
    service: value => !value
        ? 'Please select a service' : null,
    message: value => (!value || value.trim().length < 10)
        ? 'Please enter a message (minimum 10 characters)' : null,
    terms: value => !value
        ? 'Please agree to be contacted' : null
};

// Client-side form validation
function validateContactForm(data) {
    const errors = {};

    Object.keys(fieldValidators).forEach(fieldName => {
        const error = fieldValidators[fieldName](data[fieldName]);
        if (error) {
            errors[fieldName] = error;
        }
    });

    return errors;
}

// Show a single field's error
function setFieldError(field, message) {
    const formGroup = field.closest('.form-group');
    if (!formGroup) {
        return;
    }

    clearFieldError(field);
    formGroup.classList.add('error');
    field.setAttribute('aria-invalid', 'true');

    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.setAttribute('role', 'alert');
    errorDiv.style.color = '#ef4444';
    errorDiv.style.fontSize = '0.875rem';
    errorDiv.style.marginTop = '0.25rem';
    errorDiv.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;

    field.parentNode.appendChild(errorDiv);
}

// Clear a single field's error
function clearFieldError(field) {
    const formGroup = field.closest('.form-group');
    if (formGroup) {
        formGroup.classList.remove('error');
        formGroup.querySelectorAll('.error-message').forEach(el => el.remove());
    }
    field.removeAttribute('aria-invalid');
}

// Display validation errors
function displayValidationErrors(errors) {
    // Clear previous errors
    document.querySelectorAll('.error-message').forEach(el => el.remove());
    document.querySelectorAll('.form-group.error').forEach(el => el.classList.remove('error'));
    document.querySelectorAll('#contactForm [aria-invalid]').forEach(el => el.removeAttribute('aria-invalid'));

    // Display new errors
    Object.keys(errors).forEach(fieldName => {
        const field = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
        if (field) {
            setFieldError(field, errors[fieldName]);
        }
    });

    // Scroll to first error
    const firstError = document.querySelector('.error-message');
    if (firstError) {
        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    showNotification('Please correct the errors in the form', 'error');
}

// Read a field's value the same way FormData would
function getFieldValue(field) {
    return field.type === 'checkbox' ? (field.checked ? 'on' : '') : field.value;
}

// Real-time validation on blur — actually re-run the field's validator.
// The error is cleared on `input`, as the user types a correction, so a
// still-invalid field keeps its message instead of silently losing it.
document.querySelectorAll('#contactForm input, #contactForm select, #contactForm textarea').forEach(field => {
    const validator = fieldValidators[field.name];
    if (!validator) {
        return;
    }

    field.addEventListener('blur', function () {
        const error = validator(getFieldValue(this));
        if (error) {
            setFieldError(this, error);
        } else {
            clearFieldError(this);
        }
    });

    const clearEvent = (field.type === 'checkbox' || field.tagName === 'SELECT') ? 'change' : 'input';
    field.addEventListener(clearEvent, function () {
        clearFieldError(this);
    });
});
