document.addEventListener("change", function (e) {
    if (e.target.matches("select.rdg_trends_sports")) {
        e.preventDefault();
        const ajax_url = rdg_injury_report_var.ajaxurl;

        let sport = document.querySelector(
            "select.rdg_trends_sports option:checked"
        ).value;

        document.querySelector(".acf-field-key-rdg-trends-leagues select").innerHTML = "";
        document.querySelector(".acf-field-key-rdg-trends-teams select").innerHTML = "";

        if (sport == "") {
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_leagues_sports&sport=${sport}`,
        })
            .then((response) => response.text())
            .then((resultado) => {
                document.querySelector(
                    ".acf-field-key-rdg-trends-leagues select"
                ).innerHTML = resultado;
            })
            .catch((err) => console.error(err));
    } else if (e.target.matches("select.rdg_trends_leagues")) {
        e.preventDefault();
        const ajax_url = rdg_injury_report_var.ajaxurl;

        let league = document.querySelector(
            "select.rdg_trends_leagues option:checked"
        ).value;

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

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_teams_league&league=${league}`,
        })
        .then((response) => response.text())
        .then((resultado) => {
            document.querySelector(
                ".acf-field-key-rdg-trends-teams select"
            ).innerHTML = resultado;
        })
        .catch((err) => console.error(err));
    }
});
