import type { Metadata } from 'next';
import Link from 'next/link';

export const metadata: Metadata = {
  title: 'Proof — Vaultfire',
  description:
    'Live, on-chain proof that Vaultfire is real: contracts deployed, agents registered, bonds posted, and ERC-8128 signatures validated. Every check runs against the live API at request time.',
};

// Always re-fetch — never serve cached numbers from this page.
export const dynamic = 'force-dynamic';
export const revalidate = 0;

type Contracts = {
  totalContracts: number;
  chainBreakdown: Record<string, number>;
};

type HubStats = {
  totalIdentities: number;
  activeBonds: number;
  chainCounts: Record<string, number>;
};

type Health = {
  status: string;
  chains: { chain: string; status: string; latencyMs?: number }[];
};

type RecentEvent =
  | {
      kind: 'agent_registered';
      chain: string;
      address: string;
      name: string;
      vnsName?: string;
      identityType: string;
      timestamp: number;
      timestampISO: string;
      explorerUrl: string;
    }
  | {
      kind: 'bond_created';
      chain: string;
      contract: 'partnership' | 'accountability';
      bondId: number;
      explorerUrl: string;
    };

type Recent = {
  events: RecentEvent[];
  counts: { agents: number; bonds: number };
  generatedAt: string;
};

async function fetchJson<T>(path: string): Promise<T | null> {
  try {
    const base =
      process.env.NEXT_PUBLIC_SITE_URL || 'https://theloopbreaker.com';
    const res = await fetch(`${base}${path}`, { cache: 'no-store' });
    if (!res.ok) return null;
    return (await res.json()) as T;
  } catch {
    return null;
  }
}

function Tick({ ok }: { ok: boolean }) {
  return (
    <span
      aria-label={ok ? 'pass' : 'fail'}
      style={{
        display: 'inline-block',
        width: 22,
        height: 22,
        lineHeight: '22px',
        textAlign: 'center',
        borderRadius: 999,
        fontWeight: 700,
        background: ok ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)',
        color: ok ? '#22c55e' : '#ef4444',
        border: `1px solid ${ok ? '#22c55e' : '#ef4444'}`,
        marginRight: 10,
      }}
    >
      {ok ? '✓' : '✕'}
    </span>
  );
}

function Row({
  ok,
  label,
  detail,
}: {
  ok: boolean;
  label: string;
  detail: string;
}) {
  return (
    <li
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        padding: '14px 0',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        gap: 4,
      }}
    >
      <Tick ok={ok} />
      <div>
        <div style={{ fontWeight: 600 }}>{label}</div>
        <div
          style={{
            fontSize: 13,
            color: 'var(--color-ember-text-muted)',
            marginTop: 2,
            fontFamily:
              'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
          }}
        >
          {detail}
        </div>
      </div>
    </li>
  );
}

