// ============================================
// Reliq — Trust API & Registry Discovery developer docs (Increment 14)
// Public page. Route: #/trust-api
// Mirrors RELIQ_TRUST_API_DOCS.md in the prototype's style.
// ============================================

const TA = {
  api: "https://api.reliq.dev",
  site: "https://reliq.dev",
};

const Code = ({ children }) => (
  <pre style={{
    background: "var(--bg-2)", border: "1px solid var(--line-1)", borderRadius: 8,
    padding: "12px 14px", overflowX: "auto", margin: "8px 0 0",
    fontFamily: "var(--font-mono)", fontSize: 12, lineHeight: 1.6, color: "var(--fg-1)",
    whiteSpace: "pre",
  }}>{children}</pre>
);

const Method = ({ verb, path }) => {
  const color = verb === "GET" ? "var(--teal)" : "var(--violet)";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, margin: "2px 0 4px" }}>
      <span className="mono" style={{ fontSize: 10, fontWeight: 700, color, border: `1px solid ${color}`, borderRadius: 4, padding: "1px 6px" }}>{verb}</span>
      <span className="mono" style={{ fontSize: 12.5, color: "var(--fg-0)" }}>{path}</span>
    </div>
  );
};

const DocSection = ({ id, title, children }) => (
  <section id={id} style={{ marginBottom: 34, scrollMarginTop: 90 }}>
    <h2 style={{ fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 700, color: "var(--fg-0)", marginBottom: 10 }}>{title}</h2>
    {children}
  </section>
);

const P = ({ children }) => <p style={{ fontSize: 13.5, color: "var(--fg-2)", lineHeight: 1.65, margin: "0 0 8px" }}>{children}</p>;

