document.addEventListener('DOMContentLoaded', function () {

    const currentLang = document.getElementById('current_lang');
    const currentFlag = document.getElementById('current_flag');
    const langLinks = document.querySelectorAll('#lang_sel ul ul li a');
    const langSel = document.getElementById('lang_sel');

    const languages = {
        'en': { name: 'English', flag: 'https://vtiengineering.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/en.svg', url: 'https://vtiengineering.com/' },
        'es': { name: 'Español', flag: 'https://vtiengineering.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/es.svg', url: 'https://vtiengineering.com/es/' },
        'it': { name: 'Italiano', flag: 'https://vtiengineering.com/wp-content/plugins/sitepress-multilingual-cms/res/flags/it.svg', url: 'https://vtiengineering.com/it/' }
    };

    langLinks.forEach(link => {
        link.addEventListener('click', function (event) {
            event.preventDefault();
            const lang = this.dataset.lang;

            if (languages[lang]) {
                currentLang.textContent = languages[lang].name;
                currentFlag.src = languages[lang].flag;

                let currentUrl = window.location.href;
                let newUrl;

                let currentLangCode = currentUrl.match(/\/([a-z]{2})\//);
                currentLangCode = currentLangCode ? currentLangCode[1] : null;

                if (lang === 'en') {
                    // Si la URL contiene un código de idioma, se elimina
                    if (currentLangCode && currentLangCode !== 'en') {
                        newUrl = currentUrl.replace(`/${currentLangCode}/`, '/');
                    } else {
                        newUrl = 'https://vtiengineering.com/';
                    }
                } else {
                    // Si hay un idioma en la URL, reemplázalo
                    if (currentLangCode) {
                        newUrl = currentUrl.replace(`/${currentLangCode}/`, `/${lang}/`);
                    } else {
                        // Si no hay código de idioma, agrega el idioma a la ruta
                        const baseUrl = languages[lang].url.replace(/\/+$/, '');
                        const currentPath = window.location.pathname.replace(/^\/+/, '');
                        newUrl = `${baseUrl}/${currentPath}`;
                    }
                }

                // Normalizar la URL para evitar dobles barras "//"
                newUrl = newUrl.replace(/([^:]\/)\/+/g, "$1");

            	window.location.href = newUrl;
            } else {
                console.error("Idioma desconocido:", lang);
            }
        });
    });

    // Configuración inicial del idioma (al cargar la página)
    const currentPath = window.location.pathname;
    const currentLangCode = currentPath.split('/')[1];

    if (languages[currentLangCode]) {
        currentLang.textContent = languages[currentLangCode].name;
        currentFlag.src = languages[currentLangCode].flag;
    } else {
        currentLang.textContent = languages['en'].name;
        currentFlag.src = languages['en'].flag;
    }
});