document.addEventListener('DOMContentLoaded', function() {
    const difficultyFilter = document.getElementById('difficulty-filter');
    const learningStyleFilter = document.getElementById('learning-style-filter');
    const sortBy = document.getElementById('sort-by');
    const challengeList = document.querySelector('.challenge-list');

    if (difficultyFilter) {
        function fetchChallenges() {
            const difficulty = difficultyFilter.value;
            const learningStyle = learningStyleFilter.value;
            const sort = sortBy.value;

            const formData = new FormData();
            formData.append('difficulty', difficulty);
            formData.append('learning_style', learningStyle);
            formData.append('sort_by', sort);

            fetch('api/filter_challenges.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                challengeList.innerHTML = data;
            });
        }

        difficultyFilter.addEventListener('change', fetchChallenges);
        learningStyleFilter.addEventListener('change', fetchChallenges);
        sortBy.addEventListener('change', fetchChallenges);
    }

    const runCodeBtn = document.getElementById('run-code');
    if (runCodeBtn) {
        runCodeBtn.addEventListener('click', function() {
            const solution = document.getElementById('solution').value;
            const language = document.getElementById('language').value;
            const challengeId = document.querySelector('input[name="challenge_id"]').value;

            const formData = new FormData();
            formData.append('solution', solution);
            formData.append('language', language);
            formData.append('challenge_id', challengeId);

            fetch('api/run_code.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                const outputDiv = document.getElementById('output');
                outputDiv.innerHTML = data;
            });
        });
    }
});
