import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { useCallback, useEffect, useState } from "react";
import { useMediaQuery } from "../../../responsive/useMediaQuery.js";
import { useFocusWithinContainer } from "../../hooks/useFocusWithinContainer.js";
import { SELECT_ITEM_ACTION, useListWithActionsKeyboardNavigation, } from "../../hooks/useListWithActionsKeyboardNavigation.js";
import { ScopedIdStore, useScopedIdStoreValue } from "../../hooks/useScopedId.js";
import { UiDropdown } from "../../UiDropdown/UiDropdown.js";
import { UiTabsBem } from "../bem.js";
import { getTypedUiTabsContextStore } from "../context.js";
/**
 * @internal
 */
export function DefaultUiTabsAllTabs(_props) {
    const store = getTypedUiTabsContextStore();
    const { tabs, onTabSelect, AllTabsButton, selectedTabId, isOverflowing, useActionListener } = store.useContextStoreValues([
        "tabs",
        "onTabSelect",
        "selectedTabId",
        "AllTabsButton",
        "isOverflowing",
        "useActionListener",
    ]);
    const isMobile = useMediaQuery("mobileDevice");
    const [isOpen, setIsOpen] = useState(false);
    const handleDropdownSelect = useCallback((item) => () => {
        onTabSelect(item);
        setIsOpen(false);
    }, [onTabSelect]);
    const { onKeyboardNavigation, focusedItem, focusedAction, setFocusedIndex, setFocusedAction } = useListWithActionsKeyboardNavigation({
        items: tabs,
        getItemAdditionalActions: (item) => ((item.actions ?? []).length ? ["selectTabActions"] : []),
        actionHandlers: {
            selectItem: handleDropdownSelect,
            selectTabActions: () => undefined,
        },
        isSimple: true,
    });
    const scopedIdStoreValue = useScopedIdStoreValue((item) => item?.id ?? "");
    const { containerRef } = useFocusWithinContainer(scopedIdStoreValue.makeId({ item: focusedItem, specifier: focusedAction }) ?? "");
    const selectedItemId = focusedItem
        ? scopedIdStoreValue.makeId({ item: focusedItem, specifier: "container" })
        : "";
    useEffect(() => {
        document
            .getElementById(selectedItemId)
            ?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" });
    }, [selectedItemId, isOpen]);
    useActionListener(({ action, tab }) => {
        if (action.closeOnSelect === "all") {
            setIsOpen(false);
            return;
        }
        const tabContainerId = scopedIdStoreValue.makeId({ item: tab, specifier: "container" });
        window.setTimeout(() => {
            document
                .getElementById(tabContainerId)
                ?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "instant" });
        }, 50);
    });
    const handleOpenChange = useCallback((newIsOpen) => {
        setIsOpen(newIsOpen);
    }, []);
    const handleOpen = useCallback(() => {
        const selectedTabIndex = tabs.findIndex((t) => t.id === selectedTabId);
        setFocusedIndex(selectedTabIndex >= 0 ? selectedTabIndex : 0);
        setFocusedAction(SELECT_ITEM_ACTION);
    }, [tabs, selectedTabId, setFocusedIndex, setFocusedAction]);
    if (!isOverflowing) {
        return null;
    }
    return (_jsx("div", { className: UiTabsBem.e("dropdown-wrapper", { mobile: isMobile }), children: _jsx("div", { className: UiTabsBem.e("dropdown", { mobile: isMobile }), children: _jsx(UiDropdown, { renderButton: ({ toggleDropdown, isOpen, ref, ariaAttributes }) => (_jsx(AllTabsButton, { onClick: toggleDropdown, isOpen: isOpen, ref: ref, ariaAttributes: ariaAttributes })), renderBody: ({ ariaAttributes }) => {
                    return (_jsx(ScopedIdStore, { value: scopedIdStoreValue, children: _jsx("div", { className: UiTabsBem.e("tab-list", { mobile: isMobile }), ref: containerRef, onKeyDown: onKeyboardNavigation, tabIndex: -1, ...ariaAttributes, role: "grid", "aria-rowcount": tabs.length, children: tabs.map((item, index) => (_jsx(TabListItem, { item: item, index: index, focusedAction: item === focusedItem ? focusedAction : undefined, onApply: handleDropdownSelect(item) }, item.id))) }) }));
                }, autofocusOnOpen: true, enableFocusTrap: true, alignPoints: [{ align: "br tr" }, { align: "tr br" }], closeOnEscape: true, accessibilityConfig: {
                    triggerRole: "button",
                    popupRole: "listbox",
                }, onOpenChange: handleOpenChange, isOpen: isOpen, onOpen: handleOpen }) }) }));
}
function TabListItem({ item, index, focusedAction, onApply, }) {
    const store = getTypedUiTabsContextStore();
    const { TabValue, TabActions, selectedTabId } = store.useContextStoreValues([
        "TabValue",
        "TabActions",
        "selectedTabId",
    ]);
    const isSelected = item.id === selectedTabId;
    const isFocused = !!focusedAction;
    const makeId = ScopedIdStore.useContextStoreOptional((ctx) => ctx.makeId);
    const [isActionsOpen, setIsActionsOpen] = useState(false);
    const handleToggleActionsOpen = useCallback((desiredState) => setIsActionsOpen((wasOpen) => desiredState ?? !wasOpen), [setIsActionsOpen]);
    return (_jsxs("div", { className: UiTabsBem.e("tab-list-item", {
            focused: isFocused,
            "select-item": focusedAction === SELECT_ITEM_ACTION,
            "actions-open": isActionsOpen,
        }), role: "row", "aria-rowindex": index + 1, "aria-labelledby": makeId?.({ item, specifier: SELECT_ITEM_ACTION }), tabIndex: -1, id: makeId?.({ item, specifier: "container" }), children: [
            _jsx("div", { className: UiTabsBem.e("tab-list-item-value"), onClick: onApply, role: "gridcell", children: _jsx("div", { role: "button", tabIndex: isSelected ? 0 : -1, id: makeId?.({ item, specifier: SELECT_ITEM_ACTION }), className: UiTabsBem.e("tab-list-item-value-button"), "aria-label": item.label, children: _jsx(TabValue, { tab: item, isSelected: isSelected, location: "allList" }) }) }), (item.actions ?? []).length ? (_jsx("div", { className: UiTabsBem.e("tab-list-item-actions", {
                    focused: isFocused,
                }), role: "gridcell", id: makeId?.({ item, specifier: "actions" }), children: _jsx(TabActions, { tab: item, location: "allList", tabIndex: -1, id: makeId?.({ item, specifier: "selectTabActions" }), isOpen: isActionsOpen, onToggleOpen: handleToggleActionsOpen }) })) : null] }));
}
