"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useRefresh = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const react_1 = require("react");
const batchUpdate_1 = tslib_1.__importDefault(require("../utils/batchUpdate"));
const usePrevious_1 = tslib_1.__importDefault(require("../utils/usePrevious"));
const useRefresh = () => {
    const [x, update] = (0, react_1.useState)(0);
    return () => {
        update(x + 1);
    };
};
exports.useRefresh = useRefresh;
const Overlay = React.forwardRef((props, ref) => {
    const { visible, ...domProps } = props;
    const domRef = (0, react_1.useRef)(null);
    const setRef = (node) => {
        domRef.current = node;
        if (ref && typeof ref === 'function') {
            ref(node);
        }
    };
    const [opacity, setOpacity] = (0, react_1.useState)(0);
    const transitionInProgressRef = (0, react_1.useRef)(false);
    const prevVisible = (0, usePrevious_1.default)(visible, visible);
    const prevOpacity = (0, usePrevious_1.default)(opacity, opacity);
    const refresh = (0, exports.useRefresh)();
    (0, react_1.useEffect)(() => {
        (0, batchUpdate_1.default)(() => {
            transitionInProgressRef.current = true;
            setOpacity(props.visible ? 1 : 0);
        }).commit();
    }, [visible]);
    if (prevVisible && !visible) {
        transitionInProgressRef.current = true;
    }
    const onTransitionEnd = () => {
        transitionInProgressRef.current = false;
        refresh();
        props?.onTransitionEnd?.();
    };
    const renderTime = Date.now();
    const renderTimeRef = (0, react_1.useRef)(renderTime);
    renderTimeRef.current = renderTime;
    (0, react_1.useEffect)(() => {
        let timeoutId;
        if (prevOpacity && !opacity) {
            timeoutId = setTimeout(() => {
                if (renderTimeRef.current != renderTime) {
                    //we had other renders, so dont do anything - bail out
                    return;
                }
                if (!visible) {
                    onTransitionEnd();
                }
            }, 1500);
        }
        return () => {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
        };
    }, [opacity, prevOpacity, renderTime]);
    const transitionInProgress = transitionInProgressRef.current;
    if (!visible && !transitionInProgress) {
        return null;
    }
    return (React.createElement("div", { ...domProps, ref: setRef, style: { ...props.style, opacity }, onTransitionEnd: onTransitionEnd }));
});
exports.default = Overlay;
