document.addEventListener('change', function(e) {
    if (e.target.closest('[data-name="rdg_leader_board_sport"]') && e.target.matches("select")) {
        e.preventDefault();

        const ajax_url = rdg_leader_board_var.ajaxurl;
        let sport = e.target.options[e.target.selectedIndex].value;

        if (sport == "") {
            document.querySelector('[data-name="rdg_leader_board_league"] select').innerHTML = "";
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_leader_board_leagues_options&sport=${sport}`,
        })
        .then((response) => response.json())
        .then((resultado) => {
            if (Object.keys(resultado.leagues).length > 0) {
                let leagueSelect = document.querySelector('[data-name="rdg_leader_board_league"] select');
                leagueSelect.innerHTML = '';

                Object.entries(resultado.leagues).forEach(([key, value]) => {
                    const option = document.createElement("option");
                    option.value = key;
                    option.textContent = value;

                    leagueSelect.appendChild(option);
                });
            }
        })
        .catch((err) => console.error(err));
    } else if (e.target.closest('[data-name="rdg_leader_board_date_range"]') && e.target.matches("select")) {
        e.preventDefault();

        let date_range = e.target.options[e.target.selectedIndex].value;
        if (date_range == "") {
            return;
        }
        
        let picks_range =  document.querySelector('[data-name="rdg_leader_board_picks_range"] select');
        picks_range.selectedIndex = 0;
    } else if (e.target.closest('[data-name="rdg_leader_board_picks_range"]') && e.target.matches("select")) {
        e.preventDefault();

        let picks_range = e.target.options[e.target.selectedIndex].value;
        if (picks_range == "") {
            return;
        }
        
        let date_range =  document.querySelector('[data-name="rdg_leader_board_date_range"] select');
        date_range.selectedIndex = 0;
    } else if (e.target.matches(".rdg-leader-board-filter")) {
        e.preventDefault();

        let table = e.target.parentNode.parentNode.parentNode.parentNode;
        let spinner = table.parentNode.parentNode.querySelector("#wait");
        let sport = table.querySelector("#rdg-leader-board-sport");

        if (sport !== null) {
            sport.setAttribute("data-page", 1);
        }
        
        if (e.target.id === "rdg-leader-board-date-range") {
            let picks_range = table.querySelector("#rdg-leader-board-picks-range");
            picks_range.selectedIndex = 0;
        }

        if (e.target.id === "rdg-leader-board-picks-range") {
            let date_range = table.querySelector("#rdg-leader-board-date-range");
            date_range.selectedIndex = 0;
        }

        let data = getDataRequest(e.target);
        getRequest(data, spinner, 1, false, sport);
    }
});

document.addEventListener('click', function (e) {
    if (e.target.matches("#rdg-leader-board-load-more")) {
        e.preventDefault();

        let table = e.target.parentNode.parentNode.querySelector(".table");
        
        if (table) {
            let page = table.querySelector("#rdg-leader-board-sport");
            let sport = page;
            let current_page = page.getAttribute("data-page");
            let total_pages = page.getAttribute("data-total-pages");

            if (current_page >= total_pages) {
                return;
            }

            page.setAttribute("data-page", parseInt(page.getAttribute("data-page")) + 1);
            page = table.querySelector('#rdg-leader-board-sport').getAttribute('data-page');

            let spinner = table.parentNode.querySelector("#wait");
            let data = getDataRequest(e.target);
            getRequest(data, spinner, page, true, sport);
        }
    }
});

function getDataRequest(target) {
    let sport = document.querySelector("#rdg-leader-board-sport option:checked").value;
    let league = document.querySelector("#rdg-leader-board-league option:checked").value;
    let bet_type = document.querySelector("#rdg-leader-board-bet-type option:checked").value;
    let date_range = document.querySelector("#rdg-leader-board-date-range option:checked").value;
    let picks_range = document.querySelector("#rdg-leader-board-picks-range option:checked").value;
    let items = document.querySelector('#rdg-leader-board-sport').getAttribute('data-items');
    let block_id = document.querySelector('#rdg-leader-board-sport').getAttribute('data-block-id');
    let post_id = document.querySelector('#rdg-leader-board-sport').getAttribute('data-post-id');
    let post_type = document.querySelector('#rdg-leader-board-sport').getAttribute('data-post-type');

    if (target.id === "rdg-leader-board-sport") {
        league = "";
    } else if (target.id === "rdg-leader-board-date-range") {
        picks_range = "";
    } else if (target.id === "rdg-leader-board-picks-range") {
        date_range = "";
    }

    return {
        sport: sport,
        league: league,
        items: items,
        duration: date_range,
        bet_type: bet_type,
        picks_range: picks_range,
        block_id: block_id,
        post_id: post_id,
        post_type: post_type,
    };
}
// Aqui
async function getRequest(data, spinner, page, clear, sport) {
    let ajax_url = rdg_leader_board_var.ajaxurl;
    spinner.style.display = "block";

    fetch(ajax_url, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: `action=load_leader_board_leagues&items=${data.items}&duration=${data.duration}&sport=${data.sport}&league=${data.league}&bet_type=${data.bet_type}&pick_range=${data.picks_range}&page=${page}`,
    })
        .then((response) => response.json())
        .then((resultado) => {
            if (sport !== null) {
                sport.setAttribute("data-total-pages", resultado.total_pages);
            }

            let button = spinner.parentNode.querySelector("#rdg-leader-board-load-more");
            if (sport.getAttribute("data-page") < sport.getAttribute("data-total-pages")) {
                button.classList.remove("disabled");
                button.disabled = false;
            } else {
                button.classList.add("disabled");
                button.disabled = true;
            }

            if (Object.keys(resultado.leagues).length > 0) {
                let leagueSelect = document.querySelector(
                    "#rdg-leader-board-league"
                );
                leagueSelect.innerHTML = "";

                Object.entries(resultado.leagues).forEach(([key, value]) => {
                    const option = document.createElement("option");
                    option.value = key;
                    option.textContent = value;

                    if (key === data.league) {
                        option.selected = true;
                    }

                    leagueSelect.appendChild(option);
                });
            }

            if (Object.keys(resultado.data).length > 0) {
                let tableData = document.querySelector(
                    ".rdg-leader-board .sortable tbody"
                );
                if (!clear == true) {
                    tableData.innerHTML = "";
                }

                Object.entries(resultado.data).forEach(([key, item]) => {
                    if (item.id_handicapper !== undefined) {
                        const row = document.createElement("tr");

                        const rankCell = document.createElement("td");
                        rankCell.textContent = item.rank;
                        rankCell.classList.add("top", "w-1", "static-column");
                        row.appendChild(rankCell);

                        const nameCell = document.createElement("td");
                        nameCell.classList.add("name", "w-2");
                        const link = document.createElement("a");
                        link.href = item.handicapper_detail_url;
                        link.target = "_blank";
                        link.textContent = item.name;
                        nameCell.appendChild(link);
                        row.appendChild(nameCell);

                        const totalBetsCell = document.createElement("td");
                        totalBetsCell.classList.add("w-3");
                        totalBetsCell.textContent = formatPrice(
                            item.total_bets
                        );
                        row.appendChild(totalBetsCell);

                        const winCell = document.createElement("td");
                        winCell.classList.add("w-4");
                        winCell.textContent = formatPrice(item.win);
                        row.appendChild(winCell);

                        const lossCell = document.createElement("td");
                        lossCell.classList.add("w-5");
                        lossCell.textContent = formatPrice(item.loss);
                        row.appendChild(lossCell);

                        const pushCell = document.createElement("td");
                        pushCell.classList.add("w-6");
                        pushCell.textContent = item.push;
                        row.appendChild(pushCell);

                        const winPercentageCell = document.createElement("td");
                        winPercentageCell.classList.add("w-7");
                        winPercentageCell.textContent =
                            formatpercentaje(item.win_percentaje) + "%";
                        row.appendChild(winPercentageCell);

                        const netCell = document.createElement("td");
                        netCell.classList.add("w-8");
                        netCell.textContent = "$" + formatPrice(item.net);
                        row.appendChild(netCell);

                        if (resultado.members[item.id_group] === undefined) {
                            let package_name = resultado.members_default;

                            if (item.group_name !== undefined && item.group_name !== null) {
                                package_name = item.group_name;
                            }

                            const groupCell = document.createElement("td");
                            groupCell.classList.add("group", "w-9");
                            groupCell.textContent = package_name;
                            row.appendChild(groupCell);
                        } else {
                            const nameCell = document.createElement("td");
                            nameCell.classList.add("group", "w-9");
                            const link = document.createElement("a");
                            link.href = resultado.members[item.id_group].url;
                            link.target = "_blank";
                            link.textContent = resultado.members[item.id_group].name;
                            nameCell.appendChild(link);
                            row.appendChild(nameCell);
                        }

                        if (item.last_pick_date !== undefined) {
                            const riskAmount = document.createElement("td");
                            riskAmount.classList.add("w-10");
                            riskAmount.textContent = formatDateTime(item.last_pick_date);

                            row.appendChild(riskAmount);
                        } else {
                            const riskAmount = document.createElement("td");
                            riskAmount.classList.add("w-10");
                            riskAmount.textContent = "-";

                            row.appendChild(riskAmount);
                        }

                        tableData.appendChild(row);
                    }
                });
            }

            spinner.style.display = "none";
        })
        .catch((err) => console.error(err));
}

function formatPrice(amount) {
    return Number(amount).toLocaleString("en-EN", {minimumFractionDigits: 0, maximumFractionDigits: 0});
}

function formatpercentaje(amount) {
    return Number(amount).toLocaleString("en-EN", {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

function formatDateTime(dateString) {
    const formattedDateString = dateString.replace(" ", "T");
    const date = new Date(formattedDateString);

    const timeFormatter = new Intl.DateTimeFormat("en-US", {
        hour: "2-digit",
        minute: "2-digit",
        hour12: true,
    });

    const dateFormatter = new Intl.DateTimeFormat("en-CA", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
    });

    const formattedDate = dateFormatter.format(date).replace(/-/g, "/");

    return `${timeFormatter.format(date)} - ${formattedDate}`;
}
