(function () {
    'use strict';

    var STORAGE_KEY = 'site_lang';
    var DEFAULT_LANG = 'en';

    var LANGUAGES = [
        { code: 'en', native: 'English', label: 'English', flag: '🇺🇸' },
        { code: 'es', native: 'Español', label: 'Spanish', flag: '🇪🇸' },
        { code: 'zh-CN', native: '简体中文', label: 'Chinese (Simplified)', flag: '🇨🇳' },
        { code: 'hi', native: 'हिन्दी', label: 'Hindi', flag: '🇮🇳' },
        { code: 'ar', native: 'العربية', label: 'Arabic', flag: '🇸🇦' },
        { code: 'fr', native: 'Français', label: 'French', flag: '🇫🇷' },
        { code: 'pt', native: 'Português', label: 'Portuguese', flag: '🇧🇷' },
        { code: 'ru', native: 'Русский', label: 'Russian', flag: '🇷🇺' },
        { code: 'ja', native: '日本語', label: 'Japanese', flag: '🇯🇵' },
        { code: 'de', native: 'Deutsch', label: 'German', flag: '🇩🇪' }
    ];

    function getStoredLanguage() {
        try {
            return localStorage.getItem(STORAGE_KEY) || DEFAULT_LANG;
        } catch (e) {
            return DEFAULT_LANG;
        }
    }

    function setTranslateCookie(lang) {
        var cookieBase = 'googtrans=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
        document.cookie = cookieBase;
        document.cookie = cookieBase + '; domain=' + window.location.hostname;

        if (lang && lang !== DEFAULT_LANG) {
            var value = '/en/' + lang;
            document.cookie = 'googtrans=' + value + '; path=/';
            document.cookie = 'googtrans=' + value + '; path=/; domain=' + window.location.hostname;
        }
    }

    function persistLanguage(lang) {
        try {
            localStorage.setItem(STORAGE_KEY, lang);
        } catch (e) {
            /* ignore */
        }
        setTranslateCookie(lang);
    }

    function applyLanguage(lang, reload) {
        persistLanguage(lang);
        if (reload) {
            window.location.reload();
            return;
        }
        triggerGoogleTranslate(lang);
        updateSwitcherUI(lang);
    }

    function triggerGoogleTranslate(lang) {
        var select = document.querySelector('select.goog-te-combo');
        if (!select) {
            return false;
        }

        if (lang === DEFAULT_LANG) {
            select.value = '';
        } else {
            select.value = lang;
        }

        select.dispatchEvent(new Event('change'));
        return true;
    }

    function waitForGoogleTranslate(lang, attempts) {
        var remaining = attempts || 0;
        if (triggerGoogleTranslate(lang)) {
            return;
        }
        if (remaining >= 40) {
            return;
        }
        setTimeout(function () {
            waitForGoogleTranslate(lang, remaining + 1);
        }, 150);
    }

    function getLanguageMeta(code) {
        for (var i = 0; i < LANGUAGES.length; i++) {
            if (LANGUAGES[i].code === code) {
                return LANGUAGES[i];
            }
        }
        return LANGUAGES[0];
    }

    function updateSwitcherUI(lang) {
        var meta = getLanguageMeta(lang);
        var label = document.getElementById('lang-switcher-label');
        var code = document.getElementById('lang-switcher-code');
        var flag = document.getElementById('lang-switcher-flag');

        if (label) {
            label.textContent = meta.native;
        }
        if (code) {
            code.textContent = meta.code === 'zh-CN' ? 'ZH' : meta.code.toUpperCase();
        }
        if (flag) {
            flag.textContent = meta.flag;
        }

        document.querySelectorAll('[data-lang-option]').forEach(function (button) {
            var isActive = button.getAttribute('data-lang-option') === lang;
            button.classList.toggle('is-active', isActive);
            button.setAttribute('aria-selected', isActive ? 'true' : 'false');
        });
    }

    function buildMenu(container) {
        container.innerHTML = '';

        var title = document.createElement('div');
        title.className = 'lang-switcher-menu-title';
        title.textContent = 'Select Language';
        container.appendChild(title);

        LANGUAGES.forEach(function (lang) {
            var button = document.createElement('button');
            button.type = 'button';
            button.className = 'lang-switcher-option';
            button.setAttribute('data-lang-option', lang.code);
            button.setAttribute('role', 'option');
            button.innerHTML =
                '<span class="lang-switcher-flag">' + lang.flag + '</span>' +
                '<span class="lang-switcher-option-text">' +
                    '<span class="lang-switcher-option-native">' + lang.native + '</span>' +
                    '<span class="lang-switcher-option-en">' + lang.label + '</span>' +
                '</span>' +
                '<i class="fa-solid fa-check lang-switcher-option-check"></i>';

            button.addEventListener('click', function () {
                applyLanguage(lang.code, true);
            });

            container.appendChild(button);
        });
    }

    function closeMenu(menu, trigger) {
        menu.classList.remove('is-open');
        if (trigger) {
            trigger.setAttribute('aria-expanded', 'false');
        }
    }

    function initSwitcher() {
        var root = document.getElementById('lang-switcher');
        if (!root) {
            return;
        }

        var trigger = document.getElementById('lang-switcher-btn');
        var menu = document.getElementById('lang-switcher-menu');
        if (!trigger || !menu) {
            return;
        }

        buildMenu(menu);

        var currentLang = getStoredLanguage();
        updateSwitcherUI(currentLang);

        if (currentLang !== DEFAULT_LANG) {
            waitForGoogleTranslate(currentLang, 0);
        }

        trigger.addEventListener('click', function (event) {
            event.stopPropagation();
            var isOpen = menu.classList.contains('is-open');
            document.querySelectorAll('.lang-switcher-menu.is-open').forEach(function (openMenu) {
                openMenu.classList.remove('is-open');
            });
            if (!isOpen) {
                menu.classList.add('is-open');
                trigger.setAttribute('aria-expanded', 'true');
            } else {
                closeMenu(menu, trigger);
            }
        });

        document.addEventListener('click', function (event) {
            if (!root.contains(event.target)) {
                closeMenu(menu, trigger);
            }
        });

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                closeMenu(menu, trigger);
            }
        });
    }

    window.googleTranslateElementInit = function () {
        new google.translate.TranslateElement({
            pageLanguage: 'en',
            includedLanguages: 'en,es,zh-CN,hi,ar,fr,pt,ru,ja,de',
            autoDisplay: false,
            multilanguagePage: true
        }, 'google_translate_element');

        initSwitcher();
    };

    var bootLang = getStoredLanguage();
    if (bootLang && bootLang !== DEFAULT_LANG) {
        setTranslateCookie(bootLang);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            if (typeof google === 'undefined' || !google.translate) {
                initSwitcher();
            }
        });
    }
})();
