let cache_data;

window.addEventListener("load", async (event) => {
    let debug_cache = document.querySelector(".rdg-injury-report .filter").getAttribute("data-debug-cache");
    cache_data = await getCacheData();

    if (debug_cache) {
        console.log(cache_data);
    }

    updateFilters();
    getResults();
});

document.addEventListener("change", function (e) {
    if (e.target.matches("select.rdg_injury_report_leagues")) {
        e.preventDefault();
        const ajax_url = rdg_injury_report_var.ajaxurl;
        let league = document.querySelector("select.rdg_injury_report_leagues option:checked").value;

        if (league == "") {
            document.querySelector(".acf-field-key-rdg-injury-report-teams select").innerHTML = "";
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_teams_sports&league=${league}`,
        })
        .then((response) => response.text())
        .then((resultado) => {
            document.querySelector(
                ".acf-field-key-rdg-injury-report-teams select"
            ).innerHTML = resultado;
        })
        .catch((err) => console.error(err));
    } else if (e.target.matches(".rdg-injury-report .options select")) {
        document.querySelector(".rdg-injury-report .filter").setAttribute("data-current-page", 1);
        updateFilters();
        getResults();
    }
});

document.addEventListener("keypress", function (e) {
    if (e.target.matches(".rdg-injury-report #search.search")) {
        if (e.key == "Enter") {
            document.querySelector(".rdg-injury-report .filter").setAttribute("data-current-page", 1);
            updateFilters();
            getResults();
        }
    }
});

document.addEventListener("click", function (e) {
    if (e.target.matches(".rdg-injury-report .results .filter-clear")) {
        let type = e.target.getAttribute("data-clear");
        let filters = ["search", "location", "status", "display-status"];

        if (type == "all") {
            filters.forEach(function (item) {
                document.querySelector(".rdg-injury-report #" + item).value ="";
            });
        } else {
            document.querySelector(".rdg-injury-report #" + type).value = "";
        }

        updateFilters();
        getResults();
    } else if (e.target.matches(".rdg-injury-report .pagination-result a")) {
        updateFilters();
        getResults();
    }
});

function getFilterActive() {
    let count = 0;
    let filters = ["search", "location", "status", "display-status"];

    filters.forEach(function (item) {
        if (document.getElementById("filter-" + item) != null) {
            count++;
        }
    });

    return count;
}

function updateFilters() {
    let results = "";
    let count = 0;
    let filters_label = [];
    filters_label["display-status"] = "display status";
    let filters = ["search", "location", "status", "display-status"];

    filters.forEach(function (item) {
        let filter = document.querySelector(".rdg-injury-report #" + item);
        let label = filters_label[item] !== undefined ? filters_label[item] : item;

        if (filter != null && filter.value != "") {
            count++;
            results += `<a id="filter-${item}" class="filter-clear" data-clear="${item}"><b class="filter-clear" data-clear="${item}">${label}:</b> ${filter.value}</a>`;
        }
    });

    if (count != 0) {
        results += `<a id="filter-all" class="filter-clear" data-clear="all">Clear</a>`;
    }

    document.querySelector(".rdg-injury-report section.results").innerHTML =
        results;
}

function getResults() {
    let search = document.querySelector(".rdg-injury-report #search").value;
    let location = document.querySelector(".rdg-injury-report #location option:checked").value;
    let status = document.querySelector(".rdg-injury-report #status option:checked").value;
    let display_status = document.querySelector(".rdg-injury-report #display-status option:checked").value;
    let injuries_filters = [];
    document.querySelector(".rdg-injury-report .injuries").innerHTML = "";

    if (Array.isArray(cache_data) && cache_data.length > 0) {
        cache_data.forEach((injury) => {
            if (isFoundFilter(injury, search, location, status, display_status)) {
                injuries_filters.push(injury);
            }
        });

        updatePagination(injuries_filters);
        showPage(injuries_filters);

        return;
    }

    getCacheData().then((injuries) => {
        if (Array.isArray(injuries) && injuries.length > 0) {
            injuries.forEach((injury) => {
                if (isFoundFilter(injury, search, location, status, display_status)) {
                    injuries_filters.push(injury);
                }
            });

            updatePagination(injuries_filters);
            showPage(injuries_filters);
        } else {
            console.log("RDG Blocks: Records could not be obtained.");
        }
    });
}

function createInjuryElement(injury) {
    const injuryDiv = document.createElement("div");
    injuryDiv.className = "injury";

    const playerDiv = document.createElement("div");
    playerDiv.className = "player";
    const playerSpan = document.createElement("span");
    playerSpan.innerHTML = `<b>Player:</b> ${injury.player_id}`;
    playerDiv.appendChild(playerSpan);
    injuryDiv.appendChild(playerDiv);

    const contentDiv = document.createElement("div");
    contentDiv.className = "content";

    const locationSpan = document.createElement("span");
    locationSpan.className = "location";
    locationSpan.innerHTML = `<b>Location:</b> ${injury.location}`;
    contentDiv.appendChild(locationSpan);

    const startDateSpan = document.createElement("span");
    startDateSpan.className = "start-date";
    startDateSpan.innerHTML = `<b>Start Date:</b> ${injury.start_date}`;
    contentDiv.appendChild(startDateSpan);

    const statusSpan = document.createElement("span");
    statusSpan.className = "status";
    statusSpan.innerHTML = `<b>Status:</b> ${injury.status}`;
    contentDiv.appendChild(statusSpan);

    const displayStatusSpan = document.createElement("span");
    displayStatusSpan.className = "display-status";
    displayStatusSpan.innerHTML = `<b>Display Status:</b> ${injury.display_status}`;
    contentDiv.appendChild(displayStatusSpan);

    injuryDiv.appendChild(contentDiv);

    const noteDiv = document.createElement("div");
    noteDiv.className = "note";
    noteDiv.innerHTML = `<b>Note:</b> ${injury.note}`;
    injuryDiv.appendChild(noteDiv);

    return injuryDiv;
}

function isFoundFilter(injury, search, location, status, display_status) {
    if (location && location.toLowerCase() !== injury.location.toLowerCase()) {
        return false;
    }

    if (status && status.toLowerCase() !== injury.status.toLowerCase()) {
        return false;
    }

    if (display_status && display_status.toLowerCase() !== injury.display_status.toLowerCase()) {
        return false;
    }

    if (search) {
        const injuryCopy = { ...injury };
        delete injuryCopy.location;
        delete injuryCopy.status;
        delete injuryCopy.display_status;

        const injuryString = JSON.stringify(injuryCopy).toLowerCase();
        if (!injuryString.includes(search.toLowerCase())) {
            return false;
        }
    }

    return true;
}

async function getCacheData() {
    let file = "";
    let injuries = {};
    let cache_file = document.querySelector(".rdg-injury-report .filter").getAttribute("data-cache-file");

    if (rdg_blocks.cache_dir !== "" && cache_file !== "") {
        file = rdg_blocks.cache_dir + cache_file;
    }

    try {
        const response = await fetch(file);
        if (!response.ok) {
            return {};
        }

        const data = await response.json();
        if (data[0]["data-content"][0][0]["injuries"] !== undefined) {
            injuries = data[0]["data-content"][0][0]["injuries"];
        }
    } catch (error) {
        return {};
    }

    return injuries;
}

function updatePagination(injuries) {
    let totalItems = injuries.length;
    let filterElement = document.querySelector(".rdg-injury-report .filter");
    let itemsPerPage = parseInt(filterElement.getAttribute("data-items-per-page"));
    let totalPages = Math.ceil(totalItems / itemsPerPage);
    let page = parseInt(filterElement.getAttribute("data-current-page"));
    let paginationSection = document.querySelector(".rdg-injury-report section.pagination-result");
    let range = 3

    let root = document.querySelector(":root");
    let roots = getComputedStyle(root);
    let breakpoint_md = parseInt(roots.getPropertyValue("--breakpoint-md"));
    let breakpoint_sm = parseInt(roots.getPropertyValue("--breakpoint-sm"));

    if (breakpoint_md > screen.width) {
        range = 2;
    }
    
    if (breakpoint_sm > screen.width) {
        range = 1;
    }

    paginationSection.innerHTML = "";
    let paginationHTML = paginateLinks(totalPages, page, range);

    paginationHTML.forEach((menu) => {
        if (menu.class != 'dots') {
            let pageLink = document.createElement("a");
            pageLink.href = "#";
            pageLink.innerText = menu.label;
            pageLink.className = menu.class;
            pageLink.classList.add("pagination-link");

            pageLink.addEventListener("click", (event) => {
                event.preventDefault();
                filterElement.setAttribute("data-current-page", menu.page);
            });

            paginationSection.appendChild(pageLink);
        } else {
            let pageLink = document.createElement("span");
            pageLink.innerText = menu.label;
            pageLink.className = menu.class;
            paginationSection.appendChild(pageLink);
        }
    });
}

function showPage(injuries) {
    let filterElement = document.querySelector(".rdg-injury-report .filter");
    let page = filterElement.getAttribute("data-current-page");
    let itemsPerPage = parseInt(filterElement.getAttribute("data-items-per-page"));
    let startIndex = (page - 1) * itemsPerPage;
    let endIndex = startIndex + itemsPerPage;
    let paginatedInjuries = injuries.slice(startIndex, endIndex);
    let paginationLinks = document.querySelectorAll(".rdg-injury-report .pagination-link");
    let container = document.querySelector(".rdg-injury-report .injuries");
    
    container.innerHTML = "";
    paginatedInjuries.forEach((injury) => {
        let injuryElement = createInjuryElement(injury);
        container.appendChild(injuryElement);
    });

    paginationLinks.forEach((link) => {
        link.classList.remove("current");
        link.classList.add("active");

        if (link.innerText == page) {
            link.classList.add("current");
            link.classList.remove("active");
        }
    });
}

function paginateLinks(totalPages, currentPage, range) {
    if (totalPages < 2) return [];

    const generateLinkAttributes = (page, label, className) => {
        return {
            class: className,
            label: label,
            page: page,
        };
    };

    const links = [];

    // Previous link
    if (currentPage > 1) {
        links.push(generateLinkAttributes(currentPage - 1, "« Prev", "prev active"));
    }

    // Calculate start and end pages
    const startPage = Math.max(1, currentPage - range);
    const endPage = Math.min(totalPages, currentPage + range);

    // First page link if current range does not include it
    if (startPage > 1) {
        links.push(generateLinkAttributes(1, "1", "active"));
        if (startPage > 2) {
            links.push(generateLinkAttributes(null, "...", "dots"));
        }
    }

    // Page links within range
    for (let i = startPage; i <= endPage; i++) {
        const className = i === currentPage ? "current" : "active";
        links.push(generateLinkAttributes(i, i.toString(), className));
    }

    // Last page link if current range does not include it
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            links.push(generateLinkAttributes(null, "...", "dots"));
        }
        links.push(
            generateLinkAttributes(totalPages, totalPages.toString(), "active")
        );
    }

    // Next link
    if (currentPage < totalPages) {
        links.push(generateLinkAttributes(currentPage + 1, "Next »", "next active"));
    }

    return links;
}
