// Hero with three variants:
//   blueprint — full-bleed cycling day/night animated scene + the looping video sits in the mid-distance
//   sketch    — split layout: text left, looping video right
//   hybrid    — full-bleed video + a framed text card

const PHASES = ["day", "dusk", "night"];
const PHASE_DURATION_MS = 12000; // 12s each → 36s total loop

function useDayNightCycle(active, reduceMotion) {
  const [phase, setPhase] = useState(0); // 0..3 (continuous)
  const raf = useRef(0);
  const start = useRef(0);

  useEffect(() => {
    if (!active || reduceMotion) {
      setPhase(0);
      return;
    }
    const tick = (t) => {
      if (!start.current) start.current = t;
      const elapsed = (t - start.current) % (PHASE_DURATION_MS * 3);
      setPhase(elapsed / PHASE_DURATION_MS); // 0..3
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf.current);
  }, [active, reduceMotion]);

  // p[0..1] for each phase, summing roughly to 1
  const idx = Math.floor(phase) % 3;
  const f = phase - Math.floor(phase);
  const weights = [0, 0, 0];
  weights[idx] = 1 - f;
  weights[(idx + 1) % 3] = f;

  return { phase, idx, f, weights, label: PHASES[idx] };
}

function HeroBackdrop({ cycle }) {
  // Sky: linear-gradient that morphs by mixing three color stacks via opacity layers.
  const skyDay = "linear-gradient(180deg, #7fb8d6 0%, #b9d4e1 55%, #d8e0d8 100%)";
  const skyDusk = "linear-gradient(180deg, #2b1f3a 0%, #6e3650 45%, #d96c4f 80%, #f6b27a 100%)";
  const skyNight = "linear-gradient(180deg, #03060f 0%, #0a1126 50%, #1a2240 100%)";

  return (
    <div className="hero-bg" aria-hidden="true">
      <div className="sky-layer" style={{ background: skyDay, opacity: cycle.weights[0] }} />
      <div className="sky-layer" style={{ background: skyDusk, opacity: cycle.weights[1] }} />
      <div className="sky-layer" style={{ background: skyNight, opacity: cycle.weights[2] }} />

      {/* Stars during night */}
      <div className="stars" style={{ opacity: cycle.weights[2] }}>
        {Array.from({ length: 60 }).map((_, i) => {
          const seed = (i * 9301 + 49297) % 233280;
          const x = (seed / 233280) * 100;
          const y = ((i * 7 + 3) % 100) * 0.55; // upper portion only
          const size = 1 + ((i * 13) % 3) * 0.5;
          const delay = (i * 137) % 4000;
          return (
            <span
              key={i}
              style={{
                left: `${x}%`,
                top: `${y}%`,
                width: size,
                height: size,
                animationDelay: `${delay}ms`,
              }}
            />
          );
        })}
      </div>

      {/* Distant city skyline (silhouette + window lights) */}
      <div className="skyline">
        <svg viewBox="0 0 1600 200" preserveAspectRatio="none">
          <defs>
            <pattern id="cityWindows" x="0" y="0" width="14" height="14" patternUnits="userSpaceOnUse">
              <rect x="3" y="3" width="3" height="4" fill="currentColor" />
              <rect x="9" y="6" width="2" height="3" fill="currentColor" />
            </pattern>
          </defs>
          <path
            d="M0 200 V120 L40 120 L40 90 L80 90 L80 110 L130 110 L130 70 L170 70 L170 95 L210 95 L210 60 L260 60 L260 100 L300 100 L300 80 L340 80 L340 120 L390 120 L390 75 L440 75 L440 100 L490 100 L490 65 L540 65 L540 105 L590 105 L590 90 L640 90 L640 130 L690 130 L690 95 L740 95 L740 75 L790 75 L790 110 L840 110 L840 85 L890 85 L890 115 L940 115 L940 80 L990 80 L990 100 L1040 100 L1040 70 L1090 70 L1090 110 L1140 110 L1140 90 L1190 90 L1190 75 L1240 75 L1240 120 L1290 120 L1290 95 L1340 95 L1340 110 L1400 110 L1400 80 L1450 80 L1450 115 L1510 115 L1510 95 L1560 95 L1560 130 L1600 130 L1600 200 Z"
            fill="rgba(0,0,0,0.55)"
          />
          <g
            color={`rgba(255, 195, 110, ${0.85 * Math.max(cycle.weights[1] * 0.6 + cycle.weights[2], 0)})`}
          >
            <rect x="0" y="0" width="1600" height="200" fill="url(#cityWindows)" mask="url(#cityMask)" />
          </g>
          <defs>
            <mask id="cityMask">
              <rect width="1600" height="200" fill="white" />
              <path
                d="M0 200 V120 L40 120 L40 90 L80 90 L80 110 L130 110 L130 70 L170 70 L170 95 L210 95 L210 60 L260 60 L260 100 L300 100 L300 80 L340 80 L340 120 L390 120 L390 75 L440 75 L440 100 L490 100 L490 65 L540 65 L540 105 L590 105 L590 90 L640 90 L640 130 L690 130 L690 95 L740 95 L740 75 L790 75 L790 110 L840 110 L840 85 L890 85 L890 115 L940 115 L940 80 L990 80 L990 100 L1040 100 L1040 70 L1090 70 L1090 110 L1140 110 L1140 90 L1190 90 L1190 75 L1240 75 L1240 120 L1290 120 L1290 95 L1340 95 L1340 110 L1400 110 L1400 80 L1450 80 L1450 115 L1510 115 L1510 95 L1560 95 L1560 130 L1600 130 L1600 200 Z"
                fill="black"
              />
            </mask>
          </defs>
        </svg>
      </div>

      {/* Mid-distance: the looping video (cinemagraph) sits between skyline and road */}
      <div className="cinemagraph">
        <video
          src="assets/hero-loop.mp4"
          autoPlay
          muted
          loop
          playsInline
          data-hero-video
        />
        <div className="cinemagraph-tint" style={{
          opacity: cycle.weights[2] * 0.55 + cycle.weights[1] * 0.25
        }} />
      </div>

      {/* Lampposts (parallax mid layer) */}
      <div className="lampposts">
        {Array.from({ length: 6 }).map((_, i) => (
          <div className="lamppost" key={i} style={{ animationDelay: `${i * -3.5}s` }}>
            <span className="lamp" style={{
              opacity: 0.2 + cycle.weights[1] * 0.6 + cycle.weights[2] * 1
            }}/>
            <span className="post"/>
          </div>
        ))}
      </div>

      {/* Road */}
      <div className="road">
        <div className="lanes">
          {Array.from({ length: 14 }).map((_, i) => (
            <span key={i} style={{ animationDelay: `${i * -0.18}s` }} />
          ))}
        </div>
      </div>

      {/* Vignette + grain */}
      <div className="vignette" />
      <div className="grain" />
    </div>
  );
}

