// Handle Sport → League dynamic update
document.addEventListener('change', function(e) {
    if (e.target.closest('[data-name="admin_cappers_simple_sport"]') && e.target.matches("select")) {
        e.preventDefault();

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

        if (sport == "" || sport == "0") {
            let leagueSelect = document.querySelector('[data-name="admin_cappers_simple_league"] select');
            if (leagueSelect) {
                leagueSelect.innerHTML = '<option value="">Choose an option</option>';
            }
            return;
        }

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

