import React, { useRef, useCallback, useEffect, useState } from "react";
import { TransitionGroup } from "react-transition-group";
import Drawer from "../Drawer";
import TransitionSlide from "../../transitions/TransitionSlide";
import { useSide } from "./Provider";
export const SideWrapper = (props) => {
    var _a;
    // Nb Note that it's not a real queue and we need to handle where we go from each _slide_
    const { state, setSide } = useSide();
    const [queue, setQueue] = useState([]);
    const [direction, setDirection] = useState("left");
    const [transitionsEnabled, setTransitionsEnabled] = useState(false);
    const nonce = useRef(0);
    const onClose = useCallback(() => setSide(), [setSide]);
    useEffect(() => {
        setQueue(q => {
            if (!state.open || !state.Component)
                return [];
            return q.concat([Object.assign(Object.assign({}, state), { key: nonce.current++ })]);
        });
    }, [state]);
    useEffect(() => {
        let timeout;
        if (queue.length > 1) {
            const [, ...rest] = queue;
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore mismatch between nodejs and dom types
            timeout = setTimeout(() => {
                setQueue(rest);
                setDirection("left");
            }, 0);
        }
        return () => {
            if (timeout)
                clearTimeout(timeout);
        };
    }, [queue]);
    const wrappedOnBack = useCallback(() => {
        var _a;
        setDirection("right");
        const onBack = (_a = state === null || state === void 0 ? void 0 : state.props) === null || _a === void 0 ? void 0 : _a.onBack;
        onBack && onBack();
    }, [state === null || state === void 0 ? void 0 : state.props]);
    return (React.createElement(Drawer, Object.assign({}, props, { isOpen: !!state.open, onClose: onClose, onBack: ((_a = state === null || state === void 0 ? void 0 : state.props) === null || _a === void 0 ? void 0 : _a.onBack) ? wrappedOnBack : undefined, setTransitionsEnabled: setTransitionsEnabled, hideNavigation: false }),
        React.createElement(TransitionGroup, { enter: transitionsEnabled, exit: transitionsEnabled, component: null }, queue.map(({ Component, props, key }) => (React.createElement(TransitionSlide, { key: key, direction: direction }, Component && React.createElement(Component, Object.assign({}, props))))))));
};
export default SideWrapper;
//# sourceMappingURL=index.js.map