"use client";

import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "motion/react";

export function PageTransition() {
  const pathname = usePathname();
  const [label, setLabel] = useState("HOME");
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const names: Record<string, string> = {
      "/": "HOME",
      "/work": "WORK",
      "/services": "SERVICES",
      "/studio": "STUDIO",
      "/contact": "CONTACT",
    };
    setLabel(names[pathname] ?? "PROJECT");
  }, [pathname]);

  useEffect(() => {
    const handler = (event: MouseEvent) => {
      const anchor = (event.target as HTMLElement).closest("a");
      if (!anchor) return;
      const href = anchor.getAttribute("href");
      if (!href || href.startsWith("#") || href.startsWith("http") || href.startsWith("mailto:") || href.startsWith("tel:")) return;
      if (href === window.location.pathname) return;
      setVisible(true);
      window.setTimeout(() => setVisible(false), 720);
    };
    document.addEventListener("click", handler);
    return () => document.removeEventListener("click", handler);
  }, []);

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          className="page-transition"
          initial={{ y: "100%" }}
          animate={{ y: 0 }}
          exit={{ y: "-100%" }}
          transition={{ duration: 0.55, ease: [0.76, 0, 0.24, 1] }}
        >
          <span>{label}</span>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
