import { __assign, __spreadArray } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import { cloneElement, useCallback, useRef } from 'react';
import { isElement, isFragment } from 'react-is';
import { usePopoverContext } from '../Context';
import Anchor from '../Anchor';
import { useWindowEventHandler } from '../../utils/component/WindowEventHandler';
function isOutside(el, portal, anchor) {
    return !(!anchor ||
        !(anchor instanceof Element) ||
        anchor.contains(el) ||
        portal.contains(el));
}
export function PopoverClickTrigger(_a) {
    var children = _a.children, toggle = _a.toggle, getElement = _a.getElement, _b = _a.closeOnClickOutside, closeOnClickOutside = _b === void 0 ? true : _b;
    var ctx = usePopoverContext();
    var anchorRef = useRef(null);
    var globalClick = useCallback(function (e) {
        var anchor = anchorRef.current;
        if (!anchor) {
            return;
        }
        var el = anchor.getElement();
        if (closeOnClickOutside &&
            el &&
            isOutside(e.target, ctx.portalRef.current, el)) {
            ctx.popover.setVisible(false);
        }
    }, [closeOnClickOutside, ctx.popover, ctx.portalRef]);
    useWindowEventHandler('click', globalClick, {
        capture: true,
    });
    var onClick = function () {
        var _a, _b;
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        if (isElement(children)) {
            (_b = (_a = children.props).onClick) === null || _b === void 0 ? void 0 : _b.call.apply(_b, __spreadArray([_a], args));
        }
        if (toggle) {
            ctx.popover.setVisible(!ctx.visible);
        }
        else {
            ctx.popover.setVisible(true);
        }
    };
    var child;
    if (typeof children === 'function') {
        child = children({
            onClick: onClick,
        });
    }
    else if (isElement(children) && !isFragment(children)) {
        child = cloneElement(children, {
            onClick: onClick,
        });
    }
    else {
        child = _jsx("span", __assign({ onClick: onClick, "data-zv": 'v10.0.12' }, { children: children }), void 0);
    }
    return (_jsx(Anchor, __assign({ getElement: getElement, ref: anchorRef }, { children: child }), void 0));
}
export default PopoverClickTrigger;
