"use client";

import { motion, useReducedMotion } from "framer-motion";
import Image from "next/image";
import type { ReactNode } from "react";

let hasPlayedInitial = false;

const curtainEase = [0.76, 0, 0.24, 1] as const;
const contentEase = [0.16, 1, 0.3, 1] as const;

type PageTransitionProps = {
  children: ReactNode;
};

export default function PageTransition({ children }: PageTransitionProps) {
  const reducedMotion = useReducedMotion();
  const isFirstPaint = !hasPlayedInitial;
  hasPlayedInitial = true;

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

  if (isFirstPaint) {
    return (
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, ease: contentEase }}
      >
        {children}
      </motion.div>
    );
  }

  return (
    <div className="relative isolate overflow-hidden">
      <div
        aria-hidden
        className="pointer-events-none absolute inset-x-0 top-0 z-20 h-[100dvh] overflow-hidden"
      >
        <motion.div
          className="h-full w-full bg-brand"
          initial={{ y: "0%" }}
          animate={{ y: "-101%" }}
          transition={{ duration: 0.58, ease: curtainEase, delay: 0.14 }}
        />
      </div>

      <div
        aria-hidden
        className="pointer-events-none absolute inset-x-0 top-0 z-30 h-[100dvh] overflow-hidden"
      >
        <motion.div
          className="flex h-full w-full items-center justify-center bg-ink"
          initial={{ y: "0%" }}
          animate={{ y: "-101%" }}
          transition={{ duration: 0.64, ease: curtainEase }}
        >
          <motion.div
            initial={{ opacity: 0, y: 12, scale: 0.94 }}
            animate={{
              opacity: [0, 1, 1, 0],
              y: [12, 0, 0, -10],
              scale: [0.94, 1, 1, 1],
            }}
            transition={{
              duration: 0.55,
              times: [0, 0.25, 0.7, 1],
              ease: "easeOut",
            }}
          >
            <Image
              src="/homepage/logo-dark.png"
              alt=""
              width={218}
              height={50}
              priority
              className="h-9 w-auto sm:h-11"
            />
          </motion.div>
        </motion.div>
      </div>

      <motion.div
        initial={{ opacity: 0, y: 56, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        transition={{ duration: 0.6, delay: 0.32, ease: contentEase }}
        style={{ transformOrigin: "center top" }}
      >
        {children}
      </motion.div>
    </div>
  );
}
