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

export const dynamic = 'force-dynamic';
export const revalidate = 0;

type AgentStatus = {
  address: string;
  chain: string;
  registered: boolean;
  vnsName?: string | null;
  name?: string | null;
  identityType?: string | null;
  description?: string | null;
  capabilities?: string[];
  active?: boolean;
  registeredAt?: number | null;
  hasBond?: boolean;
  bondActive?: boolean;
  bondId?: number | null;
  bondCount?: number;
  bondTier?: string | null;
  bondAmountEth?: number;
  trustScore?: number;
  explorerUrl?: string;
};

const CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'] as const;
type ChainKey = (typeof CHAINS)[number];

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

const CHAIN_EXPLORER: Record<ChainKey, string> = {
  base: 'https://basescan.org',
  avalanche: 'https://snowtrace.io',
  arbitrum: 'https://arbiscan.io',
  polygon: 'https://polygonscan.com',
};

// Each chain's native gas token. Bonds are denominated in this token, NOT in
// USDC and NOT in ETH-everywhere. We must never sum across chains because
// these are different assets with different prices.
const CHAIN_NATIVE_TOKEN: Record<ChainKey, string> = {
  base: 'ETH',
  arbitrum: 'ETH',
  avalanche: 'AVAX',
  polygon: 'POL',
};

function isValidAddress(addr: string): boolean {
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
}

function tierFromScore(score: number | undefined): string {
  if (score == null) return 'Newcomer';
  if (score >= 90) return 'Diamond';
  if (score >= 75) return 'Platinum';
  if (score >= 60) return 'Gold';
  if (score >= 40) return 'Silver';
  if (score >= 20) return 'Bronze';
  return 'Newcomer';
}

function tierColor(tier: string): string {
  switch (tier) {
    case 'Diamond':
      return '#b9f2ff';
    case 'Platinum':
      return '#e5e4e2';
    case 'Gold':
      return '#ffd700';
    case 'Silver':
      return '#c0c0c0';
    case 'Bronze':
      return '#cd7f32';
    default:
      return '#888';
  }
}

async function fetchStatus(address: string, chain: ChainKey): Promise<AgentStatus | null> {
  try {
    const base = process.env.NEXT_PUBLIC_SITE_URL || 'https://theloopbreaker.com';
    const res = await fetch(
      `${base}/api/agent/status?address=${address}&chain=${chain}`,
      { cache: 'no-store' },
    );
    if (!res.ok) return null;
    return (await res.json()) as AgentStatus;
  } catch {
    return null;
  }
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ address: string }>;
}): Promise<Metadata> {
  const { address } = await params;
  if (!isValidAddress(address)) {
    return { title: 'Invalid agent address — Vaultfire' };
  }
  return {
    title: `Agent ${address.slice(0, 6)}…${address.slice(-4)} — Vaultfire`,
    description: `On-chain profile for agent ${address}: identity, trust score, partnership bonds, and verifiable history across Base, Avalanche, Arbitrum, and Polygon.`,
  };
}

