import { useEffect, useRef, useState, type CSSProperties } from "react";
import { Volume2, VolumeX } from "lucide-react";
import { heroClips } from "@/data/site";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const HOLD_MS = 2800;
const FADE_MS = 900;

type Incoming = number | "end";

export function CinematicHero() {
  const [base, setBase] = useState(0);
  const [incoming, setIncoming] = useState<Incoming | null>(null);
  const [incomingOn, setIncomingOn] = useState(false);
  const [phase, setPhase] = useState<"clips" | "end">("clips");
  const [muted, setMuted] = useState(true);
  const [ready, setReady] = useState(false);
  const baseRef = useRef<HTMLVideoElement>(null);
  const nextRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    if (phase !== "clips" || incoming !== null) return;
    const t = window.setTimeout(() => {
      setIncoming(base >= heroClips.length - 1 ? "end" : base + 1);
    }, HOLD_MS);
    return () => window.clearTimeout(t);
  }, [base, incoming, phase]);

  useEffect(() => {
    if (incoming === null) return;

    if (incoming === "end") {
      const id = window.requestAnimationFrame(() => setIncomingOn(true));
      return () => window.cancelAnimationFrame(id);
    }

    const el = nextRef.current;
    if (!el) return;
    let started = false;
    const go = () => {
      if (started) return;
      started = true;
      void el.play().catch(() => {});
      setIncomingOn(true);
    };
    if (el.readyState >= 2) go();
    else el.addEventListener("loadeddata", go, { once: true });
    const fb = window.setTimeout(go, 450);
    return () => {
      el.removeEventListener("loadeddata", go);
      window.clearTimeout(fb);
    };
  }, [incoming]);

  useEffect(() => {
    if (!incomingOn || incoming === null) return;
    const t = window.setTimeout(() => {
      if (incoming === "end") {
        setPhase("end");
      } else {
        setBase(incoming);
      }
      setIncoming(null);
      setIncomingOn(false);
    }, FADE_MS);
    return () => window.clearTimeout(t);
  }, [incomingOn, incoming]);

  useEffect(() => {
    const el = baseRef.current;
    if (!el || phase !== "clips") return;
    el.currentTime = 0;
    void el.play().catch(() => {});
  }, [base, phase]);

  useEffect(() => {
    if (phase !== "end") return;
    const t = window.setTimeout(() => setReady(true), 350);
    return () => window.clearTimeout(t);
  }, [phase]);

  const clip = heroClips[base] ?? heroClips[0];
  const nextClip = typeof incoming === "number" ? heroClips[incoming] : null;
  const fadeStyle = { transitionDuration: `${FADE_MS}ms` } as CSSProperties;
  const showEnd = phase === "end" || incoming === "end";
  const endOn = phase === "end" || (incoming === "end" && incomingOn);

  return (
    <section className="relative h-[100dvh] min-h-[640px] overflow-hidden bg-ink">
      {phase === "clips" && clip ? (
        <video
          key={`base-${clip.src}`}
          ref={baseRef}
          className="hero-clip absolute inset-0 h-full w-full"
          style={{ "--hero-focus": clip.focus } as CSSProperties}
          src={clip.src}
          poster={clip.poster}
          muted={muted}
          playsInline
          autoPlay
          preload="auto"
          aria-label={clip.label}
        />
      ) : null}

      {nextClip ? (
        <video
          key={`next-${nextClip.src}`}
          ref={nextRef}
          className={cn("hero-fade hero-clip absolute inset-0 h-full w-full", incomingOn ? "opacity-100" : "opacity-0")}
          style={{ "--hero-focus": nextClip.focus, ...fadeStyle } as CSSProperties}
          src={nextClip.src}
          poster={nextClip.poster}
          muted={muted}
          playsInline
          preload="auto"
          aria-label={nextClip.label}
        />
      ) : null}

      {showEnd ? (
        <img
          src="/images/logo-hero.jpg"
          alt="FerryLore"
          className={cn(
            "hero-fade hero-clip absolute inset-0 h-full w-full",
            endOn ? "opacity-100" : "opacity-0",
          )}
          style={fadeStyle}
        />
      ) : null}

      {phase === "clips" && incoming !== "end" ? (
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-ink/70 via-ink/10 to-ink/20" />
      ) : (
        <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-ink/55 via-transparent to-ink/10" />
      )}

      {phase === "clips" && incoming !== "end" ? (
        <div className="absolute inset-x-0 bottom-24 z-10 px-6 text-center sm:bottom-28">
          <p className="font-serif text-3xl italic text-ivory/90 sm:text-5xl">Life happens once.</p>
        </div>
      ) : (
        <div
          className={cn(
            "absolute inset-x-0 bottom-10 z-10 flex flex-col items-center gap-4 px-6 text-center transition-opacity sm:bottom-12",
            ready ? "opacity-100" : "opacity-0",
          )}
          style={fadeStyle}
        >
          <p className="font-serif text-lg italic text-ivory/90 sm:text-2xl">Your story deserves to live forever.</p>
          <div className="flex w-full flex-col items-center gap-3 sm:w-auto sm:flex-row">
            <Button to="/book">Create My Story</Button>
            <Button to="/stories" variant="outline">
              Explore Our Work
            </Button>
          </div>
        </div>
      )}

      {phase === "clips" && incoming !== "end" ? (
        <button
          type="button"
          onClick={() => setMuted((m) => !m)}
          className="absolute bottom-6 right-5 z-20 inline-flex size-11 items-center justify-center rounded-full border border-ivory/20 text-ivory/80 hover:text-ivory"
          aria-label={muted ? "Unmute" : "Mute"}
        >
          {muted ? <VolumeX className="size-4" /> : <Volume2 className="size-4" />}
        </button>
      ) : null}

      {phase === "clips" && incoming !== "end" ? (
        <div className="absolute bottom-6 left-1/2 z-20 flex -translate-x-1/2 flex-col items-center gap-2 text-ivory/60">
          <span className="text-[0.62rem] uppercase tracking-[0.28em]">Scroll</span>
          <span className="h-8 w-px bg-gold/70" style={{ animation: "pulse-line 2s ease-in-out infinite" }} />
        </div>
      ) : null}
    </section>
  );
}
