/* global React, Common */
const { Eyebrow, SectionTitle, SectionLead, Card } = Common;
const { useEffect: useHwE, useState: useHwS, useRef: useHwR } = React;

// Animated 4-stage pipeline: audio → whisper → llm → paste
function HowItWorks() {
  const [stage, setStage] = useHwS(0);
  const [running, setRunning] = useHwS(true);
  const tRef = useHwR();
  const stages = [
    {
      key: "capture",
      title: "Capture",
      sub: "your microphone",
      detail: "16kHz mono, VAD trims silence in real-time. Audio buffer never touches disk.",
      color: "#34D399",
      timing: "0ms",
    },
    {
      key: "transcribe",
      title: "Transcribe",
      sub: "whisper-large-v3-turbo",
      detail: "Runs locally on CPU/GPU via ggml. 78 MB quantized model, ~5× realtime on M1.",
      color: "#38BDF8",
      timing: "~120ms",
    },
    {
      key: "rewrite",
      title: "Rewrite",
      sub: "Gemma 4 · on your machine",
      detail: "Google's open-weights LLM. Apache 2.0, ~3 GB, no API key, no network. Pick a style: correct, professional, summarize. Skip for raw.",
      color: "#A78BFA",
      timing: "~250ms",
    },
    {
      key: "paste",
      title: "Paste",
      sub: "into the focused window",
      detail: "Clipboard simulation via system APIs. Slack, Notion, VS Code, anywhere.",
      color: "#4ADE80",
      timing: "~10ms",
    },
  ];

  useHwE(() => {
    if (!running) return;
    const id = setInterval(() => setStage((s) => (s + 1) % stages.length), 1800);
    return () => clearInterval(id);
  }, [running]);

  return (
    <section id="how" style={{ padding: "120px 32px", position: "relative" }}>
      <div className="container">
        <div style={{ textAlign: "center" }}>
          <Eyebrow num={1}>how it works</Eyebrow>
          <div style={{ height: 16 }}/>
          <SectionTitle align="center" maxWidth={780}>
            From breath to <span className="grad-text">pasted text</span><br/>
            in less than half a second.
          </SectionTitle>
          <SectionLead align="center">
            Four stages. Three of them happen on your machine. One is optional. All of them are visible in the pill.
          </SectionLead>
        </div>

        {/* Pipeline diagram */}
        <div style={{
          marginTop: 64,
          position: "relative",
          padding: "40px 24px",
          borderRadius: 20,
          border: "1px solid var(--line)",
          background: "linear-gradient(180deg, var(--bg-elev), transparent)",
        }} className="reveal">

          <div className="how-grid" style={{
            display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16,
            position: "relative",
          }}>
            {stages.map((s, i) => {
              const active = stage === i;
              const passed = stage > i;
              return (
                <div key={s.key}
                  onClick={() => { setRunning(false); setStage(i); }}
                  style={{
                    cursor: "pointer",
                    position: "relative",
                    padding: "20px 16px",
                    borderRadius: 14,
                    background: active
                      ? `linear-gradient(180deg, ${s.color}18, ${s.color}06)`
                      : "var(--bg-elev)",
                    border: `1px solid ${active ? s.color + "55" : "var(--line)"}`,
                    transition: "all 400ms cubic-bezier(0.2,0.8,0.2,1)",
                    transform: active ? "translateY(-3px)" : "translateY(0)",
                    boxShadow: active ? `0 8px 32px ${s.color}33` : "none",
                  }}>
                  <div style={{
                    display: "flex", alignItems: "center", gap: 10, marginBottom: 14,
                  }}>
                    <span style={{
                      width: 28, height: 28, borderRadius: 99,
                      background: active ? s.color : "var(--line)",
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600,
                      color: active ? "var(--bg-deep)" : "var(--fg-faint)",
                      transition: "all 400ms",
                      boxShadow: active ? `0 0 20px ${s.color}` : "none",
                    }}>{i + 1}</span>
                    <span style={{
                      fontFamily: "var(--font-mono)", fontSize: 10,
                      color: active ? s.color : "rgba(255,255,255,0.3)",
                      letterSpacing: "0.08em", textTransform: "uppercase",
                    }}>{s.timing}</span>
                  </div>
                  <div style={{
                    fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600,
                    color: "var(--fg)", marginBottom: 4,
                    letterSpacing: "-0.01em",
                  }}>{s.title}</div>
                  <div style={{
                    fontFamily: "var(--font-mono)", fontSize: 11,
                    color: active ? s.color : "var(--fg-faint)",
                    marginBottom: 10,
                  }}>{s.sub}</div>
                  <div style={{
                    fontSize: 13, color: "var(--fg-faint)",
                    lineHeight: 1.45,
                  }}>{s.detail}</div>
                  {/* Mini visual representation */}
                  <div style={{ marginTop: 14, height: 28, display: "flex", alignItems: "center" }}>
                    {i === 0 && <StageWaveform active={active} color={s.color}/>}
                    {i === 1 && <StageTokens active={active} color={s.color}/>}
                    {i === 2 && <StageSparkles active={active} color={s.color}/>}
                    {i === 3 && <StageCursor active={active} color={s.color}/>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={{
          marginTop: 24, textAlign: "center",
          fontFamily: "var(--font-mono)", fontSize: 12,
          color: "var(--fg-faint)",
        }}>
          ⌃⌥ pressed → text in your editor.&nbsp;<span style={{ color: "#4ADE80" }}>~380ms median</span>&nbsp;on m1, fully offline.
        </div>
      </div>
    </section>
  );
}

// Stage* helpers — prefixed to avoid colliding with DimmyPill's `Waveform`
// in the global Babel-in-browser scope (top-level `function` declarations
// share scope across script tags, last load wins).
function StageWaveform({ active, color }) {
  const [t, setT] = useHwS(0);
  useHwE(() => {
    if (!active) return;
    const id = setInterval(() => setT((x) => x + 1), 90);
    return () => clearInterval(id);
  }, [active]);
  return (
    <span style={{ display: "inline-flex", gap: 3, alignItems: "center", height: 24 }}>
      {[0.4, 0.7, 1, 0.6, 0.9, 0.5, 0.8, 0.4].map((w, i) => {
        const j = active ? 1 + Math.sin(t * 0.9 + i * 0.7) * 0.3 : 0.4;
        return (
          <i key={i} style={{
            width: 3, height: Math.max(3, 24 * w * j),
            background: active ? color : "rgba(255,255,255,0.2)",
            borderRadius: 1.5, transition: "background 200ms",
          }}/>
        );
      })}
    </span>
  );
}

function StageTokens({ active, color }) {
  return (
    <span style={{ display: "inline-flex", gap: 4, fontFamily: "var(--font-mono)", fontSize: 10 }}>
      {["draft", "a", "quick", "reply"].map((tok, i) => (
        <span key={i} style={{
          padding: "2px 6px", borderRadius: 4,
          background: active ? `${color}22` : "var(--line)",
          color: active ? color : "var(--fg-faint)",
          transition: "all 200ms",
          transitionDelay: `${i * 60}ms`,
        }}>{tok}</span>
      ))}
    </span>
  );
}

function StageSparkles({ active, color }) {
  return (
    <span style={{ display: "inline-flex", gap: 8, alignItems: "center", fontFamily: "var(--font-mono)", fontSize: 11 }}>
      <span style={{ color: active ? color : "rgba(255,255,255,0.3)", fontWeight: 600 }}>professional</span>
      <span style={{ color: "rgba(255,255,255,0.3)" }}>→</span>
      <span style={{ color: active ? color : "rgba(255,255,255,0.3)" }}>✦ ✦ ✦</span>
    </span>
  );
}

function StageCursor({ active, color }) {
  return (
    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)" }}>
      Hey, can you draft<span style={{ color, animation: active ? "blink 800ms steps(1) infinite" : "none" }}>▌</span>
    </span>
  );
}

window.HowItWorks = HowItWorks;
