document.addEventListener('DOMContentLoaded', function () {
    const translations = {
        ru: {
            title: "workshop",
            made_by: "Сделал: ©️𝙎𝙃∆𝙈∆𝙉©️",
            description: "Неофициальный сайт<br>с картами для CS:GO<br>из мастерской Steam",
            header: "CS:GO Workshop",
            contact: "Связаться",
            sort_by_date: "Сортировать по дате",
            show_products: "Показать продукты, попадающие в каждую из выбранных категорий:",
            game_modes: "РЕЖИМ ИГРЫ",
            game_mode_Classic: "Классический",
            game_mode_Deathmatch: "Бой насмерть",
            game_mode_Demolition: "Уничтожение объекта",
            game_mode_Armsrace: "Гонка вооружений",
            game_mode_Custom: "Пользовательский",
            game_mode_Training: "Обучение",
            "game_mode_Co-op Strike": "Совместный налёт",
            game_mode_Wingman: "Напарники",
            game_mode_Flying_Scoutsman: "Перелётные снайперы",
            search_placeholder: "Поиск по названию",
            from: "С",
            to: "ПО",
            ok: "ОК",
            cancel: "Отмена",
            filter_by_stars: "Фильтр по количеству звезд:"
        },
        en: {
            title: "Workshop",
            made_by: "Made by: ©️𝙎𝙃∆𝙈∆𝙉©️",
            description: "Unofficial site<br>with CS:GO maps<br>from Steam Workshop",
            header: "CS:GO Workshop",
            contact: "Contact",
            sort_by_date: "Sort by date",
            show_products: "Show products matching all selected categories:",
            game_modes: "GAME MODES",
            game_mode_Classic: "Classic",
            game_mode_Deathmatch: "Deathmatch",
            game_mode_Demolition: "Demolition",
            game_mode_Armsrace: "Arms Race",
            game_mode_Custom: "Custom",
            game_mode_Training: "Training",
            "game_mode_Co-op Strike": "Co-op Strike",
            game_mode_Wingman: "Wingman",
            game_mode_Flying_Scoutsman: "Flying Scoutsman",
            search_placeholder: "Search by title",
            from: "From",
            to: "To",
            ok: "OK",
            cancel: "Cancel",
            filter_by_stars: "Filter by number of stars:"
        }
    };

    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.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
            const key = element.getAttribute('data-i18n-placeholder');
            if (translations[lang][key]) {
                element.placeholder = translations[lang][key];
            } else {
                console.warn(`Placeholder translation missing for key: ${key} in language: ${lang}`);
            }
        });
        document.documentElement.lang = lang;
        localStorage.setItem('selectedLanguage', lang);
    }

    translatePage(defaultLang);

    const sortButton = document.querySelector('.sort-button');
    const modal = document.getElementById('sortModal');
    const closeButton = document.querySelector('.close-btn');
    const cancelButton = document.querySelector('.cancel-button');
    const okButton = document.querySelector('.ok-button');
    const startDateInput = document.querySelector('.first-rectangle .date-input');
    const endDateInput = document.querySelector('.second-rectangle .date-input');
    const checkboxes = document.querySelectorAll('.game-mode-checkbox');
    const params = new URLSearchParams(window.location.search);

    checkboxes.forEach(checkbox => {
        checkbox.checked = params.getAll('game_modes').includes(checkbox.value);
    });

    sortButton.addEventListener('click', function () {
        modal.style.display = 'block';
    });

    closeButton.addEventListener('click', function () {
        modal.style.display = 'none';
    });

    cancelButton.addEventListener('click', function () {
        modal.style.display = 'none';
    });

    okButton.addEventListener('click', function () {
        const startDate = startDateInput.value;
        const endDate = endDateInput.value;

        if (startDate) params.set('start_date', startDate);
        else params.delete('start_date');

        if (endDate) params.set('end_date', endDate);
        else params.delete('end_date');

        const selectedGameModes = Array.from(checkboxes)
            .filter(checkbox => checkbox.checked)
            .map(checkbox => checkbox.value);

        params.delete('game_modes');
        selectedGameModes.forEach(mode => params.append('game_modes', mode));

        params.set('page', 1);
        modal.style.display = 'none';
        window.location.search = params.toString();
    });

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            const selectedGameModes = Array.from(checkboxes)
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.value);

            params.delete('game_modes');
            selectedGameModes.forEach(mode => params.append('game_modes', mode));

            params.set('page', 1);
            window.location.search = params.toString();
        });
    });

    const searchInput = document.querySelector('.search-input');
    function performSearch() {
        const query = searchInput.value.toLowerCase();
        const cards = document.querySelectorAll('.card');

        cards.forEach(card => {
            const title = card.querySelector('.card-title').textContent.toLowerCase();
            if (title.includes(query)) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    }

    searchInput.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            performSearch();
        }
    });

    const searchButton = document.querySelector('.search-button');
    if (searchButton) {
        searchButton.addEventListener('click', performSearch);
    }

    const starsCheckboxes = document.querySelectorAll('input[name="stars"]');
    const selectedStars = params.get('stars');
    if (selectedStars) {
        starsCheckboxes.forEach(checkbox => {
            if (checkbox.value === selectedStars) {
                checkbox.checked = true;
            }
        });
    }

    starsCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            starsCheckboxes.forEach(otherCheckbox => {
                if (otherCheckbox !== checkbox) {
                    otherCheckbox.checked = false;
                }
            });

            const selectedStar = checkbox.checked ? checkbox.value : null;
            params.delete('stars');
            if (selectedStar) {
                params.set('stars', selectedStar);
            }

            params.set('page', 1);
            window.location.search = params.toString();
        });
    });
});