"use client";

import { useCallback, useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { motion, useReducedMotion } from "framer-motion";
import styles from "./ElorevoClosingDistanceMotion.module.css";

type Phase = "checking" | "play" | "complete";

export interface ClosingDistanceMotionProps {
  children?: ReactNode;
  storageKey?: string;
  onComplete?: () => void;
}

const TOTAL_SECONDS = 4.6;
const AT = (seconds: number) => seconds / TOTAL_SECONDS;
const CONVERGE_EASE = [.45, .03, .25, 1] as const;
const REVEAL_EASE = [.4, 0, .16, 1] as const;
const LEFT_PATH = "M5.35 4h6.82c1.23 0 1.96 1.09 1.74 2.25l-2.28 12.83C11.42 20.25 10.61 21 9.43 21H5.35C3.86 21 3 20.14 3 18.65V6.35C3 4.86 3.86 4 5.35 4Z";
const RIGHT_PATH = "M17.05 3h2.1c1.49 0 2.35.86 2.35 2.35v11.3c0 1.49-.86 2.35-2.35 2.35H15.6c-1.31 0-2.05-1.14-1.82-2.35l2.02-11.9C16 3.63 16.41 3 17.05 3Z";
const PREHYDRATION_CAPTURE = `(function(){if(window.__elvMotionCaptureInstalled)return;window.__elvMotionCaptureInstalled=true;window.__elvMotionIntent=false;var names=['pointerdown','touchstart','wheel','keydown','scroll'];var dismiss=function(){window.__elvMotionIntent=true;names.forEach(function(name){window.removeEventListener(name,dismiss,true);});};names.forEach(function(name){window.addEventListener(name,dismiss,{capture:true,once:true,passive:name!=='keydown'});});})();`;

export default function ClosingDistanceMotion({
  children,
  storageKey = "elorevo.motion-intro.v6",
  onComplete,
}: ClosingDistanceMotionProps) {
  const reduceMotion = useReducedMotion();
  const [phase, setPhase] = useState<Phase>("checking");
  const finished = useRef(false);
  const instanceId = useId().replaceAll(":", "");
  const maskId = `elv-held-breath-aperture-${instanceId}`;
  const featherId = `elv-held-breath-feather-${instanceId}`;

  const finish = useCallback(() => {
    if (finished.current) return;
    finished.current = true;
    setPhase("complete");
    onComplete?.();
    window.dispatchEvent(new CustomEvent("elorevo:intro-complete"));
  }, [onComplete]);

  useEffect(() => {
    const intentWindow = window as Window & { __elvMotionIntent?: boolean };
    const supportsMask = window.CSS?.supports("mask-image", "radial-gradient(circle, transparent, #000)")
      || window.CSS?.supports("-webkit-mask-image", "radial-gradient(circle, transparent, #000)");
    let nextPhase: Phase = "complete";
    if (!reduceMotion && !intentWindow.__elvMotionIntent && !document.hidden && supportsMask) {
      try {
        if (window.sessionStorage.getItem(storageKey) !== "seen") {
          window.sessionStorage.setItem(storageKey, "seen");
          finished.current = false;
          nextPhase = "play";
        }
      } catch { /* Storage failure resolves to the fully revealed state. */ }
    }
    const phaseFrame = window.requestAnimationFrame(() => setPhase(nextPhase));
    return () => window.cancelAnimationFrame(phaseFrame);
  }, [reduceMotion, storageKey]);

  useEffect(() => {
    if (phase !== "play") return;
    const interrupt = () => finish();
    const visibility = () => { if (document.hidden) finish(); };
    for (const type of ["keydown", "pointerdown", "touchstart", "wheel", "scroll"] as const) {
      window.addEventListener(type, interrupt, { passive: type !== "keydown", capture: true });
    }
    document.addEventListener("visibilitychange", visibility);
    const completion = window.setTimeout(finish, 4600);
    const watchdog = window.setTimeout(finish, 5800);
    return () => {
      window.clearTimeout(completion);
      window.clearTimeout(watchdog);
      for (const type of ["keydown", "pointerdown", "touchstart", "wheel", "scroll"] as const) {
        window.removeEventListener(type, interrupt, true);
      }
      document.removeEventListener("visibilitychange", visibility);
    };
  }, [finish, phase]);

  const playing = phase === "play";
  const complete = phase === "complete";
  const veilStyle = { "--aperture-radius": "0px", "--aperture-near": "0px", "--aperture-mid": "0px", "--aperture-far": "0px" } as CSSProperties;
  const lightStyle = { "--light-radius": "0px" } as CSSProperties;

  const heroContent = children ? (
    <div className={styles.heroInner}>{children}</div>
  ) : (
    <div className={styles.heroInner}>
      <div><p className={styles.eyebrow}>Enterprise AI</p></div>
      <div><h1>Intelligence should make work clearer.</h1></div>
      <div><p className={styles.supporting}>Elorevo builds intelligent software for organizations whose work carries consequence.</p></div>
      <div className={styles.actions}><span className={styles.primaryAction}>Talk with Elorevo</span><span className={styles.secondaryAction}>See how it works</span></div>
      <div className={styles.proof}>Purpose · Authority · Evidence</div>
      <div className={styles.environment} aria-hidden="true" />
    </div>
  );

  return (
    <div className={styles.frame}>
      <script dangerouslySetInnerHTML={{ __html: PREHYDRATION_CAPTURE }} />
      <main className={styles.hero}>
        <header className={styles.header}>
          <span className={styles.brand}>
            <svg className={styles.headerSymbol} viewBox="0 0 24 24" aria-hidden="true">
              <path d={LEFT_PATH} /><path d={RIGHT_PATH} />
            </svg><span>Elorevo</span>
          </span>
          <nav className={styles.nav} aria-label="Primary"><span>Platform</span><span>Solutions</span><span>Customers</span><span>About</span><strong>Talk with Elorevo</strong></nav>
        </header>
        {heroContent}
      </main>

      {!complete && (
        <div className={styles.overlay} aria-hidden="true">
          <motion.div
            className={styles.veil}
            initial={false}
            style={veilStyle}
            animate={playing ? {
              "--aperture-radius": ["0px", "0px", "0px", "18vmax", "30vmax", "54vmax", "84vmax", "170vmax", "170vmax"],
              "--aperture-near": ["0px", "0px", "0px", "26px", "26px", "26px", "26px", "26px", "26px"],
              "--aperture-mid": ["0px", "0px", "0px", "92px", "92px", "92px", "92px", "92px", "92px"],
              "--aperture-far": ["0px", "0px", "0px", "164px", "164px", "164px", "164px", "164px", "164px"],
            } : { "--aperture-radius": "0px", "--aperture-near": "0px", "--aperture-mid": "0px", "--aperture-far": "0px" }}
            transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(2.72), AT(3.00), AT(3.20), AT(3.55), AT(3.85), AT(3.97), AT(4.04), 1], ease: REVEAL_EASE } : { duration: 0 }}
          />
          <div className={styles.mark}>
            <svg viewBox="0 0 24 24" focusable="false">
              <defs>
                <filter id={featherId} x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation=".42" /></filter>
                <mask id={maskId} maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse" x="-2" y="-2" width="28" height="28">
                  <rect x="-2" y="-2" width="28" height="28" fill="#000" />
                  <motion.rect
                    className={styles.maskLeft}
                    x="-1" y="-1" width="15.2" height="26" fill="#fff" filter={`url(#${featherId})`}
                    initial={false}
                    animate={playing ? { scaleX: [1, 1, .92, .5, 0, 0] } : { scaleX: 1 }}
                    transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(2.90), AT(3.15), AT(3.40), AT(3.65), 1], ease: REVEAL_EASE } : { duration: 0 }}
                  />
                  <motion.rect
                    className={styles.maskRight}
                    x="13.5" y="-1" width="11.5" height="26" fill="#fff" filter={`url(#${featherId})`}
                    initial={false}
                    animate={playing ? { scaleX: [1, 1, .92, .5, 0, 0] } : { scaleX: 1 }}
                    transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(2.90), AT(3.15), AT(3.40), AT(3.65), 1], ease: REVEAL_EASE } : { duration: 0 }}
                  />
                </mask>
              </defs>
              <g mask={`url(#${maskId})`}>
                <motion.path fill="#283A8F" d={LEFT_PATH} animate={playing ? { x: ["-48%", "-48%", "0%", "0%"] } : { x: "-48%" }} transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(.42), AT(1.50), 1], ease: CONVERGE_EASE } : { duration: 0 }} />
                <motion.path fill="#283A8F" d={RIGHT_PATH} animate={playing ? { x: ["70%", "70%", "0%", "0%"] } : { x: "70%" }} transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(.42), AT(1.50), 1], ease: CONVERGE_EASE } : { duration: 0 }} />
              </g>
            </svg>
          </div>
          <motion.div
            className={styles.light}
            initial={false}
            style={lightStyle}
            animate={playing ? {
              "--light-radius": ["0px", "0px", "5vmin", "11vmin", "16vmin", "20vmin", "20vmin", "30vmax", "70vmax", "150vmax", "170vmax", "170vmax"],
              opacity: [0, 0, .22, .44, .56, .62, .62, .55, .34, .1, 0, 0],
            } : { "--light-radius": "0px", opacity: 0 }}
            transition={playing ? { duration: TOTAL_SECONDS, times: [0, AT(1.08), AT(1.50), AT(1.85), AT(2.10), AT(2.40), AT(2.72), AT(3.10), AT(3.50), AT(4.04), AT(4.20), 1], ease: REVEAL_EASE } : { duration: 0 }}
          />
        </div>
      )}
    </div>
  );
}
