import {forwardRef, useContext, useRef} from "react";
import {getRouterContext, Outlet} from "@tanstack/react-router";
import {motion, useIsPresent} from "framer-motion";
import {cloneDeep} from "lodash";

const AnimatedOutlet = forwardRef<HTMLDivElement>((_, ref) => {
    const RouterContext = getRouterContext();

    const routerContext = useContext(RouterContext);

    const renderedContext = useRef(routerContext);

    const isPresent = useIsPresent();

    if (isPresent) {
        renderedContext.current = cloneDeep(routerContext);
    }

    return (
        <motion.div ref={ref}
                    initial={{x: "-100%"}}
                    animate={{
                        x: 0,
                        transform: "",
                        transitionEnd: {
                            transform: "none"
                        }
                    }}

                    transition={{
                        duration: 0.4,
                        ease: "circInOut",
                    }}

        >
            <RouterContext.Provider value={renderedContext.current}>
                <Outlet/>
            </RouterContext.Provider>
        </motion.div>
    );
});
export default AnimatedOutlet