"use client";
import { ReactNode, useEffect } from "react";
import { useNavigationStore } from "@/store/navigation-store";
import { AnimatePresence, motion, useAnimation } from "motion/react";
import { useRouter, usePathname } from "next/navigation";
import { IntroPreloader } from "@/components/ui";
import { Modal } from "@/components/general";

type TemplateProps = {
  children: ReactNode;
};

const Template = ({ children }: TemplateProps) => {
  const { path, modal } = useNavigationStore();
  const controls = useAnimation();
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    if (!path || path === pathname) return;

    const runAnimation = async () => {
      await controls.start({
        clipPath: "polygon(0% 100%, 100% 100%, 100% 0%, 0% 0%)",
        transition: { duration: 0.5, ease: "easeInOut" },
      });
      document.documentElement.style.overflow = "hidden";
      router.push(path);
    };

    runAnimation();
  }, [path, pathname, controls, router]);

  useEffect(() => {
    controls.set({
      clipPath: "polygon(0% 100%, 100% 100%, 100% 100%, 0% 100%)",
    });
  }, [pathname, controls]);

  return (
    <>
      {children}
      <motion.div
        initial={{
          clipPath: "polygon(0% 100%, 100% 100%, 100% 100%, 0% 100%)",
        }}
        animate={controls}
        className="fixed inset-0 bg-contigo-violeta z-100000 pointer-events-none flex flex-col justify-center items-center gap-3"
      >
        <IntroPreloader />
      </motion.div>
      <AnimatePresence>{modal && <Modal />}</AnimatePresence>
    </>
  );
};

export default Template;
