document.addEventListener('DOMContentLoaded', function() {
    const currentPath = window.location.pathname;
    const supportedLanguages = ['en', 'ru', 'es'];
    const browserLang = (navigator.language || navigator.userLanguage).split('-')[0];

    // Check if the current path already includes a supported language prefix
    const isOnLangPage = currentPath.startsWith('/en/') ||
                         currentPath.startsWith('/ru/') ||
                         currentPath.startsWith('/es/');

    if (!isOnLangPage) {
        // Redirect to the browser's language version if supported, otherwise default to English
        const targetLang = supportedLanguages.includes(browserLang) ? browserLang : 'en';
        // Construct the new URL, preserving the rest of the path if any
        let newPath = currentPath;
        if (!currentPath.startsWith('/en/') && !currentPath.startsWith('/ru/') && !currentPath.startsWith('/es/')) {
            newPath = '/' + targetLang + currentPath;
        }
        window.location.replace(newPath);
    }
});