// Kevin Ortiz — Portfolio · Top sections (Hero, Reel)

/* ============================================================
   HERO — futuristic depth-scan FX + word-by-word glitch headline
   ============================================================ */
const HERO_WORDS = ["Hi,", "I'm", "Kevin"];

function HeroSection() {
  const ctx = useContext(KevCtx);
  const canvasRef = useRef(null);
  const cfgRef = useRef({});
  cfgRef.current = {
    heroScan: ctx.heroScan,
    heroBloom: ctx.heroBloom,
    heroOverlay: ctx.heroOverlay,
  };

  const [visibleWords, setVisibleWords] = useState(0);
  const [subIn, setSubIn] = useState(false);

  const fillClass =
    ctx.headline === "bone" ? "fill-bone"
    : ctx.headline === "outline" ? "fill-outline"
    : "";

  const navItems = ["About", "Work", "Focus", "Contact"];

  // Mount the three.js FX into the canvas (module may load async → wait for it)
  useEffect(() => {
    let cleanup;
    const start = () => {
      if (canvasRef.current && window.KevHeroFX && !cleanup) {
        cleanup = window.KevHeroFX.mount(canvasRef.current, () => cfgRef.current);
      }
    };
    if (window.KevHeroFX) start();
    else window.addEventListener("kevherofx:ready", start, { once: true });
    return () => {
      window.removeEventListener("kevherofx:ready", start);
      if (cleanup) cleanup();
    };
  }, []);

  // Sequenced glitch reveal: one word every 560ms, then the subtitle.
  useEffect(() => {
    if (ctx.reveal === false) { setVisibleWords(HERO_WORDS.length); setSubIn(true); return; }
    let timers = [];
    HERO_WORDS.forEach((_, i) => {
      timers.push(setTimeout(() => setVisibleWords(i + 1), 350 + i * 560));
    });
    timers.push(setTimeout(() => setSubIn(true), 350 + HERO_WORDS.length * 560 + 240));
    return () => timers.forEach(clearTimeout);
  }, [ctx.reveal]);

  const scrollToWork = () => {
    const el = document.getElementById("work");
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 1, behavior: "smooth" });
  };

  return (
    <section className="kev-hero">
      <canvas ref={canvasRef} className="kev-hero-canvas" />

      <CornerTicks size={14} inset={18} show={ctx.corners} />

      {/* ---- Nav ---- */}
      <header style={{
        position: "relative", zIndex: 20,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "clamp(22px,3vw,34px) clamp(20px,4vw,40px) 0",
      }}>
        <a href="#" style={{
          fontFamily: "var(--ko-font-sans)", fontWeight: 800,
          fontSize: "clamp(18px,1.6vw,24px)", letterSpacing: "-0.05em",
          color: "var(--ko-fg-white)", textDecoration: "none",
        }}>K.O.</a>
        <nav style={{ display: "flex", gap: "clamp(16px,2.6vw,40px)", alignItems: "center" }}>
          {navItems.map((n) => (
            <a key={n} href={`#${n.toLowerCase()}`} className="kev-nav-link"
              style={{ fontSize: "clamp(11px,0.95vw,14px)" }}>{n}</a>
          ))}
        </nav>
      </header>

      {/* spec stamp */}
      <div className="ko-spec" style={{
        position: "absolute", top: "clamp(56px,7vw,84px)", left: "clamp(20px,4vw,40px)",
        zIndex: 20, color: "var(--ko-fg-mute-2)",
      }}>
        SHEET A‑01 / PORTFOLIO / BUILDER
      </div>

      {/* ---- Glitch headline ---- */}
      <div className={`kev-hero-copy ${fillClass}`}>
        <div className="kev-hero-words">
          {HERO_WORDS.map((w, i) => (
            <span key={i} className={`kev-hero-word ${i < visibleWords ? "is-in" : ""}`}
              style={{ animationDelay: `${i * 0.06}s` }}>{w}</span>
          ))}
        </div>
        <p className={`kev-hero-sub ${subIn ? "is-in" : ""}`}>
          A builder shaping tools, systems, and interfaces that ship.
        </p>
      </div>

      {/* ---- Scroll to explore ---- */}
      <button className="explore-btn" style={{ animationDelay: "2.2s" }} onClick={scrollToWork} aria-label="Scroll to explore">
        Scroll to explore
        <span className="explore-arrow">
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg" className="arrow-svg">
            <path d="M11 5V17" strokeWidth="2" strokeLinecap="round" />
            <path d="M6 12L11 17L16 12" strokeWidth="2" strokeLinecap="round" />
          </svg>
        </span>
      </button>
    </section>
  );
}

