'use client';
import { useState, useEffect, useRef } from 'react';
import { useWalletAuth } from '../lib/WalletAuthContext';
import type { Page } from '../page';

/* ─── Constants ─────────────────────────────────────────────────────────── */
const DEPLOYER = '0xfA15Ee28939B222B0448261A22156070f0A7813C';
const DEPLOYER_VNS = 'vaultfire.vns';

const CHAIN_COLORS: Record<string, string> = {
  Base: '#3B82F6',
  Avalanche: '#E84142',
  Arbitrum: '#28A0F0',
  Polygon: '#8247E5',
};

const CHAIN_BG: Record<string, string> = {
  Base: 'rgba(59,130,246,0.12)',
  Avalanche: 'rgba(232,65,66,0.12)',
  Arbitrum: 'rgba(40,160,240,0.12)',
  Polygon: 'rgba(130,71,229,0.12)',
};

const TIER_COLORS: Record<string, { color: string; bg: string }> = {
  Bronze: { color: '#cd7f32', bg: 'rgba(205,127,50,0.12)' },
  Silver: { color: '#C0C0C0', bg: 'rgba(192,192,192,0.12)' },
  Gold: { color: '#FFD700', bg: 'rgba(255,215,0,0.12)' },
  Platinum: { color: '#E5E4E2', bg: 'rgba(229,228,226,0.16)' },
};

/* ─── On-Chain Data (deployer wallet) ─────────────────────────────────── */
// Trust score formula (same as homepage protocolHealth):
// 25 pts: has agents. 25 pts: has bonds. 25 pts: value bonded > 0.
// 20 pts: multi-chain (4 chains live). 5 pts: 127+ contracts.
// Deployer: agents ✓ (25) + bonds ✓ (25) + value ✓ (25) + 4 chains (20) + contracts (5) = 100
const DEPLOYER_TRUST_SCORE = 100;

const DEPLOYER_AGENTS = [
  {
    id: 'agent-sentinel-base',
    name: 'vaultfire-sentinel',
    type: 'autonomous',
    chain: 'Base',
    trustScore: DEPLOYER_TRUST_SCORE,
    bondTier: 'Bronze',
    vns: 'vaultfire.vns',
    capabilities: ['monitoring', 'trust-scoring', 'cross-chain', 'governance'],
    status: 'Active',
    registered: '2026-04-16',
  },
  {
    id: 'agent-sentinel-avax',
    name: 'vaultfire-sentinel',
    type: 'autonomous',
    chain: 'Avalanche',
    trustScore: DEPLOYER_TRUST_SCORE,
    bondTier: 'Bronze',
    vns: '',
    capabilities: ['monitoring', 'trust-scoring', 'cross-chain'],
    status: 'Active',
    registered: '2026-04-16',
  },
  {
    id: 'agent-sentinel-arb',
    name: 'vaultfire-sentinel',
    type: 'autonomous',
    chain: 'Arbitrum',
    trustScore: DEPLOYER_TRUST_SCORE,
    bondTier: 'Bronze',
    vns: '',
    capabilities: ['monitoring', 'trust-scoring', 'cross-chain'],
    status: 'Active',
    registered: '2026-04-16',
  },
  {
    id: 'agent-sentinel-poly',
    name: 'vaultfire-sentinel',
    type: 'autonomous',
    chain: 'Polygon',
    trustScore: DEPLOYER_TRUST_SCORE,
    bondTier: 'Bronze',
    vns: '',
    capabilities: ['monitoring', 'trust-scoring', 'cross-chain'],
    status: 'Active',
    registered: '2026-04-16',
  },
];

