/* global React, CodeBlock */

// ---------- PROBLEM ----------
const PROBLEMS = [
  {
    idx: "01",
    title: "10 providers, 10 SDKs to wire up",
    body: "Every agent ships by taping together Exa, Firecrawl, Presidio, PubMed, and four MCP servers. Ten dashboards, ten API keys, ten SDK dialects to learn.",
    foot: "avg. 7.4 providers per production agent (Synapse eval, Jan 2026)",
  },
  {
    idx: "02",
    title: "Vendor benchmarks are exploitable",
    body: "Every provider publishes their own numbers, on their own eval set, against competitors they chose. You cannot compare them and stay honest.",
    foot: "→ we run one harness, per capability, against held-out corpora",
  },
  {
    idx: "03",
    title: "PHI in your tool calls is a non-starter",
    body: "Most tool routers persist raw prompts and responses for debugging. If you work in healthcare, finance, or government, that's a deal-breaker on day one.",
    foot: "→ PHI/PII scrubbed pre-call, audit trails signed, BAA on enterprise",
  },
];

function Problem() {
  return (
    <section className="section" id="problem">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">01</span>The problem</div>
          <div>
            <h2 className="section-title">The agent toolstack is <em>a mess.</em></h2>
            <p className="section-lede">
              Agent runtimes have matured. The service layer underneath them has not.
              Here is what shipping anything serious looks like today.
            </p>
          </div>
        </div>
        <div className="problem-grid">
          {PROBLEMS.map(p => (
            <article className="problem-card" key={p.idx}>
              <div className="idx">{p.idx}</div>
              <h3>{p.title}</h3>
              <p>{p.body}</p>
              <div className="footnote">{p.foot}</div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- CAPABILITIES ----------
const CAPS = [
  {
    name: "search",
    desc: "Web and domain search, ranked by a benchmarked quality score against held-out queries per vertical.",
    providers: ["Exa", "Tavily", "Brave", "Linkup"],
    code: `// search, routes across Exa, Tavily, Brave, Linkup
await synapse.search('GLP-1 cardiovascular outcomes', { limit: 10 });`,
  },
  {
    name: "crawl",
    desc: "HTML → structured content. Handles JS rendering, auth walls, and rate limits without you touching a headless browser.",
    providers: ["Firecrawl", "Apify", "Browserbase"],
    code: `// crawl, routes across Firecrawl, Apify, Browserbase
await synapse.crawl('https://example.com', { format: 'markdown' });`,
  },
];

function Capabilities() {
  return (
    <section className="section" id="capabilities">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">02</span>Core MVP · two capabilities</div>
          <div>
            <h2 className="section-title">Start with <em>two calls.</em></h2>
            <p className="section-lede">
              Search and crawl are the first two we ship. Every call returns a normalized response
              with the provider it routed to, the cost, the latency, and a reason, so you can pin
              providers, enforce a quality floor, or let the router decide. More capabilities follow.
            </p>
          </div>
        </div>
        <div>
          {CAPS.map(c => (
            <div className="cap-row" key={c.name}>
              <div className="cap-meta">
                <div className="cap-name">
                  synapse<span className="dot">.</span>{c.name}<span className="lp">()</span>
                </div>
                <div className="cap-desc">{c.desc}</div>
                <div className="provider-chips">
                  <span className="lead">routes to →</span>
                  {c.providers.map(p => <span className="ch" key={p}>{p}</span>)}
                </div>
              </div>
              <CodeBlock file={`${c.name}.ts`} code={c.code} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- ROUTING MODES ----------
const MODES = [
  { id: "cost",     title: "cost",     desc: "Cheapest provider that clears the quality floor you set.", snip: `synapse.configure({ routingMode: 'cost' });` },
  { id: "latency",  title: "latency",  desc: "Fastest p50 for this capability and query class.",         snip: `synapse.configure({ routingMode: 'latency' });` },
  { id: "quality",  title: "quality",  desc: "Highest benchmark score, pay whatever it costs.",          snip: `synapse.configure({ routingMode: 'quality' });` },
  { id: "balanced", title: "balanced", desc: "Weighted blend. The default, and usually the right answer.", snip: `synapse.configure({ routingMode: 'balanced' });` },
];

function RoutingModes() {
  const [active, setActive] = React.useState("balanced");
  return (
    <section className="section" id="routing">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">03</span>Routing modes</div>
          <div>
            <h2 className="section-title">Pick how you want the router to <em>think.</em></h2>
            <p className="section-lede">
              Four preset strategies, or a custom scoring function. Every response tells you which
              provider was chosen and why, so you can audit decisions without logging in to a dashboard.
            </p>
          </div>
        </div>
        <div className="modes-grid">
          {MODES.map(m => (
            <button
              key={m.id}
              className={"mode-card" + (active === m.id ? " active" : "")}
              onClick={() => setActive(m.id)}
              style={{textAlign: "left"}}
            >
              <div className="tick">
                <span>routingMode</span>
                <span>{active === m.id ? "●" : "○"}</span>
              </div>
              <h4>{m.title}</h4>
              <p>{m.desc}</p>
              <div className="mini">{m.snip}</div>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- SAFETY PERIMETER ----------
const SAFETY_PRIMITIVES = [
  { idx: "01", title: "Provider allowlist",  body: "Agents only call providers you've explicitly enabled. Per-environment, per-key, per-capability. Default-deny, not default-allow." },
  { idx: "02", title: "Egress redaction",    body: "PHI, PII, and PCI patterns stripped before any provider sees the request body. Reversible on return when you need round-trips." },
  { idx: "03", title: "Response scanning",   body: "Every tool response scanned for prompt-injection patterns before it ever reaches your agent's context window." },
  { idx: "04", title: "Per-call quotas",     body: "Hard caps on cost, latency, retries, recursion depth. An infinite loop costs $0.50, not $50,000." },
  { idx: "05", title: "Signed audit trail",  body: "Every external call signed and chained, sha256 + HMAC. Compliance gets a proof; you get a forensic debugger." },
  { idx: "06", title: "Killswitch",          body: "Disable a provider, a capability, or all egress in one config flip. Propagates to all running agents in under 5 seconds." },
];

function SafetyPerimeter() {
  return (
    <section className="section" id="safety">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">04</span>Safety perimeter</div>
          <div>
            <h2 className="section-title">Bounded blast radius. <em>By default.</em></h2>
            <p className="section-lede">
              Your agent shouldn't have unlimited access to a hundred APIs. The SDK is the safety
              perimeter: every external call is scoped, scanned, and audited before it leaves your
              control plane, and again before its response reaches the agent.
            </p>
          </div>
        </div>

        <div className="safety-grid">
          <div className="safety-flow">
            <div className="safety-flow-head">
              <span className="dots" aria-hidden="true"><span /><span /><span /></span>
              <span className="title">request lifecycle, every call</span>
              <span className="status"><span className="dot" /> all checks pass</span>
            </div>
            <div className="safety-flow-body">
              <div className="safety-call">
                agent<span className="tok-punc">.</span><span className="tok-fn">crawl</span><span className="tok-punc">(</span><span className="tok-str">"https://cms.gov/...regulations"</span><span className="tok-punc">)</span>
              </div>
              <ul className="safety-steps">
                <li><span className="lbl">allowlist</span><span className="ok">crawl enabled, firecrawl in allowed providers</span></li>
                <li><span className="lbl">redact</span><span className="ok">no PHI in request payload</span></li>
                <li><span className="lbl">quota</span><span className="ok">12 / 100 calls this hour, $0.04 of $50.00</span></li>
                <li className="provider-step"><span className="lbl">provider</span><span className="dim">→ firecrawl.dev (642ms, 4.2KB)</span></li>
                <li><span className="lbl">scan</span><span className="ok">no prompt-injection patterns detected</span></li>
                <li><span className="lbl">audit</span><span className="ok">signed sha256:f90c579d</span></li>
                <li className="final-step"><span className="lbl">deliver</span><span className="ok">→ agent context</span></li>
              </ul>
            </div>
          </div>

          <div className="safety-cards">
            {SAFETY_PRIMITIVES.map(p => (
              <article className="safety-card" key={p.idx}>
                <div className="safety-idx">{p.idx}</div>
                <h4>{p.title}</h4>
                <p>{p.body}</p>
              </article>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- BENCHMARKS ----------
const BENCH = {
  search: [
    { name: "Exa",    ver: "neural-v3",   cost: 3.0, p50: 640, q: 94, swatch: "e", lead: true, note: "medical-literature class" },
    { name: "Tavily", ver: "v2.1",        cost: 2.5, p50: 710, q: 88, swatch: "t" },
    { name: "Brave",  ver: "search-api",  cost: 1.8, p50: 480, q: 79, swatch: "b" },
    { name: "Linkup", ver: "standard",    cost: 2.2, p50: 820, q: 83, swatch: "l" },
  ],
};

function Benchmarks() {
  const [tab, setTab] = React.useState("search");
  const rows = BENCH[tab];
  return (
    <section className="section" id="benchmarks">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">05</span>Published benchmarks</div>
          <div>
            <h2 className="section-title">We publish quality scores so <em>you don't have to guess.</em></h2>
            <p className="section-lede">
              One harness, per capability, against held-out corpora. Re-run nightly. The eval code
              is Apache 2.0, fork it and verify us. Teaser below; full table ships with v1.
            </p>
          </div>
        </div>
        <div className="bench-panel">
          <div className="bench-head">
            <div className="tabs">
              <button className={tab === "search" ? "on" : ""} onClick={() => setTab("search")}>search</button>
              <button disabled title="Ships with v1">crawl</button>
              <button disabled title="Ships with v1">privacy</button>
              <button disabled title="Ships with v1">knowledgeBase</button>
            </div>
            <span>n=2,400 · corpus: med-lit-v2 · 2026-04-18</span>
          </div>
          <table className="bench">
            <thead>
              <tr>
                <th>Provider</th>
                <th>Cost / 1K</th>
                <th>p50 latency</th>
                <th>Quality score</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.name} className={r.lead ? "lead" : ""}>
                  <td>
                    <span className="prov">
                      <span className={"swatch " + r.swatch} />
                      <span>
                        <span className="name">{r.name}</span>{" "}
                        <span className="ver">{r.ver}</span>
                        {r.lead && <span className="badge">routed</span>}
                      </span>
                    </span>
                  </td>
                  <td className="mono">${r.cost.toFixed(2)}</td>
                  <td className="mono">{r.p50} ms</td>
                  <td>
                    <span className="quality">
                      <span className="qbar"><span style={{width: r.q + "%"}} /></span>
                      <span className="qnum">{r.q}</span>
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="bench-foot">
            <span>Methodology · corpora · scoring →{" "}
              <a href="#">read the harness</a>
            </span>
            <span className="soon">Full dashboard · coming June 2026</span>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- HEALTHCARE ----------
const HC_CODE = `import { synapse } from '@synapse-foundry/sdk';

synapse.configure({ vertical: 'healthcare' });

// PHI is scrubbed before the provider sees it.
// The audit trail is signed and immutable.
const safe = await synapse.privacy(patientNote);
const lit  = await synapse.knowledgeBase('PubMed', query);`;

function Healthcare() {
  return (
    <section className="section" id="healthcare">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">06</span>Healthcare vertical</div>
          <div>
            <h2 className="section-title">HIPAA-safe <em>by default.</em></h2>
            <p className="section-lede">
              One config flag flips on the defaults a hospital's security team will actually accept.
              Other verticals (finance, legal) are in private preview.
            </p>
          </div>
        </div>
        <div className="hc">
          <div className="hc-copy">
            <h3>One flag. Regulated-industry defaults.</h3>
            <p className="lede">
              When <code style={{fontFamily: "var(--f-mono)", fontSize: "0.95em"}}>vertical: 'healthcare'</code> is set,
              Synapse changes its own behavior, not just the providers it picks.
            </p>
            <ul className="hc-list">
              <li><span><b>PHI redaction pre-call.</b> Detected fields are masked before the provider receives the payload, then restored on the response.</span></li>
              <li><span><b>Immutable audit trail.</b> Every call gets a signed record: query hash, provider, cost, decision. Exportable as JSONL or CSV.</span></li>
              <li><span><b>21 CFR Part 11 compatible.</b> Time-stamped, attributable, tamper-evident. Drop-in for GxP workflows.</span></li>
              <li><span><b>BAA on enterprise.</b> Execute a Business Associate Agreement in a week, not a quarter.</span></li>
            </ul>
            <div className="compliance-row">
              <span className="c">HIPAA</span>
              <span className="c">SOC 2 · Type II (Q3 2026)</span>
              <span className="c">21 CFR Part 11</span>
              <span className="c">GDPR</span>
            </div>
          </div>
          <div className="hc-code">
            <span className="hc-stamp"><span className="g" /> vertical · healthcare</span>
            <CodeBlock file="healthcare.ts" code={HC_CODE} />
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- PRICING ----------
const TIERS = [
  {
    id: "free", name: "Free", amt: "$0", per: "/month",
    limit: "1,000 calls / month",
    features: [
      "All 5 capabilities",
      "balanced routing mode",
      "Public benchmarks dashboard",
      "Community support",
    ],
    cta: "Start free",
  },
  {
    id: "pro", name: "Pro", amt: "$29", per: "/month",
    limit: "20,000 calls / month · overages at cost + 15%",
    features: [
      "All routing modes (cost · latency · quality · balanced)",
      "Provider pinning & quality floors",
      "Signed audit trail",
      "Email support · 1-day SLA",
    ],
    cta: "Upgrade to Pro",
    featured: true,
  },
  {
    id: "ent", name: "Enterprise", amt: "Custom", per: "annual contract",
    limit: "Volume pricing · dedicated routing pool",
    features: [
      "BAA + DPA + custom MSA",
      "vertical: healthcare · finance · legal",
      "Private provider pool + VPC peering",
      "99.95% SLA · dedicated Slack",
    ],
    cta: "Talk to sales",
  },
];

function Pricing() {
  return (
    <section className="section" id="pricing">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">07</span>Pricing</div>
          <div>
            <h2 className="section-title">Pay for the <em>routed call.</em> Not the dashboard.</h2>
            <p className="section-lede">
              We price like OpenRouter does for LLMs: your usage, at cost, plus a 10–20% margin.
              No seat fees, no minimum commit on Pro, no surprise overages.
            </p>
          </div>
        </div>
        <div className="price-grid">
          {TIERS.map(t => (
            <article key={t.id} className={"tier" + (t.featured ? " featured" : "")}>
              <h4>{t.name}</h4>
              <div className="price">
                <span className={"amt" + (/^\$/.test(t.amt) ? "" : " text")}>{t.amt}</span>
                <span className="per">{t.per}</span>
              </div>
              <div className="limit">{t.limit}</div>
              <ul>
                {t.features.map(f => <li key={f}>{f}</li>)}
              </ul>
              <a href="#" className="tier-cta">{t.cta}</a>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
const FAQS = [
  {
    q: "Why use this instead of calling providers directly?",
    a: <>One install instead of ten. One API key instead of ten. One typed response shape instead of ten different SDK dialects. Plus <b>published per-provider benchmarks</b> so you know which provider is actually best for your workload, not which one has the loudest marketing.</>,
  },
  {
    q: "What runtimes does the SDK support?",
    a: <>Node 18+, Bun, Cloudflare Workers, and Vercel Edge. TypeScript-first with full type safety on every method. Browser support is intentionally not on the roadmap, agent infrastructure belongs server-side.</>,
  },
  {
    q: "What happens when a provider goes down?",
    a: <>We failover. Every routing decision returns ranked candidates; if the first errors or times out, the SDK automatically retries with the next provider. The full fallback cascade is visible in the decision log on every call, no silent failures, no partial responses.</>,
  },
  {
    q: "Does this work with LangChain, the Vercel AI SDK, or Mastra?",
    a: <>Yes, the SDK is framework-agnostic. Each Synapse method returns a typed response you can wire into any agent framework as a tool. Quickstart examples for LangChain, Vercel AI SDK, Mastra, and LlamaIndex ship in the docs.</>,
  },
  {
    q: "Can I bring my own provider keys?",
    a: <>Yes, on Pro and Enterprise tiers. Pass per-provider keys via <span className="mono">synapse.configure({"{ providerKeys: { exa: '...' } }"})</span> and the SDK uses yours instead of ours, while still giving you unified routing, observability, and audit trails across all of them.</>,
  },
];

function FAQ() {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section" id="faq">
      <div className="wrap">
        <div className="section-head">
          <div className="section-kicker"><span className="num">08</span>FAQ</div>
          <div>
            <h2 className="section-title">Frequently asked <em>questions.</em></h2>
          </div>
        </div>
        <div className="faq-list" role="list">
          {FAQS.map((f, i) => (
            <div className={"faq-item" + (open === i ? " open" : "")} key={i} role="listitem">
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} aria-expanded={open === i}>
                <span className="num">{String(i + 1).padStart(2, "0")}</span>
                <span className="q">{f.q}</span>
                <span className="plus" aria-hidden="true">+</span>
              </button>
              <div className="faq-a" aria-hidden={open !== i}>
                <div className="faq-a-inner">{f.a}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-top">
          <div style={{display: "flex", flexDirection: "column", gap: 12}}>
            <Wordmark />
            <div style={{fontSize: 13, color: "var(--ink-3)", maxWidth: 40 + "ch"}}>
              Agent infrastructure for regulated industries.
            </div>
          </div>
          <div className="footer-status">
            <span className="dot" />
            <span>All systems normal · 99.98% 30-day uptime</span>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Synapse Foundry, Inc.</span>
          <div className="footer-links">
            <a href="#">Status</a>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="#">BAA info</a>
            <a href="#">Security</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Problem, Capabilities, RoutingModes, SafetyPerimeter, Benchmarks, Healthcare, Pricing, FAQ, Footer });