/* ============================================================
   REEL — two rows, scroll-driven horizontal drift
   ============================================================ */
const REEL_ROW1 = [
  ["01", "MOTION"], ["02", "WEB"], ["03", "BRAND"], ["04", "UI"], ["05", "3D"], ["06", "SYSTEM"],
  ["07", "MOTION"], ["08", "APP"], ["09", "BRAND"], ["10", "UI"], ["11", "WEB"],
];
const REEL_ROW2 = [
  ["12", "BUILD"], ["13", "OPS"], ["14", "UI"], ["15", "MOTION"], ["16", "BRAND"],
  ["17", "WEB"], ["18", "3D"], ["19", "APP"], ["20", "SYSTEM"], ["21", "BUILD"],
];

function ReelTile([num, label]) {
  return (
    <div className="kev-reel-tile" data-glow
      style={{
        "--glow-radius": 6,
        width: "clamp(280px,30vw,420px)",
        height: "clamp(180px,19vw,270px)",
      }}>
      {/* big ghost index */}
      <span style={{
        position: "absolute", top: "8%", left: "6%",
        fontFamily: "var(--ko-font-display)", fontSize: "clamp(48px,6vw,96px)",
        color: "var(--ko-fg-floor)", lineHeight: 1,
      }}>{num}</span>
      <div style={{
        position: "relative", zIndex: 2, padding: "clamp(12px,1.4vw,20px)",
        display: "flex", justifyContent: "space-between", alignItems: "flex-end", width: "100%",
      }}>
        <span className="ko-spec" style={{ color: "var(--ko-fg-mute-1)" }}>SHOT—{num}</span>
        <span className="ko-spec-strong" style={{ letterSpacing: "var(--ko-track-spec)" }}>{label}</span>
      </div>
    </div>
  );
}

function ReelSection() {
  const ctx = useContext(KevCtx);
  const sectionRef = useRef(null);
  const row1Ref = useRef(null);
  const row2Ref = useRef(null);
  const speed = ctx.reelSpeed != null ? ctx.reelSpeed : 0.3;

  useEffect(() => {
    let raf;
    const update = () => {
      const sec = sectionRef.current;
      if (!sec) return;
      const rect = sec.getBoundingClientRect();
      const offset = (window.innerHeight - rect.top) * speed;
      const t = offset - 200;
      if (row1Ref.current) row1Ref.current.style.transform = `translateX(${t}px)`;
      if (row2Ref.current) row2Ref.current.style.transform = `translateX(${-t}px)`;
    };
    const onScroll = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(update); };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    update();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); cancelAnimationFrame(raf); };
  }, [speed]);

  const tripled1 = [...REEL_ROW1, ...REEL_ROW1, ...REEL_ROW1];
  const tripled2 = [...REEL_ROW2, ...REEL_ROW2, ...REEL_ROW2];

  return (
    <section id="work" ref={sectionRef} style={{
      position: "relative", background: "var(--ko-bg-void)",
      paddingTop: "clamp(80px,12vw,160px)", paddingBottom: 40, overflow: "hidden",
      borderTop: "1px solid var(--ko-line-hairline)",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "0 clamp(20px,4vw,40px)", marginBottom: "clamp(24px,3vw,40px)",
      }}>
        <span className="ko-eyebrow">Selected work — reel</span>
        <span className="ko-spec" style={{ color: "var(--ko-fg-mute-2)" }}>21 PLATES / SCROLL-LINKED</span>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        <div ref={row1Ref} style={{ display: "flex", gap: 12, willChange: "transform", width: "max-content" }}>
          {tripled1.map((t, i) => <React.Fragment key={"r1" + i}>{ReelTile(t)}</React.Fragment>)}
        </div>
        <div ref={row2Ref} style={{ display: "flex", gap: 12, willChange: "transform", width: "max-content" }}>
          {tripled2.map((t, i) => <React.Fragment key={"r2" + i}>{ReelTile(t)}</React.Fragment>)}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroSection, ReelSection });
