/*  DS2 core (c) 2024 Alexander McIlwraith 
	import * as tabs from "../pg/patterns/layouts/tabs/_tabs.js";
	tabs.init();
 */

export function init(p = document) { 
	p.querySelectorAll(".tab-group, tabset").forEach(tabGroup => {

		if (tabGroup.querySelector("[role=tablist]") === null) {
			const tabgroup = tabGroup.getAttribute("id");
			let tablist = "";

			Array.from(tabGroup.children).forEach(child => {
				const tab = child.getAttribute("tab") || child.getAttribute("data-tab");
				if (tab !== null) {
					const tabID = tab.replace(/\W+/g, "-").toLowerCase();
					const tabPanel = document.createElement('div');
					tabPanel.id = `tab-panel-${tabgroup}-${tabID}`;
					tabPanel.className = tablist === "" ? "open" : "";
					tabPanel.setAttribute("role", "tabpanel");
					tabPanel.setAttribute("tabindex", "0");
					tabPanel.setAttribute("aria-labelledby", `tab-${tabgroup}-${tabID}`);
					tabPanel.appendChild(child.cloneNode(true));
					child.parentNode.replaceChild(tabPanel, child);
					tablist += `<li tabindex="0" role="tab" ${tablist === "" ? "class='selected'" : ""} id="tab-${tabgroup}-${tabID}"><span>${tab}</span></li>`;
				} else {
					child.classList.add("tab-hidden");
				}
			});

			const ul = document.createElement('ul');
			ul.setAttribute("role", "tablist");
			ul.innerHTML = `${tablist}<li role="separator" class="separator"></li>`;
			tabGroup.insertBefore(ul, tabGroup.firstChild);

			tabGroup.querySelectorAll('[role="tab"]').forEach(tab => {
				tab.addEventListener("click", () => {
					const siblings = Array.from(tab.parentNode.children);
					siblings.forEach(sibling => sibling.classList.remove("selected"));
					tab.classList.add("selected");

					const tabPanels = Array.from(tab.parentNode.parentNode.children)
										   .filter(child => child.getAttribute("role") === "tabpanel");
					tabPanels.forEach(panel => panel.classList.remove("open"));

					const tabPanelId = tab.getAttribute("id").replace("tab", "tab-panel");
					document.getElementById(tabPanelId).classList.add("open");
				});
			});
			
		}
	});
}
