import { jsx as _jsx } from "react/jsx-runtime";
// (C) 2021-2026 GoodData Corporation
import { useMemo, useRef, useState, } from "react";
import { objRefToString, widgetRef } from "@gooddata/sdk-model";
import { UiFocusManager, UiMenu, getSelectedMenuId, separatorStaticItem, } from "@gooddata/sdk-ui-kit";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { selectRenderMode } from "../../../../../model/store/renderMode/renderModeSelectors.js";
import { isIInsightMenuSubmenu, } from "../../types.js";
import { CustomUiMenuContentComponent, CustomUiMenuContentItemComponent, CustomUiMenuHeaderComponent, CustomUiMenuInteractiveItemComponent, } from "./CustomUiMenuComponents.js";
import { DashboardInsightEditMenuBubble } from "./DashboardInsightEditMenuBubble.js";
import { DashboardInsightMenuBubble } from "./DashboardInsightMenuBubble.js";
import { DashboardInsightMenuContainer } from "./DashboardInsightMenuContainer.js";
function getWrappedSubmenuComponent(item, latestWidgetRef, submenuComponentCache) {
    const cachedSubmenu = submenuComponentCache.get(item.itemId);
    if (cachedSubmenu && cachedSubmenu.SubmenuComponent === item.SubmenuComponent) {
        return cachedSubmenu.WrappedComponent;
    }
    const SubmenuComponent = item.SubmenuComponent;
    function WrappedSubmenuComponent({ onBack, onClose }) {
        return _jsx(SubmenuComponent, { widget: latestWidgetRef.current, onClose: onClose, onGoBack: onBack });
    }
    submenuComponentCache.set(item.itemId, {
        SubmenuComponent: item.SubmenuComponent,
        WrappedComponent: WrappedSubmenuComponent,
    });
    return WrappedSubmenuComponent;
}
const convertToUiMenuItems = (items, latestWidgetRef, submenuComponentCache) => {
    return items.map((item) => {
        if (item.type === "separator") {
            return separatorStaticItem;
        }
        if (item.type === "group") {
            return {
                type: "group",
                id: item.itemId,
                data: null,
                stringTitle: item.itemName,
                subItems: item.items
                    ? convertToUiMenuItems(item.items, latestWidgetRef, submenuComponentCache)
                    : [],
            };
        }
        const baseFocusableItem = {
            id: item.itemId,
            stringTitle: item.itemName,
            isDisabled: item.disabled,
            data: {
                icon: item.icon,
                className: item.className,
                tooltip: item.tooltip,
                onClick: item.onClick,
            },
        };
        if (isIInsightMenuSubmenu(item)) {
            if (item.items?.length) {
                return {
                    ...baseFocusableItem,
                    type: "interactive",
                    subItems: convertToUiMenuItems(item.items, latestWidgetRef, submenuComponentCache),
                    data: {
                        ...baseFocusableItem.data,
                        subMenu: true,
                    },
                };
            }
            if (item.SubmenuComponent) {
                return {
                    ...baseFocusableItem,
                    type: "content",
                    Component: getWrappedSubmenuComponent(item, latestWidgetRef, submenuComponentCache),
                    showComponentOnly: item.renderSubmenuComponentOnly,
                    data: {
                        ...baseFocusableItem.data,
                        subMenu: true,
                    },
                };
            }
        }
        return {
            ...baseFocusableItem,
            type: "interactive",
        };
    });
};
export function DashboardInsightMenuBody({ items, widget, insight, onClose, renderMode, setSubmenu, }) {
    const widgetRefAsString = objRefToString(widgetRef(widget));
    const latestWidgetRef = useRef(widget);
    latestWidgetRef.current = widget;
    // Cache submenu components to prevent remounting caused by component identity change.
    const submenuComponentCache = useRef(new Map());
    const uiMenuItems = useMemo(() => convertToUiMenuItems(items, latestWidgetRef, submenuComponentCache.current), [items]);
    const handleSelect = (item) => {
        if (item.type === "interactive" && item.data?.onClick) {
            // Call onClick directly - the event properties are not used in the handlers
            item.data.onClick({});
        }
    };
    const handleSubmenuOpen = (level, item) => {
        if (level > 0) {
            const submenuItem = items.find((i) => i.itemId === item?.id);
            if (submenuItem) {
                setSubmenu?.(submenuItem);
            }
        }
        else {
            setSubmenu?.(null);
        }
    };
    const menuId = `insight-menu-${widgetRefAsString}`;
    const menuLabelId = `${menuId}-label`;
    const getMaxHeight = (context) => {
        if (getSelectedMenuId(context) === "Alerts") {
            return 500;
        }
        return 350;
    };
    return (_jsx(UiFocusManager, { enableAutofocus: { initialFocus: menuId }, enableFocusTrap: true, enableReturnFocusOnUnmount: true, children: _jsx(DashboardInsightMenuContainer, { children: _jsx(UiMenu, { maxHeight: getMaxHeight, containerBottomPadding: "small", items: uiMenuItems, onClose: onClose, InteractiveItem: CustomUiMenuInteractiveItemComponent, ContentItem: CustomUiMenuContentItemComponent, Content: CustomUiMenuContentComponent, MenuHeader: CustomUiMenuHeaderComponent, shouldCloseOnSelect: true, ariaAttributes: {
                    id: menuId,
                    "aria-labelledby": menuLabelId,
                }, onSelect: handleSelect, onLevelChange: handleSubmenuOpen, menuCtxData: {
                    widget,
                    insight,
                    renderMode,
                } }) }) }));
}
export function DashboardInsightMenu(props) {
    const { widget, onClose } = props;
    const renderMode = useDashboardSelector(selectRenderMode);
    const [submenu, setSubmenu] = useState(null);
    return renderMode === "edit" ? (_jsx(DashboardInsightEditMenuBubble, { onClose: onClose, isSubmenu: !!submenu, children: _jsx(DashboardInsightMenuBody, { ...props, setSubmenu: setSubmenu, renderMode: renderMode }) })) : (_jsx(DashboardInsightMenuBubble, { onClose: onClose, widget: widget, isSubmenu: !!submenu, children: _jsx(DashboardInsightMenuBody, { ...props, setSubmenu: setSubmenu, renderMode: renderMode }) }));
}
