document.addEventListener('DOMContentLoaded', () => {
    const translations = {
        ru: {
            title: "workshop",
            download: "Скачать",
            game_mode_label: "Режим игры:",
            tags_label: "Метки:",
            file_size_label: "Размер файла:",
            added_time_label: "Добавлен:"
        },
        en: {
            title: "Workshop",
            download: "Download",
            game_mode_label: "Game Mode:",
            tags_label: "Tags:",
            file_size_label: "File Size:",
            added_time_label: "Added:"
        }
    };

    const savedLang = localStorage.getItem('selectedLanguage');
    const browserLang = (navigator.language || navigator.userLanguage).split('-')[0];
    const defaultLang = savedLang && translations[savedLang] ? savedLang : (translations[browserLang] ? browserLang : 'ru');

    function translatePage(lang) {
        document.querySelectorAll('[data-i18n]').forEach(element => {
            const key = element.getAttribute('data-i18n');
            if (translations[lang][key]) {
                element.innerHTML = translations[lang][key];
            } else {
                console.warn(`Translation missing for key: ${key} in language: ${lang}`);
            }
        });
        document.documentElement.lang = lang;
        localStorage.setItem('selectedLanguage', lang);
    }

    function convertBBCodeToMarkdown(text) {
        let converted = text
            .replace(/\n\s*\n/g, '\n\n') // Убираем лишние пробелы между строками
            .trim();

        // Преобразование [h1] и [h3] в Markdown-заголовки
        converted = converted.replace(/\[h1\](.*?)\[\/h1\]/g, '# $1');
        converted = converted.replace(/\[h3\](.*?)\[\/h3\]/g, '### $1');

        // Преобразование изображений и ссылок
        converted = converted.replace(/\[url=([^\]]+)\]\[img\]([^\[]+)\[\/img\]\[\/url\]/g, '[![]($2)]($1)');
        converted = converted.replace(/\[img\]([^\[]+)\[\/img\]/g, '![]($1)');
        converted = converted.replace(/\[url=([^\]]+)\]([^\[]+)\[\/url\]/g, '[$2]($1)');

        return converted;
    }

    function renderDescription() {
        const descriptionElement = document.querySelector('.description');
        if (descriptionElement && window.marked) {
            const rawText = descriptionElement.textContent;
            const markdownText = convertBBCodeToMarkdown(rawText);
            descriptionElement.innerHTML = marked.parse(markdownText);
        } else {
            console.warn('Marked.js не загружен или элемент .description не найден');
        }
    }

    translatePage(defaultLang);
    renderDescription();

    const cards = document.querySelectorAll('.card');
    cards.forEach(card => {
        card.addEventListener('click', () => {
            window.location.href = '/main';
        });
    });
});