function APISetup() {
  const { provider, setProvider, apiKey, setApiKey, testStatus, setTestStatus } = useAPI();
  const [tab, setTab] = useState("a");
  const [show, setShow] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testMsg, setTestMsg] = useState("");

  async function runTest() {
    if (!apiKey) { setTestStatus("error"); setTestMsg("Paste a key above first."); return; }
    setTesting(true); setTestStatus(null); setTestMsg("");
    try {
      const out = await callAI({
        provider, apiKey,
        system: "You are a connection test. Reply with exactly: PONG",
        user: "ping",
      });
      if (/pong/i.test(out)) {
        setTestStatus("ok");
        setTestMsg(`Connected. That was a real network round-trip to the ${provider === "openrouter" ? "OpenRouter" : "Google Gemini"} API, authenticated with your key. You just did the thing.`);
      } else {
        setTestStatus("ok");
        setTestMsg(`Connected (model replied: "${out.trim().slice(0, 60)}"). Close enough — auth works.`);
      }
    } catch (e) {
      setTestStatus("error");
      setTestMsg(e.message);
    } finally { setTesting(false); }
  }

  return (
    <section className="py-20 sm:py-28 bg-paper2 relative overflow-hidden">
      <div className="absolute inset-0 grain opacity-70 pointer-events-none"/>
      <div className="max-w-6xl mx-auto px-5 sm:px-8 relative">
        <SectionHeader
          id="api-setup"
          num="05"
          kicker="the learning moment"
          title={<>Get an API key. <em className="text-teal">Five minutes.</em></>}
          lede="Before the demos below, you're going to authenticate to an AI provider — the exact same flow every data/AI job interviews you on. This page never sees your key; it goes straight from your browser to the model."
        />

        <div className="grid lg:grid-cols-12 gap-8">
          {/* Left: tabs */}
          <div className="lg:col-span-7">
            <div className="flex flex-wrap gap-2 mb-5">
              {[
                ["a", "Option A — OpenRouter", "recommended"],
                ["b", "Option B — Gemini", "genuinely free"],
                ["c", "Option C — Skip", "static demos only"],
              ].map(([k, label, sub]) => (
                <button key={k} onClick={() => setTab(k)} aria-selected={tab === k}
                  className="tab-btn hairline rounded-full px-4 py-2 text-[13px] mono bg-[#FFFDF9]">
                  {label}
                  <span className="ml-2 opacity-60 text-[11px]">· {sub}</span>
                </button>
              ))}
            </div>

            <Card className="p-6">
              {tab === "a" && (
                <>
                  <div className="flex items-baseline gap-3 mb-2">
                    <span className="serif text-2xl text-ink">OpenRouter</span>
                    <Pill tone="teal">recommended</Pill>
                  </div>
                  <p className="text-ink2 mb-4">One key, many models, a generous free tier. This is what I'd pick if I were starting today.</p>
                  <ol className="space-y-2.5 text-ink2 mono text-[13px]">
                    <li>1. go to <a className="underline underline-offset-2 text-ink" href="https://openrouter.ai" target="_blank" rel="noreferrer">openrouter.ai</a> · sign up (Google works)</li>
                    <li>2. top-right avatar → <span className="chip">Keys</span> → <span className="chip">Create Key</span></li>
                    <li>3. name it something like <span className="chip">job-hunt-guide</span>, copy it</li>
                    <li>4. pick <span className="chip">OpenRouter</span> in the dropdown → paste below → Test</li>
                  </ol>
                  <div className="mt-4 mono text-[11px] text-muted">
                    the demos use <span className="chip">google/gemini-2.0-flash-exp:free</span> — zero cost on OpenRouter's free tier.
                  </div>
                </>
              )}
              {tab === "b" && (
                <>
                  <div className="flex items-baseline gap-3 mb-2">
                    <span className="serif text-2xl text-ink">Google AI Studio (Gemini)</span>
                    <Pill>free</Pill>
                  </div>
                  <p className="text-ink2 mb-4">If you already live in Google-land. No card, no trial — just a key.</p>
                  <ol className="space-y-2.5 text-ink2 mono text-[13px]">
                    <li>1. <a className="underline underline-offset-2 text-ink" href="https://aistudio.google.com" target="_blank" rel="noreferrer">aistudio.google.com</a> · sign in</li>
                    <li>2. left sidebar → <span className="chip">Get API key</span></li>
                    <li>3. <span className="chip">Create API key</span> · pick any project · copy</li>
                    <li>4. pick <span className="chip">Gemini</span> in the dropdown → paste below → Test</li>
                  </ol>
                </>
              )}
              {tab === "c" && (
                <>
                  <div className="flex items-baseline gap-3 mb-2">
                    <span className="serif text-2xl text-ink">Skip the API entirely</span>
                    <Pill tone="ember">no shame</Pill>
                  </div>
                  <p className="text-ink2 mb-4">You can read this whole page without a key. The three AI demos just won't run — but the <a href="#projects" className="underline underline-offset-2 text-ink">static project menu (§10)</a> gives you three UK-contextual briefs you can start tomorrow.</p>
                  <a href="#projects" className="btn-ink px-4 py-2 rounded-full text-sm inline-flex items-center gap-2">
                    Jump to static projects <I.Arrow size={14}/>
                  </a>
                </>
              )}
            </Card>

            {/* Key form */}
            <Card className="p-6 mt-5">
              <div className="grid sm:grid-cols-[180px_1fr_auto] gap-3 items-end">
                <LabelledInput label="provider">
                  <select className="select" value={provider} onChange={e => { setProvider(e.target.value); setTestStatus(null); }}>
                    <option value="openrouter">OpenRouter</option>
                    <option value="gemini">Gemini</option>
                  </select>
                </LabelledInput>
                <LabelledInput label="api key" hint={apiKey ? `${apiKey.length} chars` : "paste here"}>
                  <div className="relative">
                    <input
                      className="input pr-20"
                      type={show ? "text" : "password"}
                      placeholder={provider === "openrouter" ? "sk-or-v1-…" : "AIza…"}
                      value={apiKey}
                      onChange={e => { setApiKey(e.target.value.trim()); setTestStatus(null); }}
                    />
                    <button type="button" onClick={() => setShow(s => !s)}
                      className="absolute right-2 top-1/2 -translate-y-1/2 mono text-[11px] text-muted hover:text-ink px-2 py-1 inline-flex items-center gap-1">
                      {show ? <><I.EyeOff size={12}/>hide</> : <><I.Eye size={12}/>show</>}
                    </button>
                  </div>
                </LabelledInput>
                <button onClick={runTest} disabled={testing}
                  className="btn-teal px-5 py-2.5 rounded-lg text-sm inline-flex items-center gap-2 justify-center">
                  {testing ? <><I.Loader size={14} className="animate-spin"/>Testing</> : <><I.Bolt size={14}/>Test connection</>}
                </button>
              </div>

              <div className="mt-4 mono text-[11px] text-muted leading-relaxed">
                stored only in your browser's memory · <b className="text-ink2">never</b> sent to this site's server · refresh the page and it's gone. requests go browser → provider directly.
              </div>

              {testStatus === "ok" && (
                <div className="mt-4 rounded-lg border border-teal/40 bg-teal-soft/60 p-3 flex items-start gap-2.5">
                  <div className="text-teal-deep mt-0.5"><I.Check size={16}/></div>
                  <div className="text-sm text-ink2">{testMsg}</div>
                </div>
              )}
              {testStatus === "error" && (
                <ErrorBox>{testMsg}</ErrorBox>
              )}
            </Card>
          </div>

          {/* Right: teaching + FAQ */}
          <aside className="lg:col-span-5 space-y-5">
            <Card className="p-6 bg-ink text-paper">
              <div className="mono text-[10px] uppercase tracking-widest text-paper/60 mb-2">what just happened?</div>
              <p className="serif text-[22px] leading-snug mb-3">
                You authenticated to an API with a bearer token, hit an OpenAI-compatible endpoint, and parsed a JSON response.
              </p>
              <p className="text-paper/80 text-[14px] leading-relaxed">
                That's 80% of "AI engineering" in one request. Every production data/AI system does this. Your future employer's systems included.
              </p>
            </Card>

            <Card className="p-5">
              <div className="mono text-[11px] uppercase tracking-widest text-muted mb-3">faq, brief</div>
              {[
                ["Will this cost me money?", "No, if you stick to the :free models on OpenRouter or the Gemini free tier. Both providers make you add a card for paid tiers — don't."],
                ["Is my key safe on this page?", "It never leaves your browser except to go directly to the provider you picked. No backend here."],
                ["The test failed. Now what?", "Read the error carefully. 401 = wrong key. 429 = rate-limited, wait. Network = VPN or connection. These are the exact errors you'll debug at work."],
              ].map(([q, a], i) => (
                <details key={i} className="py-3 border-t border-line first:border-t-0 group">
                  <summary className="flex justify-between items-center gap-2">
                    <span className="text-ink2">{q}</span>
                    <span className="text-muted group-open:rotate-45 transition-transform mono text-lg leading-none">+</span>
                  </summary>
                  <p className="mt-2 text-[14px] text-ink2 leading-relaxed">{a}</p>
                </details>
              ))}
            </Card>
          </aside>
        </div>
      </div>
    </section>
  );
}
window.APISetup = APISetup;
