(function($) {
    // Sport → League AJAX dynamic update (when user manually changes sport in repeater)
    document.addEventListener('change', function(e) {
        // Check if this is a sport select within the rdg-picks-vs-categories repeater (name contains field_picks_vs_categories_sport)
        if (e.target.matches("select") && e.target.name && e.target.name.includes('field_picks_vs_categories_sport')) {
            e.preventDefault();

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

            // Extract the repeater row identifier from the sport select name
            // Name format: acf-block_[blockId][field_64b1daa829050][row-X][field_picks_vs_categories_sport]
            const sportName = sportSelect.name;
            const rowMatch = sportName.match(/\[field_64b1daa829050\]\[([^\]]+)\]/);
            
            if (!rowMatch) return;
            
            const rowId = rowMatch[1];
            
            // Extract block ID
            const blockIdMatch = sportName.match(/^(acf-block_[^[]+)/);
            if (!blockIdMatch) return;
            
            const blockId = blockIdMatch[1];
            
            // Build the league select name using the same block ID and row ID
            const leagueName = blockId + '[field_64b1daa829050][' + rowId + '][field_picks_vs_categories_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_picks_vs_categories_options&sport=${sport}`,
            })
            .then((response) => response.json())
            .then((resultado) => {
                if (Object.keys(resultado.leagues).length > 0) {
                    // Clear select - don't manually add "Choose an option" since it's already in resultado.leagues
                    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('RDG Picks Vs Categories - League Update Error:', err));
        }
    });
}) (jQuery);

