import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Vaultfire × Chainlink Oracle — On-chain price feeds for AI agents',
  description:
    'Vaultfire reads 15 Chainlink Data Feeds across Base, Avalanche, Arbitrum, and Polygon and exposes them as paid x402 endpoints. ETH/USD, BTC/USD, LINK/USD, USDC/USD, AVAX/USD, MATIC/USD. Plus the unique Vaultfire × Chainlink composition: USD-denominated agent stake.',
  openGraph: {
    title: 'Vaultfire × Chainlink Oracle',
    description:
      '15 Chainlink Data Feeds. 4 chains. 3 x402 endpoints. Truthful market data for AI agents.',
    url: 'https://theloopbreaker.com/oracle',
    type: 'website',
  },
};

// Server component fetches live status at request time so the page always
// reflects on-chain truth. Cached for 30 s (matches the chainlink-status route).
async function fetchStatus() {
  try {
    const res = await fetch(
      'https://theloopbreaker.com/api/x402/oracle/chainlink-status',
      { next: { revalidate: 30 } },
    );
    if (!res.ok) return null;
    return (await res.json()) as {
      status: string;
      totals: { feeds: number; fresh: number; stale: number; errors: number };
      feeds: Record<
        string,
        Record<
          string,
          {
            answer: number | null;
            ageSeconds: number | null;
            fresh: boolean;
            feedAddress: string;
            explorerUrl: string;
            error?: string;
          }
        >
      >;
      checkedAt: string;
    };
  } catch {
    return null;
  }
}

const CHAIN_LABEL: Record<string, string> = {
  base: 'Base',
  avalanche: 'Avalanche',
  arbitrum: 'Arbitrum',
  polygon: 'Polygon',
};

const PAIR_LABEL: Record<string, string> = {
  'eth-usd': 'ETH / USD',
  'btc-usd': 'BTC / USD',
  'usdc-usd': 'USDC / USD',
  'link-usd': 'LINK / USD',
  'avax-usd': 'AVAX / USD',
  'matic-usd': 'MATIC / USD',
};

function formatPrice(answer: number | null): string {
  if (answer == null) return '—';
  if (answer >= 1000) return `$${answer.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
  if (answer >= 1) return `$${answer.toFixed(4)}`;
  return `$${answer.toFixed(6)}`;
}

function formatAge(seconds: number | null): string {
  if (seconds == null) return '—';
  if (seconds < 60) return `${seconds}s ago`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86400)}d ago`;
}

