/* AVE FÉNIX · V12 */
(function () {
    'use strict';

    const pathname = String(
        window.location.pathname || ''
    ).toLowerCase();

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

    function visible(element) {
        if (!element) {
            return false;
        }

        const style = window.getComputedStyle(element);
        const rect = element.getBoundingClientRect();

        return style.display !== 'none'
            && style.visibility !== 'hidden'
            && rect.width > 0
            && rect.height > 0;
    }

    function closestSmallWrapper(control) {
        if (!control) {
            return null;
        }

        return control.closest(
            '.af-v12-filter-field,'
            + '.sa-filter-field,'
            + '.filter-field,'
            + '.form-group,'
            + '.dataTables_filter,'
            + '.dataTables_length,'
            + '.records-filter,'
            + 'label'
        ) || control.parentElement;
    }

    function makeExternalFormControlSafe(control) {
        if (!control || !control.form) {
            return;
        }

        const form = control.form;

        if (!form.id) {
            form.id = 'afV12Form'
                + Math.random()
                    .toString(36)
                    .slice(2, 9);
        }

        control.setAttribute('form', form.id);
    }

    function findClearControl() {
        return Array.from(
            document.querySelectorAll('button, a')
        ).find(function (element) {
            if (!visible(element)) {
                return false;
            }

            const text = normalize(element.textContent);

            return text === 'limpiar'
                || text === 'limpiar filtros';
        }) || null;
    }

    function findStateSelect() {
        const selects = Array.from(
            document.querySelectorAll('select')
        );

        return selects.find(function (select) {
            if (!visible(select)) {
                return false;
            }

            const identity = normalize(
                (select.id || '')
                + ' '
                + (select.name || '')
                + ' '
                + (
                    select.parentElement
                        ? select.parentElement.textContent
                        : ''
                )
            );

            return identity.includes(
                'estado de renovacion'
            ) || (
                identity.includes('estado')
                && identity.includes('renovacion')
            );
        }) || null;
    }

    function findShowSelect() {
        const direct = document.querySelector(
            '.dataTables_length select'
        );

        if (direct && visible(direct)) {
            return direct;
        }

        return Array.from(
            document.querySelectorAll('select')
        ).find(function (select) {
            if (!visible(select)) {
                return false;
            }

            const parentText = normalize(
                select.parentElement
                    ? select.parentElement.textContent
                    : ''
            );

            const options = Array.from(
                select.options || []
            ).map(function (option) {
                return normalize(option.textContent);
            });

            return parentText.includes('mostrar')
                || (
                    options.some(function (option) {
                        return option.includes('100 registros');
                    })
                    && options.some(function (option) {
                        return option.includes('todos');
                    })
                );
        }) || null;
    }

    function initializeAccountToolbar() {
        if (
            !pathname.endsWith(
                '/admin/gestionar_cuentas.php'
            )
        ) {
            return;
        }

        const toolbar = document.getElementById(
            'afV13AccountToolbar'
        );

        if (!toolbar) {
            return;
        }

        /*
         * La barra ya viene ordenada desde PHP. No se mueve ningún
         * control: solo se limpian clases antiguas que alteraban el
         * ancho o enviaban Limpiar a otro contenedor.
         */
        toolbar.classList.remove(
            'af-v9-filter-row',
            'af-v11-account-filterline',
            'af-v12-account-toolbar'
        );

        const search = document.getElementById('accountSearch');
        const clear = document.getElementById('clearAccountFilters');

        if (search) {
            search.classList.remove('af-v9-search-compact');
        }

        if (clear) {
            clear.classList.remove('af-v9-clear-inline');
        }

        toolbar.dataset.afV12Ready = '1';
    }

    function initializeSmtp() {
        if (
            !pathname.endsWith(
                '/admin/configurar_marca.php'
            )
        ) {
            return;
        }

        ['mail_port', 'mail_username'].forEach(
            function (id) {
                const input = document.getElementById(id);

                if (!input) {
                    return;
                }

                const field = input.closest('.wb-field');

                if (field) {
                    field.classList.add(
                        'af-v12-smtp-pair'
                    );
                }
            }
        );

        /*
         * Respaldo visual en caso de que el HTML anterior
         * permaneciera almacenado por OPcache.
         */
        const testDestination =
            document.getElementById(
                'mail_test_destination'
            );

        if (testDestination) {
            const field = testDestination.closest(
                '.wb-field'
            );

            if (field) {
                field.remove();
            }
        }

        const form = document.querySelector(
            'form[method="post"]'
        );

        if (!form) {
            return;
        }

        form.addEventListener(
            'submit',
            function (event) {
                const submitter = event.submitter;

                if (
                    !submitter
                    || submitter.name
                        !== 'test_mail_after_save'
                ) {
                    return;
                }

                let hidden = form.querySelector(
                    'input[type="hidden"]'
                    + '[name="mail_test_destination"]'
                );

                if (!hidden) {
                    hidden = document.createElement(
                        'input'
                    );

                    hidden.type = 'hidden';
                    hidden.name =
                        'mail_test_destination';

                    form.appendChild(hidden);
                }

                const fromEmail =
                    document.getElementById(
                        'mail_from_email'
                    );

                hidden.value = fromEmail
                    ? fromEmail.value
                    : '';
            },
            true
        );
    }

    function removeFirstInformationHeader() {
        const fragments = {
            '/admin/configurar_marca.php':
                'personaliza nombre, identidad visual, colores, datos comerciales',

            '/admin/gestionar_roles.php':
                'asigna permisos por rol con precision',

            '/admin/gestionar_pruebas.php':
                'revisa identificadores ya utilizados',

            '/admin/gestionar_ayudantes.php':
                'promueve o revoca ayudantes',

            '/admin/gestionar_reportes.php':
                'analiza uso, suscripciones, recursos e inactividad'
        };

        const fragment = fragments[pathname];

        if (!fragment) {
            return;
        }

        const nodes = Array.from(
            document.querySelectorAll(
                'p, span, div'
            )
        ).filter(function (element) {
            const text = normalize(element.textContent);

            return text.includes(fragment)
                && text.length < 450;
        });

        for (const node of nodes) {
            let current = node;
            let candidate = null;

            for (let level = 0; level < 7; level++) {
                if (
                    !current
                    || current === document.body
                    || current === document.documentElement
                ) {
                    break;
                }

                const rect =
                    current.getBoundingClientRect();

                const isCompactHeader =
                    rect.width >= window.innerWidth * .48
                    && rect.height >= 35
                    && rect.height <= 135;

                const protectedContainer =
                    current.matches(
                        'main,'
                        + '.sa-page,'
                        + '.wb-shell,'
                        + '.wb-layout,'
                        + '.wb-section-grid'
                    );

                if (
                    isCompactHeader
                    && !protectedContainer
                ) {
                    candidate = current;
                }

                current = current.parentElement;
            }

            if (candidate) {
                candidate.remove();
                break;
            }
        }
    }

    function watchDynamicAccountFilters() {
        if (
            !pathname.endsWith(
                '/admin/gestionar_cuentas.php'
            )
        ) {
            return;
        }

        let timer = 0;

        const observer = new MutationObserver(
            function () {
                window.clearTimeout(timer);

                timer = window.setTimeout(
                    initializeAccountToolbar,
                    80
                );
            }
        );

        observer.observe(
            document.body,
            {
                childList: true,
                subtree: true
            }
        );
    }

    function initialize() {
        initializeAccountToolbar();
        initializeSmtp();
        removeFirstInformationHeader();
        watchDynamicAccountFilters();

        /*
         * Una segunda ejecución cubre controles creados
         * después por DataTables.
         */
        window.setTimeout(
            initializeAccountToolbar,
            350
        );
    }

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