"use client";

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

const effects = ["fade-slide-up", "glitch-effect", "spin-zoom", "neon-pulse", "shutter-split"] as const;

type TransitionEffect = (typeof effects)[number];

function randomEffect(): TransitionEffect {
  return effects[Math.floor(Math.random() * effects.length)] ?? "fade-slide-up";
}

export function PageTransition() {
  const pathname = usePathname();
  const mounted = useRef(false);
  const navigatingRef = useRef(false);
  const [active, setActive] = useState(false);
  const [effect, setEffect] = useState<TransitionEffect>("fade-slide-up");

  useEffect(() => {
    function startTransition() {
      navigatingRef.current = true;
      setEffect(randomEffect());
      setActive(true);
    }

    function handleClick(event: MouseEvent) {
      if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
        return;
      }

      const anchor = (event.target as Element | null)?.closest("a");
      if (!anchor) {
        return;
      }

      const href = anchor.getAttribute("href");
      const target = anchor.getAttribute("target");
      if (!href || href.startsWith("#") || target === "_blank") {
        return;
      }

      const url = new URL(href, window.location.href);
      if (url.origin === window.location.origin && url.pathname !== window.location.pathname) {
        startTransition();
      }
    }

    document.addEventListener("click", handleClick, true);
    return () => document.removeEventListener("click", handleClick, true);
  }, []);

  useEffect(() => {
    if (!mounted.current) {
      mounted.current = true;
      return;
    }

    if (!navigatingRef.current) {
      return;
    }

    navigatingRef.current = false;
    const frame = window.requestAnimationFrame(() => {
      window.requestAnimationFrame(() => setActive(false));
    });

    return () => window.cancelAnimationFrame(frame);
  }, [pathname]);

  return (
    <div
      aria-hidden="true"
      className={active ? `page-transition-overlay active ${effect}` : "page-transition-overlay"}
    >
      <div className="page-transition-card">
        <span>Just Chill Nepal</span>
        <strong>Loading</strong>
      </div>
    </div>
  );
}
