// Variables globales
let filters = {
    categories: [],
    subcategories: [],
    types: [],
    minPrice: 0,
    maxPrice: 500,
    search: "",
};

// Obtiene los filtros seleccionados del DOM
function getSelectedFilters() {
    // Recoge los checkboxes de categorías, subcategorías y tipos
    filters.categories = Array.from(
        document.querySelectorAll(".category-checkbox:checked")
    ).map((cb) => cb.value);
    filters.subcategories = Array.from(
        document.querySelectorAll(".subcategory-checkbox:checked")
    ).map((cb) => cb.value);
    filters.types = Array.from(
        document.querySelectorAll(".type-checkbox:checked")
    ).map((cb) => cb.value);

    // Recoge el input de búsqueda
    const searchInput = document.getElementById("search-input");
    filters.search = searchInput ? searchInput.value : "";

    // Recoge los inputs de precio mínimo y máximo
    const minPriceInput = document.getElementById("min-price");
    const maxPriceInput = document.getElementById("max-price");
    filters.minPrice = minPriceInput ? parseInt(minPriceInput.value) : 0;
    filters.maxPrice = maxPriceInput ? parseInt(maxPriceInput.value) : 500;

    // Devuelve los filtros actuales
    return { ...filters };
}

// Función auxiliar para obtener el badge de tipo de curso
function getIconBadge(type) {
    switch (type) {
        case "free":
            return `<i class="fas fa-check-circle me-1"></i> Free`;
        case "pay":
            return `<i class="fas fa-dollar-sign me-1"></i> Paid`;
        case "premium":
            return `<i class="fas fa-money-bill me-1"></i> Premium`;
        default:
            return `<i class="fas fa-question-circle me-1"></i> Unknown`;
    }
}

// Función auxiliar para obtener la clase de badge de tipo de curso
function getBadgeClass(type) {
    switch (type) {
        case "free":
            return "badge bg-success";
        case "pay":
            return "badge bg-warning";
        case "premium":
            return "badge bg-danger";
        default:
            return "badge bg-secondary";
    }
}

// Función para renderizar las tarjetas de cursos
function renderCoursesCards(data) {
    const coursesContainer = document.getElementById("course-results");

    coursesContainer.innerHTML = ""; // Limpia el contenedor

    if (!data || data.length === 0) {
        coursesContainer.innerHTML = `
            <div class="alert text-center text-danger bg-light" role="alert">
            Oops! No courses found with the selected filters.
            </div>
        `;
        return;
    }

    data.forEach((course) => {
        const courseCard = document.createElement("div");
        courseCard.className = "col-md-4";
        courseCard.innerHTML = `
            <div class="card h-100 shadow-sm">
                <div class="card-body card-body-course">
                    <div class="position-relative">
                        <img src="/img/coverIMG/cover${course.id}.jpg"
                            class="imgCourse img-fluid rounded-top w-100" alt="${
                                course.title
                            } Cover"
                            style="height: 180px; object-fit: cover;">
                        <span
                            class="position-absolute top-0 end-0 m-2 badge bg-white textOrange rounded-pill">
                            ${getIconBadge(course.type)}
                        </span>
                    </div>
                    <div class="p-3">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <h5 class="card-title mb-0 flex-grow-1 text-truncate pe-2 fw-bold">
                                ${course.title}
                            </h5>
                            <span class="badge bg-custom-purple text-white rounded-pill">
                                ${course.subcategory?.category?.name || ""}
                            </span>
                        </div>
                        <p class="card-text text-muted small mb-2 line-clamp-2" style="height: 40px;">
                            ${course.description}
                        </p>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <small class="text-muted">
                                <i class="fas fa-coins me-1"></i>
                                ${course.coins} coins
                            </small>
                            <small class="text-muted">
                                <i class="far fa-calendar-alt me-1"></i>
                                Published: ${
                                    course.published_date
                                        ? new Date(
                                              course.published_date
                                          ).toLocaleDateString("en-US", {
                                              month: "short",
                                              day: "2-digit",
                                              year: "numeric",
                                          })
                                        : ""
                                }
                            </small>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <small class="text-white bg-custom-orange rounded-pill px-2">
                                ${course.subcategory?.name || ""}
                            </small>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent border-top-0 pb-3 pt-0">
                    <a href="/course/info/${
                        course.id
                    }" class="btn btn1 w-100 m-0">View Course</a>
                </div>
            </div>
        `;
        coursesContainer.appendChild(courseCard);
    });

    return;
}