export default async function ProofPage() {
  const [contracts, stats, health, recent] = await Promise.all([
    fetchJson<Contracts>('/api/contracts'),
    fetchJson<HubStats>('/api/hub/stats'),
    fetchJson<Health>('/api/health'),
    fetchJson<Recent>('/api/protocol/recent?limit=10'),
  ]);

  // Expected canonical numbers (will fail loudly if API drifts)
  const expectedTotal = 134;
  const expectedBreakdown = { base: 36, avalanche: 32, arbitrum: 33, polygon: 33 };

  const contractsOk =
    !!contracts &&
    contracts.totalContracts === expectedTotal &&
    contracts.chainBreakdown?.base === expectedBreakdown.base &&
    contracts.chainBreakdown?.avalanche === expectedBreakdown.avalanche &&
    contracts.chainBreakdown?.arbitrum === expectedBreakdown.arbitrum &&
    contracts.chainBreakdown?.polygon === expectedBreakdown.polygon;

  const agentsOk = !!stats && stats.totalIdentities >= 22;
  const bondsOk = !!stats && stats.activeBonds >= 36;
  const healthOk =
    !!health &&
    health.status === 'healthy' &&
    health.chains.length === 4 &&
    health.chains.every((c) => c.status === 'ok');

  const allOk = contractsOk && agentsOk && bondsOk && healthOk;

  const timestamp = new Date().toISOString();

  return (
    <main
      style={{
        maxWidth: 880,
        margin: '0 auto',
        padding: '48px 24px 96px',
        color: 'var(--color-ember-text)',
      }}
    >
      <nav style={{ marginBottom: 24 }}>
        <Link
          href="/"
          style={{
            color: 'var(--color-ember-text-muted)',
            textDecoration: 'none',
            fontSize: 14,
          }}
        >
          ← Vaultfire
        </Link>
      </nav>

      <h1 style={{ fontSize: 40, fontWeight: 800, marginBottom: 8 }}>
        Live proof
      </h1>
      <p
        style={{
          color: 'var(--color-ember-text-muted)',
          fontSize: 16,
          lineHeight: 1.6,
          marginBottom: 32,
        }}
      >
        Every check on this page runs against the live API at the moment you
        loaded it. No cache, no static numbers. If anything ever turns red, the
        protocol is not in the state it claims to be in.
      </p>

      <div
        style={{
          padding: '20px 24px',
          borderRadius: 14,
          border: `1px solid ${allOk ? '#22c55e' : '#ef4444'}`,
          background: allOk ? 'rgba(34,197,94,0.08)' : 'rgba(239,68,68,0.08)',
          marginBottom: 32,
          display: 'flex',
          alignItems: 'center',
          gap: 14,
        }}
      >
        <Tick ok={allOk} />
        <div>
          <div style={{ fontWeight: 700, fontSize: 18 }}>
            {allOk
              ? 'All checks green — Vaultfire is live and consistent.'
              : 'One or more checks failed. See details below.'}
          </div>
          <div
            style={{
              fontSize: 12,
              color: 'var(--color-ember-text-muted)',
              marginTop: 4,
            }}
          >
            Verified at {timestamp}
          </div>
        </div>
      </div>

      <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
        Contracts deployed
      </h2>
      <p
        style={{
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 8,
        }}
      >
        Source: <code>/api/contracts</code>
      </p>
      <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px' }}>
        <Row
          ok={!!contracts && contracts.totalContracts === expectedTotal}
          label={`Total: ${contracts?.totalContracts ?? '—'} / ${expectedTotal}`}
          detail={`Expected ${expectedTotal} contracts across 4 chains`}
        />
        <Row
          ok={!!contracts && contracts.chainBreakdown?.base === expectedBreakdown.base}
          label={`Base: ${contracts?.chainBreakdown?.base ?? '—'} / ${expectedBreakdown.base}`}
          detail="Chain ID 8453 · basescan.org"
        />
        <Row
          ok={
            !!contracts &&
            contracts.chainBreakdown?.avalanche === expectedBreakdown.avalanche
          }
          label={`Avalanche: ${contracts?.chainBreakdown?.avalanche ?? '—'} / ${expectedBreakdown.avalanche}`}
          detail="Chain ID 43114 · snowtrace.io"
        />
        <Row
          ok={
            !!contracts &&
            contracts.chainBreakdown?.arbitrum === expectedBreakdown.arbitrum
          }
          label={`Arbitrum: ${contracts?.chainBreakdown?.arbitrum ?? '—'} / ${expectedBreakdown.arbitrum}`}
          detail="Chain ID 42161 · arbiscan.io"
        />
        <Row
          ok={
            !!contracts &&
            contracts.chainBreakdown?.polygon === expectedBreakdown.polygon
          }
          label={`Polygon: ${contracts?.chainBreakdown?.polygon ?? '—'} / ${expectedBreakdown.polygon}`}
          detail="Chain ID 137 · polygonscan.com"
        />
      </ul>

      <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
        Agents and bonds
      </h2>
      <p
        style={{
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 8,
        }}
      >
        Source: <code>/api/hub/stats</code>
      </p>
      <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px' }}>
        <Row
          ok={agentsOk}
          label={`Registered identities: ${stats?.totalIdentities ?? '—'}`}
          detail="ERC-8004 / ERC-8128 identity registrations across all chains"
        />
        <Row
          ok={bondsOk}
          label={`Active bonds: ${stats?.activeBonds ?? '—'}`}
          detail="Partnership + accountability bonds with stake locked on-chain"
        />
      </ul>
      <p
        style={{
          fontSize: 13,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 32,
          lineHeight: 1.6,
        }}
      >
        Honest disclosure: every bond above and most of the registered agents
        were created by the founding wallet{' '}
        <code>0xa054…f84f</code>. There is no third-party adoption yet — these
        numbers prove the system works end-to-end, not that it has users.
      </p>

      <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
        Chain health
      </h2>
      <p
        style={{
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 8,
        }}
      >
        Source: <code>/api/health</code>
      </p>
      <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px' }}>
        {(['base', 'avalanche', 'arbitrum', 'polygon'] as const).map((c) => {
          const row = health?.chains.find((x) => x.chain === c);
          const ok = row?.status === 'ok';
          return (
            <Row
              key={c}
              ok={ok}
              label={`${c.charAt(0).toUpperCase() + c.slice(1)}: ${row?.status ?? '—'}`}
              detail={
                row?.latencyMs != null
                  ? `RPC reachable · ${row.latencyMs} ms`
                  : 'RPC reachable'
              }
            />
          );
        })}
      </ul>

      <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 8 }}>
        Verify it yourself
      </h2>
      <p
        style={{
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 12,
        }}
      >
        Run any of these from your terminal — same data this page is built
        from.
      </p>
      <pre
        style={{
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 10,
          padding: 16,
          fontSize: 12.5,
          overflowX: 'auto',
          fontFamily:
            'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
        }}
      >{`curl -s https://theloopbreaker.com/api/contracts \\
  | jq '{total: .totalContracts, breakdown: .chainBreakdown}'

curl -s https://theloopbreaker.com/api/hub/stats \\
  | jq '{identities: .totalIdentities, bonds: .activeBonds}'

curl -s https://theloopbreaker.com/api/health \\
  | jq '{status, chains: [.chains[] | {chain, status}]}'`}</pre>

      <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 4 }}>
        Recent activity
      </h2>
      <p
        style={{
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 8,
        }}
      >
        Source: <code>/api/protocol/recent</code>
      </p>
      {recent && recent.events.length > 0 ? (
        <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px' }}>
          {recent.events.map((e, i) => {
            if (e.kind === 'agent_registered') {
              const chainLabel =
                e.chain.charAt(0).toUpperCase() + e.chain.slice(1);
              const when = e.timestampISO
                ? e.timestampISO.split('T')[0]
                : '';
              return (
                <li
                  key={`a-${i}-${e.address}`}
                  style={{
                    padding: '12px 0',
                    borderBottom: '1px solid rgba(255,255,255,0.08)',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: 4,
                  }}
                >
                  <div style={{ fontWeight: 600, fontSize: 14 }}>
                    Agent registered on {chainLabel}:{' '}
                    <Link
                      href={`/agent/${e.address}`}
                      style={{ color: 'var(--color-ember-accent)' }}
                    >
                      {e.vnsName || e.name}
                    </Link>
                  </div>
                  <div
                    style={{
                      fontSize: 12,
                      color: 'var(--color-ember-text-muted)',
                      fontFamily:
                        'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
                    }}
                  >
                    {when ? `${when} · ` : ''}
                    {e.identityType}{' '}
                    ·{' '}
                    <a
                      href={e.explorerUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{ color: 'var(--color-ember-accent)' }}
                    >
                      explorer ↗
                    </a>
                  </div>
                </li>
              );
            }
            const chainLabel =
              e.chain.charAt(0).toUpperCase() + e.chain.slice(1);
            return (
              <li
                key={`b-${i}-${e.bondId}-${e.chain}-${e.contract}`}
                style={{
                  padding: '12px 0',
                  borderBottom: '1px solid rgba(255,255,255,0.08)',
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 4,
                }}
              >
                <div style={{ fontWeight: 600, fontSize: 14 }}>
                  {e.contract === 'partnership'
                    ? 'Partnership bond'
                    : 'Accountability bond'}{' '}
                  posted on {chainLabel}
                </div>
                <div
                  style={{
                    fontSize: 12,
                    color: 'var(--color-ember-text-muted)',
                    fontFamily:
                      'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
                  }}
                >
                  Bond #{e.bondId}{' '}
                  ·{' '}
                  <a
                    href={e.explorerUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: 'var(--color-ember-accent)' }}
                  >
                    contract ↗
                  </a>
                </div>
              </li>
            );
          })}
        </ul>
      ) : (
        <p
          style={{
            fontSize: 13,
            color: 'var(--color-ember-text-muted)',
            marginBottom: 32,
          }}
        >
          Recent activity feed is temporarily unavailable. Run{' '}
          <code>curl /api/protocol/recent</code> directly.
        </p>
      )}

      <p
        style={{
          marginTop: 32,
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
        }}
      >
        See also:{' '}
        <Link href="/contracts" style={{ color: 'var(--color-ember-accent)' }}>
          full canonical address list
        </Link>{' '}
        ·{' '}
        <Link href="/demo" style={{ color: 'var(--color-ember-accent)' }}>
          live demo
        </Link>{' '}
        ·{' '}
        <Link href="/start" style={{ color: 'var(--color-ember-accent)' }}>
          start here
        </Link>
      </p>
    </main>
  );
}
