// API section — keys, endpoints, playground, webhooks, usage
const ApiSection = ({ showToast }) => {
  const isMobile = useIsMobile();
  const [activeEndpoint, setActiveEndpoint] = React.useState(0);
  const [tab, setTab] = React.useState("overview");
  const [revealedKey, setRevealedKey] = React.useState(false);
  const [running, setRunning] = React.useState(false);
  const [response, setResponse] = React.useState(null);

  const endpoints = [
    { m: "POST", p: "/v2/audits", d: "Submit a design for governance audit", body: `{
  "asset_url": "https://acmepharma.com/campaigns/veltrox-hcp-v3.pdf",
  "audience": "HCP",
  "market": "US",
  "dimensions": ["regulatory", "wcag", "brand", "claims"]
}` },
    { m: "GET",  p: "/v2/audits/{id}", d: "Retrieve a completed audit report", body: null },
    { m: "GET",  p: "/v2/library/assets", d: "List all assets in your library", body: null },
    { m: "GET",  p: "/v2/library/assets/{id}/download", d: "Download a specific asset", body: null },
    { m: "POST", p: "/v2/design-md/generate", d: "Generate a design.md for AI agents", body: null },
    { m: "POST", p: "/v2/webhooks", d: "Subscribe to audit completion events", body: null },
  ];

  const ep = endpoints[activeEndpoint];

  const runRequest = () => {
    setRunning(true); setResponse(null);
    setTimeout(() => {
      setResponse({
        status: 202,
        time: 184,
        body: `{
  "audit_id": "AUD-2105",
  "status": "queued",
  "estimated_completion_seconds": 720,
  "asset_url": "https://acmepharma.com/campaigns/veltrox-hcp-v3.pdf",
  "audience": "HCP",
  "market": "US",
  "dimensions_count": 4,
  "webhook_url": null,
  "result_url": "https://api.graphite.studio/v2/audits/AUD-2105",
  "created_at": "2026-04-28T14:32:18Z"
}`
      });
      setRunning(false);
    }, 900);
  };

  const copy = (txt, label="Copied") => { navigator.clipboard?.writeText(txt); showToast(label); };

  const methodColor = (m) => ({ GET: "var(--ok)", POST: "var(--accent)", PUT: "var(--warn)", DELETE: "var(--crit)" }[m] || "var(--muted)");

  return (
    <div style={{ padding: isMobile ? "20px 16px 60px" : "36px 36px 80px", maxWidth: 1500 }}>
      <div style={{ display: "flex", flexDirection: isMobile ? "column" : "row", justifyContent: "space-between", alignItems: isMobile ? "stretch" : "flex-end", gap: isMobile ? 16 : 0, marginBottom: isMobile ? 24 : 32 }}>
        <div>
          <div className="eyebrow">API · v2.4</div>
          <h1 className="h-section" style={{ marginTop: 6 }}>Integrate Graphite into your <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", color: "var(--accent)" }}>stack</span>.</h1>
          <p style={{ color: "var(--muted)", maxWidth: 640, marginTop: 10, fontSize: 15 }}>
            Programmatic access to audits, asset library, and design.md generation. Plug into your DAM, MLR review tool, or CI pipeline.
          </p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-quiet"><Icon name="external" size={13}/> Open docs</button>
          <button className="btn btn-ghost"><Icon name="key" size={13}/> Manage keys</button>
        </div>
      </div>

      {/* Tabs */}
      <div className="tab-scroll" style={{ borderBottom: "1px solid var(--line)", display: "flex", gap: 4, marginBottom: isMobile ? 20 : 28 }}>
        {[
          { id: "overview", l: "Overview" },
          { id: "keys", l: "Keys & secrets" },
          { id: "playground", l: "Playground" },
          { id: "webhooks", l: "Webhooks" },
          { id: "usage", l: "Usage & limits" },
          { id: "sdks", l: "SDKs" },
        ].map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            padding: "12px 18px", background: "transparent", border: "none", cursor: "pointer",
            fontSize: 13, fontWeight: tab === t.id ? 500 : 400, color: tab === t.id ? "var(--ink)" : "var(--muted)",
            borderBottom: tab === t.id ? "2px solid var(--accent)" : "2px solid transparent", marginBottom: -1, whiteSpace: "nowrap"
          }}>{t.l}</button>
        ))}
      </div>

      {tab === "overview" && (
        <div>
          {/* Connection card */}
          <div className="chamfer" style={{ background: "var(--ink)", color: "var(--bone)", padding: isMobile ? 22 : 32, marginBottom: isMobile ? 20 : 28, "--chamfer": "18px", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 22 : 32 }}>
            <div>
              <div className="eyebrow eyebrow-coral" style={{ marginBottom: 12 }}>● Connection</div>
              <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", marginBottom: 18 }}>Base URL</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", background: "var(--ink-2)", border: "1px solid var(--line-dark)", borderRadius: 8, fontFamily: "var(--font-mono)", fontSize: 13 }}>
                <span style={{ color: "var(--ok)" }}>●</span>
                <span style={{ flex: 1 }}>https://api.graphite.studio/v2</span>
                <button onClick={()=>copy("https://api.graphite.studio/v2", "Base URL copied")} style={{ background: "transparent", border: "none", color: "var(--muted-2)", cursor: "pointer" }}><Icon name="copy" size={14}/></button>
              </div>
              <div style={{ marginTop: 16 }}>
                <div className="eyebrow" style={{ color: "var(--muted-2)", marginBottom: 8 }}>Authentication header</div>
                <div style={{ padding: "10px 14px", background: "var(--ink-2)", border: "1px solid var(--line-dark)", borderRadius: 8, fontFamily: "var(--font-mono)", fontSize: 12 }}>
                  Authorization: Bearer <span style={{ color: "var(--accent)" }}>$GRAPHITE_API_KEY</span>
                </div>
              </div>
            </div>
            <div>
              <div className="eyebrow eyebrow-coral" style={{ marginBottom: 12 }}>● Live key (Production)</div>
              <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", marginBottom: 18 }}>Acme Pharma · prod</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", background: "var(--ink-2)", border: "1px solid var(--line-dark)", borderRadius: 8, fontFamily: "var(--font-mono)", fontSize: 13 }}>
                <span style={{ flex: 1, fontFamily: "var(--font-mono)" }}>
                  {revealedKey ? "gph_live_4f8a2c91e7b6d3a5f0c8e2b9a4d7c1e6" : "gph_live_••••••••••••••••••••••••••••••••"}
                </span>
                <button onClick={()=>setRevealedKey(s=>!s)} style={{ background: "transparent", border: "none", color: "var(--muted-2)", cursor: "pointer" }}><Icon name="eye" size={14}/></button>
                <button onClick={()=>copy("gph_live_4f8a2c91e7b6d3a5f0c8e2b9a4d7c1e6", "Key copied")} style={{ background: "transparent", border: "none", color: "var(--muted-2)", cursor: "pointer" }}><Icon name="copy" size={14}/></button>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontSize: 12, color: "var(--muted-2)" }}>
                <span>Created Jan 18, 2026 · last used 4 min ago</span>
                <a style={{ color: "var(--accent)", cursor: "pointer" }}>Rotate →</a>
              </div>
            </div>
          </div>

          {/* Quick start */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.2fr 1fr", gap: isMobile ? 16 : 24 }}>
            <div className="card" style={{ padding: 24 }}>
              <div className="eyebrow">Quick start</div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 16 }}>Submit your first audit</div>
              <pre className="code">{`curl -X POST https://api.graphite.studio/v2/audits \\
  -H "Authorization: Bearer $GRAPHITE_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "asset_url": "https://yoursite.com/campaign.pdf",
    "audience": "HCP",
    "market": "US",
    "dimensions": ["regulatory", "wcag", "brand"]
  }'`}</pre>
              <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
                <button onClick={()=>setTab("playground")} className="btn btn-primary" style={{ padding: "8px 14px", fontSize: 12 }}>Try it in playground →</button>
                <button className="btn btn-quiet" style={{ padding: "8px 14px", fontSize: 12 }}><Icon name="copy" size={12}/> Copy curl</button>
              </div>
            </div>
            <div className="card" style={{ padding: 24 }}>
              <div className="eyebrow">Status · last 24h</div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 16 }}>All systems operational</div>
              {[
                { l: "API", v: "247ms p50", st: "ok" },
                { l: "Audit engine", v: "12.4 min p50", st: "ok" },
                { l: "Webhooks", v: "1.2s p50", st: "ok" },
                { l: "Asset CDN", v: "84ms p50", st: "ok" },
              ].map((s, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: i < 3 ? "1px solid var(--line)" : "none", fontSize: 13 }}>
                  <span style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--ok)" }}/>{s.l}</span>
                  <span style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 12 }}>{s.v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {tab === "playground" && (
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "300px 1fr", gap: isMobile ? 16 : 24 }}>
          {/* Endpoint list */}
          <div className="card" style={{ padding: 0, height: "fit-content" }}>
            <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--line)" }}>
              <div className="eyebrow">Endpoints</div>
            </div>
            {endpoints.map((e, i) => (
              <div key={i} onClick={()=>{setActiveEndpoint(i); setResponse(null)}} style={{
                padding: "12px 18px", borderBottom: i < endpoints.length - 1 ? "1px solid var(--line)" : "none",
                cursor: "pointer", background: i === activeEndpoint ? "var(--bone)" : "transparent",
                borderLeft: i === activeEndpoint ? "3px solid var(--accent)" : "3px solid transparent",
              }}>
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 600, color: methodColor(e.m), letterSpacing: "0.04em" }}>{e.m}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 500 }}>{e.p}</span>
                </div>
                <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>{e.d}</div>
              </div>
            ))}
          </div>

          {/* Request / response */}
          <div>
            <div className="card" style={{ padding: 20, marginBottom: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
                <span style={{ padding: "5px 10px", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, color: "var(--paper)", background: methodColor(ep.m), borderRadius: 4 }}>{ep.m}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 500 }}>{ep.p}</span>
                <div style={{ flex: 1 }}/>
                <button onClick={runRequest} className="btn btn-primary" style={{ padding: "7px 14px", fontSize: 12 }} disabled={running}>
                  {running ? <><Icon name="spinner" size={12}/> Running…</> : <><Icon name="play" size={11}/> Send</>}
                </button>
              </div>
              {ep.body && (
                <div>
                  <div className="eyebrow" style={{ marginBottom: 8 }}>Request body</div>
                  <pre className="code" style={{ fontSize: 12 }}>{ep.body}</pre>
                </div>
              )}
            </div>

            <div className="card" style={{ padding: 20, minHeight: 240 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                <div className="eyebrow">Response</div>
                {response && (
                  <div style={{ display: "flex", gap: 12, fontSize: 12, fontFamily: "var(--font-mono)", color: "var(--muted)" }}>
                    <span>{response.time}ms</span>
                    <span style={{ color: "var(--ok)" }}>● {response.status}</span>
                  </div>
                )}
              </div>
              {!response && !running && <div style={{ color: "var(--muted)", fontSize: 13, padding: "30px 0", textAlign: "center" }}>Hit “Send” to run the request</div>}
              {running && <div style={{ color: "var(--muted)", fontSize: 13, padding: "30px 0", textAlign: "center", display: "flex", gap: 8, justifyContent: "center", alignItems: "center" }}><Icon name="spinner" size={14}/> Calling api.graphite.studio…</div>}
              {response && <pre className="code" style={{ fontSize: 12 }}>{response.body}</pre>}
            </div>
          </div>
        </div>
      )}

      {tab === "keys" && (
        <div className="card" style={{ overflow: "hidden" }}>
          <div style={{ padding: "20px 24px", display: "flex", flexDirection: isMobile ? "column" : "row", justifyContent: "space-between", alignItems: isMobile ? "stretch" : "center", gap: isMobile ? 12 : 0, borderBottom: "1px solid var(--line)" }}>
            <div style={{ fontSize: 16, fontWeight: 500 }}>API keys</div>
            <button className="btn btn-primary" style={{ padding: "8px 14px", fontSize: 12 }}><Icon name="key" size={12}/> Create new key</button>
          </div>
          <div className="tbl-scroll">
          <table className="tbl">
            <thead><tr><th>Name</th><th>Token</th><th>Environment</th><th>Created</th><th>Last used</th><th></th></tr></thead>
            <tbody>
              {[
                { n: "Production · DAM integration", t: "gph_live_4f8a…c1e6", e: "production", c: "Jan 18", u: "4 min ago" },
                { n: "Staging · MLR pipeline", t: "gph_test_8a3c…b9f2", e: "staging", c: "Feb 12", u: "1h ago" },
                { n: "CI · GitHub Actions", t: "gph_live_2c91…d3a5", e: "production", c: "Mar 04", u: "yesterday" },
                { n: "Personal · Amelia", t: "gph_test_f0c8…e2b9", e: "staging", c: "Apr 02", u: "3d ago" },
              ].map((k, i) => (
                <tr key={i}>
                  <td style={{ fontWeight: 500 }}>{k.n}</td>
                  <td style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{k.t}</td>
                  <td><span className={`pill ${k.e === "production" ? "pill-ok" : "pill-warn"}`}><span className="pill-dot"/>{k.e}</span></td>
                  <td style={{ color: "var(--muted)" }}>{k.c}</td>
                  <td style={{ color: "var(--muted)" }}>{k.u}</td>
                  <td><button style={{ background: "transparent", border: "none", color: "var(--muted)", cursor: "pointer" }}><Icon name="more" size={16}/></button></td>
                </tr>
              ))}
            </tbody>
          </table>
          </div>
        </div>
      )}

      {tab === "webhooks" && (
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: isMobile ? 16 : 20 }}>
          <div className="card" style={{ padding: 24 }}>
            <div className="eyebrow">Endpoints</div>
            <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 18 }}>Active webhooks</div>
            {[
              { url: "https://acmepharma.com/hooks/graphite", events: "audit.completed, audit.failed", st: "ok" },
              { url: "https://mlr.acmepharma.com/api/inbox", events: "audit.completed", st: "ok" },
              { url: "https://hooks.slack.com/services/T0…", events: "audit.flagged.critical", st: "warn" },
            ].map((w, i) => (
              <div key={i} style={{ padding: "14px 0", borderBottom: i < 2 ? "1px solid var(--line)" : "none" }}>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 500, wordBreak: "break-all" }}>{w.url}</div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
                  <div style={{ fontSize: 12, color: "var(--muted)" }}>{w.events}</div>
                  <span className={`pill pill-${w.st}`}><span className="pill-dot"/>{w.st === "ok" ? "Healthy" : "Retrying"}</span>
                </div>
              </div>
            ))}
            <button className="btn btn-quiet" style={{ marginTop: 16, padding: "8px 14px", fontSize: 12 }}><Icon name="upload" size={12}/> Add webhook</button>
          </div>
          <div className="card" style={{ padding: 24 }}>
            <div className="eyebrow">Event types</div>
            <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 18 }}>Available events</div>
            {[
              { e: "audit.completed", d: "Fired when an audit finishes successfully." },
              { e: "audit.failed", d: "Fired if processing errors out." },
              { e: "audit.flagged.critical", d: "Fired when ≥1 critical finding detected." },
              { e: "library.asset.updated", d: "Fired when a library asset is republished." },
              { e: "design_md.generated", d: "Fired when a fresh design.md is built." },
            ].map((e, i) => (
              <div key={i} style={{ display: "flex", gap: 12, padding: "10px 0", fontSize: 13, borderBottom: i < 4 ? "1px solid var(--line)" : "none" }}>
                <code style={{ fontFamily: "var(--font-mono)", color: "var(--accent)", fontSize: 12, whiteSpace: "nowrap" }}>{e.e}</code>
                <span style={{ color: "var(--muted)" }}>{e.d}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "usage" && (
        <div>
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : "repeat(4, 1fr)", gap: isMobile ? 12 : 16, marginBottom: isMobile ? 16 : 24 }}>
            {[
              { k: "3.2M", l: "Calls this month", q: "of 10M plan", v: 32 },
              { k: "127", l: "Audits run", q: "Unlimited", v: null },
              { k: "847", l: "Library calls", q: "of 5K daily", v: 17 },
              { k: "$0", l: "Overage", q: "Within plan", v: 0 },
            ].map((s, i) => (
              <div key={i} className="card" style={{ padding: 22 }}>
                <div className="eyebrow">{s.l}</div>
                <div style={{ fontSize: 28, fontWeight: 500, letterSpacing: "-0.02em", marginTop: 6 }}>{s.k}</div>
                <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>{s.q}</div>
                {s.v !== null && <div className="sev-bar" style={{ marginTop: 12 }}><div className="sev-bar-fill" style={{ width: `${s.v}%` }}/></div>}
              </div>
            ))}
          </div>
          <div className="card" style={{ padding: 24 }}>
            <div className="eyebrow">Last 30 days</div>
            <div style={{ fontSize: 18, fontWeight: 500, marginTop: 4, marginBottom: 16 }}>Daily call volume</div>
            <div style={{ display: "flex", alignItems: "flex-end", gap: 4, height: 160 }}>
              {Array.from({ length: 30 }, (_, i) => {
                const h = 30 + Math.sin(i * 0.6) * 25 + Math.random() * 40;
                return <div key={i} style={{ flex: 1, height: `${h}%`, background: i === 29 ? "var(--accent)" : "var(--ink-3)", borderRadius: 2, opacity: i === 29 ? 1 : 0.3 + (i / 30) * 0.5 }}/>;
              })}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, fontSize: 11, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>
              <span>30 days ago</span><span>Today</span>
            </div>
          </div>
        </div>
      )}

      {tab === "sdks" && (
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", gap: isMobile ? 14 : 18 }}>
          {[
            { l: "JavaScript / TypeScript", p: "npm i @graphite/client", v: "v2.4.1", desc: "Node 18+ and modern browsers." },
            { l: "Python", p: "pip install graphite-client", v: "v2.4.0", desc: "Async/await with httpx." },
            { l: "Go", p: "go get github.com/graphite/go", v: "v2.3.8", desc: "Idiomatic with context.Context." },
          ].map((s, i) => (
            <div key={i} className="card chamfer-tr" style={{ padding: 24 }}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: "var(--bone)", display: "grid", placeItems: "center", marginBottom: 14 }}><Icon name="package" size={18}/></div>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{s.l}</div>
              <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>{s.desc}</div>
              <pre className="code" style={{ marginTop: 14, fontSize: 12, padding: "10px 12px" }}>{s.p}</pre>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 12 }}>
                <span className="pill">{s.v}</span>
                <a style={{ fontSize: 13, color: "var(--accent)", cursor: "pointer" }}>Docs →</a>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

window.ApiSection = ApiSection;
