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

export const TAG_NAME = "code-demo";

const SELECTOR_HEADER_BUTTON = ".header button";

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

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

	/**
	 * Set a tab as active by passing an HTMLElement with a data-lang attribute
	 * @param {HTMLElement} target 
	 */
	#setActiveTab(target) {
		[...this.querySelectorAll("[data-file]")].forEach(element => {
			element.classList.remove("active");

			// Set active if current element lang is target lang
			if (element.dataset.file === target.dataset.file) {
				element.classList.add("active");
			}
		});
	}

	connected() {
		// Bind event listeners for language tabs
		[...this.querySelectorAll(SELECTOR_HEADER_BUTTON)].forEach(element => {
			element.addEventListener("click", (event) => this.#setActiveTab(event.target.closest(SELECTOR_HEADER_BUTTON)))
		});

		// Make the first tab active on load
		this.#setActiveTab(this.querySelector(SELECTOR_HEADER_BUTTON));
	}
}

globalThis.customElements.define(TAG_NAME, HTMLCodeDemoElement);