/**
 * /x402-email — Vaultfire x402-Email Spec v0.1
 *
 * Defines the on-chain accountability layer for paid email.
 * Sender stakes a bond + posts an x402 payment. Recipient verifies
 * via /api/x402/email/verify before delivering to inbox. If the email
 * is slop, recipient files a claim against the bond.
 *
 * This page is purely informational — no on-chain calls, no payment
 * gate, no client-side state. Static text + a couple of fetch examples.
 */
import type { Metadata } from 'next';
import Link from 'next/link';

export const metadata: Metadata = {
  title: 'x402-Email — Vaultfire Accountability Spec for Paid Inboxes',
  description:
    'Specification for bond-backed, x402-paid email. The verifier and payment workflow are disabled pending release-readiness evidence.',
  openGraph: {
    title: 'x402-Email — Vaultfire Accountability Spec for Paid Inboxes',
    description:
      'Bond-backed, x402-paid email specification. Payment routes are currently release-gated.',
    url: 'https://theloopbreaker.com/x402-email',
    siteName: 'Vaultfire',
    type: 'article',
  },
};

export const dynamic = 'force-static';

const SPEC_VERSION = '0.1.0';
const VERIFIER_URL = 'https://theloopbreaker.com/api/x402/email/verify';
const WELL_KNOWN_URL = 'https://theloopbreaker.com/.well-known/x402-email.json';

