// ───────────── Hero with video bg + liquid glass nav ─────────────
// (Nav + LogoMark + Reveal live in shell.jsx)

// Custom seamless video loop fade system (JS-driven, not CSS transitions)
function useVideoFadeLoop(ref) {
  const fadingOutRef = useRef(false);
  const rafRef = useRef(null);

  useEffect(() => {
    const v = ref.current;
    if (!v) return;
    // Skip if not a real video element (HeroScene fallback)
    if (!(v instanceof HTMLVideoElement)) return;

    const cancel = () => { if (rafRef.current) cancelAnimationFrame(rafRef.current); rafRef.current = null; };

    const fadeTo = (target, duration, onDone) => {
      cancel();
      const start = performance.now();
      const from = parseFloat(v.style.opacity || "0");
      const step = (t) => {
        const k = Math.min(1, (t - start) / duration);
        const eased = k; // linear is fine
        v.style.opacity = (from + (target - from) * eased).toString();
        if (k < 1) rafRef.current = requestAnimationFrame(step);
        else { rafRef.current = null; onDone && onDone(); }
      };
      rafRef.current = requestAnimationFrame(step);
    };

    const onLoaded = () => { v.style.opacity = "0"; v.play().catch(()=>{}); fadeTo(1, 500); };
    const onTime = () => {
      if (!v.duration) return;
      const left = v.duration - v.currentTime;
      if (!fadingOutRef.current && left < 0.55) {
        fadingOutRef.current = true;
        fadeTo(0, 500);
      }
    };
    const onEnded = () => {
      v.style.opacity = "0";
      setTimeout(() => {
        v.currentTime = 0;
        v.play().catch(()=>{});
        fadingOutRef.current = false;
        fadeTo(1, 500);
      }, 100);
    };

    v.addEventListener("loadeddata", onLoaded);
    v.addEventListener("timeupdate", onTime);
    v.addEventListener("ended", onEnded);
    return () => {
      cancel();
      v.removeEventListener("loadeddata", onLoaded);
      v.removeEventListener("timeupdate", onTime);
      v.removeEventListener("ended", onEnded);
    };
  }, []);
}