export default async function AgentProfilePage({
  params,
}: {
  params: Promise<{ address: string }>;
}) {
  const { address: rawAddress } = await params;
  if (!isValidAddress(rawAddress)) notFound();

  const address = rawAddress.toLowerCase();

  // Fetch status across all 4 chains in parallel.
  const all = await Promise.all(
    CHAINS.map((c) => fetchStatus(address, c).then((s) => ({ chain: c, status: s }))),
  );

  // A "registered" entry on any chain means the agent exists somewhere on the protocol.
  const registeredOn = all.filter((x) => x.status?.registered);
  const anyRegistered = registeredOn.length > 0;
  const primary = registeredOn[0]?.status ?? null;

  const bestScore = Math.max(
    0,
    ...all.map((x) => x.status?.trustScore ?? 0),
  );
  const tier = tierFromScore(bestScore);
  const tierColorValue = tierColor(tier);

  const totalBonds = all.reduce((acc, x) => acc + (x.status?.bondCount ?? 0), 0);
  // Count chains with non-zero stake. We never sum stake across chains because
  // ETH/AVAX/POL are different assets with different prices. Per-chain amounts
  // are rendered inline in the breakdown list below using the chain's native
  // token symbol from CHAIN_NATIVE_TOKEN.
  const stakedOnChains = all.filter((x) => (x.status?.bondAmountEth ?? 0) > 0).length;

  return (
    <main
      style={{
        maxWidth: 960,
        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>

      <div style={{ marginBottom: 24 }}>
        <div
          style={{
            fontSize: 13,
            color: 'var(--color-ember-text-muted)',
            fontFamily:
              'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
            wordBreak: 'break-all',
            marginBottom: 8,
          }}
        >
          {address}
        </div>
        <h1
          style={{
            fontSize: 38,
            fontWeight: 800,
            marginBottom: 8,
            lineHeight: 1.2,
          }}
        >
          {primary?.name ?? primary?.vnsName ?? `agent-${address.slice(2, 8)}`}
        </h1>
        {primary?.description && (
          <p
            style={{
              color: 'var(--color-ember-text-muted)',
              fontSize: 16,
              lineHeight: 1.6,
              marginBottom: 0,
            }}
          >
            {primary.description}
          </p>
        )}
      </div>

      {!anyRegistered ? (
        <div
          style={{
            padding: '20px 24px',
            borderRadius: 14,
            border: '1px solid #ef4444',
            background: 'rgba(239,68,68,0.08)',
            marginBottom: 32,
          }}
        >
          <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 4 }}>
            Not registered on any Vaultfire chain
          </div>
          <div
            style={{
              fontSize: 13,
              color: 'var(--color-ember-text-muted)',
            }}
          >
            This address has no ERC-8004 identity record on Base, Avalanche,
            Arbitrum, or Polygon. If this is your agent,{' '}
            <Link
              href="/start"
              style={{ color: 'var(--color-ember-accent)' }}
            >
              start here
            </Link>
            .
          </div>
        </div>
      ) : (
        <>
          {/* Top stats bar */}
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
              gap: 12,
              marginBottom: 32,
            }}
          >
            <Stat
              label="Trust tier"
              value={tier}
              accent={tierColorValue}
              detail={`Score ${bestScore} / 95`}
            />
            <Stat
              label="Bonds"
              value={String(totalBonds)}
              detail={
                stakedOnChains > 0
                  ? `staked on ${stakedOnChains} chain${stakedOnChains === 1 ? '' : 's'}`
                  : 'no stake on this account'
              }
            />
            <Stat
              label="Active on"
              value={`${registeredOn.length} / 4 chains`}
              detail={registeredOn.map((x) => CHAIN_LABEL[x.chain as ChainKey]).join(' · ')}
            />
            <Stat
              label="Identity type"
              value={primary?.identityType ?? '—'}
              detail={primary?.vnsName ?? ''}
            />
          </div>

          {/* Per-chain breakdown */}
          <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 12 }}>
            Per-chain registration
          </h2>
          <ul style={{ listStyle: 'none', padding: 0, margin: '0 0 32px' }}>
            {all.map(({ chain, status }) => {
              const ok = !!status?.registered;
              return (
                <li
                  key={chain}
                  style={{
                    display: 'flex',
                    alignItems: 'flex-start',
                    padding: '14px 0',
                    borderBottom: '1px solid rgba(255,255,255,0.08)',
                    gap: 14,
                  }}
                >
                  <span
                    aria-label={ok ? 'registered' : 'not-registered'}
                    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(255,255,255,0.05)',
                      color: ok ? '#22c55e' : 'var(--color-ember-text-muted)',
                      border: `1px solid ${ok ? '#22c55e' : 'rgba(255,255,255,0.15)'}`,
                      flexShrink: 0,
                    }}
                  >
                    {ok ? '✓' : '—'}
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600 }}>
                      {CHAIN_LABEL[chain as ChainKey]}
                      {ok && status?.bondCount ? (
                        <span
                          style={{
                            marginLeft: 10,
                            fontSize: 12,
                            color: 'var(--color-ember-text-muted)',
                            fontWeight: 400,
                          }}
                        >
                          · {status.bondCount} bond{status.bondCount === 1 ? '' : 's'}
                        </span>
                      ) : null}
                      {ok && (status?.bondAmountEth ?? 0) > 0 ? (
                        <span
                          style={{
                            marginLeft: 10,
                            fontSize: 12,
                            color: 'var(--color-ember-text-muted)',
                            fontWeight: 400,
                          }}
                        >
                          · {status!.bondAmountEth!.toFixed(4)} {CHAIN_NATIVE_TOKEN[chain as ChainKey]} staked
                        </span>
                      ) : null}
                      {ok && status?.trustScore != null ? (
                        <span
                          style={{
                            marginLeft: 10,
                            fontSize: 12,
                            color: 'var(--color-ember-text-muted)',
                            fontWeight: 400,
                          }}
                        >
                          · score {status.trustScore}
                        </span>
                      ) : null}
                    </div>
                    <div
                      style={{
                        fontSize: 13,
                        color: 'var(--color-ember-text-muted)',
                        marginTop: 2,
                        fontFamily:
                          'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
                      }}
                    >
                      {ok
                        ? status?.registeredAt
                          ? `Registered ${new Date(status.registeredAt * 1000).toISOString().split('T')[0]}`
                          : 'Registered'
                        : 'No identity on this chain'}{' '}
                      ·{' '}
                      <a
                        href={`${CHAIN_EXPLORER[chain as ChainKey]}/address/${address}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        style={{ color: 'var(--color-ember-accent)' }}
                      >
                        explorer ↗
                      </a>
                    </div>
                  </div>
                </li>
              );
            })}
          </ul>

          {/* Capabilities */}
          {primary?.capabilities && primary.capabilities.length > 0 && (
            <>
              <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 12 }}>
                Capabilities
              </h2>
              <div
                style={{
                  display: 'flex',
                  flexWrap: 'wrap',
                  gap: 8,
                  marginBottom: 32,
                }}
              >
                {primary.capabilities.map((cap) => (
                  <span
                    key={cap}
                    style={{
                      padding: '6px 12px',
                      borderRadius: 999,
                      background: 'rgba(255,255,255,0.06)',
                      border: '1px solid rgba(255,255,255,0.1)',
                      fontSize: 13,
                      fontFamily:
                        'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
                    }}
                  >
                    {cap}
                  </span>
                ))}
              </div>
            </>
          )}

          {/* Verify yourself */}
          <h2 style={{ fontSize: 22, fontWeight: 700, marginBottom: 8 }}>
            Verify yourself
          </h2>
          <p
            style={{
              fontSize: 14,
              color: 'var(--color-ember-text-muted)',
              marginBottom: 12,
            }}
          >
            Every field on this page comes from{' '}
            <code>/api/agent/status</code>, which reads on-chain. No DB cache.
          </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/agent/status?address=${address}&chain=base" | jq

# All four chains:
for c in base avalanche arbitrum polygon; do
  curl -s "https://theloopbreaker.com/api/agent/status?address=${address}&chain=$c" | jq -c '{chain, registered, bondCount, trustScore}'
done`}</pre>
        </>
      )}

      <p
        style={{
          marginTop: 32,
          fontSize: 14,
          color: 'var(--color-ember-text-muted)',
        }}
      >
        See also:{' '}
        <Link href="/proof" style={{ color: 'var(--color-ember-accent)' }}>
          live protocol proof
        </Link>{' '}
        ·{' '}
        <Link href="/contracts" style={{ color: 'var(--color-ember-accent)' }}>
          all 134 contracts
        </Link>{' '}
        ·{' '}
        <Link href="/start" style={{ color: 'var(--color-ember-accent)' }}>
          register your own agent
        </Link>
      </p>
    </main>
  );
}

function Stat({
  label,
  value,
  detail,
  accent,
}: {
  label: string;
  value: string;
  detail?: string;
  accent?: string;
}) {
  return (
    <div
      style={{
        padding: '16px 18px',
        borderRadius: 12,
        background: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.08)',
      }}
    >
      <div
        style={{
          fontSize: 11,
          textTransform: 'uppercase',
          letterSpacing: 1,
          color: 'var(--color-ember-text-muted)',
          marginBottom: 6,
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontSize: 22,
          fontWeight: 700,
          color: accent ?? 'var(--color-ember-text)',
        }}
      >
        {value}
      </div>
      {detail && (
        <div
          style={{
            fontSize: 12,
            color: 'var(--color-ember-text-muted)',
            marginTop: 4,
          }}
        >
          {detail}
        </div>
      )}
    </div>
  );
}
