// retoor <retoor@molodetz.nl>

class Tabs {
    constructor() {
        document.querySelectorAll("[data-tabs]").forEach((root) => this.init(root));
    }

    init(root) {
        const tabs = [...root.querySelectorAll("[data-tab]")];
        const panes = [...root.querySelectorAll("[data-tab-pane]")];
        if (!tabs.length) return;

        const show = (name) => {
            tabs.forEach((t) => t.classList.toggle("active", t.dataset.tab === name));
            panes.forEach((p) => p.classList.toggle("active", p.dataset.tabPane === name));
        };

        tabs.forEach((tab) => {
            tab.addEventListener("click", () => {
                show(tab.dataset.tab);
                history.replaceState(null, "", "#" + tab.dataset.tab);
            });
        });

        const hash = (location.hash || "").slice(1);
        const initial = tabs.some((t) => t.dataset.tab === hash) ? hash : tabs[0].dataset.tab;
        show(initial);
    }
}

window.Tabs = Tabs;
export { Tabs };