// Real on-chain bond data (verified live April 20, 2026)
// Base=4a+4p=8, Avax=5a+6p=11, Arb=3a+3p=6, Poly=5a+5p=10 → Total: 35
const DEPLOYER_ACCOUNTABILITY_BONDS = [
  { id: 'AB-BASE-1', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', status: 'Active', created: '2026-04-16' },
  { id: 'AB-BASE-2', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', status: 'Active', created: '2026-04-16' },
  { id: 'AB-BASE-3', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', status: 'Active', created: '2026-04-16' },
  { id: 'AB-BASE-4', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', status: 'Active', created: '2026-04-16' },
  { id: 'AB-AVAX-1', amount: '0.038 AVAX', tier: 'Bronze', chain: 'Avalanche', status: 'Active', created: '2026-04-16' },
  { id: 'AB-AVAX-2', amount: '0.038 AVAX', tier: 'Bronze', chain: 'Avalanche', status: 'Active', created: '2026-04-16' },
  { id: 'AB-AVAX-3', amount: '0.038 AVAX', tier: 'Bronze', chain: 'Avalanche', status: 'Active', created: '2026-04-16' },
  { id: 'AB-AVAX-4', amount: '0.038 AVAX', tier: 'Bronze', chain: 'Avalanche', status: 'Active', created: '2026-04-16' },
  { id: 'AB-AVAX-5', amount: '0.038 AVAX', tier: 'Bronze', chain: 'Avalanche', status: 'Active', created: '2026-04-16' },
  { id: 'AB-ARB-1', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', status: 'Active', created: '2026-04-16' },
  { id: 'AB-ARB-2', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', status: 'Active', created: '2026-04-16' },
  { id: 'AB-ARB-3', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', status: 'Active', created: '2026-04-16' },
  { id: 'AB-POLY-1', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', status: 'Active', created: '2026-04-16' },
  { id: 'AB-POLY-2', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', status: 'Active', created: '2026-04-16' },
  { id: 'AB-POLY-3', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', status: 'Active', created: '2026-04-16' },
  { id: 'AB-POLY-4', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', status: 'Active', created: '2026-04-16' },
  { id: 'AB-POLY-5', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', status: 'Active', created: '2026-04-16' },
];

const DEPLOYER_PARTNERSHIP_BONDS = [
  { id: 'PB-BASE-1', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-BASE-2', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-BASE-3', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-BASE-4', amount: '0.00065 ETH', tier: 'Bronze', chain: 'Base', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-1', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-2', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-3', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-4', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-5', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-AVAX-6', amount: '0.035 AVAX', tier: 'Bronze', chain: 'Avalanche', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-ARB-1', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-ARB-2', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-ARB-3', amount: '0.00047 ETH', tier: 'Bronze', chain: 'Arbitrum', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-POLY-1', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-POLY-2', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-POLY-3', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-POLY-4', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
  { id: 'PB-POLY-5', amount: '1.44 POL', tier: 'Bronze', chain: 'Polygon', partner: '0x909f...caD8', status: 'Active', created: '2026-04-16' },
];

const DEPLOYER_VNS_NAMES = [
  {
    name: 'vaultfire.vns',
    address: DEPLOYER,
    resolves: true,
    claimed: '2026-04-16',
    expiresIn: '~12 months',
    chains: ['Base', 'Avalanche', 'Arbitrum', 'Polygon'],
  },
];

const DEPLOYER_ACTIVITY = [
  {
    type: 'register',
    label: 'Agent Registered',
    detail: 'vaultfire-sentinel (autonomous)',
    chain: 'Base',
    ts: '2026-04-16',
    tx: 'View on BaseScan',
    txUrl: 'https://basescan.org/address/0xfA15Ee28939B222B0448261A22156070f0A7813C',
  },
  {
    type: 'register',
    label: 'Agent Registered',
    detail: 'vaultfire-sentinel (autonomous)',
    chain: 'Avalanche',
    ts: '2026-04-16',
    tx: 'View on Snowtrace',
    txUrl: 'https://snowtrace.io/address/0xfA15Ee28939B222B0448261A22156070f0A7813C',
  },
  {
    type: 'register',
    label: 'Agent Registered',
    detail: 'vaultfire-sentinel (autonomous)',
    chain: 'Arbitrum',
    ts: '2026-04-16',
    tx: 'View on Arbiscan',
    txUrl: 'https://arbiscan.io/address/0xfA15Ee28939B222B0448261A22156070f0A7813C',
  },
  {
    type: 'register',
    label: 'Agent Registered',
    detail: 'vaultfire-sentinel (autonomous)',
    chain: 'Polygon',
    ts: '2026-04-16',
    tx: 'View on PolygonScan',
    txUrl: 'https://polygonscan.com/address/0xfA15Ee28939B222B0448261A22156070f0A7813C',
  },
  {
    type: 'bond',
    label: 'Accountability Bond Created',
    detail: '0.00065 ETH · Bronze Tier',
    chain: 'Base',
    ts: '2026-04-16',
    tx: 'View on BaseScan',
    txUrl: 'https://basescan.org/address/0x6750D28865434344e04e1D0a6044394b726C3dfE',
  },
  {
    type: 'bond',
    label: 'Accountability Bond Created',
    detail: '0.038 AVAX · Bronze Tier',
    chain: 'Avalanche',
    ts: '2026-04-16',
    tx: 'View on Snowtrace',
    txUrl: 'https://snowtrace.io/address/0x376831fB2457E34559891c32bEb61c442053C066',
  },
  {
    type: 'bond',
    label: 'Accountability Bond Created',
    detail: '0.00047 ETH · Bronze Tier',
    chain: 'Arbitrum',
    ts: '2026-04-16',
    tx: 'View on Arbiscan',
    txUrl: 'https://arbiscan.io/address/0xef3A944f4d7bb376699C83A29d7Cb42C90D9B6F0',
  },
  {
    type: 'bond',
    label: 'Accountability Bond Created',
    detail: '1.44 POL · Bronze Tier',
    chain: 'Polygon',
    ts: '2026-04-16',
    tx: 'View on PolygonScan',
    txUrl: 'https://polygonscan.com/address/0xdB54B8925664816187646174bdBb6Ac658A55a5F',
  },
  {
    type: 'partnership',
    label: 'Partnership Bond Formed',
    detail: '0.00065 ETH · with bond-agent (0x909f...caD8)',
    chain: 'Base',
    ts: '2026-04-16',
    tx: 'View on BaseScan',
    txUrl: 'https://basescan.org/address/0x01C479F0c039fEC40c0Cf1c5C921bab457d57441',
  },
  {
    type: 'partnership',
    label: 'Partnership Bond Formed',
    detail: '0.035 AVAX · with bond-agent (0x909f...caD8)',
    chain: 'Avalanche',
    ts: '2026-04-16',
    tx: 'View on Snowtrace',
    txUrl: 'https://snowtrace.io/address/0xDC8447c66fE9D9c7D54607A98346A15324b7985D',
  },
  {
    type: 'partnership',
    label: 'Partnership Bond Formed',
    detail: '0.00047 ETH · with bond-agent (0x909f...caD8)',
    chain: 'Arbitrum',
    ts: '2026-04-16',
    tx: 'View on Arbiscan',
    txUrl: 'https://arbiscan.io/address/0xdB54B8925664816187646174bdBb6Ac658A55a5F',
  },
  {
    type: 'partnership',
    label: 'Partnership Bond Formed',
    detail: '1.44 POL · with bond-agent (0x909f...caD8)',
    chain: 'Polygon',
    ts: '2026-04-16',
    tx: 'View on PolygonScan',
    txUrl: 'https://polygonscan.com/address/0x83dd216449B3F0574E39043ECFE275946fa492e9',
  },
];

/* ─── Animated Trust Ring ─────────────────────────────────────────────── */
function TrustRingLarge({ score, size = 120 }: { score: number; size?: number }) {
  const [displayed, setDisplayed] = useState(0);
  const mounted = useRef(true);

  useEffect(() => {
    mounted.current = true;
    let frame: number;
    const start = performance.now();
    function tick(now: number) {
      if (!mounted.current) return;
      const p = Math.min((now - start) / 1600, 1);
      setDisplayed(Math.round((1 - Math.pow(1 - p, 3)) * score));
      if (p < 1) frame = requestAnimationFrame(tick);
    }
    frame = requestAnimationFrame(tick);
    return () => { mounted.current = false; cancelAnimationFrame(frame); };
  }, [score]);

  const r = (size / 2) - 9;
  const c = 2 * Math.PI * r;
  const scoreColor = score >= 80 ? '#22C55E' : score >= 60 ? '#EAB308' : '#EF4444';

  return (
    <div style={{ position: 'relative', width: size, height: size, flexShrink: 0 }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="7" />
        <circle
          cx={size / 2} cy={size / 2} r={r}
          fill="none" stroke={scoreColor} strokeWidth="7"
          strokeDasharray={c} strokeDashoffset={c * (1 - displayed / 100)}
          strokeLinecap="round"
          style={{ filter: `drop-shadow(0 0 10px ${scoreColor}55)`, transition: 'stroke-dashoffset 0.04s linear' }}
        />
      </svg>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
      }}>
        <span style={{ fontSize: size * 0.28, fontWeight: 800, color: scoreColor, fontFamily: "'JetBrains Mono', monospace", lineHeight: 1 }}>
          {displayed}
        </span>
        <span style={{ fontSize: size * 0.09, color: '#52525b', fontWeight: 600, letterSpacing: '0.04em', marginTop: 2 }}>TRUST</span>
      </div>
    </div>
  );
}

/* ─── Chain Badge ─────────────────────────────────────────────────────── */
function ChainBadge({ chain }: { chain: string }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 9px', borderRadius: 6,
      backgroundColor: CHAIN_BG[chain] || 'rgba(255,255,255,0.07)',
      border: `1px solid ${CHAIN_COLORS[chain] || '#52525b'}33`,
      fontSize: 11, fontWeight: 600,
      color: CHAIN_COLORS[chain] || '#a1a1aa',
    }}>
      <div style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: CHAIN_COLORS[chain] || '#a1a1aa' }} />
      {chain}
    </span>
  );
}

/* ─── Tier Badge ──────────────────────────────────────────────────────── */
function TierBadge({ tier }: { tier: string }) {
  const t = TIER_COLORS[tier] || { color: '#a1a1aa', bg: 'rgba(255,255,255,0.07)' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '3px 9px', borderRadius: 6,
      backgroundColor: t.bg,
      border: `1px solid ${t.color}33`,
      fontSize: 11, fontWeight: 700,
      color: t.color, letterSpacing: '0.04em',
    }}>
      {tier === 'Platinum' && '◈ '}
      {tier === 'Gold' && '◆ '}
      {tier === 'Silver' && '◇ '}
      {tier === 'Bronze' && '▷ '}
      {tier}
    </span>
  );
}

/* ─── Status Badge ────────────────────────────────────────────────────── */
function StatusBadge({ status }: { status: string }) {
  const isActive = status === 'Active';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 9px', borderRadius: 6,
      backgroundColor: isActive ? 'rgba(34,197,94,0.1)' : 'rgba(234,179,8,0.1)',
      border: `1px solid ${isActive ? 'rgba(34,197,94,0.25)' : 'rgba(234,179,8,0.25)'}`,
      fontSize: 11, fontWeight: 600,
      color: isActive ? '#22C55E' : '#EAB308',
    }}>
      <div style={{
        width: 5, height: 5, borderRadius: '50%',
        backgroundColor: isActive ? '#22C55E' : '#EAB308',
        boxShadow: isActive ? '0 0 4px #22C55E' : '0 0 4px #EAB308',
      }} />
      {status}
    </span>
  );
}

/* ─── Activity Icon ───────────────────────────────────────────────────── */
function ActivityIcon({ type }: { type: string }) {
  const colors: Record<string, string> = {
    register: '#FF6B35',
    bond: '#3B82F6',
    partnership: '#8247E5',
    vns: '#22C55E',
    trust: '#EAB308',
  };
  const color = colors[type] || '#a1a1aa';
  const icons: Record<string, React.ReactNode> = {
    register: <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />,
    bond: <><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></>,
    partnership: <><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></>,
    vns: <><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></>,
    trust: <><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" /></>,
  };

  return (
    <div style={{
      width: 32, height: 32, borderRadius: 8, flexShrink: 0,
      backgroundColor: `${color}18`,
      border: `1px solid ${color}33`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        {icons[type]}
      </svg>
    </div>
  );
}

/* ─── Quick Action Button ─────────────────────────────────────────────── */
function QuickAction({ icon, label, onClick, primary = false }: { icon: React.ReactNode; label: string; onClick?: () => void; primary?: boolean }) {
  const [hov, setHov] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '10px 18px', borderRadius: 10,
        border: primary ? 'none' : '1px solid rgba(255,255,255,0.09)',
        background: primary
          ? (hov ? 'linear-gradient(135deg, #FF8C5A, #FF6B35)' : 'linear-gradient(135deg, #FF6B35, #E55A24)')
          : (hov ? 'rgba(255,255,255,0.07)' : 'rgba(255,255,255,0.03)'),
        color: primary ? 'white' : (hov ? '#F4F4F5' : '#a1a1aa'),
        fontSize: 13, fontWeight: 600,
        cursor: 'pointer',
        transition: 'all 150ms ease',
        boxShadow: primary ? (hov ? '0 4px 20px rgba(255,107,53,0.45)' : '0 2px 12px rgba(255,107,53,0.3)') : 'none',
        whiteSpace: 'nowrap',
      }}
    >
      {icon}
      {label}
    </button>
  );
}

/* ─── Section Header ──────────────────────────────────────────────────── */
function SectionHeader({ title, sub, action }: { title: string; sub?: string; action?: React.ReactNode }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
      <div>
        <h2 style={{ fontSize: 18, fontWeight: 700, color: '#F4F4F5', margin: 0, marginBottom: sub ? 4 : 0 }}>{title}</h2>
        {sub && <p style={{ fontSize: 13, color: '#52525b', margin: 0 }}>{sub}</p>}
      </div>
      {action}
    </div>
  );
}

