import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2026 GoodData Corporation
import { useCallback, useMemo, useState } from "react";
import cx from "classnames";
import { FormattedMessage } from "react-intl";
import { simplifyText } from "@gooddata/util";
import { isActionKey } from "../utils/events.js";
/**
 * @internal
 */
export function Tabs({ className = "", onTabSelect = () => { }, selectedTabId: propSelectedTabId = "", tabs = [], }) {
    const [selectedTabId, setSelectedTabId] = useState(propSelectedTabId || tabs?.[0]?.id);
    const selectTab = useCallback((tab) => {
        const newSelectedTabId = tab?.id;
        const noChange = newSelectedTabId === selectedTabId;
        if (noChange) {
            return;
        }
        setSelectedTabId(newSelectedTabId);
        onTabSelect(tab);
    }, [selectedTabId, onTabSelect]);
    const renderTab = useCallback((tab) => {
        const tabClassName = cx({
            "is-active": tab.id === selectedTabId,
            "gd-tab": true,
            [`s-${simplifyText(tab.id)}`]: true,
        });
        const handleClick = () => {
            selectTab(tab);
        };
        const handleKeyDown = (event) => {
            if (isActionKey(event)) {
                event.preventDefault();
                selectTab(tab);
            }
        };
        return (_jsx("div", { "aria-label": simplifyText(tab.id), className: tabClassName, onClick: handleClick, onKeyDown: handleKeyDown, role: "tab", "aria-selected": tab.id === selectedTabId, tabIndex: 0, "data-testid": `s-tab-${simplifyText(tab.id)}`, children: _jsxs("span", { children: [tab.iconNode ?? (tab.icon ? _jsx("i", { className: tab.icon }) : null), tab.iconOnly ? null : (_jsx(FormattedMessage, { id: tab.id, values: (tab.values ?? {}) }))] }) }, tab.id));
    }, [selectedTabId, selectTab]);
    const renderedTabs = useMemo(() => {
        return tabs.map(renderTab);
    }, [tabs, renderTab]);
    const classNames = useMemo(() => cx(className, {
        "gd-tabs": true,
        small: true,
    }), [className]);
    return (_jsx("div", { role: "tablist", className: classNames, children: renderedTabs }));
}
