(() => {
    'use strict';

    const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));
    const isVisible = (element) => {
        if (!(element instanceof HTMLElement)) return false;
        const style = getComputedStyle(element);
        return style.display !== 'none' && style.visibility !== 'hidden' && !element.classList.contains('hidden') && element.getClientRects().length > 0;
    };

    const iconFor = (field, labelText = '') => {
        const haystack = `${field.name || ''} ${field.id || ''} ${labelText}`.toLowerCase();
        const rules = [
            [/correo|email/, 'fa-envelope'], [/password|clave|contrase/, 'fa-lock'], [/telefono|phone|whatsapp/, 'fa-phone'],
            [/pais|country|ciudad/, 'fa-earth-americas'], [/nombre|usuario|cliente/, 'fa-user'], [/fecha|periodo|venc|renov/, 'fa-calendar-days'],
            [/plataforma|servicio/, 'fa-tv'], [/dominio|host|url|sitio/, 'fa-globe'], [/buzon|imap|mailbox/, 'fa-inbox'],
            [/asunto|alias|etiqueta/, 'fa-tags'], [/plan|suscrip/, 'fa-layer-group'], [/precio|monto|pago|credito|saldo/, 'fa-coins'],
            [/estado|status|activo/, 'fa-circle-check'], [/rol|permiso/, 'fa-user-shield'], [/descripcion|detalle|mensaje|contenido/, 'fa-align-left'],
            [/archivo|imagen|logo|favicon/, 'fa-file-arrow-up'], [/ip/, 'fa-network-wired'], [/puerto/, 'fa-plug'], [/codigo|id_/, 'fa-key'],
        ];
        return (rules.find(([pattern]) => pattern.test(haystack)) || [null, 'fa-pen-to-square'])[1];
    };

    const defaultPlaceholder = (field, labelText = '') => {
        const text = labelText.trim().replace(/\s+Opcional$/i, '');
        const key = `${field.name || ''} ${field.id || ''} ${text}`.toLowerCase();
        if (/correo|email/.test(key)) return 'correo@dominio.com';
        if (/telefono|phone|whatsapp/.test(key)) return '+51 999 999 999';
        if (/pais/.test(key)) return 'Perú';
        if (/dominio/.test(key)) return 'ejemplo.com';
        if (/host/.test(key)) return 'mail.ejemplo.com';
        if (/plataforma/.test(key)) return 'Netflix, Disney+ o Paramount+';
        if (/descripcion|detalle|mensaje|contenido/.test(key)) return 'Explica brevemente la información de este registro';
        if (/nombre/.test(key)) return 'Escribe un nombre descriptivo';
        return text ? `Ingresa ${text.toLowerCase()}` : '';
    };

    const findLabel = (field) => {
        if (field.id) {
            const direct = document.querySelector(`label[for="${CSS.escape(field.id)}"]`);
            if (direct) return direct;
        }
        return field.closest('label') || field.parentElement?.querySelector(':scope > label') || field.closest('div')?.querySelector(':scope > label');
    };

    const ensureErrorNode = (field) => {
        if (!field.name && !field.id) return null;
        const key = field.name || field.id;
        const form = field.closest('form');
        if (!form) return null;
        let node = form.querySelector(`[data-error-for="${CSS.escape(key)}"]`);
        if (node) return node;
        node = document.createElement('span');
        node.className = 'af-field-error';
        node.dataset.errorFor = key;
        node.setAttribute('role', 'alert');
        const anchor = field.closest('.select2-container') || field;
        const parent = anchor.parentElement;
        if (parent) parent.appendChild(node);
        return node;
    };

    const enhanceField = (field) => {
        if (!(field instanceof HTMLElement) || field.dataset.afEnhanced === '1') return;
        if (field.matches('[type="hidden"], [type="submit"], [type="button"], [type="reset"], [type="checkbox"], [type="radio"]')) return;
        field.dataset.afEnhanced = '1';
        const label = findLabel(field);
        const labelText = label?.textContent?.trim() || '';
        if (label && !label.querySelector('i, svg, .af-label-icon')) {
            const icon = document.createElement('i');
            icon.className = `fas ${iconFor(field, labelText)} af-label-icon`;
            icon.setAttribute('aria-hidden', 'true');
            label.prepend(icon);
        }
        if (label && !field.required && !label.querySelector('.af-optional') && field.getAttribute('type') !== 'file') {
            const optional = document.createElement('span');
            optional.className = 'af-optional';
            optional.textContent = 'Opcional';
            label.append(optional);
        }
        if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && !field.placeholder) {
            const placeholder = defaultPlaceholder(field, labelText);
            if (placeholder) field.placeholder = placeholder;
        }
        if (field instanceof HTMLInputElement && field.type === 'password') {
            const parent = field.parentElement;
            if (parent && !parent.querySelector('[data-af-password-toggle], [data-password-toggle], button[onclick*="togglePassword"]')) {
                parent.classList.add('af-password-wrap');
                const toggle = document.createElement('button');
                toggle.type = 'button';
                toggle.className = 'af-password-toggle';
                toggle.dataset.afPasswordToggle = '1';
                toggle.setAttribute('aria-label', 'Mostrar contraseña');
                toggle.setAttribute('title', 'Mostrar contraseña');
                toggle.innerHTML = '<i class="fas fa-eye" aria-hidden="true"></i>';
                toggle.addEventListener('click', () => {
                    const show = field.type === 'password';
                    field.type = show ? 'text' : 'password';
                    toggle.setAttribute('aria-label', show ? 'Ocultar contraseña' : 'Mostrar contraseña');
                    toggle.setAttribute('title', show ? 'Ocultar contraseña' : 'Mostrar contraseña');
                    toggle.innerHTML = show ? '<i class="fas fa-eye-slash" aria-hidden="true"></i>' : '<i class="fas fa-eye" aria-hidden="true"></i>';
                });
                parent.appendChild(toggle);
            }
        }
        if (field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) {
            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 || ''));
            });
        }
        const errorNode = ensureErrorNode(field);
        field.addEventListener('invalid', (event) => {
            event.preventDefault();
            field.setAttribute('aria-invalid', 'true');
            if (errorNode) errorNode.textContent = field.validationMessage || 'Revisa este campo.';
        });
        ['input', 'change'].forEach((eventName) => field.addEventListener(eventName, () => {
            if (typeof field.checkValidity === 'function' && field.checkValidity()) {
                field.setAttribute('aria-invalid', 'false');
                if (errorNode) errorNode.textContent = '';
            }
        }));
    };

    const enhanceForm = (form) => {
        if (!(form instanceof HTMLFormElement) || form.dataset.afModern === '1') return;
        form.dataset.afModern = '1';
        form.classList.add('af-modern-form');
        qsa('input, select, textarea', form).forEach(enhanceField);
        form.addEventListener('submit', (event) => {
            queueMicrotask(() => {
                if (event.defaultPrevented || form.dataset.noDoubleSubmit === 'true') return;
                const submit = form.querySelector('button[type="submit"], input[type="submit"]');
                if (!(submit instanceof HTMLElement) || submit.dataset.afBusy === '1') return;
                submit.dataset.afBusy = '1';
                submit.classList.add('af-submit-busy');
                if (submit instanceof HTMLButtonElement) {
                    submit.dataset.originalHtml = submit.innerHTML;
                    const loadingText = submit.dataset.loadingText || (submit.textContent?.toLowerCase().includes('guardar') ? 'Guardando…' : 'Procesando…');
                    submit.innerHTML = `<i class="fas fa-spinner" aria-hidden="true"></i><span>${loadingText}</span>`;
                    submit.disabled = true;
                } else if (submit instanceof HTMLInputElement) {
                    submit.dataset.originalValue = submit.value;
                    submit.value = 'Procesando…';
                    submit.disabled = true;
                }
                window.setTimeout(() => {
                    if (!document.contains(submit)) return;
                    submit.classList.remove('af-submit-busy');
                    submit.dataset.afBusy = '0';
                    if (submit instanceof HTMLButtonElement) {
                        if (submit.dataset.originalHtml) submit.innerHTML = submit.dataset.originalHtml;
                        submit.disabled = false;
                    } else if (submit instanceof HTMLInputElement) {
                        if (submit.dataset.originalValue) submit.value = submit.dataset.originalValue;
                        submit.disabled = false;
                    }
                }, 20000);
            });
        });
    };

    const enhanceModal = (root) => {
        if (!(root instanceof HTMLElement) || root.dataset.afModalEnhanced === '1') return;
        root.dataset.afModalEnhanced = '1';
        root.classList.add('af-modern-modal');
        root.setAttribute('aria-modal', 'true');
        if (!root.getAttribute('role')) root.setAttribute('role', 'dialog');
        const panel = root.firstElementChild instanceof HTMLElement ? root.firstElementChild : null;
        if (panel) {
            panel.classList.add('af-modern-modal-panel');
            const title = panel.querySelector('h1, h2, h3');
            if (title && title.parentElement && !title.parentElement.querySelector('.af-modal-category')) {
                const category = document.createElement('span');
                category.className = 'af-modal-category';
                const moduleTitle = document.querySelector('.premium-page-title')?.textContent?.trim() || 'Administración';
                category.textContent = `${moduleTitle} · Formulario`;
                title.parentElement.insertBefore(category, title);
            }
            const children = Array.from(panel.children).filter((child) => child instanceof HTMLElement);
            if (children.length >= 2) {
                children[0].classList.add('af-modal-sticky-header');
                children[children.length - 1].classList.add('af-modal-sticky-footer');
                if (children.length === 3) children[1].classList.add('af-modal-scroll-body');
                else {
                    const form = panel.querySelector('form');
                    if (form) form.classList.add('af-modal-scroll-body');
                }
            }
        }
    };

    const actionClass = (element) => {
        const text = `${element.title || ''} ${element.getAttribute('aria-label') || ''} ${element.textContent || ''} ${element.className || ''}`.toLowerCase();
        const icon = element.querySelector('i')?.className?.toLowerCase() || '';
        const haystack = `${text} ${icon}`;
        if (/whatsapp|fa-whatsapp|notific/.test(haystack)) return 'af-action-whatsapp';
        if (/eliminar|delete|trash|fa-trash/.test(haystack)) return 'af-action-delete';
        if (/renovar|calendar-plus|rotate|sync/.test(haystack)) return 'af-action-renew';
        if (/regenerar|refresh|arrows-rotate/.test(haystack)) return 'af-action-regenerate';
        if (/copiar|copy|fa-copy/.test(haystack)) return 'af-action-copy';
        if (/editar|edit|pencil|pen-to-square/.test(haystack)) return 'af-action-edit';
        if (/ver|detalle|eye|historial|chart/.test(haystack)) return 'af-action-view';
        if (/descargar|export|download|file-csv/.test(haystack)) return 'af-action-download';
        return 'af-action-neutral';
    };

    const enhanceActions = (root = document) => {
        qsa('td button, td a, .af-actions button, .af-actions a, [data-action]', root).forEach((element) => {
            if (!(element instanceof HTMLElement) || element.dataset.afActionEnhanced === '1') return;
            const hasIcon = !!element.querySelector('i, svg');
            const copy = element.cloneNode(true);
            copy.querySelectorAll('i, svg, .sr-only, .visually-hidden').forEach((node) => node.remove());
            const visibleText = (copy.textContent || '').trim();
            const compact = hasIcon && visibleText === '';
            if (!compact && !element.classList.contains('af-btn-icon')) return;
            element.dataset.afActionEnhanced = '1';
            element.classList.add('af-colored-action', actionClass(element));
        });
    };

    const enhanceTable = (table) => {
        if (!(table instanceof HTMLTableElement) || table.dataset.afTableEnhanced === '1') return;
        table.dataset.afTableEnhanced = '1';
        table.classList.add('af-modern-table');
        const parent = table.parentElement;
        if (parent && !parent.matches('.dataTables_wrapper, .table-responsive, .overflow-x-auto, .af-table-scroll') && !parent.closest('.dataTables_wrapper')) {
            const wrapper = document.createElement('div');
            wrapper.className = 'af-table-scroll';
            parent.insertBefore(wrapper, table);
            wrapper.appendChild(table);
        }
    };

    const normalizeLengthSelect = (select) => {
        if (!(select instanceof HTMLSelectElement) || select.dataset.afLengthEnhanced === '1') return;
        select.dataset.afLengthEnhanced = '1';
        const current = Number(select.value || 100);
        const options = [[100, '100'], [200, '200'], [400, '400'], [-1, 'Todos']];
        const allowed = options.map(([value]) => value);
        const desired = allowed.includes(current) ? current : 100;
        select.innerHTML = '';
        options.forEach(([value, label]) => {
            const option = document.createElement('option');
            option.value = String(value);
            option.textContent = label;
            if (desired === value) option.selected = true;
            select.appendChild(option);
        });
        if (current !== desired) {
            window.setTimeout(() => select.dispatchEvent(new Event('change', { bubbles: true })), 0);
        }
    };

    const enhanceAll = (root = document) => {
        document.body.classList.add('af-forms-ready');
        qsa('.admin-main form', root).forEach(enhanceForm);
        qsa('.admin-main table', root).forEach(enhanceTable);
        qsa('[id$="Modal"], [id$="modal"], .modal[role="dialog"]', root).forEach(enhanceModal);
        qsa('.dataTables_length select', root).forEach(normalizeLengthSelect);
        enhanceActions(root);
    };

    let lastModalTrigger = null;

    const topOpenModal = () => qsa('[id$="Modal"], [id$="modal"], [role="dialog"].af-modern-modal').filter(isVisible).at(-1) || null;

    document.addEventListener('click', (event) => {
        const trigger = event.target instanceof Element ? event.target.closest('button, a, [role="button"]') : null;
        if (!trigger) return;
        window.setTimeout(() => {
            const modal = topOpenModal();
            if (!modal) return;
            lastModalTrigger = trigger;
            if (!trigger.id) trigger.id = `af-modal-trigger-${Math.random().toString(36).slice(2, 10)}`;
            modal.dataset.returnFocus = trigger.id;
            const first = modal.querySelector('input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), a[href]');
            if (first instanceof HTMLElement) first.focus({ preventScroll: true });
        }, 0);
    }, true);

    window.addEventListener('keydown', (event) => {
        if (event.key !== 'Tab') return;
        const modal = topOpenModal();
        if (!modal) return;
        const focusable = qsa('a[href], button:not([disabled]), input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])', modal)
            .filter(isVisible);
        if (!focusable.length) return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        if (event.shiftKey && document.activeElement === first) {
            event.preventDefault();
            last.focus();
        } else if (!event.shiftKey && document.activeElement === last) {
            event.preventDefault();
            first.focus();
        }
    }, true);

    const closeModalOnEscape = (event) => {
        if (event.key !== 'Escape') return;
        const openModals = qsa('[id$="Modal"], [id$="modal"], [role="dialog"].af-modern-modal').filter(isVisible);
        const modal = openModals.at(-1);
        if (!modal) return;
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
        window.__afenixEscapeClosing = true;
        modal.dispatchEvent(new CustomEvent('afenixx:escape-close', { bubbles: true }));
        modal.classList.remove('is-open', 'open', 'show', 'active');
        modal.classList.add('hidden');
        modal.setAttribute('aria-hidden', 'true');
        if (modal.style.display && modal.style.display !== 'none') modal.style.display = 'none';
        document.body.classList.remove('overflow-hidden', 'modal-open');
        document.documentElement.classList.remove('overflow-hidden');
        const triggerId = modal.dataset.returnFocus;
        const trigger = triggerId ? document.getElementById(triggerId) : lastModalTrigger;
        if (trigger instanceof HTMLElement) trigger.focus({ preventScroll: true });
        window.setTimeout(() => { window.__afenixEscapeClosing = false; }, 0);
    };

    window.addEventListener('keydown', closeModalOnEscape, true);

    document.addEventListener('DOMContentLoaded', () => {
        enhanceAll();
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => mutation.addedNodes.forEach((node) => {
                if (node instanceof HTMLElement) enhanceAll(node);
            }));
        });
        observer.observe(document.body, { childList: true, subtree: true });

        if (window.jQuery) {
            window.jQuery(document).on('init.dt draw.dt', () => {
                qsa('.dataTables_length select').forEach(normalizeLengthSelect);
                enhanceActions();
            });
        }
    });
})();
