import { __assign } from "tslib";
import { createElement, forwardRef, useContext } from 'react';
import { isForwardRef } from 'react-is';
import PopoverContext from './Context';
function isClassComponent(component) {
    var _a;
    return !!((_a = component === null || component === void 0 ? void 0 : component.prototype) === null || _a === void 0 ? void 0 : _a.isReactComponent);
}
export function usePopover() {
    var ctx = useContext(PopoverContext);
    if (ctx === null) {
        throw new Error('usePopover must be used as child of Popover');
    }
    return ctx.popover;
}
export function exposePopover(propName) {
    return function expose(Base) {
        var componentName = Base.displayName || Base.constructor.name || 'Component';
        var shouldPassRef = isClassComponent(Base) || isForwardRef(Base);
        var comp = forwardRef(function (props, ref) {
            var _a;
            var popover = usePopover();
            var childProps = (_a = {},
                _a[propName] = popover,
                _a);
            if (shouldPassRef) {
                childProps.ref = ref;
            }
            return createElement(Base, __assign(__assign({}, props), childProps));
        });
        comp.displayName = "withPopover(" + componentName + ")";
        return comp;
    };
}
export default exposePopover('popover');
