import React__default, { useCallback } from 'react';
import { useDropdownContext } from './DropdownContext.js';

/**
 * DropdownTrigger component - wraps the trigger element
 */
const DropdownTrigger = ({ children, className }) => {
    var _a;
    const { isOpen, onOpenChange, triggerRef, menuId } = useDropdownContext();
    const handleClick = useCallback(() => {
        onOpenChange(!isOpen);
    }, [isOpen, onOpenChange]);
    const childElement = children;
    // Clone the child element and add our props
    const trigger = React__default.cloneElement(childElement, {
        ref: (el) => {
            triggerRef.current = el;
            // Preserve any existing ref from the child
            const childRef = childElement.ref;
            if (typeof childRef === "function") {
                childRef(el);
            }
            else if (childRef && typeof childRef === "object") {
                childRef.current = el;
            }
        },
        onClick: (e) => {
            var _a;
            // Call our handler
            handleClick();
            // Preserve any existing onClick from the child
            if ((_a = childElement.props) === null || _a === void 0 ? void 0 : _a.onClick) {
                childElement.props.onClick(e);
            }
        },
        "aria-expanded": isOpen,
        "aria-haspopup": "menu",
        "aria-controls": isOpen ? menuId : undefined,
        "data-state": isOpen ? "open" : "closed",
        className: className || ((_a = childElement.props) === null || _a === void 0 ? void 0 : _a.className),
    });
    return trigger;
};
DropdownTrigger.displayName = "Dropdown.Trigger";

export { DropdownTrigger };