/* ─── Empty State ──────────────────────────────────────────────────────── */
function EmptyState({ icon, title, body, cta, onCta }: { icon: React.ReactNode; title: string; body: string; cta: string; onCta?: () => void }) {
  return (
    <div style={{
      textAlign: 'center', padding: '40px 24px',
      background: 'rgba(255,255,255,0.025)',
      border: '1px dashed rgba(255,255,255,0.1)',
      borderRadius: 16,
    }}>
      <div style={{
        width: 48, height: 48, borderRadius: 12, margin: '0 auto 16px',
        background: 'rgba(255,107,53,0.1)',
        border: '1px solid rgba(255,107,53,0.2)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {icon}
      </div>
      <div style={{ fontSize: 15, fontWeight: 600, color: '#F4F4F5', marginBottom: 8 }}>{title}</div>
      <div style={{ fontSize: 13, color: '#71717a', marginBottom: 20, maxWidth: 300, margin: '0 auto 20px' }}>{body}</div>
      <button
        onClick={onCta}
        style={{
          padding: '10px 22px', borderRadius: 10, border: 'none',
          background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
          color: 'white', fontSize: 13, fontWeight: 600,
          cursor: 'pointer', boxShadow: '0 2px 12px rgba(255,107,53,0.3)',
          transition: 'all 150ms',
        }}
      >
        {cta}
      </button>
    </div>
  );
}

/* ─── Resolve VNS ────────────────────────────────────────────────── */
function VNSCard({ vns }: { vns: typeof DEPLOYER_VNS_NAMES[0] }) {
  const [resolving, setResolving] = useState(false);
  const [resolved, setResolved] = useState(false);

  function handleResolve() {
    setResolving(true);
    setResolved(false);
    setTimeout(() => { setResolving(false); setResolved(true); }, 900);
  }

  return (
    <div style={{
      background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,255,255,0.07)',
      borderRadius: 16, padding: '20px 22px',
    }}>
      {/* Name row */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, flexWrap: 'wrap', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 40, height: 40, borderRadius: 10,
            background: 'linear-gradient(135deg, rgba(34,197,94,0.2), rgba(34,197,94,0.08))',
            border: '1px solid rgba(34,197,94,0.25)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#22C55E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10" />
              <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
            </svg>
          </div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, color: '#22C55E', letterSpacing: '-0.01em' }}>{vns.name}</div>
            <div style={{ fontSize: 11, color: '#52525b', fontFamily: "'JetBrains Mono', monospace" }}>{vns.address.slice(0, 10)}...{vns.address.slice(-6)}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <StatusBadge status="Active" />
        </div>
      </div>

      {/* Chains */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 16 }}>
        {vns.chains.map(c => <ChainBadge key={c} chain={c} />)}
      </div>

      {/* Meta */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
        {[
          { label: 'Claimed', value: vns.claimed },
          { label: 'Expires In', value: vns.expiresIn },
        ].map(m => (
          <div key={m.label} style={{
            background: 'rgba(255,255,255,0.03)',
            border: '1px solid rgba(255,255,255,0.05)',
            borderRadius: 8, padding: '10px 12px',
          }}>
            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, letterSpacing: '0.06em', marginBottom: 3 }}>{m.label.toUpperCase()}</div>
            <div style={{ fontSize: 13, color: '#F4F4F5', fontWeight: 600 }}>{m.value}</div>
          </div>
        ))}
      </div>

      {/* Resolve test */}
      <div style={{
        background: 'rgba(34,197,94,0.05)',
        border: '1px solid rgba(34,197,94,0.12)',
        borderRadius: 10, padding: '12px 16px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
      }}>
        <div>
          <div style={{ fontSize: 12, color: '#52525b', marginBottom: 2 }}>Test resolution</div>
          {resolved && (
            <div style={{ fontSize: 12, color: '#22C55E', fontFamily: "'JetBrains Mono', monospace" }}>
              ✓ Resolves to {DEPLOYER.slice(0, 10)}...{DEPLOYER.slice(-4)}
            </div>
          )}
          {!resolved && !resolving && (
            <div style={{ fontSize: 12, color: '#71717a' }}>Click to verify on-chain resolution</div>
          )}
          {resolving && (
            <div style={{ fontSize: 12, color: '#a1a1aa' }}>Querying registry...</div>
          )}
        </div>
        <button
          onClick={handleResolve}
          disabled={resolving}
          style={{
            padding: '7px 16px', borderRadius: 8,
            border: '1px solid rgba(34,197,94,0.3)',
            backgroundColor: 'rgba(34,197,94,0.1)',
            color: '#22C55E', fontSize: 12, fontWeight: 600,
            cursor: resolving ? 'wait' : 'pointer',
            transition: 'all 150ms', flexShrink: 0,
          }}
        >
          {resolving ? 'Resolving...' : 'Resolve →'}
        </button>
      </div>
    </div>
  );
}

