/* AFENIXX-V11 */
(function () {
    'use strict';

    const pathname = location.pathname.toLowerCase();

    const normalize = function (value) {
        return String(value || '')
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/\s+/g, ' ')
            .trim()
            .toLowerCase();
    };

    const escapeHtml = function (value) {
        return String(value || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    };

    const initializeIndex = function () {
        document.querySelectorAll('.plan-card-note')
            .forEach(function (element) {
                const text = normalize(element.textContent);

                if (
                    text.includes('configuracion guiada')
                ) {
                    const icon = element.querySelector('i');

                    element.textContent = '';

                    if (icon) {
                        element.appendChild(icon);
                    }

                    element.append(
                        document.createTextNode(
                            ' Configuración guiada'
                        )
                    );
                }
            });

        const finalCard = document.querySelector(
            '.final-cta .final-card'
        );

        if (!finalCard) {
            return;
        }

        const finalCopy = finalCard.querySelector(
            '.final-copy'
        );

        if (
            finalCopy
            && !finalCopy.querySelector(
                '.af-v11-final-points'
            )
        ) {
            const points = document.createElement('div');

            points.className = 'af-v11-final-points';

            points.innerHTML = `
                <span class="af-v11-final-point">
                    <i class="fas fa-layer-group"></i>
                    <strong>Planes claros</strong>
                </span>
                <span class="af-v11-final-point">
                    <i class="fas fa-sliders"></i>
                    <strong>Configuración guiada</strong>
                </span>
                <span class="af-v11-final-point">
                    <i class="fas fa-headset"></i>
                    <strong>Activación y soporte</strong>
                </span>
            `;

            finalCopy.appendChild(points);
        }

        const button = finalCard.querySelector(
            'a.landing-btn'
        );

        if (!button) {
            return;
        }

        const message = [
            '👋 Hola, deseo información sobre *Ave Fénix*.',
            '',
            '🚀 Me interesa implementar el sistema para ',
            '*centralizar consultas, clientes, renovaciones ',
            'y accesos*.',
            '',
            '📋 *Por favor, envíame información sobre:*',
            '✅ Planes y precios disponibles',
            '✅ Funciones incluidas',
            '✅ Configuración inicial',
            '✅ Activación y soporte'
        ].join('\n');

        try {
            const url = new URL(button.href, location.href);
            const hostname = url.hostname.toLowerCase();

            if (
                hostname.includes('whatsapp.com')
                || hostname === 'wa.me'
                || hostname.endsWith('.wa.me')
            ) {
                url.searchParams.set('text', message);
                button.href = url.toString();
                button.target = '_blank';
                button.rel = 'noopener';

                button.innerHTML =
                    '<i class="fab fa-whatsapp"></i>'
                    + 'Solicitar información por WhatsApp';
            }
        } catch (error) {
            console.warn(
                'No fue posible actualizar el enlace de WhatsApp.',
                error
            );
        }
    };

    const initializeConsulta = function () {
        const instructions = document.getElementById(
            'instructions-container'
        );

        if (
            instructions
            && !instructions.dataset.afV11Applied
        ) {
            instructions.dataset.afV11Applied = '1';

            instructions.innerHTML = `
                <h3 class="text-xl font-bold mb-3 text-red-600">
                    Instrucciones de uso
                </h3>

                <p class="af-v11-instructions-intro">
                    Sigue estos pasos para localizar tu código
                    o mensaje de forma segura.
                </p>

                <div class="af-v11-instructions">
                    <article class="af-v11-instruction">
                        <span class="af-v11-instruction-number">1</span>
                        <span class="af-v11-instruction-icon">
                            <i class="fas fa-layer-group"></i>
                        </span>
                        <span class="af-v11-instruction-copy">
                            <strong>Elige la plataforma</strong>
                            <small>
                                Selecciona el servicio relacionado
                                con la cuenta.
                            </small>
                        </span>
                    </article>

                    <article class="af-v11-instruction">
                        <span class="af-v11-instruction-number">2</span>
                        <span class="af-v11-instruction-icon">
                            <i class="fas fa-envelope"></i>
                        </span>
                        <span class="af-v11-instruction-copy">
                            <strong>Ingresa el correo completo</strong>
                            <small>
                                Escríbelo exactamente como está
                                registrado.
                            </small>
                        </span>
                    </article>

                    <article class="af-v11-instruction">
                        <span class="af-v11-instruction-number">3</span>
                        <span class="af-v11-instruction-icon">
                            <i class="fas fa-magnifying-glass"></i>
                        </span>
                        <span class="af-v11-instruction-copy">
                            <strong>Realiza la consulta</strong>
                            <small>
                                Pulsa Consultar para buscar mensajes
                                recientes.
                            </small>
                        </span>
                    </article>

                    <article class="af-v11-instruction">
                        <span class="af-v11-instruction-number">4</span>
                        <span class="af-v11-instruction-icon">
                            <i class="fas fa-list-check"></i>
                        </span>
                        <span class="af-v11-instruction-copy">
                            <strong>Revisa los resultados</strong>
                            <small>
                                Verifica el asunto y la hora del
                                mensaje encontrado.
                            </small>
                        </span>
                    </article>

                    <article class="af-v11-instruction">
                        <span class="af-v11-instruction-number">5</span>
                        <span class="af-v11-instruction-icon">
                            <i class="fas fa-lock-open"></i>
                        </span>
                        <span class="af-v11-instruction-copy">
                            <strong>Abre el contenido autorizado</strong>
                            <small>
                                El contenido privado requiere un
                                ID de acceso válido.
                            </small>
                        </span>
                    </article>
                </div>
            `;
        }

        const pagination = document.getElementById(
            'platform-pagination'
        );

        if (!pagination) {
            return;
        }

        const cleanPagination = function () {
            let html = pagination.innerHTML;

            const cleaned = html
                .replace(/Anterior/gi, '')
                .replace(/Siguiente/gi, '');

            if (cleaned !== html) {
                pagination.innerHTML = cleaned;
            }

            const previous = pagination.querySelector(
                '#prev-platform'
            );

            const next = pagination.querySelector(
                '#next-platform'
            );

            if (previous) {
                previous.setAttribute(
                    'aria-label',
                    'Página anterior'
                );

                if (!previous.querySelector('i')) {
                    previous.innerHTML =
                        '<i class="fas fa-chevron-left"></i>';
                }
            }

            if (next) {
                next.setAttribute(
                    'aria-label',
                    'Página siguiente'
                );

                if (!next.querySelector('i')) {
                    next.innerHTML =
                        '<i class="fas fa-chevron-right"></i>';
                }
            }
        };

        cleanPagination();

        new MutationObserver(cleanPagination).observe(
            pagination,
            {
                childList: true,
                subtree: true,
                characterData: true
            }
        );
    };

    const resolveLogoUrl = function (value) {
        let url = String(value || '').trim();

        if (!url) {
            return '';
        }

        if (
            /^(?:https?:|data:|blob:|\/)/i.test(url)
        ) {
            return url;
        }

        url = url.replace(/^\.\//, '');

        return pathname.includes('/admin/')
            ? '../' + url
            : url;
    };

    const findPlatformTable = function () {
        return Array.from(
            document.querySelectorAll('table')
        ).find(function (table) {
            const heading = normalize(
                table.tHead
                    ? table.tHead.innerText
                    : ''
            );

            return heading.includes('plataforma')
                && heading.includes('cuenta');
        }) || null;
    };

    const decoratePlatformRows = function (
        table,
        platforms
    ) {
        if (!table) {
            return;
        }

        const headers = Array.from(
            table.querySelectorAll('thead th')
        );

        const platformIndex = headers.findIndex(
            function (header) {
                return normalize(
                    header.textContent
                ) === 'plataforma'
                    || normalize(
                        header.textContent
                    ).includes('plataforma');
            }
        );

        if (platformIndex < 0) {
            return;
        }

        table.querySelectorAll('tbody tr')
            .forEach(function (row) {
                const cell = row.cells
                    ? row.cells[platformIndex]
                    : null;

                if (!cell) {
                    return;
                }

                const platformName = String(
                    cell.dataset.afPlatformName
                    || cell.textContent
                    || ''
                ).trim();

                const platform = platforms.get(
                    normalize(platformName)
                );

                if (
                    !platform
                    || !platform.logo
                ) {
                    return;
                }

                if (
                    cell.dataset.afV11Logo
                    === platform.logo
                ) {
                    return;
                }

                cell.dataset.afPlatformName =
                    platformName;

                cell.dataset.afV11Logo =
                    platform.logo;

                const logoUrl = resolveLogoUrl(
                    platform.logo
                );

                cell.innerHTML = `
                    <span class="af-v11-platform-cell">
                        <span class="af-v11-platform-logo">
                            <img
                                src="${escapeHtml(logoUrl)}"
                                alt="${escapeHtml(platformName)}"
                                loading="lazy"
                            >
                            <i
                                class="fas fa-tv
                                af-v11-platform-logo-fallback"
                            ></i>
                        </span>

                        <strong class="af-v11-platform-name">
                            ${escapeHtml(platformName)}
                        </strong>
                    </span>
                `;

                const image = cell.querySelector('img');

                image?.addEventListener(
                    'error',
                    function () {
                        image.style.display = 'none';

                        const fallback =
                            cell.querySelector(
                                '.af-v11-platform-logo-fallback'
                            );

                        if (fallback) {
                            fallback.style.display = 'block';
                        }
                    },
                    { once: true }
                );
            });
    };

    const compactAccountFilters = function (table) {
        if (
            !table
            || document.getElementById(
                'afV11AccountFilterLine'
            )
        ) {
            return;
        }

        const searchInput = Array.from(
            document.querySelectorAll('input')
        ).find(function (input) {
            const text = normalize(
                input.placeholder
                || input.getAttribute('aria-label')
                || ''
            );

            return input.type === 'search'
                || text.includes('buscar');
        });

        const showSelect = Array.from(
            document.querySelectorAll('select')
        ).find(function (select) {
            const wrapperText = normalize(
                select.parentElement
                    ? select.parentElement.innerText
                    : ''
            );

            const optionValues = Array.from(
                select.options || []
            ).map(function (option) {
                return String(option.value);
            });

            return wrapperText.includes('mostrar')
                || (
                    optionValues.includes('25')
                    && optionValues.includes('50')
                );
        });

        const clearControl = Array.from(
            document.querySelectorAll('button, a')
        ).find(function (element) {
            return normalize(element.textContent)
                === 'limpiar';
        });

        if (
            !searchInput
            && !showSelect
            && !clearControl
        ) {
            return;
        }

        const wrapper = function (element) {
            if (!element) {
                return null;
            }

            return element.closest(
                '.filter-field,'
                + '.form-group,'
                + '.dataTables_filter,'
                + '.dataTables_length,'
                + 'label'
            ) || element.parentElement;
        };

        const searchWrapper = wrapper(searchInput);
        const showWrapper = wrapper(showSelect);
        const clearWrapper = wrapper(clearControl);

        const line = document.createElement('div');

        line.id = 'afV11AccountFilterLine';
        line.className = 'af-v11-account-filterline';

        const tableContainer =
            table.closest('.table-responsive')
            || table.parentElement;

        if (tableContainer && tableContainer.parentElement) {
            tableContainer.parentElement.insertBefore(
                line,
                tableContainer
            );
        } else {
            table.parentElement?.insertBefore(
                line,
                table
            );
        }

        [
            searchWrapper,
            showWrapper,
            clearWrapper
        ].forEach(function (element) {
            if (
                element
                && element !== line
                && !line.contains(element)
            ) {
                line.appendChild(element);
            }
        });
    };

    const initializeAccounts = async function () {
        const table = findPlatformTable();

        compactAccountFilters(table);

        try {
            const response = await fetch(
                '../api.php?action=getPlataformas&v='
                + Date.now(),
                {
                    cache: 'no-store',
                    credentials: 'same-origin',
                    headers: {
                        'X-Requested-With':
                            'XMLHttpRequest'
                    }
                }
            );

            if (!response.ok) {
                return;
            }

            const payload = await response.json();

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

            const platforms = new Map();

            records.forEach(function (platform) {
                const name = String(
                    platform.nombre || ''
                ).trim();

                const logo = String(
                    platform.imagen_url || ''
                ).trim();

                if (name) {
                    platforms.set(
                        normalize(name),
                        { name: name, logo: logo }
                    );
                }
            });

            decoratePlatformRows(
                table,
                platforms
            );

            if (table?.tBodies?.[0]) {
                new MutationObserver(function () {
                    decoratePlatformRows(
                        table,
                        platforms
                    );
                }).observe(
                    table.tBodies[0],
                    {
                        childList: true,
                        subtree: true
                    }
                );
            }

            if (
                window.jQuery
                && window.jQuery.fn
            ) {
                window.jQuery(document).on(
                    'draw.dt.afV11',
                    function () {
                        decoratePlatformRows(
                            table,
                            platforms
                        );
                    }
                );
            }
        } catch (error) {
            console.warn(
                'No se pudieron cargar los logos '
                + 'registrados en plataformas.',
                error
            );
        }
    };

    const initializeBrandPalette = function () {
        const colorKeys = [
            'marca_index_fondo',
            'marca_index_superficie',
            'marca_index_fondo_suave',
            'marca_index_texto',
            'marca_index_texto_secundario',
            'marca_index_oscuro',
            'marca_index_oscuro_secundario',
            'marca_index_texto_oscuro',
            'marca_plan_tarjeta',
            'marca_plan_borde',
            'marca_plan_destacado',
            'marca_plan_precio_fondo'
        ];

        document.addEventListener(
            'click',
            function (event) {
                const button = event.target.closest(
                    '[data-index-palette]'
                );

                if (!button) {
                    return;
                }

                /*
                 * Bloquea el controlador anterior que dejaba
                 * los campos sin sincronizar.
                 */
                event.preventDefault();
                event.stopImmediatePropagation();

                const paletteKey =
                    button.dataset.indexPalette
                    || 'personalizada';

                const paletteInput =
                    document.getElementById(
                        'marca_index_paleta'
                    );

                let colors = [];

                try {
                    colors = JSON.parse(
                        button.dataset.indexColors || '[]'
                    );
                } catch (error) {
                    colors = [];
                }

                if (
                    paletteKey !== 'personalizada'
                    && colors.length >= colorKeys.length
                ) {
                    colorKeys.forEach(
                        function (key, index) {
                            const input =
                                document.getElementById(key);

                            const picker =
                                document.getElementById(
                                    key + '_picker'
                                );

                            const value = colors[index];

                            if (input) {
                                input.value = value;

                                input.dispatchEvent(
                                    new Event(
                                        'change',
                                        { bubbles: true }
                                    )
                                );
                            }

                            if (picker) {
                                picker.value = value;

                                picker.dispatchEvent(
                                    new Event(
                                        'change',
                                        { bubbles: true }
                                    )
                                );
                            }
                        }
                    );
                }

                if (paletteInput) {
                    paletteInput.value = paletteKey;
                }

                document.querySelectorAll(
                    '[data-index-palette]'
                ).forEach(function (item) {
                    item.classList.toggle(
                        'is-active',
                        item === button
                    );
                });
            },
            true
        );
    };

    const initialize = function () {
        if (
            pathname.endsWith('/index.php')
            || pathname === '/'
            || pathname.endsWith('/')
        ) {
            initializeIndex();
        }

        if (pathname.endsWith('/consulta.php')) {
            initializeConsulta();
        }

        if (
            pathname.endsWith(
                '/admin/gestionar_cuentas.php'
            )
        ) {
            initializeAccounts();
        }

        if (
            pathname.endsWith(
                '/admin/configurar_marca.php'
            )
        ) {
            initializeBrandPalette();
        }
    };

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