"use client";

import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { usePathname } from "next/navigation";
import { ReactNode } from "react";

/**
 * Soft fade + slide on route change. Keyed on pathname so every navigation
 * re-mounts the child tree inside AnimatePresence. Respects prefers-reduced-motion.
 *
 * Important: the initial state is *not hidden* — we use `initial={false}` on the
 * first render so SSR content is visible immediately and server-rendered HTML
 * remains usable with JS disabled.
 */
export function PageTransition({ children }: { children: ReactNode }) {
  const pathname = usePathname();
  const shouldReduceMotion = useReducedMotion();

  if (shouldReduceMotion) {
    return <>{children}</>;
  }

  return (
    <AnimatePresence mode="wait" initial={false}>
      <motion.div
        key={pathname}
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: -4 }}
        transition={{ duration: 0.18, ease: [0.22, 1, 0.36, 1] }}
      >
        {children}
      </motion.div>
    </AnimatePresence>
  );
}
