"use client";

import { Fragment, useEffect, useRef, useState } from "react";
import { Pause, Play } from "lucide-react";
import Logo from "@/components/ui/Logo";
import { ensureGsap, motionEnabled } from "@/lib/motion";
import { IMAGES } from "@/content/site";
import type { Dictionary } from "@/lib/i18n";

type VideoState = "loading" | "playing" | "paused" | "failed";

/**
 * 01 — Cinematic opening.
 * Sequence: navy veil → official symbol with a drawn gold orbit → the logo's oval opens as a
 * window onto the footage → headline words rise in 3D → positioning, CTA, header.
 * The background video always autoplays muted + looped; the visitor can pause/resume at any
 * time (state shown on the control, with a loop-progress ring). If the video cannot play the
 * poster image stays as a still. Repeat visits in a session skip the veil.
 */
export default function Hero({ t }: { t: Dictionary["hero"] }) {
  const root = useRef<HTMLElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const ringRef = useRef<SVGCircleElement>(null);
  const [video, setVideo] = useState<VideoState>("loading");

  // Video: autoplay (muted is required by browsers for autoplay), track the real state.
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = true;
    const onPlay = () => setVideo("playing");
    const onPause = () => setVideo((s) => (s === "failed" ? s : "paused"));
    const onError = () => setVideo("failed");
    const onTime = () => {
      const ring = ringRef.current;
      if (ring && v.duration) ring.style.strokeDashoffset = String(1 - v.currentTime / v.duration);
    };
    v.addEventListener("playing", onPlay);
    v.addEventListener("pause", onPause);
    v.addEventListener("error", onError);
    v.addEventListener("timeupdate", onTime);
    // Errors on <source> children do not bubble to the video element.
    const lastSource = v.querySelector("source:last-of-type");
    lastSource?.addEventListener("error", onError);
    v.play().catch(() => setVideo((s) => (s === "playing" ? s : "paused")));
    return () => {
      v.removeEventListener("playing", onPlay);
      v.removeEventListener("pause", onPause);
      v.removeEventListener("error", onError);
      v.removeEventListener("timeupdate", onTime);
      lastSource?.removeEventListener("error", onError);
    };
  }, []);

  useEffect(() => {
    const el = root.current;
    if (!el || !motionEnabled()) return;
    const { gsap } = ensureGsap();
    const seen = sessionStorage.getItem("api-intro") === "1";
    sessionStorage.setItem("api-intro", "1");

    const ctx = gsap.context(() => {
      const q = (s: string) => el.querySelectorAll(s);
      const header = document.querySelector<HTMLElement>(".site-header");
      gsap.set(q("[data-hero]"), { opacity: 1 });
      gsap.set(q(".hero-word > span"), { yPercent: 120, rotateX: -75, opacity: 0, transformOrigin: "50% 100% -40px" });
      gsap.set(q("[data-hero='pos'], [data-hero='cue'], [data-hero='cta']"), { opacity: 0, y: 18 });
      gsap.set(q(".hero-rule"), { scaleX: 0 });
      if (header) gsap.set(header, { opacity: 0, y: -20 });

      const tl = gsap.timeline({ defaults: { ease: "expo.out" } });
      if (!seen) {
        tl.set(q(".hero-veil"), { autoAlpha: 1 })
          .fromTo(q(".hero-veil-mark"), { opacity: 0, scale: 0.86 }, { opacity: 1, scale: 1, duration: 0.9 })
          .fromTo(q(".hero-orbit"), { strokeDashoffset: 1 }, { strokeDashoffset: 0, duration: 1, ease: "power2.inOut" }, "<0.1")
          .to(q(".hero-veil-mark"), { opacity: 0, scale: 1.08, duration: 0.5, ease: "power2.in" }, "+=0.05")
          .to(q(".hero-veil"), { autoAlpha: 0, duration: 0.45 }, "-=0.1");
      } else {
        tl.set(q(".hero-veil"), { autoAlpha: 0 });
      }
      tl.fromTo(
        q(".hero-window"),
        { clipPath: "ellipse(9% 15% at 50% 50%)" },
        { clipPath: "ellipse(100% 100% at 50% 50%)", duration: seen ? 1.2 : 1.6, ease: "expo.inOut" },
        seen ? 0 : "-=0.4",
      )
        .fromTo(q(".hero-media"), { scale: 1.4, filter: "blur(8px)" }, { scale: 1, filter: "blur(0px)", duration: 2.4 }, "<")
        .to(q("[data-hero='brand']"), { opacity: 1, letterSpacing: "0.32em", duration: 1.2 }, "-=1.4")
        .to(q(".hero-word > span"), { yPercent: 0, rotateX: 0, opacity: 1, duration: 1.4, stagger: 0.09 }, "<0.05")
        .to(q(".hero-rule"), { scaleX: 1, duration: 1.2, ease: "expo.inOut" }, "-=1.1")
        .to(q("[data-hero='pos']"), { opacity: 1, y: 0, duration: 1, stagger: 0.12 }, "-=0.9")
        .to(header, { opacity: 1, y: 0, duration: 1 }, "<")
        .to(q("[data-hero='cta'], [data-hero='cue']"), { opacity: 1, y: 0, duration: 1, stagger: 0.1 }, "-=0.7");

      // Scroll-out: layered depth — media pushes in, headline lifts and softens, shade deepens.
      const out = { trigger: el, start: "top top", end: "bottom top", scrub: 0.6 };
      gsap.to(q(".hero-media"), { scale: 1.18, yPercent: 10, ease: "none", scrollTrigger: out });
      gsap.to(q(".hero-shade"), { opacity: 0.92, ease: "none", scrollTrigger: out });
      gsap.to(q(".hero-content"), {
        yPercent: -28,
        opacity: 0,
        filter: "blur(6px)",
        ease: "none",
        scrollTrigger: { ...out, end: "75% top" },
      });
      gsap.to(q(".hero-title"), { letterSpacing: "0.08em", ease: "none", scrollTrigger: { ...out, end: "75% top" } });

      // Pointer parallax (fine pointers only): media and type move in opposite planes.
      if (window.matchMedia("(hover: hover) and (pointer: fine)").matches) {
        const mx = gsap.quickTo(q(".hero-media-inner"), "x", { duration: 1.2, ease: "power3" });
        const my = gsap.quickTo(q(".hero-media-inner"), "y", { duration: 1.2, ease: "power3" });
        const cx = gsap.quickTo(q(".hero-depth"), "x", { duration: 1.2, ease: "power3" });
        const cy = gsap.quickTo(q(".hero-depth"), "y", { duration: 1.2, ease: "power3" });
        const onMove = (e: PointerEvent) => {
          const nx = e.clientX / window.innerWidth - 0.5;
          const ny = e.clientY / window.innerHeight - 0.5;
          mx(nx * -24);
          my(ny * -16);
          cx(nx * 12);
          cy(ny * 8);
        };
        el.addEventListener("pointermove", onMove);
        return () => el.removeEventListener("pointermove", onMove);
      }
    }, el);
    return () => ctx.revert();
  }, []);

  const toggleVideo = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) v.play().catch(() => setVideo("paused"));
    else v.pause();
  };

  const playing = video === "playing" || video === "loading";

  return (
    <section
      id="top"
      ref={root}
      data-theme="dark"
      aria-labelledby="hero-title"
      className="hero-intro relative h-[100svh] min-h-[560px] overflow-hidden bg-navy-ink text-white"
    >
      {/* Media window — opens from the logo's oval */}
      <div className="hero-window absolute inset-0">
        <div className="hero-media absolute inset-0 will-change-transform">
          <div className="hero-media-inner absolute -inset-8">
            {/* Poster underneath: shown while the video loads, and as the fallback if it fails. */}
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={IMAGES.heroPoster.src} alt="" className="media-cover" fetchPriority="high" />
            <video
              ref={videoRef}
              className={`media-cover transition-opacity duration-[1600ms] ease-out ${video === "playing" || video === "paused" ? "opacity-100" : "opacity-0"}`}
              autoPlay
              muted
              loop
              playsInline
              preload="auto"
              poster={IMAGES.heroPoster.src}
              aria-label={t.videoLabel}
            >
              <source src={IMAGES.heroVideo.mobile} type="video/mp4" media="(max-width: 767px)" />
              <source src={IMAGES.heroVideo.desktop} type="video/mp4" />
            </video>
          </div>
        </div>
        <div className="hero-shade absolute inset-0 bg-navy-ink/30" aria-hidden="true" />
        <div
          aria-hidden="true"
          className="absolute inset-0 bg-[radial-gradient(ellipse_at_50%_35%,transparent_0%,rgb(3_18_38/0.35)_55%,rgb(3_18_38/0.85)_100%)]"
        />
        <div aria-hidden="true" className="absolute inset-x-0 bottom-0 h-1/2 bg-gradient-to-t from-navy-ink via-navy-ink/50 to-transparent" />
        <div className="grain absolute inset-0" aria-hidden="true" />
      </div>

      {/* Content */}
      <div className="hero-content container-x relative z-10 flex h-full flex-col items-center justify-center pt-[var(--header-h)] text-center">
        <div className="hero-depth flex flex-col items-center">
          <p data-hero="brand" className="eyebrow mb-7 text-gold-light">
            {t.brand}
          </p>
          <h1
            id="hero-title"
            className="hero-title display display-xl max-w-[14ch] text-balance uppercase tracking-[0.02em] [perspective:900px]"
          >
            {t.tagline.split(" ").map((w, i, all) => (
              <Fragment key={i}>
                <span className="hero-word split-word" data-hero="word">
                  <span>{w}</span>
                </span>
                {i < all.length - 1 ? " " : null}
              </Fragment>
            ))}
          </h1>
          <span aria-hidden="true" className="hero-rule mt-8 block h-px w-28 origin-center bg-gold" />
          <p className="mt-7 flex flex-wrap items-center justify-center gap-x-4 gap-y-2 text-[0.72rem] font-semibold uppercase tracking-[0.3em] text-white/85 sm:text-xs">
            {t.positioning.map((p, i) => (
              <span key={p} data-hero="pos" className="flex items-center gap-4">
                {i > 0 && <span aria-hidden="true" className="h-1 w-1 rounded-full bg-gold" />}
                {p}
              </span>
            ))}
          </p>
          <a href="#overview" data-hero="cta" className="btn mt-12 text-white">
            {t.cta}
          </a>
        </div>
      </div>

      {/* Scroll cue */}
      <div data-hero="cue" className="absolute bottom-6 left-1/2 z-10 flex -translate-x-1/2 flex-col items-center gap-3 text-white/70">
        <span className="text-[0.65rem] font-semibold uppercase tracking-[0.3em]">{t.scroll}</span>
        <span className="relative block h-12 w-px overflow-hidden bg-white/20" aria-hidden="true">
          <span className="scroll-cue-line absolute inset-0 bg-gold" />
        </span>
      </div>

      {/* Video control (WCAG 2.2.2): real play/pause with visible state + loop progress */}
      {video !== "failed" && (
        <button
          type="button"
          data-hero="cue"
          onClick={toggleVideo}
          aria-label={playing ? t.pause : t.play}
          className="group absolute bottom-6 right-[var(--gutter)] z-10 inline-flex h-12 items-center gap-3 rounded-full border border-white/25 bg-navy-ink/30 py-1 pl-1 pr-4 text-white/85 backdrop-blur-md transition hover:border-gold hover:text-white"
        >
          <span className="relative inline-flex h-10 w-10 items-center justify-center">
            <svg viewBox="0 0 40 40" className="absolute inset-0 -rotate-90" aria-hidden="true">
              <circle cx="20" cy="20" r="18" fill="none" stroke="rgb(255 255 255 / 0.15)" strokeWidth="1.5" />
              <circle
                ref={ringRef}
                cx="20"
                cy="20"
                r="18"
                fill="none"
                stroke="var(--color-gold)"
                strokeWidth="1.5"
                pathLength={1}
                strokeDasharray="1"
                strokeDashoffset="1"
              />
            </svg>
            {playing ? <Pause size={15} aria-hidden="true" /> : <Play size={15} className="translate-x-px" aria-hidden="true" />}
          </span>
          <span className="flex items-center gap-2 text-[0.65rem] font-semibold uppercase tracking-[0.24em]" aria-hidden="true">
            <span className="flex h-3 items-end gap-[2px]">
              {[0, 1, 2].map((b) => (
                <span key={b} className={`eq-bar w-[2px] bg-gold ${playing ? "" : "eq-paused"}`} style={{ animationDelay: `${b * 0.18}s` }} />
              ))}
            </span>
            {playing ? t.playing : t.paused}
          </span>
        </button>
      )}
      <span className="sr-only" role="status">
        {video === "loading" || video === "failed" ? "" : playing ? t.playing : t.paused}
      </span>

      {/* Intro veil (first visit only) */}
      <div className="hero-veil pointer-events-none invisible absolute inset-0 z-20 flex items-center justify-center bg-navy-ink" aria-hidden="true">
        <div className="hero-veil-mark relative flex items-center justify-center">
          <svg viewBox="0 0 200 200" className="absolute h-56 w-56 -rotate-90">
            <ellipse
              className="hero-orbit"
              cx="100"
              cy="100"
              rx="96"
              ry="96"
              fill="none"
              stroke="var(--color-gold)"
              strokeWidth="0.75"
              pathLength={1}
              strokeDasharray="1"
              strokeDashoffset="1"
            />
          </svg>
          <Logo variant="symbol" tone="reverse" alt="" className="h-28 w-auto" priority />
        </div>
      </div>
    </section>
  );
}