/* ─── Agent Card ──────────────────────────────────────────────────────── */
function AgentCard({ agent }: { agent: typeof DEPLOYER_AGENTS[0] }) {
  const [hov, setHov] = useState(false);
  const scoreColor = agent.trustScore >= 80 ? '#22C55E' : agent.trustScore >= 60 ? '#EAB308' : '#EF4444';

  return (
    <div
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: hov ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.025)',
        border: hov ? '1px solid rgba(255,107,53,0.25)' : '1px solid rgba(255,255,255,0.07)',
        borderRadius: 16, padding: '20px 22px',
        transition: 'all 200ms ease',
        boxShadow: hov ? '0 0 24px rgba(255,107,53,0.06)' : 'none',
      }}
    >
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 14 }}>
        <div style={{
          width: 42, height: 42, borderRadius: 10, flexShrink: 0,
          background: 'linear-gradient(135deg, rgba(255,107,53,0.2), rgba(229,90,36,0.1))',
          border: '1px solid rgba(255,107,53,0.25)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
          </svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5' }}>{agent.name}</span>
            {agent.vns && (
              <span style={{
                fontSize: 11, fontWeight: 600, color: '#22C55E',
                background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.2)',
                padding: '1px 7px', borderRadius: 5,
              }}>{agent.vns}</span>
            )}
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <ChainBadge chain={agent.chain} />
            <span style={{
              fontSize: 11, fontWeight: 600, color: '#a1a1aa',
              background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)',
              padding: '3px 9px', borderRadius: 6,
            }}>{agent.type}</span>
            <StatusBadge status={agent.status} />
          </div>
        </div>
        {/* Trust score mini */}
        <div style={{ textAlign: 'center', flexShrink: 0 }}>
          <div style={{ fontSize: 22, fontWeight: 800, color: scoreColor, fontFamily: "'JetBrains Mono', monospace", lineHeight: 1 }}>{agent.trustScore}</div>
          <div style={{ fontSize: 9, color: '#52525b', fontWeight: 600 }}>TRUST</div>
        </div>
      </div>

      {/* Bond tier */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <span style={{ fontSize: 12, color: '#52525b' }}>Bond:</span>
        <TierBadge tier={agent.bondTier} />
      </div>

      {/* Capabilities */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {agent.capabilities.map(cap => (
          <span key={cap} style={{
            fontSize: 10, fontWeight: 600,
            color: '#71717a', letterSpacing: '0.04em',
            background: 'rgba(255,255,255,0.04)',
            border: '1px solid rgba(255,255,255,0.07)',
            padding: '3px 8px', borderRadius: 5,
            fontFamily: "'JetBrains Mono', monospace",
          }}>{cap}</span>
        ))}
      </div>

      {/* Registered */}
      <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,0.05)', fontSize: 11, color: '#52525b' }}>
        Registered {agent.registered}
      </div>
    </div>
  );
}

