import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Live Proof — Vaultfire',
  description:
    'Live on-chain proof of the Vaultfire Protocol. Not a video, not a mockup — real agents, real bonds, real transactions updating in real time.',
};

// Pull fresh data every 30 seconds — this is the live proof page
export const revalidate = 30;

interface Agent {
  name: string;
  fullName: string;
  address: string;
  chain: string;
  identityType: string;
  description: string;
  active: boolean;
  registeredAt: number;
  explorerUrl: string;
}

interface HubStats {
  totalIdentities: number;
  activeBonds: number;
  chainCounts: Record<string, number>;
  chainBonded: Record<string, { amount: number; token: string }>;
  timestamp: number;
}

async function fetchStats(): Promise<HubStats | null> {
  try {
    const r = await fetch('https://theloopbreaker.com/api/hub/stats', {
      next: { revalidate: 30 },
    });
    if (!r.ok) return null;
    return r.json();
  } catch {
    return null;
  }
}

async function fetchContractCount(): Promise<number | null> {
  try {
    const r = await fetch('https://theloopbreaker.com/api/contracts', {
      next: { revalidate: 300 },
    });
    if (!r.ok) return null;
    const d = await r.json();
    return typeof d.totalContracts === 'number' ? d.totalContracts : null;
  } catch {
    return null;
  }
}

async function fetchAgents(chain: string): Promise<Agent[]> {
  try {
    const r = await fetch(
      `https://theloopbreaker.com/api/agent/discover?chain=${chain}&limit=10`,
      { next: { revalidate: 30 } },
    );
    if (!r.ok) return [];
    const d = await r.json();
    return d.agents || [];
  } catch {
    return [];
  }
}

function timeAgo(unix: number) {
  const now = Math.floor(Date.now() / 1000);
  const diff = now - unix;
  if (diff < 60) return `${diff}s ago`;
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
  return `${Math.floor(diff / 2592000)}mo ago`;
}

function shorten(addr: string) {
  return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
}

