(function () {
    const openClass = ['opacity-100', 'translate-y-0'];
    const closedClass = ['pointer-events-none', 'invisible', 'opacity-0', 'translate-y-1'];

    function closeDropdown(root) {
        const trigger = root.querySelector('[data-booklio-dropdown-trigger]');
        const panel = root.querySelector('[data-booklio-dropdown-menu]');
        if (!panel) return;
        panel.classList.remove(...openClass);
        panel.classList.add(...closedClass);
        trigger?.setAttribute('aria-expanded', 'false');
    }

    function closeAllDropdowns(exceptRoot) {
        document.querySelectorAll('[data-booklio-dropdown-root]').forEach((root) => {
            if (root !== exceptRoot) closeDropdown(root);
        });
    }

    function toggleDropdown(root) {
        const trigger = root.querySelector('[data-booklio-dropdown-trigger]');
        const panel = root.querySelector('[data-booklio-dropdown-menu]');
        if (!panel) return;

        const isOpen = panel.classList.contains('opacity-100');
        closeAllDropdowns(root);

        if (isOpen) {
            closeDropdown(root);
            return;
        }

        panel.classList.remove(...closedClass);
        panel.classList.add(...openClass);
        trigger?.setAttribute('aria-expanded', 'true');
    }

    function closeSearchPanels(exceptRoot) {
        document.querySelectorAll('[data-booklio-search-root]').forEach((root) => {
            if (root === exceptRoot) return;
            const panel = root.querySelector('[data-booklio-search-panel]');
            panel?.classList.remove(...openClass);
            panel?.classList.add(...closedClass);
        });
    }

    function openSearchPanel(root) {
        const panel = root.querySelector('[data-booklio-search-panel]');
        if (!panel) return;
        closeAllDropdowns();
        closeSearchPanels(root);
        panel.classList.remove(...closedClass);
        panel.classList.add(...openClass);
    }

    const originalTextNodes = new WeakMap();
    const originalAttributes = new WeakMap();

    function normalizeText(value) {
        return String(value || '').replace(/\s+/g, ' ').trim();
    }

    function translateText(value, lookup) {
        const normalized = normalizeText(value);
        if (!normalized || !lookup) return null;

        return lookup[normalized] || null;
    }

    function shouldSkipTextNode(node) {
        const parent = node.parentElement;
        if (!parent) return true;

        return Boolean(parent.closest('script, style, svg, code, pre, textarea, [data-booklio-no-translate]'));
    }

    function applyTextTranslations(locale, lookup) {
        if (!document.body) return;

        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
            acceptNode(node) {
                if (shouldSkipTextNode(node)) return NodeFilter.FILTER_REJECT;
                return normalizeText(node.nodeValue) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            },
        });

        const nodes = [];
        while (walker.nextNode()) nodes.push(walker.currentNode);

        nodes.forEach((node) => {
            if (!originalTextNodes.has(node)) {
                originalTextNodes.set(node, node.nodeValue);
            }

            const original = originalTextNodes.get(node);
            if (locale === 'en') {
                node.nodeValue = original;
                return;
            }

            const translated = translateText(original, lookup);
            if (!translated) {
                node.nodeValue = original;
                return;
            }

            const leading = String(original).match(/^\s*/)?.[0] || '';
            const trailing = String(original).match(/\s*$/)?.[0] || '';
            node.nodeValue = `${leading}${translated}${trailing}`;
        });
    }

    function applyAttributeTranslations(locale, lookup) {
        const attributes = ['placeholder', 'title', 'aria-label'];

        document.querySelectorAll('[placeholder], [title], [aria-label]').forEach((node) => {
            if (node.closest('[data-booklio-no-translate]')) return;

            if (!originalAttributes.has(node)) {
                const values = {};
                attributes.forEach((attribute) => {
                    if (node.hasAttribute(attribute)) values[attribute] = node.getAttribute(attribute);
                });
                originalAttributes.set(node, values);
            }

            const values = originalAttributes.get(node);
            attributes.forEach((attribute) => {
                if (!(attribute in values)) return;

                if (locale === 'en') {
                    node.setAttribute(attribute, values[attribute]);
                    return;
                }

                const translated = translateText(values[attribute], lookup);
                node.setAttribute(attribute, translated || values[attribute]);
            });
        });

        if (!originalAttributes.has(document.documentElement)) {
            originalAttributes.set(document.documentElement, { title: document.title });
        }

        const originalTitle = originalAttributes.get(document.documentElement).title;
        document.title = locale === 'en' ? originalTitle : (translateText(originalTitle, lookup) || originalTitle);
    }

    function translatePage(locale, config) {
        const lookup = config?.lookup || {};
        applyTextTranslations(locale, lookup);
        applyAttributeTranslations(locale, lookup);
    }

    function applyLanguage(locale) {
        const config = window.BooklioTranslations?.languages?.[locale] || window.BooklioTranslations?.languages?.en;
        if (!config) return;

        document.documentElement.lang = locale;
        document.documentElement.dir = config.direction || 'ltr';
        document.body.classList.toggle('booklio-rtl', config.direction === 'rtl');
        translatePage(locale, config);

        document.querySelectorAll('[data-booklio-language-label]').forEach((node) => {
            node.textContent = config.name;
        });
        document.querySelectorAll('[data-booklio-language-code]').forEach((node) => {
            node.textContent = locale.toUpperCase();
        });
        document.querySelectorAll('[data-language-check]').forEach((node) => {
            node.classList.toggle('hidden', node.dataset.languageCheck !== locale);
        });

        try {
            localStorage.setItem('booklio.locale', locale);
        } catch (error) {
            // UI only: backend persistence will happen through Settings later.
        }
    }

    function initDropdowns() {
        document.addEventListener('click', (event) => {
            const trigger = event.target.closest('[data-booklio-dropdown-trigger]');
            if (trigger) {
                event.preventDefault();
                toggleDropdown(trigger.closest('[data-booklio-dropdown-root]'));
                return;
            }

            const languageOption = event.target.closest('[data-booklio-language-option]');
            if (languageOption) {
                applyLanguage(languageOption.dataset.booklioLanguageOption);
                closeAllDropdowns();
                return;
            }

            const insideDropdown = event.target.closest('[data-booklio-dropdown-root]');
            const insideSearch = event.target.closest('[data-booklio-search-root]');
            if (!insideDropdown) closeAllDropdowns();
            if (!insideSearch) closeSearchPanels();
        });

        document.addEventListener('focusin', (event) => {
            const input = event.target.closest('[data-booklio-search-input]');
            if (input) openSearchPanel(input.closest('[data-booklio-search-root]'));
        });

        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') {
                closeAllDropdowns();
                closeSearchPanels();
            }

            if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
                event.preventDefault();
                const firstSearch = document.querySelector('[data-booklio-search-input]');
                firstSearch?.focus();
            }
        });

        const queryLocale = new URLSearchParams(window.location.search).get('lang');
        const backendLocale = window.BooklioTranslations?.currentLocale;
        let locale = queryLocale || backendLocale || window.BooklioTranslations?.defaultLocale || 'en';
        try {
            locale = queryLocale || backendLocale || localStorage.getItem('booklio.locale') || locale;
        } catch (error) {
            // Ignore storage failures in the UI preview.
        }
        applyLanguage(locale);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initDropdowns);
    } else {
        initDropdowns();
    }
})();
