// Handle Sports → League dynamic update (like Scores and Odds)
document.addEventListener('change', function(e) {
    if (e.target.closest('[data-name="sport_betting_odds_sports"]') && e.target.matches("select")) {
        e.preventDefault();

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

        if (sport == "" || sport == "0") {
            let leagueSelect = document.querySelector('[data-name="sport_betting_odds_league"] select');
            if (leagueSelect) {
                leagueSelect.innerHTML = '<option value="">Choose an option</option>';
            }
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_sport_betting_odds_options&sport=${sport}`,
        })
        .then((response) => response.json())
        .then((resultado) => {
            if (resultado.leagues && Object.keys(resultado.leagues).length > 0) {
                let leagueSelect = document.querySelector('[data-name="sport_betting_odds_league"] select');
                if (leagueSelect) {
                    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('Sport Betting Odds - League Update Error:', err));
    }
});

// LEGACY: Code below is for backward compatibility with old blocks using sport_betting_odds_sports_categories field
// New blocks use the League field (sport_betting_odds_league) populated via AJAX
window.addEventListener("load", (event) => {
    // Add css to hide the text input of categories
    const style = document.createElement('style');
    style.textContent = `
        .rdg-hide-text-input input[type="text"] {
            display: none !important;
        }
    `;
    document.head.appendChild(style);
    
    let allBlocksCategories = document.querySelectorAll('[data-type="acf/rdg-sport-betting-odds"]');

    if (allBlocksCategories.length > 0) {
        allBlocksCategories.forEach((block) => {
            let is_preview = block.querySelector(".acf-block-preview");

            if (is_preview == null) {
                let block_id = block.querySelector(".acf-block-fields.acf-fields [data-name='sport_betting_odds_block_id'] input");

                if (block_id) {
                    let categories = block.querySelector("[data-name='sport_betting_odds_sports_categories']");
                    let category = block.querySelector("[data-name='sport_betting_odds_category']");
                    let sport = block.querySelector("[data-name='sport_betting_odds_sports'] select option:checked");

                    category.classList.add("block-id-" + block_id.value);
                    categories.classList.add("block-id-" + block_id.value);

                    let input_cat = category.querySelector("input");

                    if (sport && sport.value != 0) {
                        let ajax_url = rdg_sport_betting_odds_var.ajaxurl;

                        //  Only restore if there is a value saved in the category field
                        if (input_cat && input_cat.value && input_cat.value.trim() !== "") {
                            // Hide the text input immediately
                            if (input_cat) {
                                input_cat.style.display = 'none';
                            }
                            
                            fetch(ajax_url, {
                                method: "POST",
                                headers: {
                                    "Content-Type": "application/x-www-form-urlencoded",
                                },
                                body: `action=load_categories_hierarchy&sport=${sport.value}&categories=${input_cat.value}&block_id=${block_id.value}`,
                            })
                            .then((response) => response.text())
                            .then((data) => {
                                categoryList = getCategoryList(block_id.value);
                                if (categoryList) {
                                    categoryList.innerHTML = data;
                                    
                                    //  Show the categories container
                                    let categoriesField = document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" + block_id.value);
                                    if (categoriesField) {
                                        categoriesField.style.display = '';
                                    }
                                }
                            })
                            .catch((err) => console.error('RDG Sport Betting Odds Load Error:', err));
                        }
                    }
                }
            }
        });
    }
});

function getCategoryElement(block_id) {
    return document.querySelector("[name$='"+ block_id +"[key_sport_betting_odds_category]']");
}

function getCategoryList(block_id, blockElement = null) {
    // First, try to find existing container with block-id class
    if (document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" +block_id +" .acf-fields") != null) {
        return document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" +block_id +" .acf-fields");
    }
    
    // If blockElement is provided, search within it
    let categories;
    if (blockElement) {
        categories = blockElement.querySelector("[data-name='sport_betting_odds_sports_categories']");
    } else {
        // Fallback: try to find by block-id class first
        categories = document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" + block_id);
        
        if (!categories) {
            // Last resort: find the block and search within it
            let allBlocks = document.querySelectorAll('[data-type="acf/rdg-sport-betting-odds"]');
            for (let block of allBlocks) {
                let blockIdField = block.querySelector('[data-name="sport_betting_odds_block_id"] input');
                if (blockIdField && blockIdField.value === block_id) {
                    categories = block.querySelector("[data-name='sport_betting_odds_sports_categories']");
                    break;
                }
            }
        }
    }
    
    if (!categories) {
        console.error('RDG Sport Betting Odds: Categories field not found for block-id-' + block_id);
        return null;
    }
    
    // Add block-id class if not present
    if (!categories.classList.contains('block-id-' + block_id)) {
        categories.classList.add('block-id-' + block_id);
    }
    
    // Check if container already exists
    let existingContainer = categories.querySelector('.acf-fields');
    if (existingContainer) {
        return existingContainer;
    }
    
    // Hide the text input if it exists
    let textInput = categories.querySelector('input[type="text"]');
    if (textInput) {
        textInput.style.display = 'none';
    }
    
    // Create container for dynamic selects
    const categoryList = document.createElement("div");
    categoryList.setAttribute("class", "acf-fields");
    
    // Find the .acf-input div and append there
    let acfInput = categories.querySelector('.acf-input');
    if (acfInput) {
        acfInput.appendChild(categoryList);
    } else {
        categories.appendChild(categoryList);
    }
    
    return categoryList;
}

function clearCategories(level, block_id) {
    let allCategories = document.querySelectorAll(".block-id-" + block_id + " .acf-fields .category-item");

    allCategories.forEach((category) => {
        if (category.getAttribute("data-level") >= level) {
            category.remove();
        }
    });
}

function getNewCategoryNumber(block_id) {
    let countCategories = document.querySelectorAll(".block-id-" + block_id + " .acf-fields .category-item");

    if (countCategories != null) {
        return countCategories.length + 1;
    }

    return 1;
}

function createNewSelect(newSelect, block_id) {
    let ajax_url = rdg_sport_betting_odds_var.ajaxurl;
    let newCategoryValue = newSelect.options[newSelect.options.selectedIndex].value;
    let newCategoryName = newSelect.options[newSelect.options.selectedIndex].innerHTML;
    let sub_menu = newCategoryValue.includes("-child") ? true : false;
    
    let category_full = getCategoryElement(block_id);
    if (category_full === null) {
        console.log('RDG Sport Betting Odds: Error selecting Category container.')

        return;
    }

    if (sub_menu) {
        category_full.value = newCategoryValue.replace("-child", "");
        
        // Fire change event to let ACF detect the change
        if (typeof jQuery !== 'undefined') {
            jQuery(category_full).trigger('change');
        } else {
            category_full.dispatchEvent(new Event('change', { bubbles: true }));
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_ajax_sports_family&sport=${newCategoryValue}`,
        })
        .then((response) => response.json())
        .then((data) => {
            // If there are no data of leagues (only "All sub-categories"), do not create the select
            if (data && Array.isArray(data) && data.length > 1) {
                let categoryElement = createCategoryElement(
                    data,
                    newCategoryValue,
                    newCategoryName,
                    block_id
                );
                categoryList = getCategoryList(block_id);
                if (categoryList) {
                    categoryList.appendChild(categoryElement);
                }
                }
        })
        .catch((err) => console.error('RDG Sport Betting Odds Sub-category Error:', err));
    } else {
        let parent_id = newSelect.parentNode.parentNode.getAttribute("data-parent-id");

        if (newSelect.value == 0) {
            category_full.value = parent_id.replace("-child", "");
        } else {
            category_full.value = newCategoryValue.replace("-child", "");
        }
        
        // Fire change event to let ACF detect the change
        if (typeof jQuery !== 'undefined') {
            jQuery(category_full).trigger('change');
        } else {
            category_full.dispatchEvent(new Event('change', { bubbles: true }));
        }
    }
}