export default async function DemoPage() {
  const [stats, contractCount, baseAgents, avaxAgents, arbAgents, polAgents] =
    await Promise.all([
      fetchStats(),
      fetchContractCount(),
      fetchAgents('base'),
      fetchAgents('avalanche'),
      fetchAgents('arbitrum'),
      fetchAgents('polygon'),
    ]);

  const allAgents = [
    ...baseAgents,
    ...avaxAgents,
    ...arbAgents,
    ...polAgents,
  ].sort((a, b) => b.registeredAt - a.registeredAt);

  const totalBonded = stats
    ? Object.entries(stats.chainBonded)
        .map(([chain, data]) => `${data.amount} ${data.token}`)
        .join(' · ')
    : '—';

  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>

        <div className="mt-6 flex flex-wrap items-baseline gap-x-3 gap-y-2">
          <h1 className="text-4xl md:text-5xl font-bold">Live Proof</h1>
          <span className="inline-flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider px-2.5 py-1 rounded-md bg-[#10B981]/15 border border-[#10B981]/40 text-[#34D399]">
            <span className="w-1.5 h-1.5 rounded-full bg-[#10B981] animate-pulse" />
            Refreshing every 30s
          </span>
        </div>

        <p className="mt-4 text-lg text-[var(--color-ember-text-muted)] max-w-3xl">
          This page is not a video. Not a mockup. Every number and every address
          below is pulled fresh from the live Vaultfire API on page load. Click
          any row to see the transaction on its block explorer.
        </p>

        {/* ── Live stats ─────────────────────────────────────────────── */}
        <section className="mt-10">
          <h2 className="text-xl font-bold mb-4">The protocol, right now</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div className="rounded-xl border border-white/10 p-4">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)]">
                Registered agents
              </div>
              <div className="text-3xl font-bold mt-1">
                {stats?.totalIdentities ?? '—'}
              </div>
            </div>
            <div className="rounded-xl border border-white/10 p-4">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)]">
                Active bonds
              </div>
              <div className="text-3xl font-bold mt-1">
                {stats?.activeBonds ?? '—'}
              </div>
            </div>
            <div className="rounded-xl border border-white/10 p-4">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)]">
                Chains live
              </div>
              <div className="text-3xl font-bold mt-1">
                {stats ? Object.keys(stats.chainCounts).length : '—'}
              </div>
            </div>
            <div className="rounded-xl border border-white/10 p-4">
              <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)]">
                Contracts deployed
              </div>
              <div className="text-3xl font-bold mt-1">{contractCount ?? '—'}</div>
            </div>
          </div>

          <div className="mt-4 rounded-xl border border-white/10 p-4">
            <div className="text-xs uppercase tracking-wider text-[var(--color-ember-text-muted)] mb-1">
              Total value staked (across all chains)
            </div>
            <div className="text-lg font-mono">{totalBonded}</div>
          </div>
        </section>

        {/* ── Per-chain breakdown ────────────────────────────────────── */}
        <section className="mt-10">
          <h2 className="text-xl font-bold mb-4">Per-chain breakdown</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
            {stats &&
              Object.entries(stats.chainCounts).map(([chain, count]) => {
                const bonded = stats.chainBonded[chain];
                return (
                  <div
                    key={chain}
                    className="rounded-xl border border-white/10 p-4"
                  >
                    <div className="font-semibold capitalize mb-2">{chain}</div>
                    <div className="text-xs text-[var(--color-ember-text-muted)]">
                      {count} agent{count === 1 ? '' : 's'}
                    </div>
                    {bonded && (
                      <div className="text-xs text-[var(--color-ember-text-muted)] mt-1">
                        {bonded.amount} {bonded.token} staked
                      </div>
                    )}
                  </div>
                );
              })}
          </div>
        </section>

        {/* ── Recent agents ──────────────────────────────────────────── */}
        <section className="mt-10">
          <div className="flex items-baseline gap-3 mb-4">
            <h2 className="text-xl font-bold">Most recent registrations</h2>
            <span className="text-xs text-[var(--color-ember-text-muted)]">
              Showing {allAgents.length}
            </span>
          </div>
          <div className="rounded-xl border border-white/10 overflow-hidden">
            <table className="w-full text-sm">
              <thead className="bg-white/5 text-left">
                <tr>
                  <th className="px-4 py-3 font-semibold">Agent</th>
                  <th className="px-4 py-3 font-semibold">Chain</th>
                  <th className="px-4 py-3 font-semibold hidden md:table-cell">
                    Type
                  </th>
                  <th className="px-4 py-3 font-semibold">Registered</th>
                  <th className="px-4 py-3 font-semibold text-right">
                    Explorer
                  </th>
                </tr>
              </thead>
              <tbody>
                {allAgents.length === 0 && (
                  <tr>
                    <td
                      colSpan={5}
                      className="px-4 py-6 text-center text-[var(--color-ember-text-muted)]"
                    >
                      No agents loaded. Check{' '}
                      <a
                        href="/api/hub/stats"
                        className="text-[var(--color-ember-accent)] hover:underline"
                      >
                        /api/hub/stats
                      </a>
                      .
                    </td>
                  </tr>
                )}
                {allAgents.map((a) => (
                  <tr
                    key={`${a.chain}-${a.address}`}
                    className="border-t border-white/5 hover:bg-white/5"
                  >
                    <td className="px-4 py-3">
                      <div className="font-medium">{a.fullName}</div>
                      <div className="text-xs font-mono text-[var(--color-ember-text-muted)]">
                        <span className="hidden md:inline">{a.address}</span>
                        <span className="md:hidden">{shorten(a.address)}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 capitalize text-[var(--color-ember-text-muted)]">
                      {a.chain}
                    </td>
                    <td className="px-4 py-3 hidden md:table-cell text-[var(--color-ember-text-muted)]">
                      {a.identityType}
                    </td>
                    <td className="px-4 py-3 text-[var(--color-ember-text-muted)]">
                      {timeAgo(a.registeredAt)}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <a
                        href={a.explorerUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="text-[var(--color-ember-accent)] hover:underline"
                      >
                        View →
                      </a>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>

        {/* ── The walk-through ──────────────────────────────────────── */}
        <section className="mt-12">
          <h2 className="text-xl font-bold mb-4">What you&apos;re looking at</h2>
          <div className="rounded-xl border border-white/10 p-6 bg-white/[0.02] space-y-4 text-sm leading-relaxed">
            <p>
              <span className="font-semibold">Every agent above is real.</span>{' '}
              Every address resolves on BaseScan, Snowtrace, Arbiscan, or
              PolygonScan. Click any &quot;View&quot; link to confirm for
              yourself.
            </p>
            <p>
              <span className="font-semibold">Every bond above is staked.</span>{' '}
              The totals in the per-chain breakdown are real ETH, AVAX, and POL
              held in Vaultfire contracts right now. If someone calls{' '}
              <code className="text-xs bg-white/10 px-1.5 py-0.5 rounded">
                requestDistribution()
              </code>{' '}
              and the autonomy metrics pass, that money moves.
            </p>
            <p>
              <span className="font-semibold">
                Every number updates every 30 seconds.
              </span>{' '}
              Refresh this page an hour from now — the numbers will be different
              if someone has registered, bonded, or submitted metrics. No other
              trust protocol gives you this kind of live proof.
            </p>
            <p>
              <span className="font-semibold">This is KYA in practice.</span>{' '}
              Know Your Agent — not by trusting a marketing page, but by reading
              the chain yourself.
            </p>
          </div>
        </section>

        {/* ── Next ──────────────────────────────────────────────────── */}
        <section className="mt-10 flex flex-wrap gap-3 text-sm">
          <a
            href="/start"
            className="rounded-lg bg-[var(--color-ember-accent)] text-black font-semibold px-5 py-2.5"
          >
            Start building →
          </a>
          <a
            href="/contracts"
            className="rounded-lg border border-white/20 px-4 py-2 hover:border-white/40"
          >
            All contracts
          </a>
          <a
            href="/architecture"
            className="rounded-lg border border-white/20 px-4 py-2 hover:border-white/40"
          >
            Architecture
          </a>
          <a
            href="/security"
            className="rounded-lg border border-white/20 px-4 py-2 hover:border-white/40"
          >
            Security
          </a>
          <a
            href="/api/hub/stats"
            className="rounded-lg border border-white/20 px-4 py-2 hover:border-white/40"
          >
            Raw API
          </a>
        </section>
      </div>
    </main>
  );
}