function Hero({ accent, videoBg = true }) {
  const videoRef = useRef(null);
  useVideoFadeLoop(videoRef);

  return (
    <section id="top" style={{
      position: "relative", minHeight: "100vh", overflow: "hidden",
      background: "#000", display: "flex", flexDirection: "column"
    }}>
      {/* Video or fallback gradient scene */}
      {videoBg ? (
        <video
          ref={videoRef}
          muted playsInline autoPlay
          src="https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260328_115001_bcdaa3b4-03de-47e7-ad63-ae3e392c32d4.mp4"
          style={{
            position: "absolute", inset: 0, width: "100%", height: "100%",
            objectFit: "cover", transform: "translateY(12%) scale(1.05)",
            opacity: 0, zIndex: 0
          }}
        />
      ) : (
        <HeroScene accent={accent}/>
      )}
      {/* Vignettes */}
      <div style={{ position: "absolute", inset: 0, zIndex: 1, pointerEvents: "none",
        background: "radial-gradient(ellipse at 50% 30%, transparent 0%, rgba(0,0,0,0.35) 60%, rgba(0,0,0,0.78) 100%)"
      }}/>
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: "30%", zIndex: 1, pointerEvents: "none",
        background: "linear-gradient(to bottom, transparent, #07070a)"
      }}/>

      <Nav accent={accent} />

      {/* Hero content */}
      <div style={{
        position: "relative", zIndex: 10, flex: 1,
        display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        padding: "120px 24px 80px", textAlign: "center", transform: "translateY(-4%)"
      }}>
        <div className="liquid-glass" style={{
          borderRadius: 999, padding: "8px 16px 8px 12px", marginBottom: 28,
          display: "inline-flex", alignItems: "center", gap: 10,
          fontSize: 13, color: "rgba(255,255,255,0.86)", letterSpacing: "-0.005em"
        }}>
          <span style={{ display: "inline-flex", width: 24, height: 24, borderRadius: 99,
            background: `linear-gradient(135deg, ${accent[0]}, ${accent[1]}, ${accent[2]})`,
            alignItems: "center", justifyContent: "center" }}>
            <I.Sparkles size={13} stroke={2}/>
          </span>
          Booking Q3 — 4 partner slots open
          <span style={{ width: 1, height: 14, background: "rgba(255,255,255,0.15)", margin: "0 6px" }}/>
          <span style={{ color: "rgba(255,255,255,0.55)" }}>est. 2017</span>
        </div>

        <h1 className="font-serif" style={{
          fontSize: "clamp(56px, 8.6vw, 134px)",
          lineHeight: 0.94, letterSpacing: "-0.025em",
          maxWidth: 1100, color: "#fff", marginBottom: 22,
          textWrap: "balance"
        }}>
          Brand, marketing &<br/>
          <span className="italic-serif" style={{ color: "rgba(255,255,255,0.62)" }}>growth, in </span>
          <span style={{
            background: `linear-gradient(110deg, ${accent[0]}, ${accent[1]} 50%, ${accent[2]})`,
            WebkitBackgroundClip: "text", backgroundClip: "text", color: "transparent"
          }}>motion.</span>
        </h1>

        <p style={{
          maxWidth: 620, color: "rgba(255,255,255,0.72)",
          fontSize: 17, lineHeight: 1.55, marginBottom: 38, fontWeight: 400
        }}>
          Digitacurve is a small studio of strategists, designers and engineers helping ambitious
          companies <em className="italic-serif" style={{ color: "#fff" }}>find their shape</em> and ship work the internet remembers.
        </p>

        <div style={{ display: "flex", gap: 12, marginBottom: 64, flexWrap: "wrap", justifyContent: "center" }}>
          <a href="#enquiry" className="btn-primary">Start a project <I.Arrow size={16} stroke={2}/></a>
          <a href="#gallery" className="btn-ghost"><I.Play size={14} stroke={2}/> See selected work</a>
        </div>

        {/* Live stat strip */}
        <div className="liquid-glass-strong" style={{
          borderRadius: 22, padding: "14px 18px",
          display: "flex", alignItems: "center", gap: 22,
          fontSize: 13, color: "rgba(255,255,255,0.82)", flexWrap: "wrap", justifyContent: "center"
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="map-dot pulse-dot" style={{ width: 8, height: 8 }}/>
            <span>Live — 6 projects in studio</span>
          </div>
          <span style={{ opacity: 0.25 }}>|</span>
          <span>⭐ 4.96 · 142 clients</span>
          <span style={{ opacity: 0.25 }}>|</span>
          <span>↗ avg. +183% engagement YoY</span>
          <span style={{ opacity: 0.25 }}>|</span>
          <span className="font-mono" style={{ fontSize: 12, color: "rgba(255,255,255,0.55)" }}>SYD · NYC · BLR</span>
        </div>
      </div>

      {/* Bottom marquee */}
      <div style={{ position: "relative", zIndex: 10, paddingBottom: 28, overflow: "hidden" }}>
        <div style={{ display: "flex", gap: 12, width: "max-content" }} className="marquee-track">
          {[...Array(2)].map((_, k) => (
            <div key={k} style={{ display: "flex", gap: 12 }}>
              {["Brand identity","Web design","Motion","Campaigns","Performance marketing","SEO","Content strategy","Product design","Packaging","3D & CGI","Editorial","Social"].map(t=>(
                <span key={t} className="tag-chip">{t}</span>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, HeroScene });

// ───────────── Procedural 3D Hero Scene (fallback when videoBg=false) ─────────────
function HeroScene({ accent }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const onMove = (e) => {
      const x = (e.clientX / window.innerWidth - 0.5) * 2;
      const y = (e.clientY / window.innerHeight - 0.5) * 2;
      el.style.setProperty("--px", x);
      el.style.setProperty("--py", y);
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  return (
    <div ref={ref} style={{
      position: "absolute", inset: 0, zIndex: 0,
      background: "radial-gradient(ellipse at 50% 60%, #131520 0%, #07070a 70%)",
      overflow: "hidden",
      "--px": 0, "--py": 0
    }}>
      {/* Big orb */}
      <div className="floaty" style={{
        position: "absolute", left: "50%", top: "62%",
        transform: "translate(calc(-50% + var(--px) * 40px), calc(-50% + var(--py) * 30px))",
        width: 620, height: 620, borderRadius: "50%",
        background: `radial-gradient(circle at 32% 28%, ${accent[1]}, ${accent[2]} 40%, ${accent[0]}22 70%, transparent 75%)`,
        filter: "blur(8px)",
        opacity: 0.55,
      }}/>
      {/* Inner core */}
      <div style={{
        position: "absolute", left: "50%", top: "62%",
        transform: "translate(calc(-50% + var(--px) * 60px), calc(-50% + var(--py) * 45px))",
        width: 220, height: 220, borderRadius: "50%",
        background: `radial-gradient(circle at 30% 30%, #fff, ${accent[0]} 70%)`,
        boxShadow: `0 0 120px ${accent[0]}aa`,
        opacity: 0.85,
      }}/>
      {/* Concentric rings */}
      {[1.0, 1.5, 2.2, 3.0, 4.2].map((s, i) => (
        <div key={i} className={i % 2 === 0 ? "spin-slow" : "spin-rev"} style={{
          position: "absolute", left: "50%", top: "62%",
          transform: `translate(-50%,-50%) scale(${s}) rotateX(72deg)`,
          width: 360, height: 360, borderRadius: "50%",
          border: `1px solid ${accent[i % 3]}30`,
          opacity: 0.5 - i * 0.07,
          pointerEvents: "none",
        }}/>
      ))}
      {/* Stars */}
      <svg style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
        {Array.from({ length: 140 }).map((_, i) => {
          const x = (i * 37) % 100, y = (i * 53) % 100;
          return <circle key={i} cx={`${x}%`} cy={`${y}%`} r={Math.random() > 0.85 ? 1.4 : 0.6} fill="rgba(255,255,255,0.5)"/>;
        })}
      </svg>
    </div>
  );
}