function Hero({ variant = "blueprint", reduceMotion = false }) {
  const heroRef = useRef(null);
  const [active, setActive] = useState(true);
  useEffect(() => {
    const el = heroRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([e]) => setActive(e.isIntersecting),
      { threshold: 0.05 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const cycle = useDayNightCycle(active && variant !== "sketch", reduceMotion);

  const titleBlock = (
    <div className="hero-copy">
      <div className="hero-meta mono-up">
        <span>Hyundai</span><span className="dot">·</span>
        <span>2020</span><span className="dot">·</span>
        <span>Performance Pack</span>
      </div>
      <h1 className="hero-title h-display">
        i30 <span className="hero-n">N</span>
      </h1>
      <p className="hero-sub">
        Born in Namyang,<br/>Honed at Nürburgring.
      </p>
      <div className="hero-tags">
        <span>2.0 T-GDi</span>
        <span>275 PS</span>
        <span>6-spd MT</span>
        <span>E-LSD</span>
      </div>
    </div>
  );

  const phaseLabel = (
    <div className="hero-phase mono-up" aria-live="polite">
      <span className="dot-live" />
      {cycle.label}
    </div>
  );

  return (
    <section
      id="top"
      ref={heroRef}
      className={"hero hero--" + variant}
      data-phase={cycle.label}
    >
      {variant === "blueprint" && (
        <>
          <HeroBackdrop cycle={cycle} />
          <div className="hero-overlay">
            {titleBlock}
            {phaseLabel}
            <a href="#overview" className="hero-chevron" aria-label="Scroll to overview">
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <path d="M5 8l6 6 6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square"/>
              </svg>
            </a>
          </div>
        </>
      )}

      {variant === "sketch" && (
        <div className="hero-split">
          <div className="hero-split-left">
            {titleBlock}
            <a href="#overview" className="btn-ghost hero-cta">Read the spec ↓</a>
          </div>
          <div className="hero-split-right">
            <div className="hero-video-frame">
              <video src="assets/hero-loop.mp4" autoPlay muted loop playsInline data-hero-video />
              <div className="hero-video-corner mono-up"><span className="dot-live"/>Live loop</div>
            </div>
          </div>
        </div>
      )}

      {variant === "hybrid" && (
        <>
          <div className="hero-bg-video">
            <video src="assets/hero-loop.mp4" autoPlay muted loop playsInline data-hero-video />
            <div className="hero-bg-tint" />
          </div>
          <div className="hero-card-wrap">
            <div className="hero-card">
              {titleBlock}
              <a href="#overview" className="btn-ghost hero-cta">Read the spec ↓</a>
            </div>
          </div>
        </>
      )}

      <style>{`
        .hero {
          position: relative;
          min-height: 100vh;
          padding-top: 64px; /* nav clearance */
          overflow: hidden;
          isolation: isolate;
        }
        .hero-copy { display: flex; flex-direction: column; gap: 18px; max-width: 720px; }
        .hero-meta { display: inline-flex; gap: 10px; color: var(--ink-1); font-size: 12px; }
        .hero-meta .dot { opacity: 0.5; }
        .hero-title {
          font-size: clamp(96px, 18vw, 280px);
          color: var(--ink-0);
          line-height: 0.85;
          white-space: nowrap;
        }
        .hero-n { color: var(--accent); }
        .hero-sub {
          font-family: var(--font-body);
          font-size: clamp(16px, 1.5vw, 22px);
          color: var(--ink-1);
          max-width: 520px;
        }
        .hero-tags {
          display: flex; flex-wrap: wrap; gap: 8px;
          margin-top: 8px;
        }
        .hero-tags span {
          font-family: var(--font-mono);
          font-size: 11px;
          letter-spacing: 0.12em;
          text-transform: uppercase;
          padding: 7px 11px;
          border: 1px solid var(--line);
          color: var(--ink-1);
          background: color-mix(in oklab, var(--bg-0) 35%, transparent);
        }
        .hero-phase {
          position: absolute;
          top: 86px; right: var(--gutter);
          display: inline-flex; align-items: center; gap: 8px;
          color: var(--ink-0);
          mix-blend-mode: difference;
        }
        .dot-live {
          width: 7px; height: 7px; border-radius: 50%;
          background: var(--accent);
          box-shadow: 0 0 8px var(--accent-shadow);
          animation: pulse 1.6s ease-in-out infinite;
        }
        @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
        .hero-chevron {
          position: absolute;
          left: 50%; bottom: 36px;
          transform: translateX(-50%);
          color: var(--ink-0);
          mix-blend-mode: difference;
          animation: bob 2.2s ease-in-out infinite;
        }
        @keyframes bob { 0%,100% { transform: translate(-50%, 0); } 50% { transform: translate(-50%, 8px); } }
        .hero-cta { align-self: flex-start; margin-top: 12px; }

        /* ============ BLUEPRINT VARIANT ============ */
        .hero--blueprint .hero-overlay {
          position: relative;
          z-index: 4;
          height: 100%;
          min-height: calc(100vh - 64px);
          max-width: var(--max-w);
          margin: 0 auto;
          padding: 0 var(--gutter);
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          padding-bottom: 14vh;
        }
        .hero--blueprint .hero-copy { mix-blend-mode: difference; color: #fff; }
        .hero--blueprint .hero-copy .hero-title { color: #fff; }
        .hero--blueprint .hero-copy .hero-sub { color: rgba(255,255,255,0.85); }
        .hero--blueprint .hero-tags span { color: #fff; border-color: rgba(255,255,255,0.4); background: rgba(0,0,0,0.2); }
        .hero--blueprint .hero-meta { color: rgba(255,255,255,0.85); }

        .hero-bg { position: absolute; inset: 0; z-index: 0; overflow: hidden; }
        .sky-layer {
          position: absolute; inset: 0;
          transition: opacity 0.6s linear;
        }

        .stars { position: absolute; inset: 0 0 60% 0; pointer-events: none; transition: opacity 1s linear; }
        .stars span {
          position: absolute;
          background: #fff;
          border-radius: 50%;
          opacity: 0.85;
          animation: twinkle 3.4s ease-in-out infinite;
        }
        @keyframes twinkle { 0%,100% { opacity: 0.2; } 50% { opacity: 0.95; } }

        .skyline {
          position: absolute;
          left: 0; right: 0; bottom: 30%;
          height: 22%;
          z-index: 1;
        }
        .skyline svg { width: 200%; height: 100%; animation: skylinePan 120s linear infinite; }
        @keyframes skylinePan { from { transform: translateX(0); } to { transform: translateX(-50%); } }

        .cinemagraph {
          position: absolute;
          left: 50%; top: 14%;
          transform: translateX(-50%);
          width: min(96vw, 1600px);
          aspect-ratio: 2206 / 946;
          z-index: 2;
          opacity: 0.85;
          mask-image: radial-gradient(ellipse 70% 80% at center, #000 55%, transparent 95%);
          -webkit-mask-image: radial-gradient(ellipse 70% 80% at center, #000 55%, transparent 95%);
        }
        .cinemagraph video {
          width: 100%; height: 100%;
          object-fit: cover;
          filter: saturate(0.85) contrast(1.05);
        }
        .cinemagraph-tint {
          position: absolute; inset: 0;
          background: linear-gradient(180deg, rgba(0,8,32,0.55), rgba(0,2,12,0.85));
          pointer-events: none;
          transition: opacity 0.6s linear;
        }

        .lampposts {
          position: absolute;
          left: 0; right: 0; bottom: 26%;
          height: 18%;
          z-index: 2;
          pointer-events: none;
        }
        .lamppost {
          position: absolute;
          bottom: 0;
          width: 30px;
          height: 100%;
          animation: lampPan 14s linear infinite;
        }
        .lamppost .post {
          position: absolute;
          left: 14px; bottom: 0;
          width: 2px; height: 70%;
          background: rgba(0,0,0,0.65);
        }
        .lamppost .lamp {
          position: absolute;
          left: 7px; top: 28%;
          width: 16px; height: 8px;
          background: radial-gradient(circle, rgba(255, 200, 110, 0.9) 0%, rgba(255,200,110,0) 70%);
          border-radius: 50%;
          transition: opacity 0.6s linear;
          filter: blur(1px);
        }
        @keyframes lampPan { from { left: 105%; } to { left: -10%; } }

        .road {
          position: absolute;
          left: 0; right: 0; bottom: 0;
          height: 26%;
          background: linear-gradient(180deg, #15161a 0%, #07080a 100%);
          z-index: 3;
          overflow: hidden;
          border-top: 1px solid rgba(255,255,255,0.05);
        }
        .lanes { position: absolute; inset: 0; }
        .lanes span {
          position: absolute;
          top: 50%;
          height: 4px;
          width: 80px;
          background: rgba(245, 244, 241, 0.7);
          transform: translateY(-50%);
          animation: laneStreak 0.9s linear infinite;
        }
        @keyframes laneStreak { from { left: 100%; } to { left: -10%; } }

        .vignette {
          position: absolute; inset: 0; z-index: 5; pointer-events: none;
          background: radial-gradient(ellipse at center, transparent 50%, rgba(0,0,0,0.55) 100%);
        }
        .grain {
          position: absolute; inset: 0; z-index: 6; pointer-events: none;
          opacity: 0.08;
          mix-blend-mode: overlay;
          background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='160' height='160'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/></filter><rect width='100%' height='100%' filter='url(%23n)' opacity='0.7'/></svg>");
        }

        /* ============ SKETCH VARIANT ============ */
        .hero--sketch { background: var(--bg-0); }
        .hero-split {
          max-width: var(--max-w);
          margin: 0 auto;
          padding: 80px var(--gutter) 60px;
          display: grid;
          grid-template-columns: 1fr 1.2fr;
          gap: clamp(24px, 4vw, 64px);
          align-items: center;
          min-height: calc(100vh - 64px);
        }
        .hero-split-left { display: flex; flex-direction: column; gap: 24px; }
        .hero-video-frame {
          position: relative;
          aspect-ratio: 2206 / 946;
          background: var(--bg-1);
          border: 1px solid var(--line);
          overflow: hidden;
        }
        .hero-video-frame video { width: 100%; height: 100%; object-fit: cover; }
        .hero-video-corner {
          position: absolute; top: 12px; left: 12px;
          background: rgba(0,0,0,0.55);
          backdrop-filter: blur(8px);
          padding: 6px 10px;
          color: #fff;
          display: inline-flex; align-items: center; gap: 8px;
        }
        @media (max-width: 900px) {
          .hero-split { grid-template-columns: 1fr; }
        }

        /* ============ HYBRID VARIANT ============ */
        .hero--hybrid { background: #000; }
        .hero-bg-video {
          position: absolute; inset: 0; z-index: 0; overflow: hidden;
        }
        .hero-bg-video video {
          width: 100%; height: 100%; object-fit: cover;
        }
        .hero-bg-tint {
          position: absolute; inset: 0;
          background:
            linear-gradient(180deg, rgba(0,0,0,0.4), rgba(0,0,0,0.7)),
            radial-gradient(ellipse at 30% 70%, rgba(0,0,0,0.0), rgba(0,0,0,0.6));
        }
        .hero-card-wrap {
          position: relative; z-index: 2;
          max-width: var(--max-w);
          margin: 0 auto;
          padding: 0 var(--gutter);
          min-height: calc(100vh - 64px);
          display: flex; align-items: center;
        }
        .hero-card {
          background: color-mix(in oklab, var(--bg-0) 75%, transparent);
          backdrop-filter: blur(12px) saturate(120%);
          border: 1px solid color-mix(in oklab, var(--line) 80%, transparent);
          padding: 40px clamp(28px, 4vw, 56px);
          max-width: 680px;
          display: flex; flex-direction: column; gap: 20px;
        }
      `}</style>
    </section>
  );
}

window.Hero = Hero;