function createCategoryElement(categories, SportValue, SportName, block_id) {
    let categoryNumber = getNewCategoryNumber(block_id);
    const categoryDiv = document.createElement("div");
    categoryDiv.setAttribute("class", "acf-field acf-field-select category-item");
    categoryDiv.setAttribute("data-name", "category-item-" + categoryNumber);
    categoryDiv.setAttribute("data-type", "select");
    categoryDiv.setAttribute("data-level", categoryNumber);
    categoryDiv.setAttribute("data-parent-id", SportValue);

    const labelDiv = document.createElement("div");
    labelDiv.setAttribute("class", "acf-label");

    const label = document.createElement("label");
    label.innerHTML = "Category: " + SportName;
    labelDiv.appendChild(label);
    categoryDiv.appendChild(labelDiv);

    const inputDiv = document.createElement("div");
    inputDiv.setAttribute("class", "acf-input");

    const inputSelect = document.createElement("select");
    inputSelect.setAttribute("id", "category-" + categoryNumber);
    inputSelect.setAttribute("class", "category-select");
    inputSelect.setAttribute("name", "category-" + categoryNumber);

    categories.forEach((category) => {
        const opt = document.createElement("option");
        opt.setAttribute("value", category.id);
        opt.setAttribute("class", category.class);
        opt.innerHTML = category.value;
        inputSelect.appendChild(opt);
    });

    inputDiv.appendChild(inputSelect);
    categoryDiv.appendChild(inputDiv);

    return categoryDiv;
}

