window.addEventListener("load", (event) => {
    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);

                    if (sport.value != 0) {
                        let ajax_url = rdg_sport_betting_odds_var.ajaxurl;
                        let input_cat = category.querySelector("input");

                        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);
                            categoryList.innerHTML = data;
                        })
                        .catch((err) => console.error(err));
                    }
                }
            }
        });
    }
});

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

function getCategoryList(block_id) {
    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");
    } else {
        let categories = document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" + block_id);
        const categoryList = document.createElement("div");
        categoryList.setAttribute("class", "acf-fields");
        categories.appendChild(categoryList);
        return document.querySelector("[data-name='sport_betting_odds_sports_categories'].block-id-" +block_id +" .acf-fields");
    }
}

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", "");

        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) => {
            let categoryElement = createCategoryElement(
                data,
                newCategoryValue,
                newCategoryName,
                block_id
            );
            categoryList = getCategoryList(block_id);
            categoryList.appendChild(categoryElement);
        })
        .catch((err) => console.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", "");
        }
    }
}

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();

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

        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;
        }

        category_full.value = selected;

        if (selected == 0) {
            document.querySelector(".block-id-" + block_id + " .acf-fields").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;

            categoryList = getCategoryList(block_id);
            categoryList.innerHTML = "";
            let categoryElement = createCategoryElement(data, SportValue, SportName, block_id);
            categoryList.appendChild(categoryElement);
        })
        .catch((err) => console.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);
    }
});
