document.addEventListener('change', function(e) {
    if (e.target.closest('[data-name="rdg_scores_and_odds_sports"]') && 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_scores_and_odds_league"] select').innerHTML = "";
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_scores_and_odds_options&sport=${sport}`,
        })
        .then((response) => response.json())
        .then((resultado) => {
            if (Object.keys(resultado.leagues).length > 0) {
                let leagueSelect = document.querySelector('[data-name="rdg_scores_and_odds_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));
    }
});
