document.addEventListener('DOMContentLoaded', () => {
    const cleanSpaces = value =>
        String(value ?? '')
            .replace(/\s+/g, ' ')
            .trim();

    const lowerFrench = value =>
        cleanSpaces(value).toLocaleLowerCase('fr-FR');

    /**
     * Met en majuscule la première lettre de chaque composant du prénom.
     * Exemples :
     * jean pierre     -> Jean Pierre
     * jean-pierre     -> Jean-Pierre
     * marie-claire    -> Marie-Claire
     * d'angelo        -> D'Angelo
     * élise           -> Élise
     */
    const formatFirstName = value => {
        const lower = lowerFrench(value);

        return lower.replace(
            /(^|[\s'’-])(\p{L})/gu,
            (_, separator, letter) =>
                separator + letter.toLocaleUpperCase('fr-FR')
        );
    };

    const formatLastName = value =>
        cleanSpaces(value).toLocaleUpperCase('fr-FR');

    const formatEmail = value =>
        cleanSpaces(value).toLocaleLowerCase('fr-FR');

    const normalizePhoneDigits = value => {
        let digits = String(value ?? '').replace(/\D/g, '');

        if (digits.startsWith('0033')) {
            digits = digits.slice(4);
        } else if (digits.startsWith('33')) {
            digits = digits.slice(2);
        } else if (digits.startsWith('0')) {
            digits = digits.slice(1);
        }

        return digits.slice(0, 9);
    };

    const formatPhone = value => {
        const digits = normalizePhoneDigits(value);

        if (!digits) return '';

        const groups = [digits.slice(0, 1)];

        for (let index = 1; index < digits.length; index += 2) {
            groups.push(digits.slice(index, index + 2));
        }

        return '+33 ' + groups.join(' ');
    };

    document.querySelectorAll('[data-uppercase]').forEach(input => {
        const apply = () => {
            input.value = formatLastName(input.value);
        };

        input.addEventListener('blur', apply);
        input.addEventListener('change', apply);
    });

    document.querySelectorAll('[data-firstname]').forEach(input => {
        const apply = () => {
            input.value = formatFirstName(input.value);
        };

        // Correction visible dès que l'utilisateur quitte le champ.
        input.addEventListener('blur', apply);
        input.addEventListener('change', apply);

        // Évite de conserver une valeur incorrecte lors de l'envoi.
        input.form?.addEventListener('submit', apply);
    });

    document.querySelectorAll('input[type="email"], [data-email]').forEach(input => {
        const apply = () => {
            input.value = formatEmail(input.value);
        };

        input.addEventListener('blur', apply);
        input.addEventListener('change', apply);
        input.form?.addEventListener('submit', apply);
    });

    document.querySelectorAll('[data-phone]').forEach(input => {
        const apply = () => {
            input.value = formatPhone(input.value);
        };

        input.addEventListener('blur', apply);
        input.addEventListener('change', apply);
        input.form?.addEventListener('submit', apply);
    });

    document.querySelectorAll('[data-postcode]').forEach(input => {
        input.addEventListener('input', () => {
            input.value = input.value.replace(/\D/g, '').slice(0, 5);
        });
    });
});
