import * as React from 'react';
import { useEffect, useState, useRef } from 'react';
import batchUpdate from '../utils/batchUpdate';
import usePrevious from '../utils/usePrevious';
export const useRefresh = () => {
    const [x, update] = useState(0);
    return () => {
        update(x + 1);
    };
};
const Overlay = React.forwardRef((props, ref) => {
    const { visible, ...domProps } = props;
    const domRef = useRef(null);
    const setRef = (node) => {
        domRef.current = node;
        if (ref && typeof ref === 'function') {
            ref(node);
        }
    };
    const [opacity, setOpacity] = useState(0);
    const transitionInProgressRef = useRef(false);
    const prevVisible = usePrevious(visible, visible);
    const prevOpacity = usePrevious(opacity, opacity);
    const refresh = useRefresh();
    useEffect(() => {
        batchUpdate(() => {
            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 = useRef(renderTime);
    renderTimeRef.current = renderTime;
    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 }));
});
export default Overlay;