const TrustApiDocs = ({ go }) => {
  const nav = [
    { id: "ta-auth", label: "Authentication & limits" },
    { id: "ta-profile", label: "Registry profile JSON" },
    { id: "ta-discover", label: "Discovery API" },
    { id: "ta-top", label: "Top profiles API" },
    { id: "ta-badges", label: "Badge SVG endpoints" },
    { id: "ta-mcp", label: "MCP endpoint" },
    { id: "ta-publish", label: "Publishing workflow" },
    { id: "ta-agent", label: "Agent metadata" },
    { id: "ta-examples", label: "Examples" },
  ];
  const jump = (id) => { const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: "smooth", block: "start" }); };

  return (
    <LandingLayout go={go} pageTitle="Reliq Trust API — Developer Docs">
      <div style={{ maxWidth: 860, margin: "40px auto 100px", padding: "0 20px" }}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--teal)" }}>Developer Documentation</span>
        <h1 style={{ fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 700, color: "var(--fg-0)", margin: "8px 0 8px" }}>Trust API &amp; Registry Discovery</h1>
        <P>
          Public, canonical Trust Profiles for companies, products, APIs, and websites, plus a filterable
          Discovery API for humans and AI agents. Every profile reuses an existing Reliq scan/report's
          Trust Score — there is one scoring system; the registry never recomputes scores.
        </P>
        <div className="mono" style={{ fontSize: 12, color: "var(--fg-3)", marginBottom: 18 }}>
          API base <span style={{ color: "var(--fg-1)" }}>{TA.api}</span> · App base <span style={{ color: "var(--fg-1)" }}>{TA.site}</span>
        </div>

        {/* Quick nav */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 30 }}>
          {nav.map((n) => (
            <button key={n.id} onClick={() => jump(n.id)} style={{
              fontSize: 11.5, padding: "5px 10px", borderRadius: 6, cursor: "pointer",
              background: "var(--bg-2)", border: "1px solid var(--line-2)", color: "var(--fg-2)",
            }}>{n.label}</button>
          ))}
        </div>

        <DocSection id="ta-auth" title="Authentication & rate limits">
          <P>Public read endpoints need no key. Publishing requires an authenticated session with the
          <code style={{ color: "var(--fg-1)" }}> share_report</code> feature and <code style={{ color: "var(--fg-1)" }}>RUN_SCANS</code> permission.
          The MCP endpoint uses an API key (<code style={{ color: "var(--fg-1)" }}>Authorization: Bearer rq_live_…</code>); LIVE keys require the
          <code style={{ color: "var(--fg-1)" }}> mcp_access</code> feature (Team plan and up).</P>
          <P>Rate limits are per 60s window (defaults): public <strong>300</strong>, api <strong>120</strong>, scan <strong>30</strong>. Exceeding a limit returns <code style={{ color: "var(--fg-1)" }}>429</code>. Responses are wrapped as <code style={{ color: "var(--fg-1)" }}>{"{ data, meta }"}</code>.</P>
        </DocSection>

        <DocSection id="ta-profile" title="Registry profile JSON">
          <Method verb="GET" path="/v1/registry/{slug}" />
          <P>Returns the full machine-readable Trust Profile (a <code style={{ color: "var(--fg-1)" }}>.json</code> suffix is accepted). Includes Trust Score, pillars, badges, trend, history, SEO, JSON-LD, and the agent block.</P>
          <Code>{`curl ${TA.api}/v1/registry/acme-com`}</Code>
        </DocSection>

        <DocSection id="ta-discover" title="Discovery API">
          <Method verb="GET" path="/v1/registry/discover" />
          <P>Filterable, sortable, paginated feed. Filters: <code style={{ color: "var(--fg-1)" }}>kind</code>, <code style={{ color: "var(--fg-1)" }}>minTrust</code>, <code style={{ color: "var(--fg-1)" }}>minAgent</code>, <code style={{ color: "var(--fg-1)" }}>minApi</code>, <code style={{ color: "var(--fg-1)" }}>minDocs</code>, <code style={{ color: "var(--fg-1)" }}>badges</code> (CSV of trust-ready, agent-ready, integration-ready), <code style={{ color: "var(--fg-1)" }}>direction</code>. Sort: <code style={{ color: "var(--fg-1)" }}>trust</code> (default), <code style={{ color: "var(--fg-1)" }}>agent</code>, <code style={{ color: "var(--fg-1)" }}>api</code>, <code style={{ color: "var(--fg-1)" }}>docs</code>, <code style={{ color: "var(--fg-1)" }}>newest</code>, <code style={{ color: "var(--fg-1)" }}>movement</code>. Paginate with <code style={{ color: "var(--fg-1)" }}>limit</code> (max 50) + <code style={{ color: "var(--fg-1)" }}>cursor</code> (from <code style={{ color: "var(--fg-1)" }}>nextCursor</code>).</P>
          <Code>{`curl "${TA.api}/v1/registry/discover?kind=api&minTrust=75&sort=trust&limit=20"`}</Code>
          <Code>{`{
  "data": {
    "sort": "trust", "count": 1, "hasMore": false, "nextCursor": null,
    "profiles": [{
      "name": "Epsilon API", "slug": "epsilon-api", "kind": "API",
      "canonicalUrl": "${TA.site}/registry/epsilon-api",
      "jsonUrl": "${TA.api}/v1/registry/epsilon-api",
      "trustScore": 91, "grade": "Excellent",
      "pillars": { "release": 90, "security": 95, "agent": 88, "api": 96, "docs": 90 },
      "badges": { "trustReady": true, "agentReady": true, "integrationReady": true },
      "trend": { "movement30d": 3, "direction": "up" },
      "badgeUrls": { "score": "…/badge/score.svg", "trust-ready": "…/badge/trust-ready.svg" },
      "lastVerified": "2026-06-19T00:00:00.000Z"
    }]
  }
}`}</Code>
        </DocSection>

        <DocSection id="ta-top" title="Top profiles API">
          <Method verb="GET" path="/v1/registry/discover/top" />
          <P>Top N profiles (default 10, max 50) for the same filters/sorts as discovery, without a pagination cursor.</P>
          <Code>{`curl "${TA.api}/v1/registry/discover/top?sort=agent&limit=5"`}</Code>
        </DocSection>

        <DocSection id="ta-badges" title="Badge SVG endpoints">
          <Method verb="GET" path="/v1/registry/{slug}/badge/{type}.svg" />
          <P>Returns an <code style={{ color: "var(--fg-1)" }}>image/svg+xml</code> badge reflecting current status. Types: <code style={{ color: "var(--fg-1)" }}>score</code>, <code style={{ color: "var(--fg-1)" }}>trust-ready</code>, <code style={{ color: "var(--fg-1)" }}>agent-ready</code>, <code style={{ color: "var(--fg-1)" }}>integration-ready</code>. Unearned badges render a neutral “unverified” badge rather than failing.</P>
          <Code>{`curl ${TA.api}/v1/registry/acme-com/badge/score.svg`}</Code>
        </DocSection>

        <DocSection id="ta-mcp" title="MCP endpoint">
          <Method verb="POST" path="/v1/mcp" />
          <P>JSON-RPC 2.0 over HTTP with API-key auth. Methods: <code style={{ color: "var(--fg-1)" }}>initialize</code>, <code style={{ color: "var(--fg-1)" }}>ping</code>, <code style={{ color: "var(--fg-1)" }}>tools/list</code>, <code style={{ color: "var(--fg-1)" }}>tools/call</code>. Tools: <code style={{ color: "var(--fg-1)" }}>reliq_check_release_readiness</code>, <code style={{ color: "var(--fg-1)" }}>reliq_check_agent_readiness</code>, <code style={{ color: "var(--fg-1)" }}>reliq_generate_report</code>.</P>
        </DocSection>

        <DocSection id="ta-publish" title="Publishing workflow">
          <Method verb="POST" path="/v1/registry/profiles" />
          <P>Authenticated. Publish an existing public report as a Trust Profile: validates the slug (unique, safe), caches the Trust Score, and captures an initial Trust History snapshot. Returns the canonical URL, JSON URL, badge URLs, and embed snippets. Re-snapshot via <code style={{ color: "var(--fg-1)" }}>POST /v1/registry/profiles/{"{slug}"}/refresh</code>.</P>
          <Code>{`curl -X POST ${TA.api}/v1/registry/profiles \\
  -H "Authorization: Bearer <session-or-token>" \\
  -H "Content-Type: application/json" \\
  -d '{
    "workspaceId": "wsp_123", "name": "Acme", "kind": "WEBSITE",
    "slug": "acme-com", "websiteUrl": "https://acme.com",
    "reportPublicId": "rep_2k8x"
  }'`}</Code>
        </DocSection>

        <DocSection id="ta-agent" title="Agent metadata fields">
          <P>Every profile JSON includes an <code style={{ color: "var(--fg-1)" }}>agent</code> block for AI agents: trust score, grade, five pillar scores, badges, trend (movement + direction), badge URLs, public report JSON URL, and the discovery API URL.</P>
          <Code>{`"agent": {
  "trust_score": 72, "grade": "Needs Work",
  "trust_ready": false, "agent_ready": false, "integration_ready": true,
  "pillars": { "release": 78, "security": 90, "agent": 55, "api": 78, "docs": 82 },
  "previous_score": 66, "movement_30d": 6, "movement_90d": 12, "direction": "up",
  "last_verified": "2026-06-20T00:00:00.000Z",
  "report_json_url": "${TA.api}/v1/public/reports/rep_2k8x",
  "badge_urls": { "score": "…/badge/score.svg", "agent-ready": "…/badge/agent-ready.svg" },
  "discovery_url": "${TA.api}/v1/registry/discover"
}`}</Code>
        </DocSection>

        <DocSection id="ta-examples" title="Examples">
          <P><strong>Find top agent-ready APIs</strong></P>
          <Code>{`curl "${TA.api}/v1/registry/discover/top?kind=api&badges=agent-ready&sort=agent&limit=10"`}</Code>
          <P style={{ marginTop: 16 }}><strong>Find trust-ready products</strong></P>
          <Code>{`curl "${TA.api}/v1/registry/discover?kind=product&badges=trust-ready&sort=trust"`}</Code>
          <P style={{ marginTop: 16 }}><strong>Get a profile JSON</strong></P>
          <Code>{`curl ${TA.api}/v1/registry/acme-com.json`}</Code>
          <P style={{ marginTop: 16 }}><strong>Embed a Trust Ready badge</strong></P>
          <Code>{`[![Reliq Trust Ready](${TA.api}/v1/registry/acme-com/badge/trust-ready.svg)](${TA.site}/registry/acme-com)`}</Code>
          <P style={{ marginTop: 16 }}><strong>Use Reliq MCP to check agent readiness</strong></P>
          <Code>{`curl -X POST ${TA.api}/v1/mcp \\
  -H "Authorization: Bearer rq_live_xxx" \\
  -H "Content-Type: application/json" \\
  -d '{
    "jsonrpc": "2.0", "id": 1, "method": "tools/call",
    "params": { "name": "reliq_check_agent_readiness",
                "arguments": { "url": "https://acme.com" } }
  }'`}</Code>
        </DocSection>

        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", borderTop: "1px solid var(--line-1)", paddingTop: 20 }}>
          <button className="btn btn-sm" onClick={() => go("/registry")}><Icon name="globe" size={12} /> Browse the registry</button>
        </div>
      </div>
    </LandingLayout>
  );
};

Object.assign(window, { TrustApiDocs });
