(function($) {
    // Sport → League AJAX dynamic update (when user manually changes sport)
    document.addEventListener('change', function(e) {
        // Check if this is a sport select (name contains field_top_capper_sport)
        if (e.target.matches("select") && e.target.name && e.target.name.includes('field_top_capper_sport') && !e.target.name.includes('field_top_capper_sport_league')) {
            e.preventDefault();

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

            // Extract the block ID from the sport select name
            const sportName = sportSelect.name;
            const blockIdMatch = sportName.match(/^(acf-block_[^[]+)/);
            
            if (!blockIdMatch) return;
            
            const blockId = blockIdMatch[1];
            
            // Find the league select using the same block ID
            const leagueName = blockId + '[field_top_capper_sport_league]';
            const leagueSelect = document.querySelector(`select[name="${leagueName}"]`);
            
            if (!leagueSelect) return;

            if (sport == "" || sport == "0") {
                leagueSelect.innerHTML = '<option value="0">Choose an option</option>';
                return;
            }

            fetch(ajax_url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                body: `action=load_top_cappers_sport_options&sport=${sport}`,
            })
            .then((response) => response.json())
            .then((resultado) => {
                if (Object.keys(resultado.leagues).length > 0) {
                    leagueSelect.innerHTML = '<option value="0">Choose an option</option>';

                    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('RDG Top Cappers Sport - League Update Error:', err));
        }
    });
}) (jQuery);