export default async function OraclePage() {
  const status = await fetchStatus();

  return (
    <main className="min-h-screen bg-[var(--color-ember-bg)] text-[var(--color-ember-text)] px-6 py-12">
      <div className="max-w-5xl mx-auto">
        <a
          href="/"
          className="text-sm text-[var(--color-ember-text-muted)] hover:text-white transition-colors"
        >
          ← theloopbreaker.com
        </a>

        {/* ── Hero ─────────────────────────────────────────────────────── */}
        <h1 className="mt-6 text-4xl md:text-5xl font-bold">
          Vaultfire <span style={{ color: 'var(--color-ember-accent)' }}>×</span>{' '}
          Chainlink
        </h1>
        <p className="mt-4 text-lg text-[var(--color-ember-text-muted)] max-w-3xl">
          Vaultfire reads <strong>15 Chainlink Data Feeds</strong> across Base,
          Avalanche, Arbitrum, and Polygon and exposes them as paid x402
          endpoints — plus a composition that neither protocol can produce
          alone: USD-denominated agent stake.
        </p>

        {/* ── Live status banner ───────────────────────────────────────── */}
        {status ? (
          <div
            className="mt-8 rounded-xl border p-5"
            style={{
              borderColor:
                status.status === 'ok'
                  ? '#22c55e88'
                  : status.status === 'degraded'
                    ? '#eab30888'
                    : '#ef444488',
              backgroundColor:
                status.status === 'ok'
                  ? '#22c55e14'
                  : status.status === 'degraded'
                    ? '#eab30814'
                    : '#ef444414',
            }}
          >
            <div className="flex flex-wrap items-baseline gap-x-4 gap-y-1">
              <span
                className="text-xs uppercase tracking-wider font-semibold"
                style={{
                  color:
                    status.status === 'ok'
                      ? '#22c55e'
                      : status.status === 'degraded'
                        ? '#eab308'
                        : '#ef4444',
                }}
              >
                Live · {status.status}
              </span>
              <span className="text-sm">
                {status.totals.fresh} of {status.totals.feeds} feeds fresh
              </span>
              {status.totals.stale > 0 && (
                <span className="text-sm text-[var(--color-ember-text-muted)]">
                  · {status.totals.stale} stale
                </span>
              )}
              {status.totals.errors > 0 && (
                <span className="text-sm text-[var(--color-ember-text-muted)]">
                  · {status.totals.errors} errors
                </span>
              )}
              <span className="text-xs text-[var(--color-ember-text-muted)]">
                · checked {new Date(status.checkedAt).toLocaleString()}
              </span>
            </div>
          </div>
        ) : (
          <div className="mt-8 rounded-xl border border-white/10 bg-white/5 p-5">
            <span className="text-sm text-[var(--color-ember-text-muted)]">
              Live status temporarily unavailable. Try{' '}
              <a
                href="/api/x402/oracle/chainlink-status"
                className="underline hover:text-white"
              >
                /api/x402/oracle/chainlink-status
              </a>
              .
            </span>
          </div>
        )}

        {/* ── The 3 endpoints ──────────────────────────────────────────── */}
        <div className="mt-10">
          <h2 className="text-2xl font-bold mb-4">Three endpoints</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="rounded-xl border border-[var(--color-ember-accent)]/50 bg-[var(--color-ember-accent)]/10 p-5">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-accent)] mb-1">
                $0.01 USDC
              </div>
              <div className="font-mono text-sm font-semibold mb-2">
                /api/x402/oracle/price-feed
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                Read any of 15 Chainlink Data Feeds. Returns answer, decimals,
                roundId, updatedAt, freshness. Pay with USDC on Base or Solana.
              </p>
            </div>

            <div className="rounded-xl border border-[var(--color-ember-accent)]/50 bg-[var(--color-ember-accent)]/10 p-5">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-accent)] mb-1">
                $0.02 USDC
              </div>
              <div className="font-mono text-sm font-semibold mb-2">
                /api/x402/oracle/agent-stake-usd
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                Compose Vaultfire bond × Chainlink price. USD-denominated agent
                stake with full audit trail. Unique to the integration.
              </p>
            </div>

            <div className="rounded-xl border border-white/15 bg-white/5 p-5">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)] mb-1">
                Free
              </div>
              <div className="font-mono text-sm font-semibold mb-2">
                /api/x402/oracle/chainlink-status
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                Discovery beacon. Lists all supported feeds with live freshness
                per chain. No payment required.
              </p>
            </div>
          </div>
        </div>

        {/* ── Live feed matrix ─────────────────────────────────────────── */}
        {status && (
          <div className="mt-10">
            <h2 className="text-2xl font-bold mb-4">Live feed matrix</h2>
            <div className="overflow-x-auto rounded-xl border border-white/10">
              <table className="w-full text-sm">
                <thead className="bg-white/5">
                  <tr>
                    <th className="text-left p-3 font-semibold">Chain</th>
                    <th className="text-left p-3 font-semibold">Pair</th>
                    <th className="text-right p-3 font-semibold">Price</th>
                    <th className="text-right p-3 font-semibold">Updated</th>
                    <th className="text-center p-3 font-semibold">Fresh</th>
                    <th className="text-left p-3 font-semibold">Feed</th>
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(status.feeds).flatMap(([chain, pairs]) =>
                    Object.entries(pairs).map(([pair, data]) => (
                      <tr
                        key={`${chain}-${pair}`}
                        className="border-t border-white/5 hover:bg-white/5"
                      >
                        <td className="p-3">{CHAIN_LABEL[chain] ?? chain}</td>
                        <td className="p-3 font-mono text-xs">
                          {PAIR_LABEL[pair] ?? pair}
                        </td>
                        <td className="p-3 text-right font-mono">
                          {formatPrice(data.answer)}
                        </td>
                        <td className="p-3 text-right text-[var(--color-ember-text-muted)] text-xs">
                          {formatAge(data.ageSeconds)}
                        </td>
                        <td className="p-3 text-center">
                          {data.fresh ? (
                            <span style={{ color: '#22c55e' }}>●</span>
                          ) : (
                            <span style={{ color: '#ef4444' }}>○</span>
                          )}
                        </td>
                        <td className="p-3">
                          <a
                            href={data.explorerUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="font-mono text-xs underline hover:text-white text-[var(--color-ember-text-muted)]"
                          >
                            {data.feedAddress.slice(0, 6)}…
                            {data.feedAddress.slice(-4)}
                          </a>
                        </td>
                      </tr>
                    )),
                  )}
                </tbody>
              </table>
            </div>
            <p className="mt-3 text-xs text-[var(--color-ember-text-muted)]">
              All prices read live from Chainlink AggregatorV3 proxies. Vaultfire
              does not operate these feeds — Chainlink&apos;s decentralized
              oracle network is the source of truth.
            </p>
          </div>
        )}

        {/* ── Why this matters ─────────────────────────────────────────── */}
        <div className="mt-10">
          <h2 className="text-2xl font-bold mb-4">Why this matters</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="rounded-xl border border-white/10 bg-white/5 p-5">
              <div className="text-sm font-semibold mb-2">
                Chainlink owns market data
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                Decades of decentralized oracle infrastructure. Battle-tested
                price feeds securing tens of billions of TVL. Vaultfire reads
                them on-chain, no middleman.
              </p>
            </div>
            <div className="rounded-xl border border-white/10 bg-white/5 p-5">
              <div className="text-sm font-semibold mb-2">
                Vaultfire owns agent truth
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                ERC-8004 identity, accountability bonds, reputation, validation,
                cross-chain bridge — 134 verified contracts across 4 chains.
              </p>
            </div>
            <div className="rounded-xl border border-white/10 bg-white/5 p-5">
              <div className="text-sm font-semibold mb-2">
                Composed, not duplicated
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                Vaultfire&apos;s Flourishing Metrics Oracle handles agent
                truth. Chainlink handles market data. Neither replaces the
                other — they compose into things like USD-denominated agent
                stake.
              </p>
            </div>
            <div className="rounded-xl border border-white/10 bg-white/5 p-5">
              <div className="text-sm font-semibold mb-2">
                Pay-as-you-go, x402-native
              </div>
              <p className="text-sm text-[var(--color-ember-text-muted)]">
                $0.01–$0.02 per call. USDC on Base or Solana. No API keys, no
                rate-limit tiers — every read is a signed, settled
                micropayment.
              </p>
            </div>
          </div>
        </div>

        {/* ── Try it ───────────────────────────────────────────────────── */}
        <div className="mt-10">
          <h2 className="text-2xl font-bold mb-4">Try it</h2>
          <div className="rounded-xl border border-white/10 bg-black p-5 font-mono text-xs overflow-x-auto">
            <div className="text-[var(--color-ember-text-muted)]">
              # Free discovery — no payment
            </div>
            <div className="mt-1">
              curl https://theloopbreaker.com/api/x402/oracle/chainlink-status
            </div>
            <div className="mt-4 text-[var(--color-ember-text-muted)]">
              # Paid read — returns 402 with Payment-Required header
            </div>
            <div className="mt-1">
              curl
              &apos;https://theloopbreaker.com/api/x402/oracle/price-feed?pair=eth-usd&amp;chain=base&apos;
            </div>
            <div className="mt-4 text-[var(--color-ember-text-muted)]">
              # Paid composition — Vaultfire bond × Chainlink price
            </div>
            <div className="mt-1">
              curl
              &apos;https://theloopbreaker.com/api/x402/oracle/agent-stake-usd?address=0xA054f831B562e729F8D268291EBde1B2EDcFb84F&amp;chain=base&apos;
            </div>
          </div>
        </div>

        {/* ── Links ────────────────────────────────────────────────────── */}
        <div className="mt-10 flex flex-wrap gap-3">
          <a
            href="/api/x402/oracle/chainlink-status"
            className="rounded-lg border border-[var(--color-ember-accent)]/50 bg-[var(--color-ember-accent)]/10 px-4 py-2 text-sm hover:bg-[var(--color-ember-accent)]/20 transition-colors"
            style={{ color: 'var(--color-ember-accent)' }}
          >
            Live status JSON →
          </a>
          <a
            href="/.well-known/x402.json"
            className="rounded-lg border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10 transition-colors"
          >
            x402 manifest
          </a>
          <a
            href="/architecture"
            className="rounded-lg border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10 transition-colors"
          >
            Architecture
          </a>
          <a
            href="/contracts"
            className="rounded-lg border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10 transition-colors"
          >
            134 contracts
          </a>
        </div>

        <div className="mt-10 text-xs text-[var(--color-ember-text-muted)]">
          Price data provided by{' '}
          <a
            href="https://chain.link"
            target="_blank"
            rel="noopener noreferrer"
            className="underline hover:text-white"
          >
            Chainlink
          </a>
          . Vaultfire reads Chainlink AggregatorV3 proxies on-chain and exposes
          them via x402 for agent consumption — Vaultfire does not operate the
          feeds.
        </div>
      </div>
    </main>
  );
}
