(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-multi repeater (name contains field_picks_vs_multi_sport)
        if (e.target.matches("select") && e.target.name && e.target.name.includes('field_picks_vs_multi_sport')) {
            e.preventDefault();

            const ajax_url = rdg_picks_vs_multi_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][rdg_picks_vs_multi_picks_sports][row-X][field_picks_vs_multi_sport]
            const sportName = sportSelect.name;
            const rowMatch = sportName.match(/\[rdg_picks_vs_multi_picks_sports\]\[([^\]]+)\]/);
            
            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 + '[rdg_picks_vs_multi_picks_sports][' + rowId + '][field_picks_vs_multi_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_multi_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 Multi - League Update Error:', err));
        }
    });
}) (jQuery);

