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

import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useLayoutEffect, useRef, useState, } from 'react';
import { useFocusWithin, useHover } from 'react-aria';
import { tasty } from '../../../tasty/index.js';
import { mergeProps } from '../../../utils/react/index.js';
import { Item } from '../../content/Item/index.js';
import { ItemBadge } from '../../content/ItemBadge/index.js';
import { DisplayTransition } from '../../helpers/index.js';
import { ItemAction } from '../ItemAction/index.js';
import { ItemActionProvider } from '../ItemActionContext.js';
import { useAction } from '../use-action.js';
const StyledItem = tasty(Item, {
    as: 'button',
    type: 'neutral',
    theme: 'default',
    styles: {
        reset: 'button',
        placeContent: 'center stretch',
    },
});
const ActionsWrapper = tasty({
    styles: {
        display: 'grid',
        position: 'relative',
        placeContent: 'stretch',
        placeItems: 'stretch',
        $size: {
            '': '$size-md',
            'size=xsmall': '$size-xs',
            'size=small': '$size-sm',
            'size=medium': '$size-md',
            'size=large': '$size-lg',
            'size=xlarge': '$size-xl',
        },
        Actions: {
            $: '>',
            position: 'absolute',
            inset: '1bw 1bw auto auto',
            display: 'flex',
            gap: '1bw',
            placeItems: 'center',
            placeContent: 'center end',
            pointerEvents: 'auto',
            padding: '0 $side-padding',
            height: 'min ($size - 2bw)',
            opacity: {
                '': 1,
                'actions-hidden': 0,
            },
            translate: {
                '': '0 0',
                'actions-hidden': '.5x 0',
            },
            transition: 'theme, translate',
            // Size for the action buttons
            '$action-size': 'min(max((2x + 2bw), ($size - 1x - 2bw)), (4x - 2bw))',
            // Side padding for the button
            '$side-padding': '(($size - $action-size - 2bw) / 2)',
        },
    },
});
const ItemButton = forwardRef(function ItemButton(allProps, ref) {
    const { mods, to, htmlType, as, type = 'neutral', theme = 'default', onPress, 
    // Extract react-aria press callbacks to prevent them from leaking to DOM via rest.
    // These are handled by useButton inside useAction.
    onPressStart: _onPressStart, onPressEnd: _onPressEnd, onPressChange: _onPressChange, onPressUp: _onPressUp, actions, size = 'medium', wrapperStyles, showActionsOnHover = false, disableActionsFocus = false, isDisabled, isLoading = false, ...rest } = allProps;
    // Loading state makes the component disabled (same logic as Item)
    const finalIsDisabled = isDisabled === true || (isLoading && isDisabled !== false);
    const actionsRef = useRef(null);
    const [actionsWidth, setActionsWidth] = useState(0);
    const [areActionsVisible, setAreActionsVisible] = useState(false);
    const [areActionsShown, setAreActionsShown] = useState(false);
    useLayoutEffect(() => {
        if (actions && actionsRef.current) {
            const width = Math.round(actionsRef.current.offsetWidth);
            if (width !== actionsWidth) {
                setActionsWidth(width);
            }
        }
    }, [actions, areActionsVisible]);
    const [isFocusWithin, setIsFocusWithin] = useState(false);
    const [hasPressed, setHasPressed] = useState(false);
    const { hoverProps, isHovered } = useHover({});
    const { focusWithinProps } = useFocusWithin({
        onFocusWithinChange: setIsFocusWithin,
    });
    // Watch for data-pressed attribute on any descendant element
    useLayoutEffect(() => {
        const actionsEl = actionsRef.current;
        if (!actionsEl || !showActionsOnHover)
            return;
        const checkPressed = () => {
            setHasPressed(actionsEl.querySelector('[data-pressed]') !== null);
        };
        const observer = new MutationObserver(checkPressed);
        observer.observe(actionsEl, {
            attributes: true,
            attributeFilter: ['data-pressed'],
            subtree: true,
        });
        checkPressed();
        return () => observer.disconnect();
    }, [areActionsVisible, showActionsOnHover]);
    const shouldShowActions = isHovered || isFocusWithin || hasPressed;
    const { actionProps } = useAction({
        ...allProps,
        htmlType,
        to,
        as,
        mods,
        isDisabled: finalIsDisabled,
    }, ref);
    const button = (_jsx(StyledItem, { actions: actions ? true : undefined, ...mergeProps(rest, actionProps), htmlType: actionProps.type, type: type, theme: theme, size: size, isLoading: isLoading, isDisabled: isDisabled }));
    if (actions) {
        return (_jsxs(ActionsWrapper, { ...hoverProps, "data-size": size, mods: { 'actions-hidden': !areActionsShown && showActionsOnHover }, styles: wrapperStyles, style: {
                '--actions-width': areActionsVisible || !showActionsOnHover
                    ? `${actionsWidth}px`
                    : '0px',
                ...(typeof size === 'number' && { '--size': `${size}px` }),
            }, children: [button, _jsx(ItemActionProvider, { type: type, theme: theme, disableActionsFocus: disableActionsFocus, isDisabled: finalIsDisabled, children: showActionsOnHover ? (_jsx(DisplayTransition, { exposeUnmounted: true, isShown: shouldShowActions, onPhaseChange: (phase) => {
                            setAreActionsVisible(phase !== 'unmounted');
                        }, onToggle: (isShown) => {
                            setAreActionsShown(isShown);
                        }, children: ({ ref: transitionRef }) => {
                            return (_jsx("div", { ...focusWithinProps, ref: (node) => {
                                    actionsRef.current = node;
                                    transitionRef(node);
                                }, "data-element": "Actions", children: actions }));
                        } })) : (_jsx("div", { ref: actionsRef, "data-element": "Actions", children: actions })) })] }));
    }
    return button;
});
const _ItemButton = Object.assign(ItemButton, {
    Action: ItemAction,
    Badge: ItemBadge,
});
export { _ItemButton as ItemButton };

        