import { CustomElement } from "../CustomElement.mjs";

export const TAG_NAME = "nav-menu";

class HTMLNavMenuElement extends CustomElement {
	constructor() {
		super();

		this.importElementStylesheet(this.constructor.name);
	}

	open() {
		document.body.classList.add("menu-open");
		this.classList.add("active");
	}

	close() {
		this.classList.remove("active");

		// Remove classname from body tag if this was the last menu that was open
		if (!document.querySelector(TAG_NAME + ".active")) {
			document.body.classList.remove("menu-open");
		}
	}

	toggle() {
		this.classList.contains("active") ? this.close() : this.open();
	}

	connected() {
		// Close menu when a link is clicked
		[...document.querySelectorAll("a")].forEach(element => element.addEventListener("click", () => this.close()));
	}
}

globalThis.customElements.define(TAG_NAME, HTMLNavMenuElement);