// Phone validation and formatting function
export function validatePhoneLive(inputEl) {
    // Get current value and remove any non-digit characters
    let val = inputEl.value.replace(/\D/g, '');

    // Format the phone number as 123-456-7890
    let formattedValue = '';
    if (val.length > 0) {
        formattedValue = val.substring(0, 3);
        if (val.length > 3) {
            formattedValue += '-' + val.substring(3, 6);
        }
        if (val.length > 6) {
            formattedValue += '-' + val.substring(6, 10);
        }
    }

    // Update the input value with formatted version
    inputEl.value = formattedValue;

    // Check if the phone number is valid (exactly 10 digits)
    const valid = val.length === 10;

    // Update validation UI - add red border for invalid input
    if (val.length === 0) {
        inputEl.classList.remove('is-invalid', 'is-valid');
    } else if (valid) {
        inputEl.classList.remove('is-invalid');
        inputEl.classList.add('is-valid');
    } else {
        inputEl.classList.remove('is-valid');
        inputEl.classList.add('is-invalid');
    }

    return valid;
}

// Prevent form submission if phone is invalid
function preventInvalidSubmission() {
    const phoneInputs = document.querySelectorAll('#phoneInput');
    phoneInputs.forEach(phoneInput => {
        const form = phoneInput.closest('form');
        if (!form) {
            return;
        }

        form.addEventListener('submit', function (e) {
            if (!validatePhoneLive(phoneInput)) {
                e.preventDefault();
                phoneInput.focus();
                return false;
            }
        });
    });
}

// Initialize the event listener when the page loads
document.addEventListener('DOMContentLoaded', function () {
    const phoneInput = document.getElementById('phoneInput');
    if (!phoneInput) {
        return;
    }

    // Add input event listener for live validation and formatting
    phoneInput.addEventListener('input', function () {
        validatePhoneLive(this);
    });

    // Add blur event listener to finalize formatting
    phoneInput.addEventListener('blur', function () {
        validatePhoneLive(this);
    });

    // Add focus event to select all text when focused
    phoneInput.addEventListener('focus', function () {
        this.select();
    });

    // Prevent form submission for invalid phone numbers
    preventInvalidSubmission();
});