// Función para renderizar la paginación
function renderPagination(pagination) {
    const paginationContainer = document.getElementById("pagination");
    paginationContainer.innerHTML = ""; // Limpia el contenedor

    if (!pagination) return;

    const { current_page, last_page, total } = pagination;

    // Botones prev/next y primera/última página
    let html = `
        <nav aria-label="Course pagination">
            <ul class="pagination justify-content-center mb-1">
                <li class="page-item${current_page === 1 ? ' disabled' : ''}">
                    <a class="page-link" href="#" data-page="1" tabindex="-1" aria-label="First">
                        <span class="textBlue" aria-hidden="true">&laquo;&laquo;</span>
                    </a>
                </li>
                <li class="page-item${current_page === 1 ? ' disabled' : ''} bg-custom">
                    <a class="page-link" href="#" data-page="${current_page - 1}" tabindex="-1" aria-label="Previous">
                        <span class="textBlue" aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <li class="page-item disabled">
                    <span class="page-link bg-light text-dark border-0" style="pointer-events:none;">
                        Page ${current_page} of ${last_page}
                    </span>
                </li>
                <li class="page-item${current_page === last_page ? ' disabled' : ''}">
                    <a class="page-link" href="#" data-page="${current_page + 1}" aria-label="Next">
                        <span class="textBlue" aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <li class="page-item${current_page === last_page ? ' disabled' : ''}">
                    <a class="page-link" href="#" data-page="${last_page}" aria-label="Last">
                        <span class="textBlue" aria-hidden="true">&raquo;&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
        <div class="text-center small text-muted m-3">
            Found ${total} courses
        </div>
    `;

    paginationContainer.innerHTML = html;

    // Eventos para paginación
    paginationContainer.querySelectorAll('.page-link[data-page]').forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const page = parseInt(this.dataset.page);
            if (!isNaN(page) && page >= 1 && page <= last_page && page !== current_page) {
                const filters = getSelectedFilters();
                filters.page = page;
                fetchCourses(filters);
            }
        });
    });
}

// Realiza la petición fetch para obtener los cursos filtrados
function fetchCourses(currentFilters) {
    const queryString = new URLSearchParams(currentFilters).toString();

    fetch(`/api/courses?${queryString}`)
        .then((response) => {
            if (!response.ok) throw new Error("Network response was not ok");
            return response.json();
        })
        .then((data) => {
            renderCoursesCards(data.data); // Renderiza las tarjetas de cursos

            // Solo renderiza la paginación si hay resultados
            if (data.data && data.data.length > 0) {
                renderPagination(data.pagination);
            } else {
                document.getElementById("pagination").innerHTML = "";
            }
        })
        .catch((error) => {
            console.error("Error fetching courses:", error);
        });
}

// Aplica los filtros actuales y actualiza la vista
function applyFilters() {
    const selectedFilters = getSelectedFilters();
    fetchCourses(selectedFilters);
}

function clearFilters() {
    // Limpia los checkboxes de categorías, subcategorías y tipos
    document
        .querySelectorAll(
            ".category-checkbox, .subcategory-checkbox, .type-checkbox"
        )
        .forEach((cb) => (cb.checked = false));

    // Cierra solo los collapses de subcategorías que están abiertos
    document
        .querySelectorAll('.collapse.show[id^="subcategory-list-"]')
        .forEach((el) => {
            const collapseInstance = bootstrap.Collapse.getOrCreateInstance(el);
            collapseInstance.hide();
        });

    // Limpia el input de búsqueda
    const searchInput = document.getElementById("search-input");
    if (searchInput) searchInput.value = "";

    // Reinicia los precios a sus valores por defecto
    const minPriceInput = document.getElementById("min-price");
    const maxPriceInput = document.getElementById("max-price");
    if (minPriceInput) minPriceInput.value = 0;
    if (maxPriceInput) maxPriceInput.value = 500;

    // Pone los sliders a sus valores por defecto
    const minRange = document.querySelector('.min-range');
    const maxRange = document.querySelector('.max-range');

    if (minRange) minRange.value = 0;
    if (maxRange) maxRange.value = 500;

    // Actualiza visualización del rango de precio
    updateSliderRange();

    applyFilters();
}

