(() => {
    'use strict';

    const escapeHtml = (value) => String(value)
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#039;');

    document.querySelectorAll('[data-clear-placeholder]').forEach((field) => {
        const original = field.getAttribute('placeholder') || '';
        field.dataset.originalPlaceholder = original;
        field.addEventListener('focus', () => field.setAttribute('placeholder', ''));
        field.addEventListener('blur', () => {
            if (field.value.trim() === '') field.setAttribute('placeholder', field.dataset.originalPlaceholder || '');
        });
        field.addEventListener('input', () => {
            field.setAttribute('placeholder', field.value !== '' ? '' : (field.dataset.originalPlaceholder || ''));
        });
    });

    document.querySelectorAll('[data-password-toggle]').forEach((button) => {
        button.addEventListener('click', () => {
            const input = document.getElementById(button.dataset.passwordToggle || '');
            if (!input) return;
            const shouldShow = input.type === 'password';
            input.type = shouldShow ? 'text' : 'password';
            button.setAttribute('aria-label', shouldShow ? 'Ocultar contraseña' : 'Mostrar contraseña');
            button.setAttribute('title', shouldShow ? 'Ocultar contraseña' : 'Mostrar contraseña');
            button.innerHTML = shouldShow ? '<i class="fas fa-eye-slash"></i>' : '<i class="fas fa-eye"></i>';
        });
    });

    document.querySelectorAll('[data-password-strength]').forEach((input) => {
        const form = input.closest('form');
        const bar = form?.querySelector('[data-password-strength-bar]');
        const text = form?.querySelector('[data-password-strength-text]');
        const update = () => {
            const value = input.value;
            let score = 0;
            if (value.length >= 10) score++;
            if (/[a-z]/.test(value)) score++;
            if (/[A-Z]/.test(value)) score++;
            if (/[0-9]/.test(value)) score++;
            if (/[^A-Za-z0-9]/.test(value)) score++;
            if (bar) {
                bar.style.width = `${Math.min(100, score * 20)}%`;
                bar.style.background = score <= 2 ? '#c83d4f' : score <= 4 ? '#d98b12' : '#11875d';
            }
            if (text) text.textContent = score <= 2 ? 'Contraseña débil.' : score <= 4 ? 'Contraseña aceptable.' : 'Contraseña segura.';
        };
        input.addEventListener('input', update);
        update();
    });

    const showFieldError = (field, message) => {
        const name = field.name || field.id;
        const form = field.closest('form');
        if (!form || !name) return;
        const error = form.querySelector(`[data-error-for="${CSS.escape(name)}"]`)
            || form.querySelector(`[data-error-for="${CSS.escape(field.id || '')}"]`);
        field.setAttribute('aria-invalid', message ? 'true' : 'false');
        if (error) error.textContent = message || '';
    };

    document.querySelectorAll('[data-auth-form]').forEach((form) => {
        const controls = [...form.querySelectorAll('input, select, textarea')].filter((field) => field.type !== 'hidden');
        controls.forEach((field) => {
            field.addEventListener('invalid', (event) => {
                event.preventDefault();
                showFieldError(field, field.validationMessage || 'Revisa este campo.');
            });
            field.addEventListener('input', () => {
                if (field.checkValidity()) showFieldError(field, '');
            });
            field.addEventListener('change', () => {
                if (field.checkValidity()) showFieldError(field, '');
            });
        });

        form.addEventListener('submit', (event) => {
            controls.forEach((field) => showFieldError(field, ''));
            if (!form.checkValidity()) {
                event.preventDefault();
                const firstInvalid = controls.find((field) => !field.checkValidity());
                if (firstInvalid) {
                    showFieldError(firstInvalid, firstInvalid.validationMessage || 'Revisa este campo.');
                    firstInvalid.focus();
                }
                return;
            }

            const submit = form.querySelector('button[type="submit"]');
            if (!submit) return;
            if (submit.disabled) {
                event.preventDefault();
                return;
            }
            const loadingText = submit.dataset.loadingText || 'Procesando…';
            submit.dataset.originalHtml = submit.innerHTML;
            submit.disabled = true;
            submit.setAttribute('aria-busy', 'true');
            submit.innerHTML = `<i class="fas fa-spinner" aria-hidden="true"></i><span>${escapeHtml(loadingText)}</span>`;
        });
    });
})();
