/* global React, Common, DimmyPill, Motion */
const { Keycap, Button, OSLogo, detectOS, BrandMark, useGitHubStars, formatStars, useLatestRelease } = Common;
const { SplitText, Magnetic, Tilt, useElementProgress, useGlobalMouse, useTheme } = Motion;
const { useState: useHS, useEffect: useHE, useRef: useHR } = React;

// Ambient waveform canvas. Reacts to mouse, "breathes" continuously.
function AmbientWave() {
  const canvasRef = useHR();
  const mouseRef = useHR({ x: 0.5, y: 0.5, vel: 0 });
  const lastPosRef = useHR({ x: 0, y: 0, t: 0 });
  useHE(() => {
    const onMove = (e) => {
      const now = performance.now();
      const dt = Math.max(1, now - lastPosRef.current.t);
      const dx = e.clientX - lastPosRef.current.x;
      const dy = e.clientY - lastPosRef.current.y;
      const v = Math.min(1, Math.hypot(dx, dy) / dt * 0.5);
      mouseRef.current = {
        x: e.clientX / window.innerWidth,
        y: e.clientY / window.innerHeight,
        vel: Math.max(mouseRef.current.vel * 0.85, v),
      };
      lastPosRef.current = { x: e.clientX, y: e.clientY, t: now };
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  useHE(() => {
    const c = canvasRef.current;
    if (!c) return;
    // Skip the continuous-paint canvas on mobile and reduced-motion: it's
    // ~60fps of GPU work that fights iOS scroll smoothness for no benefit
    // on a small screen.
    if (typeof window !== "undefined") {
      const skip = window.matchMedia("(max-width: 760px), (prefers-reduced-motion: reduce)").matches;
      if (skip) return;
    }
    const ctx = c.getContext("2d");
    let raf, t = 0;
    const resize = () => {
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      c.width = c.offsetWidth * dpr;
      c.height = c.offsetHeight * dpr;
      ctx.scale(dpr, dpr);
    };
    resize();
    window.addEventListener("resize", resize);
    const draw = () => {
      t += 0.012;
      const w = c.offsetWidth, h = c.offsetHeight;
      ctx.clearRect(0, 0, w, h);
      const m = mouseRef.current;
      mouseRef.current.vel *= 0.95;
      // 3 sine waves, each slightly shifted, blend mode "lighter"
      const stripes = [
        { color: "rgba(52,211,153,0.55)", phase: 0, freq: 0.018, amp: 14 },
        { color: "rgba(56,189,248,0.55)", phase: Math.PI / 3, freq: 0.022, amp: 18 },
        { color: "rgba(129,140,248,0.55)", phase: Math.PI / 1.5, freq: 0.014, amp: 12 },
      ];
      ctx.globalCompositeOperation = "lighter";
      stripes.forEach((s, idx) => {
        ctx.beginPath();
        for (let x = 0; x <= w; x += 2) {
          const dx = Math.abs(x / w - m.x);
          const ripple = Math.exp(-dx * 8) * (8 + m.vel * 80);
          const y = h / 2
            + Math.sin(x * s.freq + t * (1 + idx * 0.3) + s.phase) * (s.amp + m.vel * 14)
            + Math.sin(x * 0.005 + t * 0.5) * 8
            + ripple * Math.sin(t * 6 + idx);
          if (x === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
        }
        ctx.lineWidth = 1.5;
        ctx.strokeStyle = s.color;
        ctx.shadowColor = s.color;
        ctx.shadowBlur = 6 + m.vel * 14;
        ctx.stroke();
      });
      ctx.globalCompositeOperation = "source-over";
      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
  }, []);
  return (
    <canvas ref={canvasRef} style={{
      position: "absolute", left: 0, right: 0, bottom: "8%",
      width: "100%", height: 220,
      pointerEvents: "none",
      maskImage: "linear-gradient(90deg, transparent, black 15%, black 85%, transparent)",
      WebkitMaskImage: "linear-gradient(90deg, transparent, black 15%, black 85%, transparent)",
      opacity: 0.85,
      zIndex: 0,
    }}/>
  );
}

// Hero with interactive demo: hold Space (or click) to record, release to "transcribe"
function Hero() {
  const os = detectOS();
  const { theme } = useTheme();
  const stars = useGitHubStars("KonradDallaOrg/dimmy");
  const starsLabel = formatStars(stars);
  const release = useLatestRelease("KonradDallaOrg/dimmy");
  const [phase, setPhase] = useHS("idle"); // idle | recording | transcribing | processing | typing | done
  const [text, setText] = useHS("");
  const [timer, setTimer] = useHS("00:00");
  const startedRef = useHR(0);
  const sectionRef = useHR();
  const cardRef = useHR();
  const cardProgress = useElementProgress(cardRef);
  const { x: mx, y: my } = useGlobalMouse();

  // Conversation-style headline animation: "Ehi" → "Dimmy"
  // Cycles through a few salutations to feel international: Ehi, Hey, Hej, Hola
  const greetings = ["Ehi,", "Hey,", "Hola,", "Salut,"];
  const [gIdx, setGIdx] = useHS(0);
  const [convo, setConvo] = useHS({ g: "", d: "", showD: false, listening: false });

  useHE(() => {
    let cancelled = false;
    const run = async () => {
      const wait = (ms) => new Promise((r) => setTimeout(r, ms));
      while (!cancelled) {
        const greeting = greetings[gIdx % greetings.length];
        // Type greeting char by char
        setConvo({ g: "", d: "", showD: false, listening: true });
        for (let i = 1; i <= greeting.length; i++) {
          if (cancelled) return;
          setConvo((c) => ({ ...c, g: greeting.slice(0, i) }));
          await wait(70 + Math.random() * 50);
        }
        await wait(280);
        // Show "Dimmy" growing in
        setConvo((c) => ({ ...c, showD: true, listening: false }));
        for (let i = 1; i <= 5; i++) {
          if (cancelled) return;
          setConvo((c) => ({ ...c, d: "Dimmy".slice(0, i) }));
          await wait(75);
        }
        await wait(2200);
        // Fade out before next greeting
        setConvo({ g: "", d: "", showD: false, listening: false });
        await wait(400);
        if (cancelled) return;
        setGIdx((i) => i + 1);
      }
    };
    run();
    return () => { cancelled = true; };
    // eslint-disable-next-line
  }, [gIdx]);

  const transcript = "Hey, can you draft a quick reply saying we're aligned and want to ship by Friday.";

  useHE(() => {
    if (phase !== "recording") return;
    startedRef.current = Date.now();
    const id = setInterval(() => {
      const s = Math.floor((Date.now() - startedRef.current) / 1000);
      setTimer(`00:${String(s).padStart(2, "0")}`);
    }, 200);
    return () => clearInterval(id);
  }, [phase]);

  const start = () => {
    if (phase !== "idle" && phase !== "done") return;
    setText(""); setPhase("recording");
  };
  const stop = () => {
    if (phase !== "recording") return;
    setPhase("transcribing");
    setTimeout(() => {
      setPhase("processing");
      setTimeout(() => {
        setPhase("typing");
        let i = 0;
        const id = setInterval(() => {
          i++;
          setText(transcript.slice(0, i));
          if (i >= transcript.length) {
            clearInterval(id);
            setPhase("done");
            setTimeout(() => { setPhase("idle"); setTimer("00:00"); }, 2400);
          }
        }, 22);
      }, 380);
    }, 460);
  };

  // Spacebar to record. Two layered bugs were making this unusable:
  //  1. armed was tied to (scrollY < 200) but the playground card sits well
  //     past 200px, so by the time the user reads "Hold Space" armed is
  //     already false and Space goes back to scrolling the page.
  //  2. Holding Space fires keydown at ~30Hz with e.repeat=true. The original
  //     code returned early on repeat, so preventDefault ran ONLY on the
  //     first press. Every subsequent repeat scrolled the page a notch — it
  //     looked like Space was "scrolling to the bottom of the site".
  // Fix: arm based on the card being in viewport, and once we've claimed
  // Space (first press while armed) keep preventing default on every repeat
  // and the keyup, until release. Modifier chords (Cmd+Space spotlight,
  // Ctrl+Space, etc.) and focused buttons/links/inputs are left alone.
  const armedRef = useHR(true);
  const claimedSpaceRef = useHR(false);
  useHE(() => {
    const blockHotkey = () => {
      const a = document.activeElement;
      if (!a || a === document.body) return false;
      if (a.isContentEditable) return true;
      const t = a.tagName;
      return t === "INPUT" || t === "TEXTAREA" || t === "SELECT" ||
             t === "BUTTON" || t === "A";
    };
    const updateArmed = () => {
      const el = cardRef.current;
      if (!el) { armedRef.current = false; return; }
      const r = el.getBoundingClientRect();
      armedRef.current = r.bottom > 0 && r.top < window.innerHeight;
    };
    updateArmed();
    window.addEventListener("scroll", updateArmed, { passive: true });
    window.addEventListener("resize", updateArmed);

    const down = (e) => {
      if (e.code !== "Space") return;
      if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;

      // If Space is being held and we already claimed it, keep blocking
      // the browser's native repeat-scroll behavior.
      if (e.repeat) {
        if (claimedSpaceRef.current) e.preventDefault();
        return;
      }

      // Fresh press. Only intercept if the playground is visible AND no
      // editable / clickable element has focus.
      if (!armedRef.current || blockHotkey()) return;
      e.preventDefault();
      claimedSpaceRef.current = true;
      start();
    };
    const up = (e) => {
      if (e.code !== "Space") return;
      if (!claimedSpaceRef.current) return;
      e.preventDefault();
      claimedSpaceRef.current = false;
      stop();
    };
    // Tab away mid-press: release the claim so the page can scroll again.
    const onBlur = () => {
      if (claimedSpaceRef.current) {
        claimedSpaceRef.current = false;
        stop();
      }
    };
    window.addEventListener("keydown", down);
    window.addEventListener("keyup", up);
    window.addEventListener("blur", onBlur);
    return () => {
      window.removeEventListener("keydown", down);
      window.removeEventListener("keyup", up);
      window.removeEventListener("blur", onBlur);
      window.removeEventListener("scroll", updateArmed);
      window.removeEventListener("resize", updateArmed);
    };
  });

  const pillState =
    phase === "recording" ? "recording"
    : phase === "transcribing" ? "transcribing"
    : phase === "processing" ? "processing"
    : phase === "typing" ? "processing"
    : phase === "done" ? "done"
    : "idle";

  // Scroll-driven parallax for the card. Disabled on mobile + reduced-motion:
  // on iOS the URL bar grows/shrinks during scroll, the resulting transform
  // updates lag behind the viewport and the card visibly stutters. Static =
  // calmer.
  const [calmScroll, setCalmScroll] = useHS(false);
  useHE(() => {
    if (typeof window === "undefined") return;
    const mq = window.matchMedia("(max-width: 760px), (prefers-reduced-motion: reduce)");
    const apply = () => setCalmScroll(mq.matches);
    apply();
    if (mq.addEventListener) mq.addEventListener("change", apply);
    else mq.addListener(apply);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", apply);
      else mq.removeListener(apply);
    };
  }, []);
  const cardScale = calmScroll ? 1 : 0.96 + Math.min(0.04, cardProgress * 0.08);
  const cardLift = calmScroll ? 0 : (1 - Math.min(1, cardProgress * 1.5)) * 40;
  // Aurora follows mouse a touch
  const auroraX = (mx - 0.5) * 40;
  const auroraY = (my - 0.5) * 30;

  return (
    <section ref={sectionRef} style={{ position: "relative", padding: "88px 32px 110px", overflow: "hidden" }}>
      {/* Background grid */}
      <div className="bg-grid" style={{
        position: "absolute", inset: 0,
        maskImage: "radial-gradient(ellipse 80% 60% at 50% 30%, black, transparent 70%)",
        WebkitMaskImage: "radial-gradient(ellipse 80% 60% at 50% 30%, black, transparent 70%)",
        pointerEvents: "none",
      }}/>

      {/* Aurora glow, drifts with the mouse */}
      <div style={{
        position: "absolute", top: -220, left: "50%",
        transform: `translate3d(calc(-50% + ${auroraX}px), ${auroraY}px, 0)`,
        width: 1100, height: 700,
        background: theme === "dark"
          ? "radial-gradient(circle, rgba(56,189,248,0.22), transparent 60%), radial-gradient(circle at 30% 60%, rgba(167,139,250,0.18), transparent 60%), radial-gradient(circle at 70% 40%, rgba(74,222,128,0.14), transparent 60%)"
          : "radial-gradient(circle, rgba(56,189,248,0.16), transparent 60%), radial-gradient(circle at 30% 60%, rgba(167,139,250,0.14), transparent 60%), radial-gradient(circle at 70% 40%, rgba(74,222,128,0.12), transparent 60%)",
        filter: "blur(60px)",
        pointerEvents: "none", zIndex: 0,
        transition: "transform 400ms cubic-bezier(0.2,0.8,0.2,1)",
      }}/>

      {/* Floating noise grain */}
      <div style={{
        position: "absolute", inset: 0,
        opacity: theme === "dark" ? 0.05 : 0.04,
        mixBlendMode: theme === "dark" ? "overlay" : "multiply",
        pointerEvents: "none",
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>\")",
      }}/>

      {/* Ambient waveform, reactive to mouse */}
      <AmbientWave/>

      <div style={{ position: "relative", maxWidth: 1100, margin: "0 auto", textAlign: "center" }}>
        {/* Status pill */}
        <div className="reveal" style={{
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "5px 12px",
          borderRadius: 999,
          background: "var(--bg-elev)",
          border: "1px solid var(--line-strong)",
          fontSize: 12, color: "var(--fg-muted)",
          marginBottom: 32, fontFamily: "var(--font-mono)",
          backdropFilter: "blur(10px)",
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 99, background: "#4ADE80",
            boxShadow: "0 0 8px #4ADE80", animation: "dimmy-pulse 2s ease-in-out infinite",
          }}/>
          {release || "v1.4.0"} · now on linux{starsLabel ? ` · ${starsLabel} stars on github` : ""}
        </div>

        <h1 style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "clamp(56px, 9.2vw, 128px)",
          lineHeight: 0.94, letterSpacing: "-0.04em",
          margin: 0, color: "var(--fg)",
          textWrap: "balance",
          minHeight: "1.9em",
          position: "relative",
          // line-height < 1 + section overflow:hidden was clipping the 'y' descender
          paddingBottom: "0.14em",
        }}>
          {/* Line 1: greeting being spoken into the void */}
          <span style={{
            display: "block",
            position: "relative",
            color: "var(--fg)",
          }}>
            <span style={{ position: "relative", display: "inline-block" }}>
              {convo.g || "\u00A0"}
              {/* Listening indicator while typing greeting */}
              {convo.listening && convo.g && (
                <span style={{
                  display: "inline-flex", verticalAlign: "0.32em", marginLeft: "0.18em", gap: 4,
                }} aria-hidden="true">
                  {[0, 1, 2].map((i) => (
                    <i key={i} style={{
                      display: "block", width: 6, height: 6, borderRadius: 99,
                      background: "#4ADE80",
                      animation: `dimmy-pulse 1.2s ease-in-out ${i * 0.18}s infinite`,
                      boxShadow: "0 0 12px #4ADE80",
                    }}/>
                  ))}
                </span>
              )}
            </span>
          </span>
          {/* Line 2: "Dimmy" answers, gradient */}
          <span className="grad-text" style={{
            display: "block",
            // line-height < 1 was making the 'y' descender escape the span's
            // background box, and background-clip:text only paints the gradient
            // inside that box → the descender came out as transparent.
            // Bumping line-height + bottom padding gives the gradient enough
            // canvas to cover the full glyph.
            lineHeight: 1.05,
            paddingBottom: "0.18em",
            opacity: convo.showD ? 1 : 0,
            transform: convo.showD ? "translateY(0) scale(1)" : "translateY(0.15em) scale(0.96)",
            filter: convo.showD ? "blur(0)" : "blur(8px)",
            transition: "opacity 500ms cubic-bezier(0.2,0.8,0.2,1), transform 600ms cubic-bezier(0.34,1.56,0.64,1), filter 500ms",
          }}>
            {convo.d || "\u00A0"}
            <span style={{
              display: "inline-block", marginLeft: "0.05em",
              opacity: convo.showD && convo.d.length === 5 ? 1 : 0,
              transform: convo.showD && convo.d.length === 5 ? "scale(1)" : "scale(0)",
              transition: "all 400ms cubic-bezier(0.34,1.8,0.64,1) 100ms",
              fontFamily: "var(--font-display)",
            }}>.</span>
          </span>
        </h1>

        {/* Static value tagline. Sits between the animated h1 and the subhead. */}
        <div className="reveal" style={{
          marginTop: 18,
          fontFamily: "var(--font-display)",
          fontSize: "clamp(22px, 2.6vw, 32px)",
          fontWeight: 600,
          letterSpacing: "-0.01em",
          color: "var(--fg)",
          transitionDelay: "900ms",
        }}>
          Detto, fatto.{" "}
          <span style={{
            fontFamily: "var(--font-mono)",
            fontSize: "clamp(11px, 1.1vw, 13px)",
            fontWeight: 400,
            color: "var(--fg-faint)",
            verticalAlign: "middle",
            marginLeft: 2,
          }}>said, done.</span>
        </div>

        <p className="reveal" style={{
          marginTop: 22, fontSize: 21, lineHeight: 1.5,
          color: "var(--fg-muted)",
          maxWidth: 620, marginInline: "auto",
          textWrap: "pretty",
          transitionDelay: "1100ms",
        }}>
          Voice dictation for macOS, Windows, Linux. Press a key, talk, release. Your words land where the cursor is. <span style={{ color: "var(--fg)" }}>Offline by default.</span>
        </p>

        {/* Try it inline */}
        <div className="reveal" style={{
          marginTop: 32, display: "inline-flex", alignItems: "center", gap: 10,
          color: "var(--fg-faint)", fontSize: 13,
          padding: "10px 16px", borderRadius: 999,
          border: "1px dashed var(--line-strong)",
          fontFamily: "var(--font-mono)",
          transitionDelay: "1300ms",
        }}>
          <span style={{ display: "inline-flex", gap: 6 }}>
            <Keycap size="sm">Hold</Keycap>
            <Keycap size="sm">Space</Keycap>
          </span>
          <span>or tap the pill below. Try it right here.</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 5v14M5 12l7 7 7-7"/></svg>
        </div>

        {/* Interactive playground */}
        <div ref={cardRef} style={{
          marginTop: 44, position: "relative",
          background: "linear-gradient(180deg, var(--bg-elev), transparent)",
          border: "1px solid var(--line)",
          borderRadius: 26,
          padding: "26px 26px 30px",
          maxWidth: 880, marginInline: "auto",
          transform: `scale(${cardScale}) translateY(${cardLift}px)`,
          transition: "transform 80ms linear, border-color 200ms",
          boxShadow: theme === "dark"
            ? "0 30px 80px -20px rgba(56,189,248,0.18), 0 0 0 1px var(--bg-elev) inset"
            : "0 30px 80px -20px rgba(56,189,248,0.20), 0 0 0 1px var(--fg-faint) inset",
        }}>
          {/* Faux desktop chrome row */}
          <div style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "0 6px 14px",
            borderBottom: "1px dashed var(--line)",
            marginBottom: 18,
            color: "var(--fg-faint)",
            fontFamily: "var(--font-mono)", fontSize: 11,
          }}>
            <span style={{ display: "inline-flex", gap: 6 }}>
              <i style={{ width: 10, height: 10, borderRadius: 99, background: "#FF5F57" }}/>
              <i style={{ width: 10, height: 10, borderRadius: 99, background: "#FEBC2E" }}/>
              <i style={{ width: 10, height: 10, borderRadius: 99, background: "#28C840" }}/>
            </span>
            <span style={{ marginLeft: 8 }}>~/work/draft.txt</span>
            <span style={{ flex: 1 }}/>
            <span style={{
              padding: "2px 8px", borderRadius: 99,
              background: phase === "recording" ? "rgba(239,68,68,0.15)"
                       : phase === "done" ? "rgba(74,222,128,0.15)"
                       : "var(--bg-elev)",
              color: phase === "recording" ? "#F87171"
                   : phase === "done" ? "#4ADE80"
                   : "var(--fg-faint)",
              transition: "all 200ms",
            }}>
              {phase === "recording" ? "● rec" : phase === "transcribing" ? "transcribing…" : phase === "processing" ? "processing…" : phase === "typing" ? "pasting…" : phase === "done" ? "done ✓" : "ready"}
            </span>
          </div>

          {/* Faux text area */}
          <div style={{
            minHeight: 120,
            padding: "20px 22px",
            textAlign: "left",
            fontSize: 19, lineHeight: 1.55,
            fontFamily: "var(--font-sans)",
            color: "var(--fg)",
            background: theme === "dark" ? "rgba(0,0,0,0.3)" : "var(--fg-faint)",
            border: "1px solid var(--line)",
            borderRadius: 14,
            position: "relative",
            textWrap: "pretty",
          }}>
            {text || (
              <span style={{ color: "var(--fg-faint)" }}>
                Hold <Keycap size="sm">Space</Keycap> and say something —
                <span style={{ marginLeft: 8, fontStyle: "italic" }}>
                  e.g. "draft a reply saying we're aligned and want to ship by Friday."
                </span>
              </span>
            )}
            {(phase === "typing" || phase === "done") && text && <span className="caret" style={{ background: phase === "typing" ? "#38BDF8" : "transparent" }}/>}
          </div>

          {/* Pill row, magnetic */}
          <div style={{
            marginTop: 22,
            display: "flex", justifyContent: "center", alignItems: "center", gap: 12,
          }}
            onMouseDown={(e) => { e.preventDefault(); start(); }}
            onMouseUp={stop}
            onMouseLeave={() => phase === "recording" && stop()}
            onTouchStart={(e) => { e.preventDefault(); start(); }}
            onTouchEnd={stop}
          >
            <Magnetic strength={0.18}>
              <div style={{ cursor: "pointer", userSelect: "none" }}>
                <DimmyPill state={pillState} border="rainbow" waveform="bars" timer={pillState === "recording" ? timer : null}/>
              </div>
            </Magnetic>
          </div>

          <div style={{
            marginTop: 16, fontSize: 11,
            fontFamily: "var(--font-mono)", color: "var(--fg-faint)",
            letterSpacing: "0.06em",
            display: "flex", justifyContent: "center", gap: "0 14px", flexWrap: "wrap",
          }}>
            <span>offline</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>whisper-large-v3-turbo</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span>78 mb</span>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ color: "#4ADE80" }}>~0.4s round-trip on m1</span>
          </div>
        </div>

        {/* Download CTAs */}
        <div id="download" className="reveal" style={{
          marginTop: 64,
          display: "flex", justifyContent: "center", alignItems: "center", gap: 14,
          flexWrap: "wrap",
          transitionDelay: "200ms",
        }}>
          <Magnetic strength={0.2}>
            <Button primary href="#" icon={<OSLogo os={os} size={16}/>} sub={
              os === "mac" ? "apple silicon · intel · macos 12+" :
              os === "win" ? "windows 10 · 11 · arm64" :
              "gtk4 · libadwaita · x86_64 + arm"
            }>
              Download for {os === "mac" ? "macOS" : os === "win" ? "Windows" : "Linux"}
            </Button>
          </Magnetic>
          <div style={{ display: "flex", gap: 8 }}>
            {["mac", "win", "linux"].filter((p) => p !== os).map((p) => (
              <a key={p} href="#" style={{
                display: "inline-flex", alignItems: "center", gap: 8,
                padding: "10px 14px", borderRadius: 10,
                border: "1px solid var(--line-strong)",
                color: "var(--fg-muted)", textDecoration: "none",
                fontSize: 13, fontFamily: "var(--font-sans)",
                transition: "all 180ms",
              }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--fg-faint)"; e.currentTarget.style.color = "var(--fg)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line-strong)"; e.currentTarget.style.color = "var(--fg-muted)"; }}
              >
                <OSLogo os={p} size={14}/>
                {p === "mac" ? "macOS" : p === "win" ? "Windows" : "Linux"}
              </a>
            ))}
          </div>
        </div>

        <div className="reveal" style={{
          marginTop: 22, fontSize: 12,
          color: "var(--fg-faint)", fontFamily: "var(--font-mono)",
          display: "inline-flex", flexWrap: "wrap", justifyContent: "center", gap: "6px 16px",
          transitionDelay: "300ms",
        }}>
          <span>free forever</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>open source</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>opt-out telemetry</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>no account</span>
          <span style={{ opacity: 0.4 }}>·</span>
          <span>~12 mb installer</span>
        </div>

        {/* Stat strip */}
        <div className="reveal hero-stats" style={{
          marginTop: 80,
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 0,
          maxWidth: 920, marginInline: "auto",
          padding: "26px 0",
          borderTop: "1px solid var(--line)",
          borderBottom: "1px solid var(--line)",
          transitionDelay: "400ms",
        }}>
          {[
            ["~0.4s", "median latency"],
            ["13", "rewrite styles"],
            ["100+", "supported apps"],
            ["0", "audio bytes saved"],
          ].map(([n, l], i) => (
            <div key={i} style={{
              padding: "0 12px", textAlign: "center",
              borderRight: i < 3 ? "1px solid var(--line)" : "none",
            }}>
              <div style={{
                fontFamily: "var(--font-display)", fontSize: 30, fontWeight: 700,
                color: "var(--fg)", letterSpacing: "-0.02em", lineHeight: 1,
              }}>{n}</div>
              <div style={{
                marginTop: 6, fontSize: 11, fontFamily: "var(--font-mono)",
                color: "var(--fg-faint)", textTransform: "uppercase", letterSpacing: "0.08em",
              }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Scroll hint */}
      <div style={{
        marginTop: 64, display: "flex", justifyContent: "center",
        color: "var(--fg-faint)", fontFamily: "var(--font-mono)", fontSize: 11,
        letterSpacing: "0.12em", textTransform: "uppercase",
      }}>
        <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
          <span>scroll to explore</span>
          <div style={{
            width: 1, height: 36,
            background: "linear-gradient(180deg, var(--line-strong), transparent)",
            animation: "float-y 2.5s ease-in-out infinite",
          }}/>
        </div>
      </div>
    </section>
  );
}

window.Hero = Hero;