// Prepara los botones de filtro
function setupButtons() {
    const applyFiltersButton = document.getElementById("btn-apply");
    const clearFiltersButton = document.getElementById("btn-clear");
    const searchInput = document.getElementById("search-input");

    if (applyFiltersButton) {
        applyFiltersButton.addEventListener("click", applyFilters);
    }
    if (clearFiltersButton) {
        clearFiltersButton.addEventListener("click", clearFilters);
    }
    if (searchInput) {
        // Debounce para el input de búsqueda
        let debounceTimeout;
        searchInput.addEventListener("input", function () {
            clearTimeout(debounceTimeout);
            debounceTimeout = setTimeout(() => {
                applyFilters();
            }, 500);
        });
    }
}

// --- Adaptación: Slider de rango de precio visual y funcional ---
function updateSliderRange() {
    const minRange = document.querySelector('.min-range');
    const maxRange = document.querySelector('.max-range');
    const sliderRange = document.querySelector('.slider-range');

    if (!minRange || !maxRange || !sliderRange) return;

    let min = parseInt(minRange.value);
    let max = parseInt(maxRange.value);
    let sliderMin = parseInt(minRange.min || 0);
    let sliderMax = parseInt(maxRange.max || 500);
    let total = sliderMax - sliderMin;

    // Asegura el mínimo gap visual (al menos 1)
    if (max < min + 1) {
        max = min + 1;
        maxRange.value = max;
    }
    if (min > max - 1) {
        min = max - 1;
        minRange.value = min;
    }

    let leftPercent = ((min - sliderMin) / total) * 100;
    let rightPercent = ((max - sliderMin) / total) * 100;

    sliderRange.style.left = leftPercent + "%";
    sliderRange.style.width = (rightPercent - leftPercent) + "%";
}

// Función para configurar el rango de precios mediante el slider
function setupPriceRange() {
    const minPriceInput = document.getElementById('min-price');
    const maxPriceInput = document.getElementById('max-price');
    const minRange = document.querySelector('.min-range');
    const maxRange = document.querySelector('.max-range');

    let minVal = parseInt(minRange.value);
    let maxVal = parseInt(maxRange.value);

    minRange.addEventListener('input', function() {
        minVal = parseInt(this.value);
        if (minVal > maxVal - 1) {
            minVal = maxVal - 1;
            this.value = minVal;
        }
        minPriceInput.value = minVal;
        updateSliderRange();
        // applyFilters();
    });

    maxRange.addEventListener('input', function() {
        maxVal = parseInt(this.value);
        if (maxVal < minVal + 1) {
            maxVal = minVal + 1;
            this.value = maxVal;
        }
        maxPriceInput.value = maxVal;
        updateSliderRange();
        // applyFilters();
    });

    minPriceInput.addEventListener('input', function() {
        minVal = parseInt(this.value) || 0;
        if (minVal < 0) minVal = 0;
        if (minVal > 500) minVal = 500;
        if (minVal > maxVal - 1) minVal = maxVal - 1;
        minRange.value = minVal;
        this.value = minVal;
        updateSliderRange();
        // applyFilters();
    });

    maxPriceInput.addEventListener('input', function() {
        maxVal = parseInt(this.value) || 500;
        if (maxVal > 500) maxVal = 500;
        if (maxVal < minVal + 1) maxVal = minVal + 1;
        maxRange.value = maxVal;
        this.value = maxVal;
        updateSliderRange();
        // applyFilters();
    });

    // Inicializa el estilo visual del rango
    updateSliderRange();
}

// Inicializa la página
function init() {
    setupButtons(); // Configura los botones de filtro
    setupPriceRange(); // Configura el rango de precios visual y funcional
    applyFilters(); // Aplica los filtros al cargar la página
}

document.addEventListener("DOMContentLoaded", init);