'use strict'; // Cookie-based redirection (function () { const SUPPORTED_LANGS = new Set(['en', 'pt-BR', 'es-ES']); const DEFAULT_LANG = [...SUPPORTED_LANGS][0]; const COOKIE_NAME = 'lang'; const COOKIE_DELIMITER = '|||'; function getCurrentLang() { const [, lang] = window.location.pathname.match(/\/([a-z]{2}-[a-z]{2})(\/|$)/) || []; const detectedLang = lang || DEFAULT_LANG; console.log('[LANGUAGE SYNC]: Current language detected:', detectedLang); return detectedLang; } function normalizePath(path) { return path || '/'; } function buildNewPath(targetLang, currentLang, currentPath) { let newPath = currentPath; if (currentLang !== DEFAULT_LANG) { newPath = newPath.replace(`/${currentLang}`, ''); } if (targetLang !== DEFAULT_LANG) { newPath = `/${targetLang}${newPath === '/' ? '' : newPath}`; } return normalizePath(newPath); } function redirectToLang(lang) { console.log( '[LANGUAGE SYNC]: Received request to redirect to language:', lang ); const normalizedTargetLang = lang.toLowerCase(); const currentLang = getCurrentLang(); if (currentLang === normalizedTargetLang) { console.log( '[LANGUAGE SYNC]: Language matches current page, no redirect needed' ); return; } const newPath = buildNewPath( normalizedTargetLang, currentLang, window.location.pathname ); const newUrl = `${newPath}${window.location.search}${window.location.hash}`; if ( newUrl !== `${window.location.pathname}${window.location.search}${window.location.hash}` ) { console.log('[LANGUAGE SYNC]: Performing redirect to:', newUrl); window.location.href = newUrl; } } function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) { const lastPart = parts.pop(); if (lastPart) { const cookieValue = lastPart.split(';').shift(); return cookieValue ? decodeURIComponent(cookieValue) : undefined; } } return undefined; } function getTargetLangFromCookie() { const cookieValue = getCookie(COOKIE_NAME); // no cookie found if (!cookieValue) { console.log('[LANGUAGE SYNC]: No valid language cookie found'); return null; } const langPart = cookieValue.split(COOKIE_DELIMITER)[0]; // fallback to default lang if language is not supported if (!SUPPORTED_LANGS.has(langPart)) { console.log( '[LANGUAGE SYNC]: Unsupported language in cookie:', langPart, 'defaulting to:', DEFAULT_LANG ); return DEFAULT_LANG; } // valid language found in cookie console.log('[LANGUAGE SYNC]: Found language in cookie:', langPart); return langPart; } function attemptCookieBasedRedirect() { const targetLang = getTargetLangFromCookie(); if (!targetLang) { return; } redirectToLang(targetLang); } attemptCookieBasedRedirect(); })();