import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useState, useCallback } from 'react';
import { useConsolidatedRef, useI18n } from '../../hooks';
import Actions from '../Actions';
import MenuButton from '../MenuButton';
const SelectionCardActions = forwardRef(function SelectionCardActions({ actions, disabled = false, contextualLabel, ...restProps }, ref) {
    const t = useI18n();
    const menuButtonRef = useConsolidatedRef(ref);
    const [isLoading, setIsLoading] = useState(false);
    const [menuItems, setMenuItems] = useState([]);
    const mapActions = useCallback((fetchedActions) => fetchedActions.map(({ text, onClick, ...action }) => ({
        ...action,
        primary: text,
        onClick: onClick
            ? (id, e) => {
                onClick(id, e, menuButtonRef.current ?? undefined);
                menuButtonRef.current?.focus();
            }
            : undefined
    })), []);
    const handleClick = useCallback(async (e) => {
        if (typeof actions !== 'function')
            return;
        if (e.currentTarget.getAttribute('aria-expanded') === 'true')
            return;
        setIsLoading(true);
        setMenuItems([]);
        try {
            const fetchedActions = await actions();
            setMenuItems(mapActions(fetchedActions));
        }
        catch {
            // rejection handled silently
        }
        finally {
            setIsLoading(false);
        }
    }, [actions, mapActions]);
    if (typeof actions === 'function') {
        return (_jsx(MenuButton, { ...restProps, ref: menuButtonRef, text: t('actions'), "aria-label": contextualLabel ? t('actions_for', [contextualLabel]) : undefined, iconOnly: true, icon: 'more', variant: 'simple', disabled: disabled, onClick: handleClick, menu: {
                items: menuItems,
                loading: isLoading
            } }));
    }
    return (_jsx(Actions, { ...restProps, items: actions, menuAt: 1, disabled: disabled, contextualLabel: contextualLabel }));
});
export default SelectionCardActions;
//# sourceMappingURL=SelectionCardActions.js.map