"use client";

import { createContext, useContext, useState, useEffect, useRef } from "react";
import { usePathname, useRouter } from "next/navigation";
import { PageTransition } from "@/components/ui/page-transition";

type TransitionContextType = {
  startTransition: (url: string) => void;
};
const TransitionContext = createContext<TransitionContextType>({
  startTransition: () => {},
});
export const usePageTransition = () => useContext(TransitionContext);

export const LayoutWithTransition = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [pendingUrl, setPendingUrl] = useState<string | null>(null);
  const [direction, setDirection] = useState<"reveal" | "unreveal">("unreveal");
  const [pageReady, setPageReady] = useState(false);

  const router = useRouter();
  const pathname = usePathname();
  const prevPath = useRef<string | null>(null);

  /* --------------------------------------------------------------
     🔹 User clicks → exit animation (reveal)
   -------------------------------------------------------------- */
  const startTransition = (url: string) => {
    setDirection("reveal"); // going out
    setPendingUrl(url);
    setIsOpen(true); // start reveal animation
  };

  /* --------------------------------------------------------------
     🔹 When GSAP reveal animation finishes → navigate
   -------------------------------------------------------------- */
  const handleAnimationComplete = () => {
    if (pendingUrl) {
      router.push(pendingUrl);
      setPendingUrl(null);
      setPageReady(false); // reset entry state
    }
  };

  /* --------------------------------------------------------------
     🔹 When route changes (new page load)
     play "unreveal" after slight delay
   -------------------------------------------------------------- */
  useEffect(() => {
    if (prevPath.current && prevPath.current !== pathname) {
      // only play unreveal on navigation, not on first load
      const timer = setTimeout(() => {
        setDirection("unreveal");
        setIsOpen(true);
        setTimeout(() => setIsOpen(false), 1200); // animation duration
      }, 250); // give React time to render page
      return () => clearTimeout(timer);
    }
    prevPath.current = pathname;
  }, [pathname]);

  return (
    <TransitionContext.Provider value={{ startTransition }}>
      <main className="relative min-h-screen overflow-hidden bg-white">
        {/* Page content */}
        <div className="relative z-10">{children}</div>

        {/* Animated overlay */}
        <PageTransition
          isOpen={isOpen}
          direction={direction}
          onComplete={handleAnimationComplete}
        />
      </main>
    </TransitionContext.Provider>
  );
};
