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

            const ajax_url = rdg_picks_vs_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_picks_vs_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_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 - League Update Error:', err));
        }
    });

    // LEGACY: Frontend category selector (old blocks)
    $(document).on('change','#rdg-picks-vs-category',function(e) {
        e.preventDefault();
        $(".rdg-blocks .rdg-picks-vs .picks .message").hide();
        
        let ajax_url = rdg_picks_vs_var.ajaxurl;
        let items = $(e.target).attr('data-items');
        let block_id = $(e.target).attr('data-block-id');
        let cat_seleted = $('#'+block_id+' #rdg-picks-vs-category option:selected').val();
        let sport = $('#'+block_id).attr('data-sport');
        let buttons = $('.buttons .link-info, .buttons .link-default');
        let title_heading = $('#rdg-picks-vs-title').attr('data-heading');
        let custom_title = $('#rdg-picks-vs-title').attr('data-custom-title');

        let data = {'data_date_type':'', 'data_since_date':'', 'data_to_date':''};
        let data_date_type = $(this).attr('data-date-type');
        let data_since_date = $(this).attr('data-since-date');
        let data_to_date = $(this).attr('data-to-date');

        let custom_link_show = $(this).attr('data-custom-link-show');
        let custom_link_url = $(this).attr('data-custom-link-url');
        let custom_link_target = $(this).attr('data-custom-link-target');
        let buttom_date = false;

        $.each(buttons, function(key, val) {
            if ($(val).hasClass('link-info')) {
                buttom_date = true;
                data.data_date_type = $(val).attr('data-date-type');
                data.data_since_date = $(val).attr('data-since-date');
                data.data_to_date = $(val).attr('data-to-date');
            }
        }, data);

        if(custom_title == 0) {
            $.ajax({
                url : ajax_url,
                type: 'post',
                data: {
                    action : 'load_picks_vs_title',
                    id_sub_category: cat_seleted,
                },
                success: function(resultado) {
                    $('.rdg-blocks #'+block_id).find('#rdg-picks-vs-title')
                        .html(`<${title_heading}>${resultado}</${title_heading}>`);
                }
            });
        }

        if (buttom_date == false) {
            data.data_date_type = $('#'+block_id).attr('data-date-type');
            data.data_since_date = $('#'+block_id).attr('data-since-date');
            data.data_to_date = $('#'+block_id).attr('data-to-date');
        }

        $.ajax({
            url : ajax_url,
            type: 'post',
            data: {
                action : 'load_picks_vs',
                items: items,
                id_sub_category: cat_seleted,
                sport: sport,
                data_date_type: data.data_date_type,
                data_since_date: data.data_since_date,
                data_to_date: data.data_to_date,
                custom_link_show: custom_link_show,
                custom_link_url: custom_link_url,
                custom_link_target: custom_link_target,
            },
            beforeSend: function() {
                $('#wait').show();
            },
            success: function(resultado) {
                $('.rdg-blocks #'+block_id).find('.picks').html(resultado);
                $('#wait').hide();
                setTimeout(function() {
                    $(".rdg-blocks #"+block_id+" .picks .message").fadeOut(1500);
                }, 4000);
            }
        });
    });

    $(document).on('click','.rdg-picks-vs .buttons a',function(e) {
        e.preventDefault();

        if ($(e.target).hasClass('link-info')) {
            return;
        }

        let block_id = $(e.target).attr('data-block-id');
        $(".rdg-blocks #"+block_id+" .rdg-picks-vs .picks .message").hide();

        let ajax_url = rdg_picks_vs_var.ajaxurl;
        let buttons = $('#'+block_id+' .buttons .link-info, #'+block_id+' .buttons .link-default');

        let button_id = $(this).attr('id');
        let items = $(this).attr('data-items');
        let data_date_type = $(this).attr('data-date-type');
        let data_since_date = $(this).attr('data-since-date');
        let data_to_date = $(this).attr('data-to-date');
        let custom_link_show = $(this).attr('data-custom-link-show');
        let custom_link_url = $(this).attr('data-custom-link-url');
        let custom_link_target = $(this).attr('data-custom-link-target');
        let filter_category = $(this).attr('data-category');
        let cat_seleted = $('#'+block_id+' #rdg-picks-vs-category option:selected').val();
        let sport = $('#'+block_id).attr('data-sport');

        if (cat_seleted === undefined) {
            cat_seleted = filter_category;
        }

        $.each(buttons, function(key, val) {      
            if (button_id == $(val).attr("id")) {
                $(val).removeClass('link-default');
                $(val).addClass('link-info');
            } else {
                $(val).removeClass('link-info');
                $(val).addClass('link-default');
            }
        }, button_id); 

        $.ajax({
            url : ajax_url,
            type: 'post',
            data: {
                action : 'load_picks_vs',
                items: items,
                id_sub_category: cat_seleted,
                sport: sport,
                data_date_type: data_date_type,
                data_since_date: data_since_date,
                data_to_date: data_to_date,
                custom_link_show: custom_link_show,
                custom_link_url: custom_link_url,
                custom_link_target: custom_link_target,
            },
            beforeSend: function() {
                $('#wait').show();
            },
            success: function(resultado) {
                $('.rdg-blocks #'+block_id).find('.picks').html(resultado);
                $('#wait').hide();
                setTimeout(function() {
                    $(".rdg-blocks #"+block_id+" .picks .message").fadeOut(1500);
                }, 4000);
            }
        });
    });
}) (jQuery);
