/* Ave Fénix · Superadmin unificado 3.0
   No mueve botones, filtros, tablas ni modales. */
(() => {
    'use strict';

    if (document.body?.dataset.role !== 'Superadmin') return;

    const visible = (element) => {
        if (!(element instanceof HTMLElement)) return false;
        const style = window.getComputedStyle(element);
        return style.display !== 'none' && style.visibility !== 'hidden' && !element.classList.contains('hidden') && element.getClientRects().length > 0;
    };

    const topModal = () => {
        const modals = [...document.querySelectorAll('.sa-modal-overlay, .sa-native-modal, [data-sa-modal], [id$="Modal"], [id$="modal"]')].filter(visible);
        return modals.at(-1) || null;
    };

    const closeModal = (modal) => {
        if (!(modal instanceof HTMLElement)) return;
        const closeControl = modal.querySelector('[data-sa-close], .close-modal-btn, [id*="closeModal" i], [id*="cancelModal" i]');
        if (closeControl instanceof HTMLElement) {
            closeControl.click();
        } else {
            modal.classList.add('hidden');
            modal.classList.remove('is-open', 'open', 'show', 'active');
            modal.setAttribute('aria-hidden', 'true');
        }
        document.body.classList.remove('overflow-hidden', 'modal-open', 'af-modal-open');
        document.documentElement.classList.remove('overflow-hidden');
    };

    window.addEventListener('keydown', (event) => {
        if (event.key !== 'Escape') return;
        if (window.Swal && typeof window.Swal.isVisible === 'function' && window.Swal.isVisible()) {
            event.preventDefault();
            event.stopImmediatePropagation();
            window.Swal.close();
            return;
        }
        const modal = topModal();
        if (!modal) return;
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
        closeModal(modal);
    }, true);

    document.addEventListener('click', (event) => {
        const opener = event.target.closest('[data-sa-open]');
        if (opener) {
            const selector = opener.getAttribute('data-sa-open');
            const modal = selector ? document.querySelector(selector) : null;
            if (modal instanceof HTMLElement) {
                modal.classList.remove('hidden');
                modal.classList.add('is-open');
                modal.setAttribute('aria-hidden', 'false');
                modal.querySelector('input:not([type="hidden"]),select,textarea,button')?.focus({preventScroll: true});
            }
        }
        const closer = event.target.closest('[data-sa-close]');
        if (closer) closeModal(closer.closest('.sa-modal-overlay,.sa-native-modal,[data-sa-modal],[id$="Modal"],[id$="modal"]'));
    });

    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 (String(field.value || '').trim() === '') field.setAttribute('placeholder', original);
        });
    });

    document.querySelectorAll('[data-auto-submit]').forEach((control) => {
        control.addEventListener('change', () => control.form?.requestSubmit());
    });

    document.querySelectorAll('form[data-prevent-double-submit]').forEach((form) => {
        form.addEventListener('submit', () => {
            const button = form.querySelector('button[type="submit"],input[type="submit"]');
            if (!(button instanceof HTMLElement) || button.dataset.submitting === '1') return;
            button.dataset.submitting = '1';
            button.setAttribute('disabled', 'disabled');
            if (button.tagName === 'BUTTON') {
                button.dataset.originalHtml = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin" aria-hidden="true"></i><span>Procesando…</span>';
            }
            window.setTimeout(() => {
                button.removeAttribute('disabled');
                button.dataset.submitting = '0';
                if (button.dataset.originalHtml) button.innerHTML = button.dataset.originalHtml;
            }, 12000);
        });
    });

    const initializeUnifiedTables = () => {
        document.querySelectorAll('[data-sa-client-table]').forEach((table) => {
            if (!window.jQuery || !window.jQuery.fn?.DataTable) return;
            const defaultOrder = table.dataset.orderColumn ? [[Number(table.dataset.orderColumn), table.dataset.orderDirection || 'asc']] : [];
            const alreadyInitialized = window.jQuery.fn.dataTable.isDataTable(table);
            const api = alreadyInitialized
                ? window.jQuery(table).DataTable()
                : window.jQuery(table).DataTable({
                    language: {url: '//cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json'},
                    dom: 'rt',
                    pageLength: 100,
                    lengthMenu: [[100, 200, 400, -1], [100, 200, 400, 'Todos']],
                    order: defaultOrder,
                    autoWidth: false
                });
            if (![100, 200, 400, -1].includes(api.page.len())) api.page.len(100).draw(false);
            const panel = table.closest('.sa-records-panel');
            const search = panel?.querySelector('[data-sa-table-search]');
            const perPage = panel?.querySelector('[data-sa-table-length]');
            const counter = panel?.querySelector('[data-sa-table-counter]');
            const pagination = panel?.querySelector('[data-sa-table-pagination]');
            const filters = [...(panel?.querySelectorAll('[data-sa-column-filter]') || [])];
        
            const renderMeta = () => {
                const info = api.page.info();
                if (counter) counter.innerHTML = `Mostrando <strong>${info.recordsDisplay ? info.start + 1 : 0}</strong>–<strong>${info.end}</strong> de <strong>${info.recordsDisplay}</strong> registros`;
                if (!pagination) return;
                pagination.innerHTML = '';
                const button = (label, page, active = false, disabled = false) => {
                    const node = document.createElement('button');
                    node.type = 'button';
                    node.className = `sa-page-button${active ? ' is-active' : ''}${disabled ? ' is-disabled' : ''}`;
                    node.textContent = label;
                    node.disabled = disabled;
                    node.addEventListener('click', () => api.page(page).draw('page'));
                    pagination.appendChild(node);
                };
                button('Anterior', Math.max(0, info.page - 1), false, info.page === 0);
                const start = Math.max(0, info.page - 2);
                const end = Math.min(info.pages - 1, info.page + 2);
                if (start > 0) button('1', 0, false, false);
                if (start > 1) pagination.insertAdjacentHTML('beforeend', '<span class="sa-page-ellipsis">…</span>');
                for (let page = start; page <= end; page++) button(String(page + 1), page, page === info.page, false);
                if (end < info.pages - 2) pagination.insertAdjacentHTML('beforeend', '<span class="sa-page-ellipsis">…</span>');
                if (end < info.pages - 1) button(String(info.pages), info.pages - 1, false, false);
                button('Siguiente', Math.min(info.pages - 1, info.page + 1), false, info.page >= info.pages - 1 || info.pages === 0);
            };
            search?.addEventListener('input', () => api.search(search.value).draw());
            perPage?.addEventListener('change', () => api.page.len(perPage.value === 'all' ? -1 : Number(perPage.value)).draw());
            filters.forEach((filter) => filter.addEventListener('change', () => api.column(Number(filter.dataset.saColumnFilter)).search(filter.value).draw()));
            api.on('draw', renderMeta);
            renderMeta();
        });
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => window.setTimeout(initializeUnifiedTables, 0), { once: true });
    } else {
        window.setTimeout(initializeUnifiedTables, 0);
    }
})();
