// Language switching functionality for QR Rapido
// SEO Strategy:
// - Portuguese (pt-BR): URLs without prefix (/, /pix, /wifi, etc.) - canonical
// - Spanish (es):       URLs with /es prefix (/es, /es/pix, etc.)
// - English (en):       URLs with /en prefix (/en, /en/pix, etc.)

document.addEventListener('DOMContentLoaded', function () {
    const languageDropdownItems = document.querySelectorAll('.dropdown-item[data-lang]');
    const currentLangSpan = document.getElementById('current-lang');

    // Cultures that use a URL prefix
    const prefixedCultures = ['es', 'en'];

    // Get current culture from URL
    function getCurrentCulture() {
        const pathSegments = window.location.pathname.split('/').filter(segment => segment);
        if (pathSegments.length > 0) {
            const first = pathSegments[0].toLowerCase();
            if (first === 'es-py' || first === 'es') return 'es';
            if (first === 'en')    return 'en';
        }
        return 'pt-BR'; // Default — no prefix
    }

    // Update current language display in header
    function updateCurrentLanguageDisplay(culture) {
        const langMap = {
            'pt-BR': 'PT',
            'es':    'ES',
            'en':    'EN'
        };
        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;

        // Strip any existing culture prefix
        let pathSegments = currentPath.split('/').filter(segment => segment);
        if (pathSegments.length > 0) {
            const first = pathSegments[0].toLowerCase();
            if (first === 'es-py' || first === 'es' || first === 'pt-br' || first === 'en') {
                pathSegments.shift();
            }
        }

        const rest = pathSegments.length > 0 ? '/' + pathSegments.join('/') : '';

        let newPath;
        if (newCulture === 'pt-BR') {
            // Portuguese: no prefix (canonical URLs)
            newPath = rest || '/';
        } else {
            // Spanish / English: add culture prefix
            newPath = '/' + newCulture + rest;
        }

        return newPath + queryString + hash;
    }

    // Set culture cookie
    function setCultureCookie(culture) {
        // ASP.NET Core culture cookie format
        const cookieValue = `c=${culture}|uic=${culture}`;
        document.cookie = `.AspNetCore.Culture=${encodeURIComponent(cookieValue)}; path=/; max-age=31536000; SameSite=Lax`;

        // Also store in localStorage for quick access
        localStorage.setItem('preferredLanguage', culture);
    }

    // Handle language selection
    languageDropdownItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.preventDefault();

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

            // Don't do anything if same language selected
            if (selectedLang === currentCulture) {
                return;
            }

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

            // Save preference
            setCultureCookie(selectedLang);

            // Navigate to new URL with selected language
            const newUrl = buildLocalizedUrl(selectedLang);
            window.location.href = newUrl;
        });
    });

    // Initialize
    const currentCulture = getCurrentCulture();
    updateCurrentLanguageDisplay(currentCulture);

    // Ensure cookie matches URL culture
    setCultureCookie(currentCulture);
});

// Utility function to get user's preferred language (for external use)
function getUserPreferredLanguage() {
    const storedLang = localStorage.getItem('preferredLanguage');
    if (storedLang) {
        return storedLang;
    }
    return 'pt-BR'; // Default
}
