/**
 * singleproduktvergleichtabellefilter.js
 *
 * JavaScript für Filter, Sortierung und Pagination in der Produktvergleichstabelle.
 *
 * @package boxyfy
 */

document.addEventListener("DOMContentLoaded", function() {
    const produktBoxen         = document.querySelectorAll(".produkt-box");
    const searchInput          = document.getElementById("produktSuche");
    const accordion            = document.querySelector(".accordion");
    const accordionContent     = document.querySelector(".accordion-content");
    const resetButton          = document.getElementById("resetFilters");
    const sliders              = document.querySelectorAll(".slider-range");
    const closeCross           = document.querySelector(".close-cross");
    const closeButtons         = document.querySelectorAll(".close-filter-button");
    const filterCheckboxes     = document.querySelectorAll(".filter-checkbox");
    const dealCheckbox         = document.getElementById("dealFilterCheckbox");
    const filterHeader         = document.querySelector(".filter-header");
    const paginationContainer  = document.querySelector(".tspagination-container");

    // Pagination-Einstellungen (wird per wp_localize_script übergeben)
    let currentPage = 1;
	// Pagination-Einstellungen (wird per wp_localize_script übergeben)
	const boxesPerPage = parseInt(boxyfy_filter_settings.boxesPerPage, 10) || 12;
	
    // Sortier-Parameter
    let currentSortOrder = "rank_asc";
    const sortButton = document.querySelector(".sort-button");
    const accordionLabel = accordion.querySelector(".accordion-tslabel");

    function scrollToProductContainer() {
        const container = document.getElementById("productListTop");
        if (!container) return;
        const rect = container.getBoundingClientRect();
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const offsetTop = rect.top + scrollTop - 80;
        window.scrollTo({ top: offsetTop, behavior: "smooth" });
    }

    function getVisibleBoxes() {
        const allBoxes = document.querySelectorAll(".produkt-box");
        return Array.from(allBoxes).filter(box => box.style.display !== "none");
    }

    function updateFilterCounts(visibleBoxes) {
        const filterItems = document.querySelectorAll(".listen-liste ul li");
        filterItems.forEach(li => {
            const checkbox = li.querySelector(".filter-checkbox");
            if (!checkbox) return;
            const filterName = checkbox.dataset.name;
            const filterValue = checkbox.dataset.filter;
            const countSpan = li.querySelector(".tsfilter-count");
            if (!countSpan) return;
            let count = 0;
            visibleBoxes.forEach(box => {
                const boxValue = box.getAttribute("data-" + filterName);
                if (boxValue === filterValue) {
                    count++;
                }
            });
            countSpan.textContent = count;
        });
    }

    function filterProducts() {
        const searchText = searchInput.value.toLowerCase();
        produktBoxen.forEach(box => {
            let show = true;
            sliders.forEach(slider => {
                const name = slider.id.split("_")[1];
                const minSlider = document.getElementById("minRangeSlider_" + name);
                const maxSlider = document.getElementById("maxRangeSlider_" + name);
                const boxValue = box.getAttribute("data-" + name);
                if (boxValue) {
                    const boxValueFloat = parseFloat(boxValue);
                    if (isNaN(boxValueFloat) ||
                        boxValueFloat < parseFloat(minSlider.value) ||
                        boxValueFloat > parseFloat(maxSlider.value)) {
                        show = false;
                    }
                } else {
                    if (parseFloat(minSlider.value) !== parseFloat(minSlider.min) ||
                        parseFloat(maxSlider.value) !== parseFloat(maxSlider.max)) {
                        show = false;
                    }
                }
            });
            filterCheckboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    const filterName = checkbox.dataset.name;
                    const filterValue = checkbox.dataset.filter;
                    const boxValue = box.getAttribute("data-" + filterName);
                    if (boxValue !== filterValue) {
                        show = false;
                    }
                }
            });
            if (dealCheckbox.checked) {
                const dealRibbon = box.querySelector(".produkt-deal-ribbon");
                if (!dealRibbon) {
                    show = false;
                }
            }
            const titleElement = box.querySelector(".produkt-titel a");
            if (titleElement) {
                const title = titleElement.innerText.toLowerCase();
                if (!title.includes(searchText)) {
                    show = false;
                }
            }
            box.style.display = show ? "block" : "none";
        });
        const visibleBoxes = getVisibleBoxes();
        updateFilterCounts(visibleBoxes);
    }

    function updateSliderValues(name) {
        const minSlider = document.getElementById("minRangeSlider_" + name);
        const maxSlider = document.getElementById("maxRangeSlider_" + name);
        const minValueLabel = document.getElementById("rangeMinValue_" + name);
        const maxValueLabel = document.getElementById("rangeMaxValue_" + name);
        const unit = minValueLabel.getAttribute("data-unit") || "";
        const sliderContainer = minSlider.parentElement.parentElement;
        const isDecimal = (sliderContainer.getAttribute("data-decimal") === "1");

        if (isDecimal) {
            minValueLabel.textContent = parseFloat(minSlider.value).toFixed(2) + " " + unit;
            maxValueLabel.textContent = parseFloat(maxSlider.value).toFixed(2) + " " + unit;
        } else {
            minValueLabel.textContent = parseInt(minSlider.value, 10) + " " + unit;
            maxValueLabel.textContent = parseInt(maxSlider.value, 10) + " " + unit;
        }
    }

    function sortProducts() {
        const order = currentSortOrder;
        const container = document.querySelector(".produkt-container");
        const products = Array.from(container.children);
        products.sort(function(a, b) {
            if (order === "rank_asc" || order === "rank_desc") {
                const rankA = parseInt(a.getAttribute("data-ranking"), 10) || 0;
                const rankB = parseInt(b.getAttribute("data-ranking"), 10) || 0;
                return (order === "rank_asc") ? (rankA - rankB) : (rankB - rankA);
            } else {
                const priceA = parseFloat(a.getAttribute("data-price")) || 0;
                const priceB = parseFloat(b.getAttribute("data-price")) || 0;
                return (order === "asc") ? (priceA - priceB) : (priceB - priceA);
            }
        });
        products.forEach(function(product) {
            container.appendChild(product);
        });
    }

    function showPage(pageNumber, visibleBoxes) {
        visibleBoxes.forEach(box => { box.style.display = "none"; });
        const startIndex = (pageNumber - 1) * boxesPerPage;
        const endIndex = startIndex + boxesPerPage;
        for (let i = startIndex; i < endIndex && i < visibleBoxes.length; i++) {
            visibleBoxes[i].style.display = "block";
        }
    }

    function renderPagination(visibleBoxes) {
        const totalBoxes = visibleBoxes.length;
        const totalPages = Math.ceil(totalBoxes / boxesPerPage);
        if (totalPages <= 1) {
            paginationContainer.innerHTML = "";
            return;
        }
        let html = "";
        if (currentPage > 1) {
            html += `<a href="#" class="pagination-prev" style="margin-right: 10px;">« Zurück</a>`;
        }
        for (let page = 1; page <= totalPages; page++) {
            if (page === currentPage) {
                html += `<strong style="margin: 0 6px;">[${page}]</strong>`;
            } else {
                html += `<a href="#" class="pagination-link" data-page="${page}" style="margin: 0 6px;">${page}</a>`;
            }
        }
        if (currentPage < totalPages) {
            html += `<a href="#" class="pagination-next" style="margin-left: 10px;">Weiter »</a>`;
        }
        paginationContainer.innerHTML = html;

        const pageLinks = paginationContainer.querySelectorAll(".pagination-link");
        pageLinks.forEach(link => {
            link.addEventListener("click", (e) => {
                e.preventDefault();
                currentPage = parseInt(link.getAttribute("data-page"), 10);
                showPage(currentPage, visibleBoxes);
                renderPagination(visibleBoxes);
                scrollToProductContainer();
            });
        });

        const prevLink = paginationContainer.querySelector(".pagination-prev");
        if (prevLink) {
            prevLink.addEventListener("click", (e) => {
                e.preventDefault();
                currentPage = Math.max(1, currentPage - 1);
                showPage(currentPage, visibleBoxes);
                renderPagination(visibleBoxes);
                scrollToProductContainer();
            });
        }

        const nextLink = paginationContainer.querySelector(".pagination-next");
        if (nextLink) {
            nextLink.addEventListener("click", (e) => {
                e.preventDefault();
                currentPage = currentPage + 1;
                showPage(currentPage, visibleBoxes);
                renderPagination(visibleBoxes);
                scrollToProductContainer();
            });
        }
    }

    function applyFiltersAndPagination() {
        sortProducts();
        filterProducts();
        const visibleBoxes = getVisibleBoxes();
        currentPage = 1;
        showPage(currentPage, visibleBoxes);
        renderPagination(visibleBoxes);
    }

    accordion.addEventListener("click", function() {
        const isVisible = accordionContent.classList.toggle("show");
        accordionLabel.textContent = isVisible ? "Filter schließen" : "Filter anzeigen";
        if (isVisible) {
            const stickyHeaderHeight = filterHeader.offsetHeight;
            const rect = accordionContent.getBoundingClientRect();
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const contentTop = rect.top + scrollTop;
            window.scrollTo({ top: contentTop - stickyHeaderHeight - 15, behavior: "smooth" });
        } else {
            const rect = filterHeader.getBoundingClientRect();
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const headerTop = rect.top + scrollTop;
            window.scrollTo({ top: headerTop, behavior: "smooth" });
        }
    });

    if (closeCross) {
        closeCross.addEventListener("click", function() {
            accordionContent.classList.remove("show");
            accordionLabel.textContent = "Filter anzeigen";
            const rect = filterHeader.getBoundingClientRect();
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const headerTop = rect.top + scrollTop;
            window.scrollTo({ top: headerTop, behavior: "smooth" });
        });
    }

    closeButtons.forEach(button => {
        button.addEventListener("click", function() {
            accordionContent.classList.remove("show");
            accordionLabel.textContent = "Filter anzeigen";
            const rect = filterHeader.getBoundingClientRect();
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const headerTop = rect.top + scrollTop;
            window.scrollTo({ top: headerTop, behavior: "smooth" });
        });
    });

    sliders.forEach(slider => {
        slider.addEventListener("input", function() {
            const name = this.id.split("_")[1];
            updateSliderValues(name);
            applyFiltersAndPagination();
        });
    });

    searchInput.addEventListener("input", applyFiltersAndPagination);

    filterCheckboxes.forEach(checkbox => {
        checkbox.addEventListener("change", applyFiltersAndPagination);
    });

    dealCheckbox.addEventListener("change", applyFiltersAndPagination);

    const nativeSortSelect = document.getElementById("boxyfy-native-sort");
	
    resetButton.addEventListener("click", function() {
        sliders.forEach(slider => {
            const name = slider.id.split("_")[1];
            const minSlider = document.getElementById("minRangeSlider_" + name);
            const maxSlider = document.getElementById("maxRangeSlider_" + name);
            minSlider.value = minSlider.min;
            maxSlider.value = maxSlider.max;
            updateSliderValues(name);
        });
        filterCheckboxes.forEach(checkbox => { checkbox.checked = false; });
        dealCheckbox.checked = false;
        searchInput.value = "";
        produktBoxen.forEach(box => { box.style.display = "block"; });
        applyFiltersAndPagination();
    });

    applyFiltersAndPagination();
	

	 const sortMenuButton = document.getElementById("boxyfy-sort-toggle");
const sortMenu = document.getElementById("boxyfy-sort-menu");

if (sortMenuButton && sortMenu) {
    // Toggle Menü anzeigen/verstecken
    sortMenuButton.addEventListener("click", (e) => {
        e.stopPropagation();
        sortMenu.style.display = (sortMenu.style.display === "flex") ? "none" : "flex";
    });

    // Klick auf Sortieroption
    sortMenu.querySelectorAll(".sort-option").forEach(option => {
        option.addEventListener("click", () => {
            currentSortOrder = option.getAttribute("data-sort");
            applyFiltersAndPagination();
            scrollToProductContainer();
            sortMenu.style.display = "none";

            // aktive Option hervorheben
            sortMenu.querySelectorAll(".sort-option").forEach(opt => opt.classList.remove("active"));
            option.classList.add("active");
        });
    });

    // Klick außerhalb schließt das Menü
    document.addEventListener("click", (e) => {
        if (!sortMenu.contains(e.target) && !sortMenuButton.contains(e.target)) {
            sortMenu.style.display = "none";
        }
    });
}

	
});
