let parentSelectorCategories = '[data-name="sport_betting_odds_sports_categories"]';
let selectorCategory = '[data-name="sport_betting_odds_sports_categories"] .acf-fields .category-item';

function getCategoryList() {
    if (document.querySelector(parentSelectorCategories + " .acf-fields") != null) {
        return document.querySelector(parentSelectorCategories + " .acf-fields");
    } else {
        let categories = document.querySelector(parentSelectorCategories);
        const categoryList = document.createElement("div");
        categoryList.setAttribute("class", "acf-fields");
        categories.appendChild(categoryList);

        return document.querySelector(parentSelectorCategories + " .acf-fields");
    }
}

function clearCategories(level) {
    let allCategories = document.querySelectorAll(selectorCategory);

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

function getNewCategoryNumber() {
    let countCategories = document.querySelectorAll(selectorCategory);

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

    return 1;
}

function createNewSelect(newSelect) {
    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;

    if (sub_menu) {
        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);
            categoryList = getCategoryList();
            categoryList.appendChild(categoryElement);
        })
        .catch((err) => console.error(err));
    } else {
        let category_full = document.querySelector("#sports_hierarchy_category input");
        category_full.value = newCategoryValue;
    }
}

function createCategoryElement(categories, SportValue, SportName, level, parentId) {
    let categoryNumber = getNewCategoryNumber();
    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 ajax_url = rdg_sport_betting_odds_var.ajaxurl;
        let sport = document.querySelector(
            ".sports_hierarchy select option:checked"
        ).value;

        fetch(ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `action=load_ajax_sports_family&sport=${sport}`,
        })
        .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();
            categoryList.innerHTML = "";
            let categoryElement = createCategoryElement(
                data,
                SportValue,
                SportName
            );
            categoryList.appendChild(categoryElement);
        })
        .catch((err) => console.error(err));
    } else if (e.target.matches(parentSelectorCategories + " .acf-fields select")) {
        e.preventDefault();
        let level = e.target.parentNode.parentNode.getAttribute('data-level');

        clearCategories(level + 1);
        createNewSelect(e.target);
        console.log(e.target.parentNode.parentNode);
    }
});