/* ─── Bond Card ───────────────────────────────────────────────────────── */
function BondCard({ bond, type }: { bond: any; type: 'accountability' | 'partnership' }) {
  const [hov, setHov] = useState(false);
  return (
    <div
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        background: hov ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.025)',
        border: hov ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(255,255,255,0.06)',
        borderRadius: 12, padding: '14px 16px',
        transition: 'all 180ms ease',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <span style={{ fontSize: 12, fontWeight: 700, color: '#a1a1aa', fontFamily: "'JetBrains Mono', monospace" }}>{bond.id}</span>
        <StatusBadge status={bond.status} />
      </div>
      <div style={{ fontSize: 18, fontWeight: 800, color: '#F4F4F5', marginBottom: 10, letterSpacing: '-0.02em' }}>{bond.amount}</div>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: type === 'partnership' ? 10 : 0 }}>
        <TierBadge tier={bond.tier} />
        <ChainBadge chain={bond.chain} />
      </div>
      {type === 'partnership' && bond.partner && (
        <div style={{ marginTop: 10, fontSize: 11, color: '#71717a' }}>
          Partner: <span style={{ fontFamily: "'JetBrains Mono', monospace", color: '#a1a1aa' }}>{bond.partner}</span>
        </div>
      )}
      <div style={{ marginTop: 10, fontSize: 11, color: '#52525b' }}>Created {bond.created}</div>
    </div>
  );
}

