(function($) {
    'use strict';

    // Listen for changes in the Sport field to dynamically load leagues
    document.addEventListener('change', function(e) {
        // Check if the changed element is within the sports_picks_sport field
        if (e.target.closest('[data-name="sports_picks_sport"]') && e.target.matches("select")) {
            var sportSelect = e.target;
            var sportValue = sportSelect.value;
            var block = sportSelect.closest('.acf-block-fields');
            
            if (!block) return;
            
            var leagueField = block.querySelector('[data-name="sports_picks_league"] select');
            
            if (!leagueField) return;

            // Clear and disable league select while loading
            leagueField.innerHTML = '<option value="0">Loading...</option>';
            leagueField.disabled = true;

            if (!sportValue || sportValue === '0') {
                leagueField.innerHTML = '<option value="0">Choose an option</option>';
                leagueField.disabled = false;
                return;
            }

            // Make AJAX request to load leagues for the selected sport
            var ajaxUrl = (typeof ajaxurl !== 'undefined') ? ajaxurl : '/wp-admin/admin-ajax.php';
            
            fetch(ajaxUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'load_sports_picks_options',
                    sport: sportValue
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.leagues) {
                    // Populate league select with new options
                    var options = '<option value="0">Choose an option</option>';
                    
                    for (var key in data.data.leagues) {
                        if (data.data.leagues.hasOwnProperty(key)) {
                            options += '<option value="' + key + '">' + data.data.leagues[key] + '</option>';
                        }
                    }
                    
                    leagueField.innerHTML = options;
                    leagueField.disabled = false;
                } else {
                    leagueField.innerHTML = '<option value="0">No leagues available</option>';
                    leagueField.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error loading leagues:', error);
                leagueField.innerHTML = '<option value="0">Error loading leagues</option>';
                leagueField.disabled = false;
            });
        }
    });

})(jQuery);

