class MainMenu extends HTMLElement {
    constructor() {
        super();
        this.generateMenu();
    }

    async generateMenu() {
        let menu = await (await fetch("/API/mainMenu.json")).json();
        let menuContainer = document.createElement("div");
        menuContainer.className = "mainmenuContainer";

        let burgerMenu = document.createElement("div");
        burgerMenu.id = "burgerMenu";

        burgerMenu.onclick = () => {
            document.getElementById("burgerMenu").classList.toggle("change");
            document.querySelector(".mainmenuContainer").classList.toggle("visible");

        }

        for (let i = 1; i <= 3; i++) {
            let bar = document.createElement("div");
            bar.className = "bar" + i;
            burgerMenu.appendChild(bar);
        }
        this.appendChild(burgerMenu);


        menu.forEach((element) => {
            if (element["type"] === "link") {
                let a = document.createElement("a");
                a.href = element["url"];
                a.innerText = element["name"];
                a.classList.add("navLink");

                menuContainer.appendChild(a);

                if (window.location['pathname'] === element["url"]) {
                    document.title = element["name"] + " - Jonas Leder";
                }

            } else if (element["type"] === "dropdown") {
                let dropdown = document.createElement("div");
                dropdown.className = "dropdown";

                let a = document.createElement("a");
                a.href = element["url"];
                a.classList.add("navLink");
                a.innerText = element["name"];

                dropdown.appendChild(a)
                let dropdownContent = document.createElement("div");
                dropdownContent.className = "dropdown-content"

                element["childElements"].forEach((childElement) => {
                    let a = document.createElement("a");
                    a.href = childElement["url"];
                    a.innerText = childElement["name"];

                    dropdownContent.appendChild(a);

                    let br = document.createElement("br");
                    dropdownContent.appendChild(br);

                    if (window.location['pathname'] === childElement["url"]) {
                        document.title = childElement["name"] + " - Jonas Leder";
                    }
                });

                dropdown.appendChild(dropdownContent);
                menuContainer.appendChild(dropdown);
            }
        });

        this.appendChild(menuContainer);
        if(document.title == "") {
            document.title = this.getAttribute("data-title") + " - Jonas Leder";
        }
    }
}

customElements.define("jl-main_menu", MainMenu);