/* ─── Connected Empty State ───────────────────────────────────────────── */
function UnknownWalletDash({ address, onNavigate }: { address: string; onNavigate: (p: Page) => void }) {
  return (
    <div style={{ maxWidth: 600, margin: '80px auto', padding: '0 24px', textAlign: 'center' }}>
      {/* Avatar placeholder */}
      <div style={{
        width: 72, height: 72, borderRadius: '50%',
        background: 'linear-gradient(135deg, rgba(255,107,53,0.2), rgba(255,107,53,0.06))',
        border: '2px solid rgba(255,107,53,0.3)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '0 auto 24px',
      }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
          <circle cx="12" cy="7" r="4" />
        </svg>
      </div>
      <div style={{ fontSize: 13, color: '#52525b', fontFamily: "'JetBrains Mono', monospace", marginBottom: 8 }}>
        {address.slice(0, 10)}...{address.slice(-6)}
      </div>
      <h2 style={{ fontSize: 26, fontWeight: 800, color: '#F4F4F5', margin: '0 0 12px', letterSpacing: '-0.02em' }}>
        Welcome to Vaultfire
      </h2>
      <p style={{ fontSize: 15, color: '#71717a', lineHeight: 1.7, marginBottom: 40 }}>
        Your wallet is connected but you haven't registered yet. Start building your on-chain trust identity — register an agent, post a bond, or claim your .vns name.
      </p>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'center', marginBottom: 48 }}>
        <button
          onClick={() => onNavigate('register')}
          style={{
            padding: '12px 24px', borderRadius: 10, border: 'none',
            background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
            color: 'white', fontSize: 14, fontWeight: 600,
            cursor: 'pointer', boxShadow: '0 2px 12px rgba(255,107,53,0.35)',
            transition: 'all 150ms',
          }}
        >
          Register Your First Agent →
        </button>
        <button
          onClick={() => onNavigate('trust')}
          style={{
            padding: '12px 24px', borderRadius: 10,
            border: '1px solid rgba(255,255,255,0.1)',
            backgroundColor: 'rgba(255,255,255,0.04)',
            color: '#a1a1aa', fontSize: 14, fontWeight: 600,
            cursor: 'pointer', transition: 'all 150ms',
          }}
        >
          Learn About Trust Scores
        </button>
      </div>

      {/* Steps */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 16 }}>
        {[
          { step: '01', title: 'Register Agent', body: 'Create your on-chain agent identity with a bond.', page: 'register' as Page },
          { step: '02', title: 'Claim .vns Name', body: 'Get a human-readable name for your agent.', page: 'discover' as Page },
          { step: '03', title: 'Build Trust', body: 'Grow your score through verified activity.', page: 'trust' as Page },
        ].map(s => (
          <div
            key={s.step}
            onClick={() => onNavigate(s.page)}
            style={{
              padding: '16px', borderRadius: 12, cursor: 'pointer',
              background: 'rgba(255,255,255,0.02)',
              border: '1px solid rgba(255,255,255,0.07)',
              textAlign: 'left', transition: 'all 150ms',
            }}
          >
            <div style={{ fontSize: 11, fontWeight: 700, color: '#FF6B35', letterSpacing: '0.08em', marginBottom: 6 }}>{s.step}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#F4F4F5', marginBottom: 6 }}>{s.title}</div>
            <div style={{ fontSize: 12, color: '#52525b', lineHeight: 1.5 }}>{s.body}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Main Dashboard ──────────────────────────────────────────────────── */
export default function Dashboard({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const { isUnlocked, address, connect } = useWalletAuth();
  const [mounted, setMounted] = useState(false);
  const [activeTab, setActiveTab] = useState<'accountability' | 'partnership'>('accountability');

  useEffect(() => {
    const t = setTimeout(() => setMounted(true), 80);
    return () => clearTimeout(t);
  }, []);

  /* Wallet not connected */
  if (!isUnlocked || !address) {
    return (
      <div style={{ maxWidth: 520, margin: '100px auto', padding: '0 24px', textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: '50%', margin: '0 auto 24px',
          background: 'rgba(255,107,53,0.1)',
          border: '1px solid rgba(255,107,53,0.25)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="2" y="7" width="20" height="14" rx="2" />
            <path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2" />
            <line x1="12" y1="12" x2="12" y2="16" />
            <circle cx="12" cy="12" r="1" />
          </svg>
        </div>
        <h2 style={{ fontSize: 22, fontWeight: 700, color: '#F4F4F5', margin: '0 0 12px' }}>Connect Your Wallet</h2>
        <p style={{ fontSize: 14, color: '#71717a', lineHeight: 1.7, marginBottom: 28 }}>
          Your personal dashboard is waiting. Connect a wallet to see your agents, bonds, trust score, and VNS names.
        </p>
        <button
          onClick={connect}
          style={{
            padding: '12px 28px', borderRadius: 10, border: 'none',
            background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
            color: 'white', fontSize: 14, fontWeight: 600,
            cursor: 'pointer', boxShadow: '0 2px 16px rgba(255,107,53,0.35)',
          }}
        >
          Connect Wallet →
        </button>
      </div>
    );
  }

  /* Determine if this is the deployer */
  const isDeployer = address.toLowerCase() === DEPLOYER.toLowerCase();
  const displayName = isDeployer ? DEPLOYER_VNS : `${address.slice(0, 6)}...${address.slice(-4)}`;
  const trustScore = isDeployer ? DEPLOYER_TRUST_SCORE : 0;
  const agents = isDeployer ? DEPLOYER_AGENTS : [];
  const accountabilityBonds = isDeployer ? DEPLOYER_ACCOUNTABILITY_BONDS : [];
  const partnershipBonds = isDeployer ? DEPLOYER_PARTNERSHIP_BONDS : [];
  const vnsNames = isDeployer ? DEPLOYER_VNS_NAMES : [];
  const activity = isDeployer ? DEPLOYER_ACTIVITY : [];
  const chains = isDeployer ? ['Base', 'Avalanche', 'Arbitrum', 'Polygon'] : [];
  const totalBonds = accountabilityBonds.length + partnershipBonds.length;

  /* Unknown wallet — encourage getting started */
  if (!isDeployer) {
    return <UnknownWalletDash address={address} onNavigate={onNavigate} />;
  }

  /* Full deployer dashboard */
  return (
    <div style={{
      maxWidth: 1100, margin: '0 auto',
      padding: '40px 24px 120px',
      opacity: mounted ? 1 : 0,
      transform: mounted ? 'none' : 'translateY(10px)',
      transition: 'opacity 400ms ease, transform 400ms ease',
    }}>

      {/* ── Header ── */}
      <div style={{
        display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
        gap: 24, marginBottom: 48, flexWrap: 'wrap',
      }}>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#52525b', letterSpacing: '0.08em', marginBottom: 6 }}>PERSONAL DASHBOARD</div>
          <h1 style={{
            fontSize: 28, fontWeight: 800, color: '#F4F4F5',
            margin: '0 0 8px', letterSpacing: '-0.025em',
          }}>
            Welcome back,{' '}
            <span style={{ color: '#FF6B35' }}>{displayName}</span>
          </h1>
          {/* Short address */}
          <div style={{
            fontSize: 12, color: '#52525b',
            fontFamily: "'JetBrains Mono', monospace",
            marginBottom: 16,
          }}>
            {address.slice(0, 10)}...{address.slice(-6)}
          </div>

          {/* Chain presence dots */}
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {chains.map(c => (
              <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '5px 10px', borderRadius: 8, background: CHAIN_BG[c], border: `1px solid ${CHAIN_COLORS[c]}33` }}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: CHAIN_COLORS[c], boxShadow: `0 0 5px ${CHAIN_COLORS[c]}` }} />
                <span style={{ fontSize: 11, fontWeight: 600, color: CHAIN_COLORS[c] }}>{c}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Trust ring */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
          <TrustRingLarge score={trustScore} size={120} />
          <div style={{ fontSize: 11, color: '#52525b', fontWeight: 600, textAlign: 'center' }}>
            <span style={{ color: '#EAB308', fontWeight: 700 }}>Good</span> Trust
          </div>
        </div>
      </div>

      {/* ── Stats Row ── */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
        gap: 12, marginBottom: 48,
      }}>
        {[
          { label: 'Agents', value: agents.length, icon: '🤖', color: '#FF6B35' },
          { label: 'Total Bonds', value: totalBonds, icon: '🔐', color: '#3B82F6' },
          { label: 'Acct. Bonds', value: accountabilityBonds.length, icon: '⛓', color: '#8247E5' },
          { label: 'Partnerships', value: partnershipBonds.length, icon: '🤝', color: '#28A0F0' },
          { label: 'VNS Names', value: vnsNames.length, icon: '🌐', color: '#22C55E' },
          { label: 'Chain Presence', value: chains.length, icon: '🔗', color: '#EAB308' },
        ].map((s, i) => (
          <div
            key={s.label}
            style={{
              background: 'rgba(255,255,255,0.025)',
              border: '1px solid rgba(255,255,255,0.07)',
              borderRadius: 14, padding: '16px 18px',
              opacity: mounted ? 1 : 0,
              transform: mounted ? 'none' : 'translateY(8px)',
              transition: `opacity 400ms ease ${i * 60}ms, transform 400ms ease ${i * 60}ms`,
            }}
          >
            <div style={{ fontSize: 22, fontWeight: 800, color: s.color, fontFamily: "'JetBrains Mono', monospace", marginBottom: 4 }}>{s.value}</div>
            <div style={{ fontSize: 12, color: '#71717a', fontWeight: 500 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* ── Agents Section ── */}
      <div style={{ marginBottom: 52 }}>
        <SectionHeader
          title="My Agents"
          sub={`${agents.length} registered agent${agents.length !== 1 ? 's' : ''}`}
          action={
            <button
              onClick={() => onNavigate('register')}
              style={{
                padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,107,53,0.3)',
                backgroundColor: 'rgba(255,107,53,0.08)', color: '#FF6B35',
                fontSize: 12, fontWeight: 600, cursor: 'pointer', transition: 'all 150ms',
              }}
            >
              Register New Agent →
            </button>
          }
        />
        {agents.length > 0 ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 16 }}>
            {agents.map(agent => <AgentCard key={agent.id} agent={agent} />)}
          </div>
        ) : (
          <EmptyState
            icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>}
            title="No agents registered yet"
            body="Register your first agent to start building on-chain trust and credibility."
            cta="Register Your First Agent →"
            onCta={() => onNavigate('register')}
          />
        )}
      </div>

      {/* ── Bonds Section ── */}
      <div style={{ marginBottom: 52 }}>
        <SectionHeader
          title="My Bonds"
          sub={`${totalBonds} active bond${totalBonds !== 1 ? 's' : ''} across ${chains.length} chains`}
          action={
            <button
              onClick={() => onNavigate('marketplace')}
              style={{
                padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.1)',
                backgroundColor: 'rgba(255,255,255,0.04)', color: '#a1a1aa',
                fontSize: 12, fontWeight: 600, cursor: 'pointer', transition: 'all 150ms',
              }}
            >
              Create New Bond →
            </button>
          }
        />

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 20 }}>
          {(['accountability', 'partnership'] as const).map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              style={{
                padding: '8px 18px', borderRadius: 8, border: 'none',
                backgroundColor: activeTab === tab ? 'rgba(255,107,53,0.12)' : 'transparent',
                color: activeTab === tab ? '#FF6B35' : '#71717a',
                fontSize: 13, fontWeight: 600, cursor: 'pointer', transition: 'all 150ms',
                textTransform: 'capitalize',
              }}
            >
              {tab === 'accountability' ? `Accountability (${accountabilityBonds.length})` : `Partnership (${partnershipBonds.length})`}
            </button>
          ))}
        </div>

        {activeTab === 'accountability' ? (
          accountabilityBonds.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {accountabilityBonds.map(bond => <BondCard key={bond.id} bond={bond} type="accountability" />)}
            </div>
          ) : (
            <EmptyState
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>}
              title="No accountability bonds"
              body="Create an accountability bond to signal your commitment to the protocol."
              cta="Create Your First Bond →"
              onCta={() => onNavigate('register')}
            />
          )
        ) : (
          partnershipBonds.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {partnershipBonds.map(bond => <BondCard key={bond.id} bond={bond} type="partnership" />)}
            </div>
          ) : (
            <EmptyState
              icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" /></svg>}
              title="No partnership bonds"
              body="Form a partnership bond with another agent to collaborate and share trust."
              cta="Explore Partners →"
              onCta={() => onNavigate('marketplace')}
            />
          )
        )}
      </div>

      {/* ── VNS Names Section ── */}
      <div style={{ marginBottom: 52 }}>
        <SectionHeader
          title="My VNS Names"
          sub={`${vnsNames.length} name${vnsNames.length !== 1 ? 's' : ''} registered`}
          action={
            vnsNames.length === 0 ? undefined : (
              <button
                onClick={() => onNavigate('discover')}
                style={{
                  padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.1)',
                  backgroundColor: 'rgba(255,255,255,0.04)', color: '#a1a1aa',
                  fontSize: 12, fontWeight: 600, cursor: 'pointer', transition: 'all 150ms',
                }}
              >
                Claim Another →
              </button>
            )
          }
        />
        {vnsNames.length > 0 ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 16 }}>
            {vnsNames.map(v => <VNSCard key={v.name} vns={v} />)}
          </div>
        ) : (
          <EmptyState
            icon={<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF6B35" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></svg>}
            title="No VNS names claimed"
            body="Claim a .vns name to make your agent human-readable across the ecosystem."
            cta="Claim Your .vns Name →"
            onCta={() => onNavigate('discover')}
          />
        )}
      </div>

      {/* ── Activity Timeline ── */}
      <div style={{ marginBottom: 52 }}>
        <SectionHeader
          title="Activity Timeline"
          sub="Your on-chain events, newest first"
        />
        {activity.length > 0 ? (
          <div style={{
            background: 'rgba(255,255,255,0.02)',
            border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: 16, overflow: 'hidden',
          }}>
            {[...activity].reverse().map((ev, i) => (
              <div
                key={i}
                style={{
                  display: 'flex', alignItems: 'flex-start', gap: 14,
                  padding: '16px 20px',
                  borderBottom: i < activity.length - 1 ? '1px solid rgba(255,255,255,0.05)' : 'none',
                  opacity: mounted ? 1 : 0,
                  transform: mounted ? 'none' : 'translateX(-8px)',
                  transition: `opacity 400ms ease ${i * 40}ms, transform 400ms ease ${i * 40}ms`,
                }}
              >
                <ActivityIcon type={ev.type} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap', marginBottom: 3 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5' }}>{ev.label}</span>
                    <ChainBadge chain={ev.chain} />
                  </div>
                  <div style={{ fontSize: 12, color: '#71717a', marginBottom: 4 }}>{ev.detail}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 11, color: '#52525b' }}>{ev.ts}</span>
                    <a
                      href={ev.txUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        fontSize: 11, color: '#FF6B35',
                        textDecoration: 'none', fontFamily: "'JetBrains Mono', monospace",
                        display: 'flex', alignItems: 'center', gap: 3,
                      }}
                    >
                      {ev.tx}
                      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 2 }}>
                        <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                        <polyline points="15 3 21 3 21 9" />
                        <line x1="10" y1="14" x2="21" y2="3" />
                      </svg>
                    </a>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            textAlign: 'center', padding: '32px 24px',
            background: 'rgba(255,255,255,0.02)',
            border: '1px dashed rgba(255,255,255,0.07)',
            borderRadius: 14, color: '#52525b', fontSize: 14,
          }}>
            No on-chain activity yet. Register an agent to get started.
          </div>
        )}
      </div>

      {/* ── Quick Actions Bar ── */}
      <div style={{
        position: 'sticky', bottom: 24,
        background: 'rgba(9,9,11,0.88)',
        backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)',
        border: '1px solid rgba(255,255,255,0.09)',
        borderRadius: 16,
        padding: '14px 20px',
        display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center',
        justifyContent: 'center',
        boxShadow: '0 8px 40px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,107,53,0.04)',
        zIndex: 50,
      }}>
        <span style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', marginRight: 4 }}>QUICK ACTIONS</span>
        <QuickAction
          primary
          icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>}
          label="Register Agent"
          onClick={() => onNavigate('register')}
        />
        <QuickAction
          icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>}
          label="Create Bond"
          onClick={() => onNavigate('marketplace')}
        />
        <QuickAction
          icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></svg>}
          label="Claim VNS"
          onClick={() => onNavigate('discover')}
        />
        <QuickAction
          icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>}
          label="Message Agent"
          onClick={() => onNavigate('discover')}
        />
        <QuickAction
          icon={<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" /><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" /></svg>}
          label="View Docs"
          onClick={() => onNavigate('docs')}
        />
      </div>

      {/* ── Protocol Disclaimer ── */}
      <div style={{
        marginTop: 64, paddingTop: 32,
        borderTop: '1px solid rgba(255,255,255,0.06)',
        textAlign: 'center',
      }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 14px', borderRadius: 100, marginBottom: 12,
          border: '1px solid rgba(234,179,8,0.2)',
          backgroundColor: 'rgba(234,179,8,0.04)',
        }}>
          <div style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: '#EAB308' }} />
          <span style={{ fontSize: 10, fontWeight: 600, color: '#EAB308', letterSpacing: '0.05em' }}>
            ALPHA — LIVE ON-CHAIN DATA
          </span>
        </div>
        <p style={{ fontSize: 12, color: '#3f3f46', maxWidth: 520, margin: '0 auto', lineHeight: 1.7 }}>
          This dashboard displays live on-chain data from the Vaultfire protocol alpha. All agent registrations,
          bonds, and VNS names shown are verified on-chain at{' '}
          <a
            href="https://basescan.org/address/0xfA15Ee28939B222B0448261A22156070f0A7813C"
            target="_blank" rel="noopener noreferrer"
            style={{ color: '#FF6B35', textDecoration: 'none' }}
          >
            0xA054...84F
          </a>
          . Full live-query integration coming in v1.0.
        </p>
        <p style={{ fontSize: 11, color: '#27272a', maxWidth: 600, margin: '12px auto 0', lineHeight: 1.7 }}>
          <strong style={{ color: '#71717a' }}>{String.fromCharCode(9888)} Disclaimer:</strong> Vaultfire is experimental, unaudited software in active development.
          Smart contracts have not been formally audited. Use at your own risk. Nothing on this site constitutes financial,
          legal, or investment advice. Users are solely responsible for evaluating risks before interacting with on-chain
          contracts. Transactions are irreversible. Always do your own research.
        </p>
      </div>
    </div>
  );
}