export default function X402EmailSpecPage() {
  return (
    <div className="min-h-screen bg-[#09090B] text-zinc-200">
      <main className="mx-auto max-w-3xl px-6 py-16">
        <div className="mb-4">
          <Link
            href="/"
            className="text-xs uppercase tracking-wider text-zinc-500 hover:text-zinc-300"
          >
            ← Vaultfire
          </Link>
        </div>

        <div className="mb-3">
          <span className="inline-block rounded border border-cyan-700/50 bg-cyan-900/20 px-2 py-1 text-[11px] uppercase tracking-wider text-cyan-300">
            Spec v{SPEC_VERSION} · Release-gated
          </span>
        </div>

        <h1 className="mb-4 text-4xl font-bold text-white sm:text-5xl">
          x402-Email
        </h1>
        <p className="mb-8 text-lg text-zinc-300">
          An open accountability layer for paid email. Senders stake a bond
          and post an x402 payment. Recipients verify both before delivery
          and file claims on slop. No new identity layer, no central
          authority — just headers, a bond, and an HTTP call.
        </p>
        <div className="mb-8 rounded border border-amber-700/50 bg-amber-900/20 p-4 text-sm text-amber-100">
          x402 payment and verifier routes are disabled pending release-readiness
          evidence. This page describes a proposed interface only; do not submit
          payment payloads or treat the examples as a live settlement workflow.
        </div>

        <SectionH2>The problem</SectionH2>
        <p className="mb-4">
          AI agents can draft a thousand personalized cold emails an hour.
          Receiving inboxes already filter most of them as slop. The next
          decade of agent-to-human and agent-to-agent communication needs
          a primitive that lets a sender say{' '}
          <em className="not-italic text-zinc-100">
            &quot;I have skin in the game — claim my bond if this is slop&quot;
          </em>
          , and lets the recipient verify that claim before opening the
          message.
        </p>
        <p className="mb-8">
          x402 already solves the &quot;pay-per-request&quot; half. Vaultfire
          accountability bonds solve the &quot;commit-to-quality&quot; half.
          x402-Email composes both into the email envelope.
        </p>

        <SectionH2>The protocol in three lines</SectionH2>
        <ol className="mb-8 list-decimal space-y-2 pl-6 text-zinc-300">
          <li>
            Sender posts a Vaultfire accountability bond on Base mainnet
            and (optionally) an x402 micro-payment via the Coinbase
            facilitator.
          </li>
          <li>
            Sender attaches the bond ID, payment tx, and signing address as
            email headers.
          </li>
          <li>
            Recipient&apos;s mail server (or filter, or worker) calls{' '}
            <CodeInline>{VERIFIER_URL}</CodeInline> and routes the message
            based on the response.
          </li>
        </ol>

        <SectionH2>Header format</SectionH2>
        <p className="mb-3">
          A compliant sender SHOULD attach the following headers to any
          outbound email it wants verified:
        </p>
        <CodeBlock>{`X-Vaultfire-Sender:   0xfA15Ee28939B222B0448261A22156070f0A7813C
X-Vaultfire-Bond:     <bondId>
X-Vaultfire-Chain:    base
X-Vaultfire-Spec:     x402-email/${SPEC_VERSION}
X-402-Payment:        base:<txHash>            (optional)
X-402-Amount:         0.01 USDC                (optional)`}</CodeBlock>
        <p className="mb-2 mt-3 text-sm text-zinc-400">
          All headers are optional individually — the verifier returns
          whatever it can confirm. At minimum either{' '}
          <CodeInline>X-Vaultfire-Sender</CodeInline> or{' '}
          <CodeInline>X-Vaultfire-Bond</CodeInline> must be present.
        </p>
        <p className="mb-8 text-sm text-zinc-400">
          Casing follows RFC 5322 — header names are case-insensitive on
          the wire. Vaultfire publishes the canonical casing above for
          interop.
        </p>

        <SectionH2>Recipient flow</SectionH2>
        <p className="mb-3">
          Any mail server, filter, or worker can call the verifier. The
          response tells you whether the bond is real, whether payment
          settled, the sender&apos;s combined trust score, and a non-binding
          routing recommendation:
        </p>
        <CodeBlock>{`POST ${VERIFIER_URL}
Content-Type: application/json

{
  "headers": {
    "x-vaultfire-sender": "0xfA15Ee28939B222B0448261A22156070f0A7813C",
    "x-vaultfire-bond":   "0x6750D28865434344e04e1D0a6044394b726C3dfE:42",
    "x-vaultfire-chain":  "base",
    "x-402-payment":      "base:0xabc...",
    "x-402-amount":       "0.01 USDC"
  }
}`}</CodeBlock>
        <p className="mt-3 mb-2">Response shape:</p>
        <CodeBlock>{`{
  "specVersion": "${SPEC_VERSION}",
  "verified": true,
  "sender": {
    "address":       "0xfA15...813C",
    "trustScore":    72,
    "registered":    true,
    "vnsName":       "ghostkey.base.eth"
  },
  "bond": {
    "id":            "...",
    "active":        true,
    "stakedEth":     "0.0050",
    "chain":         "base",
    "explorer":      "https://basescan.org/..."
  },
  "payment": {
    "settled":       true,
    "amount":        "0.01",
    "asset":         "USDC",
    "tx":            "0xabc..."
  },
  "recommendation": "inbox",   // "inbox" | "review" | "spam"
  "claimUrl":       "https://theloopbreaker.com/api/x402/email/claim",
  "tookMs":         284
}`}</CodeBlock>
        <p className="mt-3 mb-8 text-sm text-zinc-400">
          The recommendation is a heuristic from combined trust score, bond
          status, and payment settlement — never a hard authorization.
          Recipients are free to ignore it.
        </p>

        <SectionH2>Slop claim flow</SectionH2>
        <p className="mb-8">
          If a recipient marks a verified email as slop, they can file a
          claim against the bond. Claims are public, on-chain, and adjudicated
          through the same{' '}
          <Link href="/how-resolution-works" className="text-cyan-300 hover:underline">
            VaultfireDisputeResolution
          </Link>{' '}
          flow that powers all accountability bonds. Bonds are non-slashing
          — distribution flows through the flourishing metric, not punitive
          burns. See the resolution page for the contract mechanism.
        </p>

        <SectionH2>Discovery</SectionH2>
        <p className="mb-3">
          The machine-readable spec lives at:
        </p>
        <CodeBlock>{WELL_KNOWN_URL}</CodeBlock>
        <p className="mt-3 mb-8 text-sm text-zinc-400">
          Implementations should fetch this once at startup to discover
          the verifier URL, supported chains, and current spec version.
        </p>

        <SectionH2>Reference implementations</SectionH2>
        <ul className="mb-8 list-disc space-y-1 pl-6 text-zinc-300">
          <li>
            <span className="text-zinc-100">Verifier:</span>{' '}
            <CodeInline>{VERIFIER_URL}</CodeInline> (currently release-gated)
          </li>
          <li>
            <span className="text-zinc-100">SDK:</span>{' '}
            <Link
              href="https://www.npmjs.com/package/@vaultfire/agent-sdk"
              className="text-cyan-300 hover:underline"
            >
              @vaultfire/agent-sdk
            </Link>{' '}
            — bond + tx-builder helpers a sender can use to mint a bond
            before sending
          </li>
          <li>
            <span className="text-zinc-100">Cloudflare Email Worker:</span>{' '}
            planned (v0.2) — a forkable worker that calls the verifier and
            tags messages
          </li>
          <li>
            <span className="text-zinc-100">Postfix milter:</span> planned
            (v0.2)
          </li>
        </ul>

        <SectionH2>Status</SectionH2>
        <p className="mb-3">
          v{SPEC_VERSION} is a draft. The x402-email verifier and payment
          workflow are release-gated and this page does not activate them.
          The examples describe the proposed Base integration; header names,
          response shape, and routing recommendations may change before v1.0.
        </p>
        <p className="mb-12">
          Feedback, forks, and reference implementations welcome —{' '}
          <Link
            href="https://gitlawb.com/z6MkryiNsYdFEMHv95wxzSQ1vtFXPyVQQrxXdPw3tE5HpfxV/vaultfire"
            className="text-cyan-300 hover:underline"
          >
            vaultfire on gitlawb
          </Link>
          .
        </p>

        <hr className="my-10 border-zinc-800" />
        <p className="text-xs text-zinc-500">
          x402-Email is an open spec. No license fees, no central registry,
          no Vaultfire-only requirement. If activated after release review,
          bond and payment state would be publicly verifiable on Base; the
          verifier is one possible implementation.
        </p>
      </main>
    </div>
  );
}

function SectionH2({ children }: { children: React.ReactNode }) {
  return (
    <h2 className="mb-4 mt-10 text-2xl font-semibold text-white">
      {children}
    </h2>
  );
}

function CodeInline({ children }: { children: React.ReactNode }) {
  return (
    <code className="rounded bg-zinc-800 px-1.5 py-0.5 text-[0.85em] text-zinc-200">
      {children}
    </code>
  );
}

function CodeBlock({ children }: { children: string }) {
  return (
    <pre className="overflow-x-auto rounded-lg border border-zinc-800 bg-zinc-950 p-4 text-xs leading-relaxed text-zinc-200 sm:text-[13px]">
      <code>{children}</code>
    </pre>
  );
}
