document.addEventListener('DOMContentLoaded', function() {
    const courseStatus = document.getElementById('courseStatus');

    courseStatus.addEventListener('change', function() {
        const status = this.value;

        fetch('/filter-courses', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({ status: status })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.error || 'Error al filtrar los cursos');
                    });
                }
                return response.json();
            })
            .then(data => {

                const container = document.getElementById('coursesContainer');

                if (!data.courses || data.courses.length === 0) {
                    container.innerHTML = `
                    <div class="alert alert-warning text-center shadow-sm" role="alert">
                        Not found courses with this status.
                    </div>
                `;
                    return;
                }

                let html = '<div class="row">';
                data.courses.forEach(course => {
                    const isFavorited = course.favorite == 1;

                    html += `
                    <div class="col-md-3 mb-4">
                        <div class="card h-100">
                            <div class="card-body card-body-course">
                                <p class="card-text card-img">
                                    <img src="/img/coverIMG/cover${course.id}.jpg" class="imgCourse" alt="Course Cover" />
                                </p>
                                <div class="d-flex justify-content-between align-items-start padding-card gap-2">
                                    <h5 class="card-title mb-0 flex-grow-1 text-truncate" style="max-width: 70%;">${course.title}</h5>

                                    <div class="d-flex align-items-center flex-shrink-0">
                                    <small class="text-muted me-1 favorite-count">${course.favorites}</small>
                                        <button class="favorite-btn border-0 bg-transparent p-0" data-course-id="${course.id}" data-url="/course/toggle-favorite">
                                            <svg class="corazon ${isFavorited ? 'active' : ''}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                                            <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
                                            </svg>
                                        </button>
                                    </div>
                                </div>

                                <p class="card-text padding-card d-flex justify-content-between">
                                    <small class="text-muted">
                                        Status: ${(course.status_id === 2 || course.status_id === 3) ? 'Not completed' : 'Completed'}
                                    </small>
                                </p>
                            </div>
                            <div class="card-footer">
                                <a href="/course/info/${course.id}" class="btn btn1 w-100 mx-0">View Course</a>
                            </div>
                        </div>
                    </div>
                `;
                });
                html += '</div>';
                container.innerHTML = html;

                // Reinicializa los botones de favoritos después de renderizar
                if (typeof initFavoriteButtons === 'function') {
                    initFavoriteButtons();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                const container = document.getElementById('coursesContainer');
                container.innerHTML = `
                <div class="alert alert-danger">
                    ${error.message}
                </div>
            `;
            });
    });

    function initFavoriteButtons() {
        document.querySelectorAll('.favorite-btn').forEach(button => {
            button.addEventListener('click', function() {
                const courseId = this.getAttribute('data-course-id');
                const svg = this.querySelector('svg.corazon');
                const countSpan = this.parentElement.querySelector('.favorite-count');
                let count = parseInt(countSpan.textContent);

                const isLiked = svg.classList.contains('active');
                if (isLiked) {
                    count--;
                    svg.classList.remove('active');
                } else {
                    count++;
                    svg.classList.add('active');
                }
                countSpan.textContent = count;

                fetch(this.dataset.url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        },
                        body: JSON.stringify({ course_id: courseId })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (!data.success) {
                            if (svg.classList.contains('active')) {
                                svg.classList.remove('active');
                                countSpan.textContent = count - 1;
                            } else {
                                svg.classList.add('active');
                                countSpan.textContent = count + 1;
                            }
                        }
                    });
            });
        });
    }

    // Exporta la función para que el otro script la pueda usar
    window.initFavoriteButtons = initFavoriteButtons;

    // Llama una vez al cargar
    document.addEventListener('DOMContentLoaded', initFavoriteButtons);

});