/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-9f40d0e
 * Released under the MIT license.
 */

import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useSyncRef } from '@react-aria/utils';
import { useDOMRef } from '@react-spectrum/utils';
import React, { useMemo } from 'react';
import { useMenu } from 'react-aria';
import { Section as BaseSection, useTreeState } from 'react-stately';
import { CONTAINER_STYLES, extractStyles, filterBaseProps, } from '../../../tasty/index.js';
import { mergeProps } from '../../../utils/react/index.js';
import { CollectionItem } from '../../CollectionItem.js';
import { useMenuContext } from './context.js';
import { MenuItem } from './MenuItem.js';
import { MenuSection } from './MenuSection.js';
import { MenuTrigger } from './MenuTrigger.js';
import { StyledDivider, StyledFooter, StyledHeader, StyledMenu, StyledMenuWrapper, } from './styled.js';
import { SubMenuTrigger } from './SubMenuTrigger.js';
function Menu(props, ref) {
    const { header, footer, menuStyles, headerStyles, footerStyles, itemStyles, sectionStyles, sectionHeadingStyles, size = 'medium', focusOnHover = false, qa, selectedKeys, defaultSelectedKeys, onSelectionChange, ...rest } = props;
    const domRef = useDOMRef(ref);
    const contextProps = useMenuContext();
    // Convert string[] to Set<Key> for React Aria compatibility
    const ariaSelectedKeys = selectedKeys ? new Set(selectedKeys) : undefined;
    const ariaDefaultSelectedKeys = defaultSelectedKeys
        ? new Set(defaultSelectedKeys)
        : undefined;
    const handleSelectionChange = onSelectionChange
        ? (keys) => {
            if (keys === 'all') {
                // Handle 'all' selection case - collect all available keys
                const allKeys = Array.from(state.collection.getKeys()).map((key) => String(key));
                onSelectionChange(allKeys);
            }
            else if (keys instanceof Set) {
                onSelectionChange(Array.from(keys).map((key) => String(key)));
            }
            else {
                onSelectionChange([]);
            }
        }
        : undefined;
    const completeProps = mergeProps(contextProps, rest, {
        focusOnHover,
        selectedKeys: ariaSelectedKeys,
        defaultSelectedKeys: ariaDefaultSelectedKeys,
        onSelectionChange: handleSelectionChange,
    });
    // Props used for collection building.
    const treeProps = completeProps;
    const state = useTreeState(treeProps);
    const collectionItems = [...state.collection];
    const hasSections = collectionItems.some((item) => item.type === 'section');
    const { menuProps } = useMenu(completeProps, state, domRef);
    const styles = useMemo(() => extractStyles(completeProps, CONTAINER_STYLES), [completeProps]);
    const wrapperMods = useMemo(() => {
        return {
            popover: completeProps.mods?.popover,
            footer: !!footer,
            header: !!header,
        };
    }, [completeProps.mods?.popover, footer, header]);
    const menuMods = useMemo(() => {
        return {
            sections: hasSections,
        };
    }, [hasSections]);
    // Sync the ref stored in the context object with the DOM ref returned by useDOMRef.
    // The helper from @react-aria/utils expects the context object as the first argument
    // to keep it up-to-date, and a ref object as the second.
    useSyncRef(contextProps, domRef);
    const renderedItems = useMemo(() => {
        const items = [];
        let isFirstSection = true;
        collectionItems.forEach((item) => {
            if (item.type === 'section') {
                if (!isFirstSection) {
                    items.push(_jsx(StyledDivider, { role: "separator", "aria-orientation": "horizontal" }, `divider-${String(item.key)}`));
                }
                items.push(_jsx(MenuSection, { item: item, state: state, styles: sectionStyles, itemStyles: itemStyles, headingStyles: sectionHeadingStyles, size: size }, item.key));
                isFirstSection = false;
                return;
            }
            let menuItem = (_jsx(MenuItem, { item: item, state: state, styles: itemStyles, size: size, onAction: item.onAction }, item.key));
            // Apply tooltip wrapper if tooltip property is provided
            // if (item.props.tooltip) {
            //   const tooltipProps =
            //     typeof item.props.tooltip === 'string'
            //       ? { title: item.props.tooltip }
            //       : item.props.tooltip;
            //   menuItem = (
            //     <TooltipProvider key={item.key} placement="right" {...tooltipProps}>
            //       {menuItem}
            //     </TooltipProvider>
            //   );
            // }
            // Apply custom wrapper if provided
            if (item.props?.wrapper) {
                menuItem = item.props.wrapper(menuItem);
            }
            else if (item.wrapper) {
                // Handle wrapper from collection nodes (e.g., SubMenuTrigger)
                menuItem = item.wrapper(menuItem);
            }
            // Ensure every child has a stable key, even if the wrapper component didn't set one.
            items.push(React.cloneElement(menuItem, { key: item.key }));
        });
        return items;
    }, [collectionItems, state, sectionStyles, itemStyles, sectionHeadingStyles]);
    return (_jsxs(StyledMenuWrapper, { qa: qa, styles: styles, mods: wrapperMods, ...filterBaseProps(completeProps), children: [header ? (_jsx(StyledHeader, { "data-size": size, styles: headerStyles, children: header })) : (_jsx("div", { role: "presentation" })), _jsx(StyledMenu, { ...mergeProps({
                    styles: menuStyles,
                    'data-size': size,
                    mods: menuMods,
                }, menuProps), ref: domRef, role: menuProps.role ?? 'menu', children: renderedItems }), footer ? (_jsx(StyledFooter, { "data-size": size, styles: footerStyles, children: footer })) : (_jsx("div", { role: "presentation" }))] }));
}
// forwardRef doesn't support generic parameters, so cast the result to the correct type
// https://stackoverflow.com/questions/58469229/react-with-typescript-generics-while-using-react-forwardref
const _Menu = React.forwardRef(Menu);
const Section = Object.assign(BaseSection, {
    displayName: 'Section',
});
const __Menu = Object.assign(_Menu, {
    Item: CollectionItem,
    Section,
    SubMenuTrigger,
    Trigger: MenuTrigger,
    displayName: 'Menu',
});
__Menu.displayName = 'Menu';
export { __Menu as Menu };

        