(function () {
    'use strict';

    const config = window.AfenixConsultaConfig || {};
    const itemsPerPage = 6;

    const state = {
        platforms: Array.isArray(config.initialPlatforms)
            ? config.initialPlatforms.slice()
            : [],
        page: 1,
        selectedId: '',
        userId: String(config.userId || ''),
        resumeOpened: false
    };

    const elements = {};

    function byId(id) {
        return document.getElementById(id);
    }

    function asText(value) {
        return String(value == null ? '' : value);
    }

    function normalizePlatform(platform) {
        return {
            id: Number(platform && platform.id) || 0,
            nombre: asText(platform && platform.nombre).trim() || 'Plataforma',
            imagen_url: asText(platform && platform.imagen_url).trim()
        };
    }

    function removeStaleOverlays(force) {
        /*
         * La limpieza normal de SweetAlert no debe retirar la clase
         * results-modal-open mientras #resultsModal siga presente.
         */
        if (force) {
            document.querySelectorAll(
                '#resultsModal'
            ).forEach(function (node) {
                node.remove();
            });
        }

        const activeResultsModal =
            document.getElementById('resultsModal');

        const resultsModalOpen = Boolean(
            activeResultsModal
            && activeResultsModal.isConnected
        );

        const swalVisible = Boolean(
            window.Swal
            && typeof window.Swal.isVisible === 'function'
            && window.Swal.isVisible()
        );

        if (force || !swalVisible) {
            document.querySelectorAll(
                '.swal2-container'
            ).forEach(function (node) {
                node.remove();
            });

            document.documentElement.classList.remove(
                'swal2-shown',
                'swal2-height-auto'
            );

            if (document.body) {
                document.body.classList.remove(
                    'swal2-shown',
                    'swal2-height-auto'
                );
            }
        }

        /*
         * En V17 esta limpieza quitaba results-modal-open unos
         * milisegundos después de crear el modal. El CSS lo ocultaba
         * inmediatamente, aunque la API ya hubiera recuperado el correo.
         */
        if (force || !resultsModalOpen) {
            document.documentElement.style.removeProperty(
                'overflow'
            );
            document.documentElement.style.removeProperty(
                'pointer-events'
            );
            document.documentElement.removeAttribute(
                'inert'
            );

            if (document.body) {
                document.body.classList.remove(
                    'results-modal-open',
                    'modal-open',
                    'overflow-hidden'
                );
                document.body.style.removeProperty(
                    'overflow'
                );
                document.body.style.removeProperty(
                    'padding-right'
                );
                document.body.style.removeProperty(
                    'pointer-events'
                );
                document.body.removeAttribute(
                    'inert'
                );
            }

            document.querySelectorAll(
                '.public-topbar,'
                + ' .public-query-main,'
                + ' .public-footer'
            ).forEach(function (node) {
                node.removeAttribute('inert');
                node.style.removeProperty(
                    'pointer-events'
                );
            });
        } else if (document.body) {
            document.body.classList.add(
                'results-modal-open'
            );
        }
    }


    function alertMessage(options) {
        const settings = Object.assign({
            title: 'Atención',
            text: '',
            icon: 'info'
        }, options || {});

        if (window.Swal && typeof window.Swal.fire === 'function') {
            return window.Swal.fire(settings).finally(function () {
                window.setTimeout(function () {
                    removeStaleOverlays(false);
                }, 25);
            });
        }

        window.alert(
            (settings.title ? settings.title + '\n\n' : '')
            + (settings.text || '')
        );

        return Promise.resolve({ isConfirmed: true });
    }

    function openLoading(title, text) {
        if (window.Swal && typeof window.Swal.fire === 'function') {
            window.Swal.fire({
                title: title,
                text: text || '',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: function () {
                    if (window.Swal && typeof window.Swal.showLoading === 'function') {
                        window.Swal.showLoading();
                    }
                }
            });
        }
    }

    function closeLoading() {
        if (window.Swal && typeof window.Swal.close === 'function') {
            window.Swal.close();
        }

        window.setTimeout(function () {
            removeStaleOverlays(false);
        }, 25);
    }

    async function fetchJson(url, options) {
        const response = await fetch(url, Object.assign({
            credentials: 'same-origin',
            cache: 'no-store',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        }, options || {}));

        const text = await response.text();
        let payload = {};

        try {
            payload = text ? JSON.parse(text) : {};
        } catch (error) {
            throw new Error(
                'El servidor devolvió una respuesta inválida.'
            );
        }

        if (!response.ok) {
            const failure = new Error(
                payload.message
                || 'No se pudo completar la operación.'
            );
            failure.payload = payload;
            throw failure;
        }

        return payload;
    }

    function totalPages() {
        return Math.max(
            1,
            Math.ceil(state.platforms.length / itemsPerPage)
        );
    }

    function setSelectedPlatform(id) {
        const normalized = String(Number(id) || '');

        state.selectedId = normalized;

        if (elements.selectedPlatform) {
            elements.selectedPlatform.value = normalized;
        }

        document.querySelectorAll('.platform-box').forEach(function (box) {
            const selected = String(box.dataset.id || '') === normalized;
            box.classList.toggle('selected-platform', selected);
            box.setAttribute('aria-pressed', selected ? 'true' : 'false');
        });
    }

    function createPlatformCard(platform) {
        const card = document.createElement('button');
        card.type = 'button';
        card.className = 'platform-box';
        card.dataset.id = String(platform.id);
        card.setAttribute('aria-label', 'Seleccionar ' + platform.nombre);
        card.setAttribute('aria-pressed', 'false');

        const logo = document.createElement('span');
        logo.className = 'logo-circle';

        if (platform.imagen_url) {
            const image = document.createElement('img');
            image.src = platform.imagen_url;
            image.alt = platform.nombre;
            image.loading = 'lazy';
            image.addEventListener('error', function () {
                image.remove();

                const fallback = document.createElement('i');
                fallback.className = 'fas fa-tv';
                fallback.setAttribute('aria-hidden', 'true');
                logo.appendChild(fallback);
            }, { once: true });

            logo.appendChild(image);
        } else {
            const fallback = document.createElement('i');
            fallback.className = 'fas fa-tv';
            fallback.setAttribute('aria-hidden', 'true');
            logo.appendChild(fallback);
        }

        const name = document.createElement('span');
        name.className = 'platform-name';
        name.title = platform.nombre;
        name.textContent = platform.nombre;

        card.append(logo, name);

        card.addEventListener('click', function () {
            setSelectedPlatform(platform.id);
        });

        return card;
    }

    function renderPlatforms() {
        if (!elements.platforms || !elements.pagination) {
            return;
        }

        const pages = totalPages();

        state.page = Math.min(
            pages,
            Math.max(1, Number(state.page) || 1)
        );

        const start = (state.page - 1) * itemsPerPage;
        const pagePlatforms = state.platforms.slice(
            start,
            start + itemsPerPage
        );

        elements.platforms.replaceChildren();

        if (!pagePlatforms.length) {
            const empty = document.createElement('div');
            empty.className = 'platform-empty';
            empty.innerHTML = '<span><i class="fas fa-layer-group"></i>No hay plataformas disponibles.</span>';
            elements.platforms.appendChild(empty);
        } else {
            pagePlatforms.forEach(function (platform) {
                elements.platforms.appendChild(
                    createPlatformCard(platform)
                );
            });
        }

        const navigation = document.createElement('div');
        navigation.className = 'af-consulta-pagination';
        navigation.setAttribute(
            'aria-label',
            'Navegación de plataformas'
        );

        const previous = document.createElement('button');
        previous.type = 'button';
        previous.className = 'af-consulta-page-arrow';
        previous.setAttribute('aria-label', 'Plataformas anteriores');
        previous.title = 'Plataformas anteriores';
        previous.disabled = state.page <= 1;
        previous.innerHTML = '<i class="fas fa-chevron-left"></i>';
        previous.addEventListener('click', function () {
            if (previous.disabled) {
                return;
            }

            state.page -= 1;
            renderPlatforms();
        });

        const indicator = document.createElement('span');
        indicator.className = 'af-consulta-page-indicator';
        indicator.textContent =
            'Página ' + state.page
            + ' de ' + pages
            + ' · ' + state.platforms.length
            + ' plataforma' + (state.platforms.length === 1 ? '' : 's');

        const next = document.createElement('button');
        next.type = 'button';
        next.className = 'af-consulta-page-arrow';
        next.setAttribute('aria-label', 'Más plataformas');
        next.title = 'Más plataformas';
        next.disabled = state.page >= pages;
        next.innerHTML = '<i class="fas fa-chevron-right"></i>';
        next.addEventListener('click', function () {
            if (next.disabled) {
                return;
            }

            state.page += 1;
            renderPlatforms();
        });

        navigation.append(previous, indicator, next);
        elements.pagination.replaceChildren(navigation);

        if (state.selectedId) {
            setSelectedPlatform(state.selectedId);
        }
    }

    async function loadPlatforms() {
        state.platforms = state.platforms
            .map(normalizePlatform)
            .filter(function (platform) {
                return platform.id > 0;
            });

        renderPlatforms();

        try {
            const payload = await fetchJson(
                'api.php?action=getPlataformas&v=' + Date.now()
            );

            const records = Array.isArray(payload.plataformas)
                ? payload.plataformas
                : (
                    payload.data
                    && Array.isArray(payload.data.plataformas)
                        ? payload.data.plataformas
                        : []
                );

            const normalized = records
                .map(normalizePlatform)
                .filter(function (platform) {
                    return platform.id > 0;
                });

            if (normalized.length) {
                state.platforms = normalized;
                renderPlatforms();
            }
        } catch (error) {
            if (!state.platforms.length) {
                elements.platforms.innerHTML =
                    '<div class="platform-empty"><span><i class="fas fa-triangle-exclamation"></i>'
                    + 'No se pudo cargar el catálogo de plataformas.'
                    + '</span></div>';
                elements.pagination.replaceChildren();
            }
        }
    }

    function setResultsVisible(visible) {
        if (!elements.instructions || !elements.resultsContainer) {
            return;
        }

        elements.instructions.hidden = Boolean(visible);
        elements.resultsContainer.classList.toggle(
            'hidden',
            !visible
        );
    }

    function makeResultButton(result) {
        const button = document.createElement('button');
        const isPublic = Boolean(Number(result.es_publico));

        button.type = 'button';
        button.className =
            'view-content-btn '
            + (isPublic ? 'is-public' : 'is-private');
        button.dataset.asuntoId = String(
            Number(result.asunto_id) || 0
        );
        button.dataset.esPublico = isPublic ? '1' : '0';
        button.innerHTML = isPublic
            ? '<i class="fas fa-eye"></i> Ver público'
            : '<i class="fas fa-lock"></i> Ver privado';

        return button;
    }

    function renderResults(results) {
        elements.resultsList.replaceChildren();

        const list = document.createElement('ul');
        list.className = 'af-consulta-results';

        results.forEach(function (result) {
            const item = document.createElement('li');
            item.className = 'af-consulta-result';

            const content = document.createElement('div');
            content.className = 'af-consulta-result-copy';

            const title = document.createElement('strong');
            title.textContent = asText(
                result.asunto_nombre || 'Mensaje encontrado'
            );

            const match = document.createElement('span');
            match.className =
                'af-consulta-match '
                + (
                    result.match_tipo === 'alias'
                        ? 'is-alias'
                        : 'is-subject'
                );

            const matchType =
                result.match_tipo === 'alias'
                    ? 'Alias'
                    : 'Asunto';

            match.textContent =
                'Coincidió por ' + matchType + ': '
                + asText(result.match_texto || result.asunto_nombre);

            const date = document.createElement('small');
            date.textContent =
                'Recibido: ' + asText(result.fecha || '—');

            content.append(title, match, date);

            if (result.asunto_real) {
                const receivedSubject = document.createElement('small');
                receivedSubject.textContent =
                    'Asunto recibido: ' + asText(result.asunto_real);
                content.appendChild(receivedSubject);
            }

            const actions = document.createElement('div');
            actions.className = 'af-consulta-result-actions';
            actions.appendChild(makeResultButton(result));

            item.append(content, actions);
            list.appendChild(item);
        });

        elements.resultsList.appendChild(list);
        setResultsVisible(true);
    }

    function pendingState(subjectId) {
        return {
            plataforma: state.selectedId,
            correo: asText(elements.email.value).trim(),
            asunto: String(Number(subjectId) || '')
        };
    }

    function savePending(subjectId) {
        try {
            sessionStorage.setItem(
                'afenix_consulta_pendiente',
                JSON.stringify(pendingState(subjectId))
            );
        } catch (error) {
            // La consulta puede continuar aunque el navegador bloquee sessionStorage.
        }
    }

    function clearPending() {
        try {
            sessionStorage.removeItem(
                'afenix_consulta_pendiente'
            );
        } catch (error) {
            // No requiere acción.
        }

        fetch('consulta.php?clear_pending=1', {
            credentials: 'same-origin',
            cache: 'no-store',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        }).catch(function () {});
    }

    function closeResultsModal() {
        const modal = byId('resultsModal');

        if (modal) {
            modal.setAttribute('aria-hidden', 'true');
            modal.remove();
        }

        document.body.classList.remove(
            'results-modal-open'
        );
        document.body.style.removeProperty('overflow');
        document.documentElement.style.removeProperty('overflow');

        const trigger = state.lastModalTrigger;
        state.lastModalTrigger = null;

        if (
            trigger
            && typeof trigger.focus === 'function'
        ) {
            trigger.focus();
        }
    }

    function openResultsModal(html, trigger) {
        closeResultsModal();
        removeStaleOverlays(false);

        const modal = document.createElement('div');
        modal.id = 'resultsModal';
        modal.className = 'af-consulta-modal';
        modal.setAttribute('role', 'dialog');
        modal.setAttribute('aria-modal', 'true');
        modal.setAttribute(
            'aria-label',
            'Detalle de la consulta'
        );

        const shell = document.createElement('div');
        shell.className = 'af-consulta-modal-shell';
        shell.innerHTML = html;

        modal.appendChild(shell);
        document.body.appendChild(modal);

        state.lastModalTrigger = trigger || document.activeElement;
        document.body.classList.add('results-modal-open');

        modal.hidden = false;
        modal.setAttribute('aria-hidden', 'false');
        modal.style.setProperty(
            'display',
            'flex',
            'important'
        );
        modal.style.setProperty(
            'visibility',
            'visible',
            'important'
        );
        modal.style.setProperty(
            'pointer-events',
            'auto',
            'important'
        );

        modal.addEventListener('click', function (event) {
            const closeControl = event.target.closest(
                '#closeModalButton, #closeModalButtonFooter, [data-consulta-close]'
            );

            if (event.target === modal || closeControl) {
                event.preventDefault();
                closeResultsModal();
            }
        });

        const closeButton = modal.querySelector(
            '#closeModalButton, #closeModalButtonFooter'
        );

        if (closeButton) {
            window.setTimeout(function () {
                closeButton.focus();
            }, 0);
        }
    }

    async function openResult(button) {
        const subjectId = Number(button.dataset.asuntoId || 0);
        const isPublic =
            String(button.dataset.esPublico || '') === '1';

        if (!isPublic && !state.userId) {
            savePending(subjectId);

            const params = new URLSearchParams({
                plataforma: state.selectedId,
                correo: asText(elements.email.value).trim(),
                asunto: String(subjectId),
                continuar: '1'
            });

            const result = await alertMessage({
                title: 'Acceso requerido',
                text: 'Necesitas iniciar sesión para ver este mensaje privado.',
                icon: 'info',
                showCancelButton: true,
                confirmButtonText: 'Iniciar sesión',
                cancelButtonText: 'Cancelar'
            });

            if (result && result.isConfirmed) {
                window.location.href =
                    'login_consulta.php?' + params.toString();
            }

            return;
        }

        openLoading(
            'Cargando contenido…',
            'Espera mientras recuperamos el mensaje.'
        );

        try {
            const body = new URLSearchParams({
                plataforma: state.selectedId,
                asunto: String(subjectId),
                correo: asText(elements.email.value).trim()
            });

            const payload = await fetchJson(
                'api.php?action=realizarConsulta&v=' + Date.now(),
                {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type':
                            'application/x-www-form-urlencoded;charset=UTF-8',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: body.toString()
                }
            );

            closeLoading();

            if (payload.success && payload.html) {
                openResultsModal(payload.html, button);
                return;
            }

            await alertMessage({
                icon: payload.icon || 'error',
                title: payload.title || 'Error',
                text:
                    payload.message
                    || 'No se pudo obtener el contenido.'
            });
        } catch (error) {
            closeLoading();

            await alertMessage({
                icon:
                    error.payload
                    && error.payload.icon
                        ? error.payload.icon
                        : 'error',
                title:
                    error.payload
                    && error.payload.title
                        ? error.payload.title
                        : 'Error',
                text: error.message
            });
        }
    }

    async function submitQuery(event) {
        event.preventDefault();

        const email = asText(elements.email.value).trim();

        if (!state.selectedId) {
            await alertMessage({
                title: 'Atención',
                text: 'Selecciona una plataforma.',
                icon: 'warning'
            });
            return;
        }

        if (!email) {
            await alertMessage({
                title: 'Atención',
                text: 'Ingresa el correo electrónico completo.',
                icon: 'warning'
            });
            return;
        }

        elements.submit.disabled = true;
        openLoading(
            'Consultando…',
            'Buscando mensajes recientes autorizados.'
        );

        try {
            const body = new URLSearchParams({
                plataforma: state.selectedId,
                correo: email
            });

            const payload = await fetchJson(
                'api.php?action=realizarConsultaPublica&v='
                + Date.now(),
                {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type':
                            'application/x-www-form-urlencoded;charset=UTF-8',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: body.toString()
                }
            );

            closeLoading();

            if (
                payload.success
                && Array.isArray(payload.results)
                && payload.results.length
            ) {
                renderResults(payload.results);
                continueResumeIfNeeded();
                return;
            }

            setResultsVisible(false);

            await alertMessage({
                icon: payload.icon || 'warning',
                title: payload.title || 'Atención',
                text:
                    payload.message
                    || 'No se encontraron resultados.'
            });
        } catch (error) {
            closeLoading();
            setResultsVisible(false);

            await alertMessage({
                icon:
                    error.payload
                    && error.payload.icon
                        ? error.payload.icon
                        : 'error',
                title:
                    error.payload
                    && error.payload.title
                        ? error.payload.title
                        : 'Error',
                text:
                    error.message
                    || 'No se pudo comunicar con el servidor.'
            });
        } finally {
            elements.submit.disabled = false;
            elements.submit.textContent =
                asText(config.buttonLabel) || 'Consultar';
        }
    }

    function getStoredResume() {
        try {
            const stored = JSON.parse(
                sessionStorage.getItem(
                    'afenix_consulta_pendiente'
                ) || '{}'
            );

            return stored && typeof stored === 'object'
                ? stored
                : {};
        } catch (error) {
            return {};
        }
    }

    function mergedResume() {
        const configured =
            config.resume
            && typeof config.resume === 'object'
                ? config.resume
                : {};

        const stored = getStoredResume();

        return {
            enabled:
                Boolean(configured.enabled)
                || Boolean(
                    configured.plataforma
                    || stored.plataforma
                ),
            plataforma:
                configured.plataforma
                || stored.plataforma
                || '',
            correo:
                configured.correo
                || stored.correo
                || '',
            asunto:
                configured.asunto
                || stored.asunto
                || ''
        };
    }

    function continueResumeIfNeeded() {
        const resume = mergedResume();
        const subjectId = Number(resume.asunto || 0);

        if (
            !resume.enabled
            || !subjectId
            || state.resumeOpened
            || !state.userId
        ) {
            return;
        }

        const button = elements.resultsList.querySelector(
            '.view-content-btn[data-asunto-id="'
            + subjectId
            + '"]'
        );

        if (!button) {
            clearPending();
            return;
        }

        state.resumeOpened = true;
        clearPending();

        if (window.history && window.history.replaceState) {
            window.history.replaceState(
                {},
                document.title,
                'consulta.php'
            );
        }

        window.setTimeout(function () {
            button.click();
        }, 120);
    }

    function applyResume() {
        const resume = mergedResume();

        if (!resume.enabled) {
            if (state.platforms.length) {
                setSelectedPlatform(state.platforms[0].id);
            }

            return;
        }

        const platformId =
            String(Number(resume.plataforma) || '');

        const index = state.platforms.findIndex(
            function (platform) {
                return String(platform.id) === platformId;
            }
        );

        if (index >= 0) {
            state.page = Math.floor(index / itemsPerPage) + 1;
            renderPlatforms();
            setSelectedPlatform(platformId);
        } else if (state.platforms.length) {
            setSelectedPlatform(state.platforms[0].id);
        }

        if (resume.correo) {
            elements.email.value = asText(resume.correo);
        }

        if (platformId && resume.correo) {
            elements.form.requestSubmit();
        }
    }

    function bindEvents() {
        elements.form.addEventListener(
            'submit',
            submitQuery
        );

        elements.resultsList.addEventListener(
            'click',
            function (event) {
                const button = event.target.closest(
                    '.view-content-btn'
                );

                if (!button) {
                    return;
                }

                event.preventDefault();
                openResult(button);
            }
        );

        document.addEventListener(
            'keydown',
            function (event) {
                if (
                    event.key === 'Escape'
                    && byId('resultsModal')
                ) {
                    event.preventDefault();
                    closeResultsModal();
                }
            },
            true
        );

        document.querySelectorAll(
            '.js-consulta-login-link'
        ).forEach(function (link) {
            link.addEventListener('click', function () {
                const email =
                    asText(elements.email.value).trim();

                if (!state.selectedId || !email) {
                    return;
                }

                const params = new URLSearchParams({
                    plataforma: state.selectedId,
                    correo: email,
                    continuar: '1'
                });

                link.href =
                    'login_consulta.php?'
                    + params.toString();
            });
        });

        window.addEventListener(
            'pageshow',
            function () {
                removeStaleOverlays(true);
            }
        );
    }

    async function initialize() {
        if (document.documentElement.dataset.afConsultaReady === '1') {
            return;
        }

        document.documentElement.dataset.afConsultaReady = '1';

        elements.platforms = byId('plataformas-container');
        elements.pagination = byId('platform-pagination');
        elements.form = byId('consultaForm');
        elements.email = byId('correo');
        elements.submit = byId('submitBtn');
        elements.selectedPlatform = byId('selected_platform_id');
        elements.instructions = byId('instructions-container');
        elements.resultsContainer = byId('results-container');
        elements.resultsList = byId('results-list');

        if (
            !elements.platforms
            || !elements.pagination
            || !elements.form
            || !elements.email
            || !elements.submit
            || !elements.selectedPlatform
            || !elements.resultsList
        ) {
            return;
        }

        removeStaleOverlays(true);
        bindEvents();

        await loadPlatforms();
        applyResume();
    }

    if (document.readyState === 'loading') {
        document.addEventListener(
            'DOMContentLoaded',
            initialize,
            { once: true }
        );
    } else {
        initialize();
    }
})();
