import TabElement from "./Tab";
import React, { useEffect, useRef, useState, } from "react";
const Tabs = (props) => {
    const [currentTabName, setCurrentTabName] = useState(null);
    const hasInitialized = useRef(false);
    // Initialize current tab only once, or when the tab list names change
    useEffect(() => {
        const tabNames = props.tabs.map((t) => {
            return t.name;
        });
        if (!hasInitialized.current && props.tabs.length > 0) {
            hasInitialized.current = true;
            setCurrentTabName(props.tabs[0].name);
            return;
        }
        // If current tab no longer exists in the list, reset to first
        if (currentTabName && !tabNames.includes(currentTabName)) {
            setCurrentTabName(props.tabs.length > 0 ? props.tabs[0].name : null);
        }
    }, [
        props.tabs
            .map((t) => {
            return t.name;
        })
            .join(","),
    ]);
    // Find the current tab object by name
    const currentTab = props.tabs.find((t) => {
        return t.name === currentTabName;
    });
    useEffect(() => {
        if (currentTab && props.onTabChange) {
            props.onTabChange(currentTab);
        }
    }, [currentTabName]);
    const tabPanelId = `tabpanel-${currentTabName || "default"}`;
    return (React.createElement("div", null,
        React.createElement("nav", { role: "tablist", className: "flex space-x-2 overflow-x-auto md:overflow-visible md:space-x-4", "aria-label": "Tabs" }, props.tabs.map((tab) => {
            return (React.createElement(TabElement, { key: tab.name, tab: tab, onClick: () => {
                    setCurrentTabName(tab.name);
                }, isSelected: tab.name === currentTabName, tabPanelId: tabPanelId }));
        })),
        React.createElement("div", { id: tabPanelId, role: "tabpanel", "aria-labelledby": `tab-${currentTabName || "default"}`, className: "mt-3 ml-1" }, currentTab && currentTab.children)));
};
export default Tabs;
//# sourceMappingURL=Tabs.js.map