document.addEventListener("change", function (e) {
    if (e.target.matches(".sports_hierarchy select")) {
        e.preventDefault();

        // Get the reference element (the .acf-fields container that holds all fields)
        let referenceElement = e.target.parentNode.parentNode.parentNode;
        
        // Find block ID within the reference element
        let blockIdField = referenceElement.querySelector('[data-name="sport_betting_odds_block_id"] input');
        if (!blockIdField) {
            console.error('RDG Sport Betting Odds: Could not find block ID field');
            return;
        }

        let block_id = blockIdField.value;
        
        // Now find the actual block container going up from referenceElement
        let blockContainer = referenceElement.closest('[data-type="acf/rdg-sport-betting-odds"]');
        if (!blockContainer) {
            // Fallback: the referenceElement itself might be good enough
            blockContainer = referenceElement;
        }
        let ajax_url = rdg_sport_betting_odds_var.ajaxurl;
        let sport = document.querySelector("[name$='"+ block_id +"[key_sport_betting_odds_sports]']");
        if (sport === null) {
            console.log('RDG Sport Betting Odds: Error selecting Sport container.')
            return;
        }

        let selected = sport.querySelector("option:checked").value;

        let category_full = getCategoryElement(block_id);
        if (category_full === null) {
            console.log('RDG Sport Betting Odds: Error selecting Category container.')
            return;
        }

        //  Clear the category field when the Sport is changed
        // The value will be saved when the user selects a specific League
        category_full.value = "";
        
        // Fire change event to let ACF detect the change
        if (typeof jQuery !== 'undefined') {
            jQuery(category_full).trigger('change');
        } else {
            category_full.dispatchEvent(new Event('change', { bubbles: true }));
        }

        if (selected == 0) {
            let existingFields = document.querySelector(".block-id-" + block_id + " .acf-fields");
            if (existingFields) {
                existingFields.remove();
            }
            return;
        }

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_ajax_sports_family&sport=${selected}`,
        })
        .then((response) => response.json())
        .then((data) => {
            let SportName = e.target.options[e.target.options.selectedIndex].innerHTML;
            let SportValue = e.target.options[e.target.options.selectedIndex].value;

            // Pass blockContainer to getCategoryList for context
            categoryList = getCategoryList(block_id, blockContainer);
            if (categoryList) {
                categoryList.innerHTML = "";
                
                // Get the categories container
                let categoriesField = document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" + block_id);
                
                // If there are no data of leagues (only "All sub-categories"), do not create the select
                if (data && Array.isArray(data) && data.length > 1) {
                    let categoryElement = createCategoryElement(data, SportValue, SportName, block_id);
                    categoryList.appendChild(categoryElement);
                    
                    // Show the container if it was hidden
                    if (categoriesField) {
                        categoriesField.style.display = '';
                    }
                } else {
                    //  Hide the container if there are no leagues
                    if (categoriesField) {
                        categoriesField.style.display = 'none';
                    }
                }
            } else {
                console.error('RDG Sport Betting Odds: Could not create category list container');
            }
        })
        .catch((err) => console.error('RDG Sport Betting Odds AJAX Error:', err));
    } else if (e.target.matches('[data-name="sport_betting_odds_sports_categories"] .acf-fields select')) {
        e.preventDefault();
        let level = e.target.parentNode.parentNode.getAttribute("data-level");

        var referenceElement =e.target.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
        var blockElement = referenceElement.querySelector('[data-name="sport_betting_odds_block_id"]');
        let block_id = blockElement.querySelector("input").value;

        clearCategories(level + 1, block_id);
        createNewSelect(e.target, block_id);
    }
});
