// Language switching functionality for QR Rapido
document.addEventListener('DOMContentLoaded', function () {
    // FORCE: Respect the URL culture above all else
    let currentCulture = getCurrentCulture();

    console.log('Current culture:', currentCulture);

    localStorage.setItem('preferredLanguage', currentCulture);

    const languageDropdownItems = document.querySelectorAll('.dropdown-item[data-lang]');
    const currentLangSpan = document.getElementById('current-lang');
    
    // Get current culture from URL or default to pt-BR
    function getCurrentCulture() {
        const pathSegments = window.location.pathname.split('/').filter(segment => segment);
        const supportedCultures = ['pt-BR', 'es-PY', 'es'];
        
        if (pathSegments.length > 0 && supportedCultures.includes(pathSegments[0])) {
            return pathSegments[0];
        }

        return 'pt-BR';
    }
    
    // Update current language display
    function updateCurrentLanguageDisplay(culture) {
        const langMap = {
            'pt-BR': 'PT',
            'es-PY': 'ES',
            'es': 'ES'
        };
        
        if (currentLangSpan) {
            currentLangSpan.textContent = langMap[culture] || 'PT';
        }
    }
    
    // Build new URL with selected culture
    function buildLocalizedUrl(newCulture) {
        const currentPath = window.location.pathname;
        const queryString = window.location.search;
        const hash = window.location.hash;
        
        // Remove existing culture from path if present
        const pathSegments = currentPath.split('/').filter(segment => segment);
        const supportedCultures = ['pt-BR', 'es-PY', 'es'];
        
        // Remove current culture if it's the first segment
        if (pathSegments.length > 0 && supportedCultures.includes(pathSegments[0])) {
            pathSegments.shift();
        }
        
        // Build new path with selected culture
        const newPath = '/' + newCulture + (pathSegments.length > 0 ? '/' + pathSegments.join('/') : '');
        
        return newPath + queryString + hash;
    }
    
    // Handle language selection
    // Handle language selection
    languageDropdownItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.preventDefault();

            const selectedLang = this.getAttribute('data-lang');
            currentCulture = getCurrentCulture();

            // Track language change for analytics
            if (typeof window.trackLanguageChange === 'function') {
                window.trackLanguageChange(currentCulture, selectedLang);
            }

            // Store language preference in localStorage
            localStorage.setItem('preferredLanguage', selectedLang);

            // Set culture cookie for server-side processing
            document.cookie = `culture=${selectedLang}; path=/; max-age=31536000; SameSite=Lax`;

            // Navigate to new URL with selected language
            const newUrl = buildLocalizedUrl(selectedLang);
            window.location.href = newUrl;
        });
    });
    
    // Initialize current language display
    currentCulture = getCurrentCulture();
    updateCurrentLanguageDisplay(currentCulture);
    
    // Store current culture in localStorage if not already set
    if (!localStorage.getItem('preferredLanguage')) {
        localStorage.setItem('preferredLanguage', currentCulture);
    }
});

// Utility function to get user's preferred language
function getUserPreferredLanguage() {
    // Check localStorage first
    const storedLang = localStorage.getItem('preferredLanguage');
    if (storedLang) {
        return storedLang;
    }
    
    // Check browser language
    const browserLang = navigator.language || navigator.userLanguage;
    
    // Map browser languages to supported cultures
    const langMap = {
        'pt': 'pt-BR',
        'pt-BR': 'pt-BR',
        'es': 'es-PY',
        'es-PY': 'es-PY'
    };
    
    // Check exact match first
    if (langMap[browserLang]) {
        return langMap[browserLang];
    }
    
    // Check language part only (e.g., 'es' from 'es-AR')
    const langPart = browserLang.split('-')[0];
    if (langMap[langPart]) {
        return langMap[langPart];
    }

}


