'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import type { Page } from '../page';
import { AGENT_DIRECTORY as SHARED_AGENTS, type DirectoryAgent } from '../lib/agent-directory';

// ─── Types ────────────────────────────────────────────────────────────────────

interface AgentData {
  address: string;
  name: string;
  type: 'autonomous' | 'assistant' | 'validator' | 'oracle';
  trustScore: number;
  bondAmount: string;
  vnsName?: string;
  chain: 'Base' | 'Avalanche' | 'Arbitrum' | 'Polygon';
  isActive: boolean;
  capabilities?: string[];
}

interface HubStats {
  totalIdentities: number;
  totalChains: number;
  totalBonds: number;
  totalBonded: string;
}

type ChainFilter = 'All' | 'Base' | 'Avalanche' | 'Arbitrum' | 'Polygon';
type TypeFilter = 'All' | 'autonomous' | 'assistant' | 'validator' | 'oracle';
type SortOption = 'trust' | 'newest' | 'bonded';

// ─── Static Agent Directory ───────────────────────────────────────────────────

// Agent directory — imported from shared module (19 on-chain registered agents)
const AGENT_DIRECTORY = SHARED_AGENTS as unknown as AgentData[];

// ─── Chain Config ─────────────────────────────────────────────────────────────

const CHAIN_CONFIG: Record<string, { color: string; bg: string; border: string; dot: string; explorer: string; explorerName: string }> = {
  Base:      { color: '#3B82F6', bg: 'rgba(59,130,246,0.12)',  border: 'rgba(59,130,246,0.25)',  dot: '#3B82F6', explorer: 'https://basescan.org/address/',     explorerName: 'BaseScan' },
  Avalanche: { color: '#EF4444', bg: 'rgba(239,68,68,0.12)',   border: 'rgba(239,68,68,0.25)',   dot: '#EF4444', explorer: 'https://snowtrace.io/address/',     explorerName: 'SnowTrace' },
  Arbitrum:  { color: '#28A0F0', bg: 'rgba(40,160,240,0.12)',  border: 'rgba(40,160,240,0.25)',  dot: '#28A0F0', explorer: 'https://arbiscan.io/address/',      explorerName: 'ArbScan' },
  Polygon:   { color: '#8247E5', bg: 'rgba(130,71,229,0.12)',  border: 'rgba(130,71,229,0.25)',  dot: '#8247E5', explorer: 'https://polygonscan.com/address/',  explorerName: 'PolygonScan' },
};

const TYPE_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  autonomous: { label: 'Autonomous', color: '#FF6B35', bg: 'rgba(255,107,53,0.1)' },
  assistant:  { label: 'Assistant',  color: '#A78BFA', bg: 'rgba(167,139,250,0.1)' },
  validator:  { label: 'Validator',  color: '#34D399', bg: 'rgba(52,211,153,0.1)' },
  oracle:     { label: 'Oracle',     color: '#FCD34D', bg: 'rgba(252,211,77,0.1)' },
};

// ─── Verification Badge Logic ─────────────────────────────────────────────────

const POST_QUANTUM_ADDRESS = '0xfA15Ee28939B222B0448261A22156070f0A7813C';

// Build a set of addresses that appear on multiple chains
function buildMultiChainAddresses(): Set<string> {
  const chainsByAddr = new Map<string, Set<string>>();
  for (const agent of AGENT_DIRECTORY) {
    const addr = agent.address.toLowerCase();
    if (!chainsByAddr.has(addr)) chainsByAddr.set(addr, new Set());
    chainsByAddr.get(addr)!.add(agent.chain);
  }
  const multiChain = new Set<string>();
  chainsByAddr.forEach((chains, addr) => {
    if (chains.size > 1) multiChain.add(addr);
  });
  return multiChain;
}

const MULTI_CHAIN_ADDRESSES = buildMultiChainAddresses();

// Get all chains an address appears on
function getChainsForAddress(address: string): string[] {
  const chains = new Set<string>();
  for (const agent of AGENT_DIRECTORY) {
    if (agent.address.toLowerCase() === address.toLowerCase()) {
      chains.add(agent.chain);
    }
  }
  return Array.from(chains);
}

// Get count of agents per chain for a given address
function getAgentCountByChain(address: string): Record<string, number> {
  const counts: Record<string, number> = {};
  for (const agent of AGENT_DIRECTORY) {
    if (agent.address.toLowerCase() === address.toLowerCase()) {
      counts[agent.chain] = (counts[agent.chain] || 0) + 1;
    }
  }
  return counts;
}

// Get bond amounts per chain for an address
function getBondsByChain(address: string): Record<string, string> {
  const bonds: Record<string, string> = {};
  for (const agent of AGENT_DIRECTORY) {
    if (agent.address.toLowerCase() === address.toLowerCase()) {
      bonds[agent.chain] = agent.bondAmount;
    }
  }
  return bonds;
}

interface VerificationBadge {
  key: string;
  icon: string;
  label: string;
  color: string;
  bg: string;
  border: string;
}

function getVerificationBadges(agent: AgentData): VerificationBadge[] {
  const badges: VerificationBadge[] = [];

  if (MULTI_CHAIN_ADDRESSES.has(agent.address.toLowerCase())) {
    badges.push({
      key: 'multi-chain',
      icon: '🌐',
      label: 'Multi-Chain',
      color: '#818CF8',
      bg: 'rgba(99,102,241,0.12)',
      border: 'rgba(99,102,241,0.28)',
    });
  }

  if (agent.bondAmount && parseFloat(agent.bondAmount) > 0) {
    badges.push({
      key: 'bonded',
      icon: '🔒',
      label: 'Bonded',
      color: '#10B981',
      bg: 'rgba(16,185,129,0.12)',
      border: 'rgba(16,185,129,0.28)',
    });
  }

  if (agent.vnsName) {
    badges.push({
      key: 'vns',
      icon: '✦',
      label: 'VNS',
      color: '#FF6B35',
      bg: 'rgba(255,107,53,0.12)',
      border: 'rgba(255,107,53,0.28)',
    });
  }

  if (agent.address.toLowerCase() === POST_QUANTUM_ADDRESS.toLowerCase()) {
    badges.push({
      key: 'pq',
      icon: '🛡️',
      label: 'Post-Quantum',
      color: '#60A5FA',
      bg: 'rgba(59,130,246,0.12)',
      border: 'rgba(59,130,246,0.28)',
    });
  }

  return badges;
}

// ─── Trust Score Breakdown ────────────────────────────────────────────────────

interface TrustBreakdown {
  label: string;
  score: number;
  max: number;
  color: string;
}

function getTrustBreakdown(agent: AgentData): TrustBreakdown[] {
  const chains = getChainsForAddress(agent.address);
  const bondVal = parseFloat(agent.bondAmount) || 0;
  const bondScore = Math.min(25, Math.round((bondVal / 0.01) * 25));
  const multiChainScore = Math.min(20, chains.length * 5);

  return [
    { label: 'Identity',     score: 15,           max: 15, color: '#FF6B35' },
    { label: 'Bond Stake',   score: bondScore,     max: 25, color: '#10B981' },
    { label: 'Multi-Chain',  score: multiChainScore, max: 20, color: '#818CF8' },
    { label: 'Partnerships', score: Math.round((agent.trustScore / 100) * 20), max: 20, color: '#FCD34D' },
    { label: 'Longevity',    score: Math.round((agent.trustScore / 100) * 15), max: 15, color: '#34D399' },
    { label: 'Community',    score: agent.isActive ? 5 : 2, max: 5, color: '#A78BFA' },
  ];
}

// ─── Helper: Identicon Avatar ─────────────────────────────────────────────────

function getAvatarGradient(address: string, chain: string): string {
  const chainColors: Record<string, string[]> = {
    Base:      ['#1D4ED8', '#3B82F6', '#60A5FA'],
    Avalanche: ['#991B1B', '#EF4444', '#F87171'],
    Arbitrum:  ['#0C4A6E', '#28A0F0', '#7DD3FC'],
    Polygon:   ['#4C1D95', '#8247E5', '#C084FC'],
  };
  const palette = chainColors[chain] || ['#1a1a2e', '#16213e', '#0f3460'];
  const h1 = parseInt(address.slice(2, 4), 16) % 360;
  const h2 = (h1 + 60) % 360;
  return `linear-gradient(135deg, ${palette[0]}, ${palette[1]}, hsl(${h2}, 70%, 55%))`;
}

function getInitials(address: string): string {
  return address.slice(2, 4).toUpperCase();
}

// ─── Trust Ring Component ─────────────────────────────────────────────────────

function TrustRing({ score, size = 52 }: { score: number; size?: number }) {
  const radius = (size - 8) / 2;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (score / 100) * circumference;
  const color = score >= 80 ? '#22C55E' : score >= 60 ? '#EAB308' : score >= 40 ? '#F97316' : '#EF4444';
  const grade = score >= 90 ? 'A+' : score >= 80 ? 'A' : score >= 70 ? 'B' : score >= 60 ? 'C' : 'D';

  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={radius}
          fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={4}
        />
        <circle
          cx={size / 2} cy={size / 2} r={radius}
          fill="none" stroke={color} strokeWidth={4}
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          style={{ transition: 'stroke-dashoffset 1s cubic-bezier(0.4,0,0.2,1)', filter: `drop-shadow(0 0 4px ${color}60)` }}
        />
      </svg>
      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        gap: 0,
      }}>
        <span style={{ fontSize: size < 48 ? 9 : 11, fontWeight: 800, color, lineHeight: 1 }}>{grade}</span>
        <span style={{ fontSize: size < 48 ? 7 : 9, color: '#71717a', lineHeight: 1 }}>{score}</span>
      </div>
    </div>
  );
}

// ─── Stat Card ────────────────────────────────────────────────────────────────

function StatCard({ label, value, color }: { label: string; value: string | number; color?: string }) {
  return (
    <div style={{
      flex: '1 1 0', minWidth: 100,
      padding: '14px 18px',
      borderRadius: 12,
      background: 'rgba(255,255,255,0.025)',
      border: '1px solid rgba(255,255,255,0.07)',
      display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ fontSize: 20, fontWeight: 800, color: color || '#F4F4F5', letterSpacing: '-0.03em' }}>{value}</div>
      <div style={{ fontSize: 11, color: '#71717a', fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</div>
    </div>
  );
}

// ─── Filter Chip ─────────────────────────────────────────────────────────────

function FilterChip({
  label, active, color, bg, border, onClick,
}: {
  label: string; active: boolean; color?: string; bg?: string; border?: string; onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '5px 14px', borderRadius: 100,
        border: `1px solid ${active ? (border || 'rgba(255,107,53,0.4)') : 'rgba(255,255,255,0.08)'}`,
        background: active ? (bg || 'rgba(255,107,53,0.12)') : 'rgba(255,255,255,0.03)',
        color: active ? (color || '#FF6B35') : '#71717a',
        fontSize: 12, fontWeight: active ? 700 : 500,
        cursor: 'pointer',
        transition: 'all 0.15s ease',
        letterSpacing: '0.02em',
        whiteSpace: 'nowrap',
      }}
    >
      {label}
    </button>
  );
}

// ─── Capability Pills ─────────────────────────────────────────────────────────

function CapabilityPills({ capabilities, max = 3 }: { capabilities: string[]; max?: number }) {
  if (!capabilities || capabilities.length === 0) return null;
  const shown = capabilities.slice(0, max);
  const extra = capabilities.length - max;
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 8 }}>
      {shown.map(cap => (
        <span key={cap} style={{
          fontSize: 10, color: '#71717a',
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.06)',
          borderRadius: 6, padding: '2px 8px',
          whiteSpace: 'nowrap',
        }}>
          {cap}
        </span>
      ))}
      {extra > 0 && (
        <span style={{
          fontSize: 10, color: '#52525b',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.05)',
          borderRadius: 6, padding: '2px 8px',
        }}>
          +{extra} more
        </span>
      )}
    </div>
  );
}

// ─── XTMP Chat Panel ─────────────────────────────────────────────────────────

interface ChatMessage {
  id: string;
  role: 'agent' | 'user';
  text: string;
  timestamp: Date;
}

function XTMPChatPanel({
  agent,
  userTrustScore,
  onClose,
}: {
  agent: AgentData;
  userTrustScore: number;
  onClose: () => void;
}) {
  const MIN_TRUST = 40;
  const trustPassed = userTrustScore >= MIN_TRUST;

  const [gateState, setGateState] = useState<'checking' | 'passed' | 'failed'>('checking');
  const [visible, setVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const threadRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const avatarGrad = getAvatarGradient(agent.address, agent.chain);

  // Slide in on mount
  useEffect(() => {
    const t = setTimeout(() => setVisible(true), 10);
    return () => clearTimeout(t);
  }, []);

  // Trust gate animation
  useEffect(() => {
    const t = setTimeout(() => {
      setGateState(trustPassed ? 'passed' : 'failed');
    }, 1400);
    return () => clearTimeout(t);
  }, [trustPassed]);

  // Pre-populate demo messages after gate passes
  useEffect(() => {
    if (gateState !== 'passed') return;
    const bondTier = parseFloat(agent.bondAmount) >= 0.01 ? 'Gold' : parseFloat(agent.bondAmount) >= 0.005 ? 'Silver' : 'Bronze';
    const initial: ChatMessage[] = [
      {
        id: 'demo-1',
        role: 'agent',
        text: `Hello! I'm ${agent.name}${
          agent.vnsName ? ` (${agent.vnsName})` : ''
        }. How can I help you today?`,
        timestamp: new Date(Date.now() - 120000),
      },
      {
        id: 'demo-2',
        role: 'user',
        text: "I'd like to explore a partnership bond.",
        timestamp: new Date(Date.now() - 90000),
      },
      {
        id: 'demo-3',
        role: 'agent',
        text: `I'd be happy to discuss that. My current bond tier is ${bondTier} with ${agent.bondAmount} staked. What tier are you considering?`,
        timestamp: new Date(Date.now() - 60000),
      },
    ];
    const t = setTimeout(() => setMessages(initial), 200);
    return () => clearTimeout(t);
  }, [gateState, agent]);

  // Auto-scroll to bottom when messages change
  useEffect(() => {
    if (threadRef.current) {
      threadRef.current.scrollTop = threadRef.current.scrollHeight;
    }
  }, [messages, isTyping]);

  function formatTime(d: Date) {
    return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  function handleSend() {
    const text = inputValue.trim();
    if (!text || isTyping) return;

    const userMsg: ChatMessage = {
      id: `user-${Date.now()}`,
      role: 'user',
      text,
      timestamp: new Date(),
    };
    setMessages(prev => [...prev, userMsg]);
    setInputValue('');

    // Typing indicator after 1.5s
    setTimeout(() => {
      setIsTyping(true);
      // Auto-reply after another 1.5s
      setTimeout(() => {
        setIsTyping(false);
        const agentReply: ChatMessage = {
          id: `agent-${Date.now()}`,
          role: 'agent',
          text: `Thanks for reaching out! I've logged your interest. You can initiate a partnership bond from the Register page. My current trust score is ${agent.trustScore}/100 — feel free to review my full profile anytime.`,
          timestamp: new Date(),
        };
        setMessages(prev => [...prev, agentReply]);
      }, 1500);
    }, 1500);
  }

  function handleClose() {
    setVisible(false);
    setTimeout(onClose, 320);
  }

  const scoreColor = userTrustScore >= 80 ? '#22C55E' : userTrustScore >= 60 ? '#EAB308' : userTrustScore >= 40 ? '#F97316' : '#EF4444';

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={handleClose}
        style={{
          position: 'fixed', inset: 0, zIndex: 999,
          background: 'rgba(0,0,0,0.5)',
          backdropFilter: 'blur(2px)',
          WebkitBackdropFilter: 'blur(2px)',
          opacity: visible ? 1 : 0,
          transition: 'opacity 0.3s cubic-bezier(0.4,0,0.2,1)',
        }}
      />

      {/* Panel */}
      <div
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0,
          width: 400, zIndex: 1000,
          display: 'flex', flexDirection: 'column',
          background: 'rgba(9,9,11,0.92)',
          backdropFilter: 'blur(24px)',
          WebkitBackdropFilter: 'blur(24px)',
          borderLeft: '1px solid rgba(255,255,255,0.09)',
          boxShadow: '-8px 0 48px rgba(0,0,0,0.6), -1px 0 0 rgba(255,107,53,0.08)',
          transform: visible ? 'translateX(0)' : 'translateX(100%)',
          transition: 'transform 0.32s cubic-bezier(0.4,0,0.2,1)',
        }}
      >
        {/* Ambient glow top */}
        <div style={{
          position: 'absolute', top: -40, right: -40,
          width: 180, height: 180, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(255,107,53,0.07) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />

        {/* ── Header ── */}
        <div style={{
          padding: '18px 20px',
          borderBottom: '1px solid rgba(255,255,255,0.07)',
          display: 'flex', alignItems: 'center', gap: 12,
          flexShrink: 0, position: 'relative',
        }}>
          {/* Avatar */}
          <div style={{
            width: 40, height: 40, borderRadius: 12, flexShrink: 0,
            background: avatarGrad,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 800, color: 'rgba(255,255,255,0.9)',
            border: `1px solid ${CHAIN_CONFIG[agent.chain]?.color || '#3B82F6'}30`,
            letterSpacing: '0.05em',
          }}>
            {getInitials(agent.address)}
          </div>

          {/* Name block */}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 1 }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5', letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                {agent.name}
              </span>
              <div style={{
                width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
                backgroundColor: agent.isActive ? '#10b981' : '#52525b',
                boxShadow: agent.isActive ? '0 0 6px rgba(16,185,129,0.6)' : 'none',
              }} />
            </div>
            {agent.vnsName && (
              <div style={{ fontSize: 11, color: '#FF6B35', fontWeight: 600 }}>✦ {agent.vnsName}</div>
            )}
          </div>

          {/* Trust score badge */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 4,
            padding: '4px 10px', borderRadius: 8,
            background: `${scoreColor}18`,
            border: `1px solid ${scoreColor}30`,
            flexShrink: 0,
          }}>
            <span style={{ fontSize: 11, fontWeight: 800, color: scoreColor, fontFamily: "'JetBrains Mono', monospace" }}>
              {agent.trustScore}
            </span>
            <span style={{ fontSize: 9, color: scoreColor, fontWeight: 600, opacity: 0.8 }}>SC</span>
          </div>

          {/* Close */}
          <button
            onClick={handleClose}
            style={{
              width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
              border: '1px solid rgba(255,255,255,0.1)',
              background: 'rgba(255,255,255,0.04)',
              color: '#71717a', fontSize: 16, lineHeight: 1,
              cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'all 0.15s ease',
            }}
            onMouseEnter={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(239,68,68,0.15)';
              (e.currentTarget as HTMLButtonElement).style.color = '#F87171';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(239,68,68,0.3)';
            }}
            onMouseLeave={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
              (e.currentTarget as HTMLButtonElement).style.color = '#71717a';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
            }}
          >
            ×
          </button>
        </div>

        {/* ── Trust Gate ── */}
        <div style={{
          margin: '12px 16px 0 16px',
          padding: '10px 14px',
          borderRadius: 10,
          background: gateState === 'checking'
            ? 'rgba(255,255,255,0.03)'
            : gateState === 'passed'
              ? 'rgba(16,185,129,0.07)'
              : 'rgba(239,68,68,0.07)',
          border: `1px solid ${
            gateState === 'checking'
              ? 'rgba(255,255,255,0.08)'
              : gateState === 'passed'
                ? 'rgba(16,185,129,0.25)'
                : 'rgba(239,68,68,0.25)'
          }`,
          transition: 'all 0.3s ease',
          flexShrink: 0,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {gateState === 'checking' ? (
              <>
                <span style={{
                  display: 'inline-block', width: 12, height: 12, flexShrink: 0,
                  border: '2px solid rgba(255,255,255,0.15)',
                  borderTopColor: '#FF6B35',
                  borderRadius: '50%',
                  animation: 'xtmpSpin 0.7s linear infinite',
                }} />
                <span style={{ fontSize: 12, color: '#71717a', fontWeight: 500 }}>Verifying trust gate...</span>
              </>
            ) : gateState === 'passed' ? (
              <>
                <span style={{ fontSize: 13, color: '#10B981', flexShrink: 0 }}>✓</span>
                <span style={{ fontSize: 12, color: '#10B981', fontWeight: 600, lineHeight: 1.4 }}>
                  Trust gate passed — Street Cred <strong>{userTrustScore}/100</strong> exceeds minimum threshold of {MIN_TRUST}
                </span>
              </>
            ) : (
              <>
                <span style={{ fontSize: 13, color: '#F87171', flexShrink: 0 }}>✗</span>
                <span style={{ fontSize: 12, color: '#F87171', fontWeight: 600, lineHeight: 1.4 }}>
                  Trust gate failed — minimum Street Cred of {MIN_TRUST} required to message this agent
                </span>
              </>
            )}
          </div>
        </div>

        {/* ── E2E Encryption badge ── */}
        {gateState === 'passed' && (
          <div style={{
            margin: '8px 16px 0 16px',
            padding: '7px 12px',
            borderRadius: 8,
            background: 'rgba(255,255,255,0.02)',
            border: '1px solid rgba(255,255,255,0.07)',
            display: 'flex', alignItems: 'center', gap: 6,
            flexShrink: 0,
          }}>
            <span style={{ fontSize: 12 }}>🔒</span>
            <span style={{ fontSize: 11, color: '#52525b', fontWeight: 500 }}>End-to-end encrypted via XTMP</span>
          </div>
        )}

        {/* ── Message Thread ── */}
        <div
          ref={threadRef}
          style={{
            flex: 1,
            overflowY: 'auto',
            padding: '16px',
            display: 'flex', flexDirection: 'column', gap: 12,
            scrollbarWidth: 'thin',
            scrollbarColor: 'rgba(255,255,255,0.08) transparent',
          }}
        >
          {gateState === 'failed' ? (
            <div style={{
              flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              gap: 12, padding: '40px 20px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 36, opacity: 0.3 }}>🔐</div>
              <div style={{ fontSize: 14, color: '#52525b', lineHeight: 1.5 }}>
                Build your Street Cred score to unlock messaging.
              </div>
              <div style={{
                fontSize: 11, color: '#3f3f46',
                background: 'rgba(255,255,255,0.02)',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 8, padding: '6px 12px',
              }}>
                Register an agent and stake a bond to increase your score.
              </div>
            </div>
          ) : gateState === 'checking' ? (
            <div style={{
              flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <span style={{
                display: 'inline-block', width: 24, height: 24,
                border: '2px solid rgba(255,255,255,0.08)',
                borderTopColor: 'rgba(255,107,53,0.5)',
                borderRadius: '50%',
                animation: 'xtmpSpin 0.8s linear infinite',
              }} />
            </div>
          ) : (
            messages.map(msg => (
              <div
                key={msg.id}
                style={{
                  display: 'flex',
                  flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
                  gap: 8,
                  alignItems: 'flex-end',
                }}
              >
                {/* Avatar dot */}
                {msg.role === 'agent' && (
                  <div style={{
                    width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                    background: avatarGrad,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 9, fontWeight: 800, color: 'rgba(255,255,255,0.8)',
                    letterSpacing: '0.05em',
                    marginBottom: 2,
                  }}>
                    {getInitials(agent.address)}
                  </div>
                )}

                <div style={{
                  maxWidth: '75%',
                  display: 'flex', flexDirection: 'column',
                  gap: 3,
                  alignItems: msg.role === 'user' ? 'flex-end' : 'flex-start',
                }}>
                  <div style={{
                    padding: '9px 13px',
                    borderRadius: msg.role === 'user'
                      ? '14px 14px 4px 14px'
                      : '14px 14px 14px 4px',
                    background: msg.role === 'user'
                      ? 'linear-gradient(135deg, #FF6B35, #E55A24)'
                      : 'rgba(255,255,255,0.06)',
                    border: msg.role === 'user'
                      ? 'none'
                      : '1px solid rgba(255,255,255,0.09)',
                    color: msg.role === 'user' ? '#fff' : '#E4E4E7',
                    fontSize: 13,
                    lineHeight: 1.5,
                    fontWeight: 400,
                    boxShadow: msg.role === 'user'
                      ? '0 2px 12px rgba(255,107,53,0.25)'
                      : '0 1px 4px rgba(0,0,0,0.3)',
                  }}>
                    {msg.text}
                  </div>
                  <span style={{
                    fontSize: 10, color: '#3f3f46',
                    fontFamily: "'JetBrains Mono', monospace",
                  }}>
                    {formatTime(msg.timestamp)}
                  </span>
                </div>
              </div>
            ))
          )}

          {/* Typing indicator */}
          {isTyping && (
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                background: avatarGrad,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 9, fontWeight: 800, color: 'rgba(255,255,255,0.8)',
                letterSpacing: '0.05em',
              }}>
                {getInitials(agent.address)}
              </div>
              <div style={{
                padding: '10px 14px',
                borderRadius: '14px 14px 14px 4px',
                background: 'rgba(255,255,255,0.06)',
                border: '1px solid rgba(255,255,255,0.09)',
                display: 'flex', alignItems: 'center', gap: 4,
              }}>
                {[0, 1, 2].map(i => (
                  <div
                    key={i}
                    style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: '#52525b',
                      animation: `xtmpBounce 1.2s ease-in-out ${i * 0.2}s infinite`,
                    }}
                  />
                ))}
              </div>
            </div>
          )}
        </div>

        {/* ── Input Row ── */}
        <div style={{
          padding: '12px 16px',
          borderTop: '1px solid rgba(255,255,255,0.07)',
          flexShrink: 0,
        }}>
          {gateState === 'passed' ? (
            <div style={{ display: 'flex', gap: 8 }}>
              <input
                ref={inputRef}
                value={inputValue}
                onChange={e => setInputValue(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && !e.shiftKey && handleSend()}
                placeholder={`Message ${agent.name}...`}
                disabled={isTyping}
                style={{
                  flex: 1,
                  padding: '10px 14px',
                  borderRadius: 10,
                  border: '1px solid rgba(255,255,255,0.1)',
                  background: 'rgba(255,255,255,0.04)',
                  color: '#F4F4F5',
                  fontSize: 13,
                  outline: 'none',
                  fontFamily: "'Inter', system-ui, sans-serif",
                  transition: 'border-color 0.15s ease',
                  opacity: isTyping ? 0.6 : 1,
                }}
                onFocus={e => { (e.currentTarget as HTMLInputElement).style.borderColor = 'rgba(255,107,53,0.4)'; }}
                onBlur={e => { (e.currentTarget as HTMLInputElement).style.borderColor = 'rgba(255,255,255,0.1)'; }}
              />
              <button
                onClick={handleSend}
                disabled={!inputValue.trim() || isTyping}
                style={{
                  padding: '10px 16px',
                  borderRadius: 10,
                  border: 'none',
                  background: inputValue.trim() && !isTyping
                    ? 'linear-gradient(135deg, #FF6B35, #E55A24)'
                    : 'rgba(255,107,53,0.2)',
                  color: '#fff',
                  fontSize: 13, fontWeight: 700,
                  cursor: inputValue.trim() && !isTyping ? 'pointer' : 'not-allowed',
                  transition: 'all 0.15s ease',
                  flexShrink: 0,
                  letterSpacing: '0.02em',
                  boxShadow: inputValue.trim() && !isTyping ? '0 2px 10px rgba(255,107,53,0.3)' : 'none',
                }}
                onMouseEnter={e => {
                  if (inputValue.trim() && !isTyping) {
                    (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(-1px)';
                    (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 4px 14px rgba(255,107,53,0.4)';
                  }
                }}
                onMouseLeave={e => {
                  (e.currentTarget as HTMLButtonElement).style.transform = '';
                  (e.currentTarget as HTMLButtonElement).style.boxShadow = inputValue.trim() && !isTyping ? '0 2px 10px rgba(255,107,53,0.3)' : 'none';
                }}
              >
                Send
              </button>
            </div>
          ) : (
            <div style={{
              padding: '10px 14px', borderRadius: 10,
              background: 'rgba(255,255,255,0.02)',
              border: '1px solid rgba(255,255,255,0.06)',
              textAlign: 'center',
              fontSize: 12, color: '#3f3f46',
            }}>
              {gateState === 'checking' ? 'Verifying access...' : 'Messaging unavailable — trust gate failed'}
            </div>
          )}
        </div>

        {/* ── Powered by footer ── */}
        <div style={{
          padding: '8px 16px 12px',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          gap: 6, flexShrink: 0,
        }}>
          <span style={{ fontSize: 10, color: '#3f3f46', letterSpacing: '0.03em' }}>Powered by XTMP</span>
          <span style={{ fontSize: 10, color: '#27272a' }}>·</span>
          <span style={{
            fontSize: 10, color: '#3f3f46',
            fontFamily: "'JetBrains Mono', monospace",
            letterSpacing: '0.02em',
          }}>@vaultfire/xmtp</span>
        </div>

        {/* Keyframes */}
        <style>{`
          @keyframes xtmpSpin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
          @keyframes xtmpBounce {
            0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
            30% { transform: translateY(-5px); opacity: 1; }
          }
        `}</style>
      </div>
    </>
  );
}

// ─── VNS Resolution Card ──────────────────────────────────────────────────────

function VNSResolutionCard({
  agent,
  onClose,
  onNavigate,
  onViewProfile,
  onOpenChat,
}: {
  agent: AgentData;
  onClose: () => void;
  onNavigate: (p: Page) => void;
  onViewProfile: (agent: AgentData) => void;
  onOpenChat?: (agent: AgentData) => void;
}) {
  const [copied, setCopied] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [barsVisible, setBarsVisible] = useState(false);

  useEffect(() => {
    const t1 = setTimeout(() => setMounted(true), 10);
    const t2 = setTimeout(() => setBarsVisible(true), 200);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  const chains = getChainsForAddress(agent.address);
  const agentCountByChain = getAgentCountByChain(agent.address);
  const badges = getVerificationBadges(agent);
  const breakdown = getTrustBreakdown(agent);
  const avatarGrad = getAvatarGradient(agent.address, agent.chain);
  const truncAddr = `${agent.address.slice(0, 14)}...${agent.address.slice(-5)}`;

  const totalScore = breakdown.reduce((s, b) => s + b.score, 0);
  const totalMax = breakdown.reduce((s, b) => s + b.max, 0);
  const grade = totalScore >= 90 ? 'A+' : totalScore >= 80 ? 'A' : totalScore >= 70 ? 'B' : totalScore >= 60 ? 'C' : 'D';
  const gradeColor = totalScore >= 80 ? '#22C55E' : totalScore >= 60 ? '#EAB308' : '#F97316';

  const ALL_CHAINS = ['Base', 'Avalanche', 'Arbitrum', 'Polygon'];

  function handleCopyAddress() {
    navigator.clipboard.writeText(agent.address).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    });
  }

  return (
    <div style={{
      marginBottom: 28,
      borderRadius: 20,
      padding: '28px 28px',
      background: 'linear-gradient(135deg, rgba(255,107,53,0.05) 0%, rgba(99,102,241,0.03) 50%, rgba(59,130,246,0.02) 100%)',
      border: '1px solid rgba(255,107,53,0.2)',
      backdropFilter: 'blur(24px)',
      WebkitBackdropFilter: 'blur(24px)',
      position: 'relative',
      overflow: 'hidden',
      opacity: mounted ? 1 : 0,
      transform: mounted ? 'translateY(0)' : 'translateY(-8px)',
      transition: 'opacity 0.3s cubic-bezier(0.4,0,0.2,1), transform 0.3s cubic-bezier(0.4,0,0.2,1)',
      boxShadow: '0 8px 32px rgba(255,107,53,0.08), 0 2px 8px rgba(0,0,0,0.3)',
    }}>
      {/* Ambient glow top-right */}
      <div style={{
        position: 'absolute', top: -80, right: -80,
        width: 240, height: 240, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,107,53,0.08) 0%, transparent 70%)',
        pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', bottom: -60, left: -60,
        width: 180, height: 180, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(99,102,241,0.05) 0%, transparent 70%)',
        pointerEvents: 'none',
      }} />

      {/* ── Resolved header ── */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 22, flexWrap: 'wrap', gap: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 10px', borderRadius: 100,
            background: 'rgba(16,185,129,0.12)', border: '1px solid rgba(16,185,129,0.3)',
          }}>
            <div style={{
              width: 6, height: 6, borderRadius: '50%',
              background: '#10B981', boxShadow: '0 0 6px rgba(16,185,129,0.7)',
            }} />
            <span style={{ fontSize: 11, fontWeight: 700, color: '#10B981', letterSpacing: '0.07em' }}>
              RESOLVED
            </span>
          </div>
          <span style={{ fontSize: 12, color: '#52525b' }}>
            {agent.vnsName ? `✦ ${agent.vnsName}` : agent.address.slice(0, 10) + '...'}
          </span>
        </div>
        <button
          onClick={onClose}
          style={{
            width: 28, height: 28, borderRadius: '50%',
            border: '1px solid rgba(255,255,255,0.1)',
            background: 'rgba(255,255,255,0.04)',
            color: '#71717a', fontSize: 15, lineHeight: 1,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.15s ease',
            flexShrink: 0,
          }}
          onMouseEnter={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(239,68,68,0.15)';
            (e.currentTarget as HTMLButtonElement).style.color = '#F87171';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(239,68,68,0.3)';
          }}
          onMouseLeave={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
            (e.currentTarget as HTMLButtonElement).style.color = '#71717a';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
          }}
        >
          ×
        </button>
      </div>

      {/* ── Identity block ── */}
      <div style={{ display: 'flex', gap: 18, alignItems: 'flex-start', marginBottom: 24, flexWrap: 'wrap' }}>
        {/* Avatar */}
        <div style={{
          width: 64, height: 64, borderRadius: 16, flexShrink: 0,
          background: avatarGrad,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20, fontWeight: 800, color: 'rgba(255,255,255,0.9)',
          border: `1px solid ${CHAIN_CONFIG[agent.chain]?.color || '#3B82F6'}30`,
          boxShadow: `0 4px 16px ${CHAIN_CONFIG[agent.chain]?.color || '#3B82F6'}20`,
          letterSpacing: '0.05em',
        }}>
          {getInitials(agent.address)}
        </div>

        {/* Name + VNS + address */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
            <h2 style={{
              fontSize: 20, fontWeight: 800, color: '#F4F4F5',
              letterSpacing: '-0.02em', margin: 0, lineHeight: 1.1,
            }}>
              {agent.name}
            </h2>
            <div style={{
              width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
              backgroundColor: agent.isActive ? '#10b981' : '#52525b',
              boxShadow: agent.isActive ? '0 0 7px rgba(16,185,129,0.7)' : 'none',
            }} />
          </div>

          {agent.vnsName ? (
            <div style={{
              fontSize: 16, color: '#FF6B35', fontWeight: 700,
              letterSpacing: '0.01em', marginBottom: 6,
            }}>
              ✦ {agent.vnsName}
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{ fontSize: 13, color: '#52525b', fontStyle: 'italic' }}>No .vns name claimed</span>
              <button
                onClick={() => onNavigate('register')}
                style={{
                  fontSize: 11, color: '#FF6B35', fontWeight: 700,
                  background: 'rgba(255,107,53,0.1)', border: '1px solid rgba(255,107,53,0.25)',
                  borderRadius: 6, padding: '2px 8px', cursor: 'pointer',
                }}
              >
                Claim →
              </button>
            </div>
          )}

          <button
            onClick={handleCopyAddress}
            title="Click to copy address"
            style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 0,
              display: 'flex', alignItems: 'center', gap: 6,
            }}
          >
            <code style={{
              fontSize: 12, color: copied ? '#10B981' : '#52525b',
              fontFamily: "'JetBrains Mono', 'SF Mono', monospace",
              letterSpacing: '0.02em',
              transition: 'color 0.2s ease',
            }}>
              {truncAddr}
            </code>
            <span style={{ fontSize: 10, color: copied ? '#10B981' : '#52525b', transition: 'color 0.2s ease' }}>
              {copied ? '✓ copied' : '⧉'}
            </span>
          </button>
        </div>

        {/* Trust score badge */}
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, flexShrink: 0,
        }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 4 }}>
            Trust Score
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{
              padding: '6px 14px', borderRadius: 10,
              background: 'rgba(255,255,255,0.04)', border: `1px solid ${gradeColor}30`,
            }}>
              <span style={{ fontSize: 28, fontWeight: 800, color: gradeColor, letterSpacing: '-0.02em', fontFamily: "'JetBrains Mono', monospace" }}>
                {totalScore}
              </span>
            </div>
            <div style={{
              fontSize: 18, fontWeight: 800, color: gradeColor,
              background: `${gradeColor}18`, border: `1px solid ${gradeColor}30`,
              borderRadius: 8, padding: '4px 10px',
            }}>
              {grade}
            </div>
          </div>
        </div>
      </div>

      {/* ── Panels grid ── */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%, 260px), 1fr))',
        gap: 14,
        marginBottom: 18,
      }}>

        {/* Chain Presence */}
        <div style={{
          padding: '16px 18px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 12 }}>
            Chain Presence
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {ALL_CHAINS.map(chain => {
              const cfg = CHAIN_CONFIG[chain];
              const isActive = chains.includes(chain);
              const count = agentCountByChain[chain] || 0;
              return (
                <div key={chain} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{
                    width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                    background: isActive ? cfg.dot : '#3f3f46',
                    boxShadow: isActive ? `0 0 7px ${cfg.dot}80` : 'none',
                    transition: 'all 0.2s ease',
                  }} />
                  <span style={{
                    fontSize: 13, fontWeight: 600,
                    color: isActive ? '#F4F4F5' : '#3f3f46',
                  }}>
                    {chain}
                  </span>
                  {isActive && (
                    <span style={{
                      marginLeft: 'auto',
                      fontSize: 11, color: '#71717a',
                      fontFamily: "'JetBrains Mono', monospace",
                    }}>
                      {count} {count === 1 ? 'agent' : 'agents'}
                    </span>
                  )}
                  {!isActive && (
                    <span style={{
                      marginLeft: 'auto',
                      fontSize: 11, color: '#3f3f46',
                    }}>
                      —
                    </span>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Trust Breakdown */}
        <div style={{
          padding: '16px 18px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
          gridColumn: 'span 2',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 14,
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Trust Breakdown
            </div>
            <div style={{
              fontSize: 12, fontWeight: 800, color: '#FF6B35',
              background: 'rgba(255,107,53,0.1)', border: '1px solid rgba(255,107,53,0.25)',
              borderRadius: 6, padding: '2px 9px',
              fontFamily: "'JetBrains Mono', monospace",
            }}>
              {totalScore}/{totalMax}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {breakdown.map((item, idx) => (
              <div key={item.label}>
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  marginBottom: 5,
                }}>
                  <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 500 }}>{item.label}</span>
                  <span style={{
                    fontSize: 11, fontWeight: 700, color: item.color,
                    fontFamily: "'JetBrains Mono', monospace",
                  }}>
                    {item.score}/{item.max}
                  </span>
                </div>
                <div style={{
                  height: 8, borderRadius: 4,
                  background: 'rgba(255,255,255,0.06)',
                  overflow: 'hidden',
                }}>
                  <div style={{
                    height: '100%',
                    width: barsVisible ? `${(item.score / item.max) * 100}%` : '0%',
                    background: `linear-gradient(90deg, ${item.color}cc, ${item.color})`,
                    borderRadius: 4,
                    boxShadow: `0 0 8px ${item.color}50`,
                    transition: `width ${0.5 + idx * 0.08}s cubic-bezier(0.4,0,0.2,1)`,
                  }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Verification Badges */}
        <div style={{
          padding: '16px 18px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
            Verification Badges
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {badges.length === 0 ? (
              <span style={{ fontSize: 12, color: '#52525b' }}>None earned</span>
            ) : badges.map(badge => (
              <span key={badge.key} style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                fontSize: 12, fontWeight: 700,
                color: badge.color,
                background: badge.bg,
                border: `1px solid ${badge.border}`,
                borderRadius: 100, padding: '4px 11px',
              }}>
                <span style={{ fontSize: 13 }}>{badge.icon}</span>
                {badge.label}
              </span>
            ))}
          </div>
        </div>

        {/* Capabilities */}
        {agent.capabilities && agent.capabilities.length > 0 && (
          <div style={{
            padding: '16px 18px',
            background: 'rgba(255,255,255,0.02)',
            border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: 14,
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
              Capabilities
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {agent.capabilities.map(cap => (
                <span key={cap} style={{
                  fontSize: 11, color: '#a1a1aa',
                  background: 'rgba(255,255,255,0.04)',
                  border: '1px solid rgba(255,255,255,0.08)',
                  borderRadius: 6, padding: '3px 10px',
                }}>
                  {cap}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* ── Footer action row ── */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        {chains.map(chain => {
          const cfg = CHAIN_CONFIG[chain];
          return (
            <a
              key={chain}
              href={`${cfg.explorer}${agent.address}`}
              target="_blank"
              rel="noopener noreferrer"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '7px 14px', borderRadius: 9,
                background: `${cfg.color}0f`,
                border: `1px solid ${cfg.color}22`,
                textDecoration: 'none',
                fontSize: 12, fontWeight: 600, color: cfg.color,
                transition: 'all 0.15s ease',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLAnchorElement).style.background = cfg.bg;
                (e.currentTarget as HTMLAnchorElement).style.borderColor = cfg.border;
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLAnchorElement).style.background = `${cfg.color}0f`;
                (e.currentTarget as HTMLAnchorElement).style.borderColor = `${cfg.color}22`;
              }}
            >
              View on {cfg.explorerName} ↗
            </a>
          );
        })}
        {onOpenChat && (
          <button
            onClick={e => { e.stopPropagation(); onOpenChat(agent); }}
            style={{
              padding: '7px 14px', borderRadius: 9,
              border: '1px solid rgba(255,255,255,0.1)',
              background: 'rgba(255,255,255,0.04)',
              color: '#a1a1aa', fontSize: 12, fontWeight: 600, cursor: 'pointer',
              transition: 'all 0.15s ease',
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}
            onMouseEnter={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.1)';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
              (e.currentTarget as HTMLButtonElement).style.color = '#FF6B35';
            }}
            onMouseLeave={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
              (e.currentTarget as HTMLButtonElement).style.color = '#a1a1aa';
            }}
          >
            💬 Message
          </button>
        )}
        <button
          onClick={() => onViewProfile(agent)}
          style={{
            marginLeft: 'auto',
            padding: '7px 16px', borderRadius: 9,
            border: '1px solid rgba(255,107,53,0.3)',
            background: 'rgba(255,107,53,0.1)',
            color: '#FF6B35', fontSize: 12, fontWeight: 700, cursor: 'pointer',
            transition: 'all 0.15s ease',
          }}
          onMouseEnter={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.18)';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.5)';
          }}
          onMouseLeave={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.1)';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
          }}
        >
          View Full Profile →
        </button>
      </div>
    </div>
  );
}

// ─── Agent Profile Panel ──────────────────────────────────────────────────────

function AgentProfilePanel({ agent, onClose, onOpenChat }: { agent: AgentData; onClose: () => void; onOpenChat?: (agent: AgentData) => void }) {
  const [copied, setCopied] = useState(false);
  const [mounted, setMounted] = useState(false);

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

  const chains = getChainsForAddress(agent.address);
  const bondsByChain = getBondsByChain(agent.address);
  const badges = getVerificationBadges(agent);
  const breakdown = getTrustBreakdown(agent);
  const avatarGrad = getAvatarGradient(agent.address, agent.chain);

  function handleCopyAddress() {
    navigator.clipboard.writeText(agent.address).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    });
  }

  const totalScore = breakdown.reduce((s, b) => s + b.score, 0);
  const totalMax = breakdown.reduce((s, b) => s + b.max, 0);

  return (
    <div style={{
      marginBottom: 24,
      borderRadius: 20,
      padding: '32px',
      background: 'rgba(255,255,255,0.03)',
      border: '1px solid rgba(255,107,53,0.15)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      position: 'relative',
      overflow: 'hidden',
      opacity: mounted ? 1 : 0,
      transform: mounted ? 'translateY(0)' : 'translateY(-12px)',
      transition: 'opacity 0.25s cubic-bezier(0.4,0,0.2,1), transform 0.25s cubic-bezier(0.4,0,0.2,1)',
    }}>
      {/* Background glow */}
      <div style={{
        position: 'absolute', top: -60, right: -60,
        width: 200, height: 200, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,107,53,0.07) 0%, transparent 70%)',
        pointerEvents: 'none',
      }} />

      {/* Close button + Message Agent button */}
      <div style={{ position: 'absolute', top: 16, right: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
        {onOpenChat && (
          <button
            onClick={() => onOpenChat(agent)}
            style={{
              padding: '6px 12px', borderRadius: 8,
              border: '1px solid rgba(255,255,255,0.1)',
              background: 'rgba(255,255,255,0.04)',
              color: '#a1a1aa', fontSize: 12, fontWeight: 600,
              cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 5,
              transition: 'all 0.15s ease',
              whiteSpace: 'nowrap',
            }}
            onMouseEnter={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.1)';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
              (e.currentTarget as HTMLButtonElement).style.color = '#FF6B35';
            }}
            onMouseLeave={e => {
              (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
              (e.currentTarget as HTMLButtonElement).style.color = '#a1a1aa';
            }}
          >
            💬 Message Agent
          </button>
        )}
        <button
          onClick={onClose}
          style={{
            width: 30, height: 30, borderRadius: '50%',
            border: '1px solid rgba(255,255,255,0.1)',
            background: 'rgba(255,255,255,0.05)',
            color: '#71717a', fontSize: 16, lineHeight: 1,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'all 0.15s ease',
          }}
          onMouseEnter={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(239,68,68,0.15)';
            (e.currentTarget as HTMLButtonElement).style.color = '#F87171';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(239,68,68,0.3)';
          }}
          onMouseLeave={e => {
            (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.05)';
            (e.currentTarget as HTMLButtonElement).style.color = '#71717a';
            (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
          }}
        >
          ×
        </button>
      </div>

      {/* ── Panel Header ───────────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', marginBottom: 28, flexWrap: 'wrap' }}>
        {/* Large avatar */}
        <div style={{
          width: 64, height: 64, borderRadius: 16, flexShrink: 0,
          background: avatarGrad,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 20, fontWeight: 800, color: 'rgba(255,255,255,0.9)',
          border: `1px solid ${CHAIN_CONFIG[agent.chain]?.color || '#3B82F6'}30`,
          boxShadow: `0 4px 16px ${CHAIN_CONFIG[agent.chain]?.color || '#3B82F6'}20`,
          letterSpacing: '0.05em',
        }}>
          {getInitials(agent.address)}
        </div>

        {/* Name block */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginBottom: 4 }}>
            <h2 style={{
              fontSize: 22, fontWeight: 800, color: '#F4F4F5',
              letterSpacing: '-0.02em', margin: 0, lineHeight: 1.1,
            }}>
              {agent.name}
            </h2>
            <div style={{
              width: 9, height: 9, borderRadius: '50%', flexShrink: 0,
              backgroundColor: agent.isActive ? '#10b981' : '#52525b',
              boxShadow: agent.isActive ? '0 0 8px rgba(16,185,129,0.7)' : 'none',
            }} />
          </div>

          {agent.vnsName && (
            <div style={{
              fontSize: 13, color: '#FF6B35', fontWeight: 600,
              letterSpacing: '0.01em', marginBottom: 6,
            }}>
              ✦ {agent.vnsName}
            </div>
          )}

          <button
            onClick={handleCopyAddress}
            title="Click to copy address"
            style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 0,
              display: 'flex', alignItems: 'center', gap: 6,
            }}
          >
            <code style={{
              fontSize: 11, color: copied ? '#10B981' : '#52525b',
              fontFamily: "'JetBrains Mono', 'SF Mono', monospace",
              letterSpacing: '0.03em',
              transition: 'color 0.2s ease',
            }}>
              {agent.address}
            </code>
            <span style={{ fontSize: 10, color: copied ? '#10B981' : '#52525b', transition: 'color 0.2s ease' }}>
              {copied ? '✓ copied' : '⧉'}
            </span>
          </button>
        </div>

        {/* Trust ring large */}
        <TrustRing score={agent.trustScore} size={64} />
      </div>

      {/* ── Grid layout for panels ────────────────────────────────────── */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%, 280px), 1fr))',
        gap: 16,
      }}>

        {/* Trust Score Breakdown */}
        <div style={{
          padding: '18px 20px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
          gridColumn: 'span 2',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 14,
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Trust Score Breakdown
            </div>
            <div style={{
              fontSize: 13, fontWeight: 800, color: '#FF6B35',
              background: 'rgba(255,107,53,0.1)', border: '1px solid rgba(255,107,53,0.25)',
              borderRadius: 8, padding: '2px 10px',
            }}>
              {totalScore}/{totalMax}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {breakdown.map(item => (
              <div key={item.label}>
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  marginBottom: 4,
                }}>
                  <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 500 }}>{item.label}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, color: item.color }}>
                    {item.score}/{item.max}
                  </span>
                </div>
                <div style={{
                  height: 5, borderRadius: 100,
                  background: 'rgba(255,255,255,0.06)',
                  overflow: 'hidden',
                }}>
                  <div style={{
                    height: '100%',
                    width: `${(item.score / item.max) * 100}%`,
                    background: item.color,
                    borderRadius: 100,
                    boxShadow: `0 0 6px ${item.color}60`,
                    transition: 'width 0.8s cubic-bezier(0.4,0,0.2,1)',
                  }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Chain Presence */}
        <div style={{
          padding: '18px 20px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 12 }}>
            Chain Presence
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {chains.map(chain => {
              const cfg = CHAIN_CONFIG[chain];
              return (
                <div key={chain} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{
                    width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                    background: cfg?.dot || '#fff',
                    boxShadow: `0 0 6px ${cfg?.dot || '#fff'}80`,
                  }} />
                  <span style={{ fontSize: 13, color: '#F4F4F5', fontWeight: 600 }}>{chain}</span>
                  <span style={{ fontSize: 11, color: '#52525b', marginLeft: 'auto', fontFamily: "'JetBrains Mono', monospace" }}>
                    {bondsByChain[chain] || '—'}
                  </span>
                </div>
              );
            })}
          </div>

          {/* Bond details */}
          <div style={{
            marginTop: 14, paddingTop: 14,
            borderTop: '1px solid rgba(255,255,255,0.05)',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
              Bond Details
            </div>
            {Object.entries(bondsByChain).map(([chain, bond]) => (
              <div key={chain} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                marginBottom: 4,
              }}>
                <span style={{ fontSize: 11, color: '#71717a' }}>{chain}</span>
                <span style={{
                  fontSize: 11, fontWeight: 700,
                  color: '#10B981',
                  fontFamily: "'JetBrains Mono', monospace",
                }}>
                  {bond}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* Verification Badges + Capabilities + Links */}
        <div style={{
          padding: '18px 20px',
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 14,
          display: 'flex', flexDirection: 'column', gap: 16,
        }}>
          {/* Badges */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
              Verification Badges
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
              {badges.length === 0 ? (
                <span style={{ fontSize: 12, color: '#52525b' }}>None earned</span>
              ) : badges.map(badge => (
                <span key={badge.key} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 5,
                  fontSize: 12, fontWeight: 700,
                  color: badge.color,
                  background: badge.bg,
                  border: `1px solid ${badge.border}`,
                  borderRadius: 100, padding: '4px 12px',
                }}>
                  <span style={{ fontSize: 13 }}>{badge.icon}</span>
                  {badge.label}
                </span>
              ))}
            </div>
          </div>

          {/* Capabilities */}
          {agent.capabilities && agent.capabilities.length > 0 && (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
                Capabilities
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
                {agent.capabilities.map(cap => (
                  <span key={cap} style={{
                    fontSize: 11, color: '#a1a1aa',
                    background: 'rgba(255,255,255,0.04)',
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 6, padding: '3px 10px',
                  }}>
                    {cap}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* External links */}
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10 }}>
              Explorer Links
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {chains.map(chain => {
                const cfg = CHAIN_CONFIG[chain];
                return (
                  <a
                    key={chain}
                    href={`${cfg.explorer}${agent.address}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                      padding: '7px 12px', borderRadius: 8,
                      background: 'rgba(255,255,255,0.02)',
                      border: `1px solid ${cfg.color}20`,
                      textDecoration: 'none',
                      transition: 'all 0.15s ease',
                    }}
                    onMouseEnter={e => {
                      (e.currentTarget as HTMLAnchorElement).style.background = `${cfg.bg}`;
                      (e.currentTarget as HTMLAnchorElement).style.borderColor = cfg.border;
                    }}
                    onMouseLeave={e => {
                      (e.currentTarget as HTMLAnchorElement).style.background = 'rgba(255,255,255,0.02)';
                      (e.currentTarget as HTMLAnchorElement).style.borderColor = `${cfg.color}20`;
                    }}
                  >
                    <span style={{ fontSize: 12, color: cfg.color, fontWeight: 600 }}>
                      {cfg.explorerName}
                    </span>
                    <span style={{ fontSize: 11, color: '#52525b' }}>{chain} ↗</span>
                  </a>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Agent Card ───────────────────────────────────────────────────────────────

function AgentCard({
  agent,
  highlighted,
  onNavigate,
  onSelect,
  isSelected,
  onOpenChat,
}: {
  agent: AgentData;
  highlighted?: boolean;
  onNavigate: (p: Page) => void;
  onSelect?: (agent: AgentData) => void;
  isSelected?: boolean;
  onOpenChat?: (agent: AgentData) => void;
}) {
  const [hovered, setHovered] = useState(false);
  const chain = CHAIN_CONFIG[agent.chain] || CHAIN_CONFIG.Base;
  const typeConf = TYPE_CONFIG[agent.type] || TYPE_CONFIG.autonomous;
  const avatarGrad = getAvatarGradient(agent.address, agent.chain);
  const truncAddr = `${agent.address.slice(0, 6)}...${agent.address.slice(-4)}`;
  const badges = getVerificationBadges(agent);
  const explorerBase: Record<string, string> = {
    Base:      'https://basescan.org/address/',
    Avalanche: 'https://snowtrace.io/address/',
    Arbitrum:  'https://arbiscan.io/address/',
    Polygon:   'https://polygonscan.com/address/',
  };

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={() => onSelect && onSelect(agent)}
      style={{
        position: 'relative',
        borderRadius: 16,
        padding: '20px',
        background: isSelected
          ? 'rgba(255,107,53,0.08)'
          : highlighted
            ? 'rgba(255,107,53,0.06)'
            : hovered
              ? 'rgba(255,255,255,0.04)'
              : 'rgba(255,255,255,0.02)',
        border: isSelected
          ? '1px solid rgba(255,107,53,0.4)'
          : highlighted
            ? '1px solid rgba(255,107,53,0.3)'
            : hovered
              ? `1px solid ${chain.color}35`
              : '1px solid rgba(255,255,255,0.07)',
        boxShadow: isSelected
          ? '0 4px 24px rgba(255,107,53,0.15)'
          : hovered
            ? `0 8px 32px rgba(0,0,0,0.4), 0 0 0 1px ${chain.color}15, 0 0 24px ${chain.color}08`
            : highlighted
              ? '0 4px 20px rgba(255,107,53,0.1)'
              : 'none',
        transform: hovered ? 'translateY(-3px)' : 'translateY(0)',
        transition: 'all 0.2s cubic-bezier(0.4,0,0.2,1)',
        cursor: 'pointer',
        overflow: 'hidden',
      }}
    >
      {/* Shimmer overlay on hover */}
      <div style={{
        position: 'absolute', top: 0, left: hovered ? '100%' : '-100%',
        width: '100%', height: '100%',
        background: `linear-gradient(90deg, transparent, ${chain.color}08, transparent)`,
        transition: 'left 0.5s ease',
        pointerEvents: 'none',
      }} />

      {highlighted && (
        <div style={{
          position: 'absolute', top: 10, right: 12,
          fontSize: 10, fontWeight: 700, color: '#FF6B35',
          background: 'rgba(255,107,53,0.15)', border: '1px solid rgba(255,107,53,0.3)',
          borderRadius: 100, padding: '2px 8px', letterSpacing: '0.06em',
        }}>SEARCH RESULT</div>
      )}

      {/* Selected indicator */}
      {isSelected && (
        <div style={{
          position: 'absolute', top: 10, right: highlighted ? 110 : 12,
          fontSize: 10, fontWeight: 700, color: '#FF6B35',
          background: 'rgba(255,107,53,0.15)', border: '1px solid rgba(255,107,53,0.3)',
          borderRadius: 100, padding: '2px 8px', letterSpacing: '0.06em',
        }}>EXPANDED ▲</div>
      )}

      {/* Top row: avatar + name + trust ring */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 14 }}>
        {/* Avatar */}
        <div style={{
          width: 44, height: 44, borderRadius: 12, flexShrink: 0,
          background: avatarGrad,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 800, color: 'rgba(255,255,255,0.9)',
          border: `1px solid ${chain.color}30`,
          letterSpacing: '0.05em',
          boxShadow: `0 2px 8px ${chain.color}20`,
        }}>
          {getInitials(agent.address)}
        </div>

        {/* Name + meta */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 3 }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5', letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>
              {agent.name}
            </span>
            {/* Active dot */}
            <div style={{
              width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
              backgroundColor: agent.isActive ? '#10b981' : '#52525b',
              boxShadow: agent.isActive ? '0 0 6px rgba(16,185,129,0.6)' : 'none',
            }} />
          </div>

          {agent.vnsName && (
            <div style={{ fontSize: 12, color: '#FF6B35', fontWeight: 600, marginBottom: 4, letterSpacing: '0.01em' }}>
              {agent.vnsName}
            </div>
          )}

          <div style={{
            fontSize: 11, color: '#52525b',
            fontFamily: "'JetBrains Mono', 'SF Mono', monospace",
            letterSpacing: '0.02em',
          }}>
            {truncAddr}
          </div>
        </div>

        {/* Trust ring — right side */}
        <TrustRing score={agent.trustScore} size={50} />
      </div>

      {/* Tags row: chain + type + verification badges */}
      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginBottom: badges.length > 0 || (agent.capabilities && agent.capabilities.length > 0) ? 8 : 14 }}>
        {/* Chain badge */}
        <span style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.06em',
          padding: '3px 9px', borderRadius: 100,
          color: chain.color, background: chain.bg, border: `1px solid ${chain.border}`,
          textTransform: 'uppercase',
        }}>
          {agent.chain}
        </span>
        {/* Type badge */}
        <span style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.06em',
          padding: '3px 9px', borderRadius: 100,
          color: typeConf.color, background: typeConf.bg,
          border: `1px solid ${typeConf.color}25`,
          textTransform: 'uppercase',
        }}>
          {typeConf.label}
        </span>
        {/* Verification badges */}
        {badges.map(badge => (
          <span key={badge.key} style={{
            display: 'inline-flex', alignItems: 'center', gap: 3,
            fontSize: 9, fontWeight: 700, letterSpacing: '0.04em',
            padding: '3px 7px', borderRadius: 100,
            color: badge.color, background: badge.bg, border: `1px solid ${badge.border}`,
          }}>
            <span style={{ fontSize: 9 }}>{badge.icon}</span>
            {badge.label}
          </span>
        ))}
      </div>

      {/* Capability pills */}
      {agent.capabilities && agent.capabilities.length > 0 && (
        <div style={{ marginBottom: 14 }}>
          <CapabilityPills capabilities={agent.capabilities} max={3} />
        </div>
      )}

      {/* Bond row */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.05)',
      }}>
        <div>
          <div style={{ fontSize: 9, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', marginBottom: 2 }}>BOND</div>
          <div style={{ fontSize: 12, color: '#a1a1aa', fontWeight: 600, fontFamily: "'JetBrains Mono', monospace" }}>
            {agent.bondAmount}
          </div>
        </div>

        {/* Right side: Message button + view link */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {onOpenChat && (
            <button
              onClick={e => { e.stopPropagation(); onOpenChat(agent); }}
              style={{
                padding: '5px 10px', borderRadius: 7,
                border: '1px solid rgba(255,255,255,0.08)',
                background: 'rgba(255,255,255,0.04)',
                color: '#71717a', fontSize: 11, fontWeight: 600,
                cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 4,
                transition: 'all 0.15s ease',
                whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.1)';
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
                (e.currentTarget as HTMLButtonElement).style.color = '#FF6B35';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.08)';
                (e.currentTarget as HTMLButtonElement).style.color = '#71717a';
              }}
            >
              💬 Message
            </button>
          )}
          <a
            href={`${explorerBase[agent.chain]}${agent.address}`}
            target="_blank"
            rel="noopener noreferrer"
            style={{
              fontSize: 12, fontWeight: 600,
              color: hovered ? chain.color : '#52525b',
              textDecoration: 'none',
              display: 'flex', alignItems: 'center', gap: 4,
              transition: 'color 0.15s ease',
              opacity: hovered ? 1 : 0.5,
            }}
            onClick={e => e.stopPropagation()}
          >
            View →
          </a>
        </div>
      </div>
    </div>
  );
}

// ─── Skeleton Card ────────────────────────────────────────────────────────────

function SkeletonCard() {
  return (
    <div style={{
      borderRadius: 16, padding: 20,
      background: 'rgba(255,255,255,0.015)',
      border: '1px solid rgba(255,255,255,0.05)',
    }}>
      <div style={{ display: 'flex', gap: 14, marginBottom: 14 }}>
        <div className="skeleton" style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0 }} />
        <div style={{ flex: 1 }}>
          <div className="skeleton" style={{ height: 14, width: '60%', marginBottom: 6 }} />
          <div className="skeleton" style={{ height: 11, width: '40%' }} />
        </div>
        <div className="skeleton" style={{ width: 50, height: 50, borderRadius: '50%', flexShrink: 0 }} />
      </div>
      <div style={{ display: 'flex', gap: 6, marginBottom: 14 }}>
        <div className="skeleton" style={{ height: 20, width: 60, borderRadius: 100 }} />
        <div className="skeleton" style={{ height: 20, width: 80, borderRadius: 100 }} />
      </div>
      <div className="skeleton" style={{ height: 1, width: '100%', marginBottom: 12 }} />
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <div className="skeleton" style={{ height: 12, width: 80 }} />
        <div className="skeleton" style={{ height: 12, width: 80 }} />
      </div>
    </div>
  );
}

// ─── VNS Stats Banner ─────────────────────────────────────────────────────────

function VNSStatsBanner() {
  const vnsCount = AGENT_DIRECTORY.filter(a => a.vnsName).length;
  const uniqueVns = new Set(AGENT_DIRECTORY.filter(a => a.vnsName).map(a => a.vnsName)).size;

  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 0,
      padding: '9px 16px',
      borderRadius: 10,
      background: 'rgba(255,107,53,0.03)',
      border: '1px solid rgba(255,107,53,0.1)',
      marginBottom: 20,
      flexWrap: 'wrap',
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        paddingRight: 14,
        borderRight: '1px solid rgba(255,255,255,0.06)',
        marginRight: 14,
      }}>
        <span style={{ fontSize: 13 }}>✦</span>
        <span style={{ fontSize: 11, color: '#FF6B35', fontWeight: 700 }}>.vns Names Active:</span>
        <span style={{
          fontSize: 11, color: '#F4F4F5', fontWeight: 700,
          fontFamily: "'JetBrains Mono', monospace",
        }}>
          {uniqueVns}
        </span>
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        paddingRight: 14,
        borderRight: '1px solid rgba(255,255,255,0.06)',
        marginRight: 14,
      }}>
        <span style={{ fontSize: 11, color: '#71717a', fontWeight: 600 }}>Chains:</span>
        <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 700, fontFamily: "'JetBrains Mono', monospace" }}>4</span>
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        paddingRight: 14,
        borderRight: '1px solid rgba(255,255,255,0.06)',
        marginRight: 14,
      }}>
        <span style={{ fontSize: 11, color: '#71717a', fontWeight: 600 }}>Registrations:</span>
        <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 700, fontFamily: "'JetBrains Mono', monospace" }}>{vnsCount}</span>
      </div>
      <div style={{ marginLeft: 'auto' }}>
        <span style={{
          fontSize: 10, fontWeight: 700, color: '#52525b',
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.07)',
          borderRadius: 6, padding: '2px 8px',
          fontFamily: "'JetBrains Mono', monospace",
          letterSpacing: '0.03em',
        }}>
          @vaultfire/vns
        </span>
      </div>
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function Discover({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const [query, setQuery] = useState('');
  const [chainFilter, setChainFilter] = useState<ChainFilter>('All');
  const [typeFilter, setTypeFilter] = useState<TypeFilter>('All');
  const [sortBy, setSortBy] = useState<SortOption>('trust');
  const [searchResult, setSearchResult] = useState<AgentData | null>(null);
  const [searching, setSearching] = useState(false);
  const [searchError, setSearchError] = useState('');
  const [hasSearched, setHasSearched] = useState(false);
  const [stats, setStats] = useState<HubStats>({ totalIdentities: 0, totalChains: 4, totalBonds: 0, totalBonded: '0' });
  const [statsLoading, setStatsLoading] = useState(true);
  const [isVisible, setIsVisible] = useState(false);
  const [selectedAgent, setSelectedAgent] = useState<AgentData | null>(null);
  const [chatAgent, setChatAgent] = useState<AgentData | null>(null);
  const [inputFocused, setInputFocused] = useState(false);
  const profilePanelRef = useRef<HTMLDivElement>(null);
  const vnsCardRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Page entrance animation
  useEffect(() => {
    const t = setTimeout(() => setIsVisible(true), 50);
    return () => clearTimeout(t);
  }, []);

  // Fetch live stats
  useEffect(() => {
    async function loadStats() {
      try {
        const res = await fetch('/api/hub/stats');
        if (res.ok) {
          const data = await res.json();
          setStats({
            totalIdentities: data.totalIdentities ?? 0,
            totalChains: 4,
            totalBonds: data.activeBonds ?? 0,
            totalBonded: data.totalBondedEth != null ? `${data.totalBondedEth}` : '0',
          });
        }
      } catch {
        // keep defaults
      } finally {
        setStatsLoading(false);
      }
    }
    loadStats();
  }, []);

  // Scroll profile panel into view when opened
  useEffect(() => {
    if (selectedAgent && profilePanelRef.current) {
      profilePanelRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }, [selectedAgent]);

  // Scroll VNS card into view when search resolves
  useEffect(() => {
    if (searchResult && vnsCardRef.current) {
      setTimeout(() => {
        vnsCardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }, 100);
    }
  }, [searchResult]);

  // Enhanced search: resolves .vns names, addresses, and agent names locally first
  async function handleSearch() {
    const q = query.trim();
    if (!q) return;
    setSearching(true);
    setSearchError('');
    setHasSearched(true);
    setSearchResult(null);

    // Simulate brief "resolving" animation
    await new Promise(r => setTimeout(r, 480));

    // Local resolution: .vns name
    if (q.toLowerCase().endsWith('.vns')) {
      const found = AGENT_DIRECTORY.find(a => a.vnsName?.toLowerCase() === q.toLowerCase());
      if (found) {
        setSearchResult(found);
        setSearching(false);
        return;
      }
    }

    // Local resolution: agent name (partial match)
    const byName = AGENT_DIRECTORY.find(a => a.name.toLowerCase().includes(q.toLowerCase()));
    if (byName) {
      setSearchResult(byName);
      setSearching(false);
      return;
    }

    // Local resolution: address match
    const byAddr = AGENT_DIRECTORY.find(a => a.address.toLowerCase() === q.toLowerCase());
    if (byAddr) {
      setSearchResult(byAddr);
      setSearching(false);
      return;
    }

    // Fall back to API for live resolution
    try {
      const res = await fetch(`/api/agent/status?address=${encodeURIComponent(q)}`);
      const data = await res.json();
      if (data && data.address) {
        setSearchResult({
          address: data.address,
          name: data.name || data.agentName || 'Unknown Agent',
          type: (data.type || data.agentType || 'autonomous') as AgentData['type'],
          trustScore: data.trustScore ?? data.overallScore ?? 0,
          bondAmount: data.bondAmount || '0',
          vnsName: data.vnsName,
          chain: (data.chain || 'Base') as AgentData['chain'],
          isActive: data.isRegistered ?? data.isActive ?? false,
        });
      } else {
        setSearchError('No registered agent found. Try a .vns name, wallet address, or agent name.');
      }
    } catch {
      setSearchError('Could not reach the network. Check your connection.');
    } finally {
      setSearching(false);
    }
  }

  function clearSearch() {
    setQuery('');
    setSearchResult(null);
    setSearchError('');
    setHasSearched(false);
    inputRef.current?.focus();
  }

  function handleQuickExample(value: string) {
    setQuery(value);
    // Small timeout so React updates query state before search fires
    setTimeout(async () => {
      setSearching(true);
      setSearchError('');
      setHasSearched(true);
      setSearchResult(null);

      await new Promise(r => setTimeout(r, 380));

      if (value.toLowerCase().endsWith('.vns')) {
        const found = AGENT_DIRECTORY.find(a => a.vnsName?.toLowerCase() === value.toLowerCase());
        if (found) { setSearchResult(found); setSearching(false); return; }
      }
      const byAddr = AGENT_DIRECTORY.find(a => a.address.toLowerCase() === value.toLowerCase());
      if (byAddr) { setSearchResult(byAddr); setSearching(false); return; }
      const byName = AGENT_DIRECTORY.find(a => a.name.toLowerCase().includes(value.toLowerCase()));
      if (byName) { setSearchResult(byName); setSearching(false); return; }

      setSearchError('No registered agent found for that example.');
      setSearching(false);
    }, 20);
  }

  const handleSelectAgent = useCallback((agent: AgentData) => {
    setSelectedAgent(prev =>
      prev && prev.address === agent.address && prev.chain === agent.chain ? null : agent
    );
  }, []);

  // Filter + sort the directory
  const filteredAgents = AGENT_DIRECTORY
    .filter(a => chainFilter === 'All' || a.chain === chainFilter)
    .filter(a => typeFilter === 'All' || a.type === typeFilter)
    .sort((a, b) => {
      if (sortBy === 'trust') return b.trustScore - a.trustScore;
      if (sortBy === 'bonded') {
        const av = parseFloat(a.bondAmount);
        const bv = parseFloat(b.bondAmount);
        return bv - av;
      }
      return 0; // newest: keep original order
    });

  const chains: ChainFilter[] = ['All', 'Base', 'Avalanche', 'Arbitrum', 'Polygon'];
  const types: { value: TypeFilter; label: string }[] = [
    { value: 'All', label: 'All Types' },
    { value: 'autonomous', label: 'Autonomous' },
    { value: 'assistant', label: 'Assistant' },
    { value: 'validator', label: 'Validator' },
    { value: 'oracle', label: 'Oracle' },
  ];

  const DEPLOYER_SHORT = '0xA054...84F';
  const quickExamples = [
    { label: 'vaultfire.vns', value: 'vaultfire.vns' },
    { label: 'oracle.vns', value: 'oracle.vns' },
    { label: 'defi.vns', value: 'defi.vns' },
    { label: DEPLOYER_SHORT, value: '0xfA15Ee28939B222B0448261A22156070f0A7813C' },
  ];

  return (
    <div style={{
      padding: 'clamp(32px, 5vw, 72px) clamp(16px, 4vw, 32px)',
      maxWidth: 1160,
      margin: '0 auto',
      opacity: isVisible ? 1 : 0,
      transform: isVisible ? 'translateY(0)' : 'translateY(12px)',
      transition: 'opacity 0.35s ease, transform 0.35s ease',
    }}>

      {/* ── Header ─────────────────────────────────────────────────────────── */}
      <div style={{ marginBottom: 32 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8, flexWrap: 'wrap' }}>
          <h1 style={{
            fontSize: 'clamp(24px, 4vw, 36px)', fontWeight: 800,
            color: '#F4F4F5', letterSpacing: '-0.03em', margin: 0, lineHeight: 1.1,
          }}>
            Discover Agents
          </h1>
          {/* Live count badge */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '4px 12px', borderRadius: 100,
            background: 'rgba(255,107,53,0.1)', border: '1px solid rgba(255,107,53,0.25)',
          }}>
            <div style={{
              width: 6, height: 6, borderRadius: '50%',
              background: '#FF6B35', boxShadow: '0 0 6px rgba(255,107,53,0.6)',
            }} />
            <span style={{ fontSize: 12, fontWeight: 700, color: '#FF6B35', letterSpacing: '0.02em' }}>
              {statsLoading ? '...' : `${stats.totalIdentities} Agents Registered`}
            </span>
          </div>
        </div>
        <p style={{ fontSize: 14, color: '#71717a', margin: 0, lineHeight: 1.6, maxWidth: 520 }}>
          Browse all registered agents across 4 chains. Every identity is verified on-chain.{' '}
          <span style={{
            fontSize: 11, color: '#52525b',
            background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: 4, padding: '1px 6px', fontStyle: 'italic',
          }}>
            showing cached directory · refreshes periodically
          </span>
        </p>
      </div>

      {/* ── Stats Bar ──────────────────────────────────────────────────────── */}
      <div style={{
        display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 28,
      }}>
        <StatCard label="Agents" value={statsLoading ? '...' : stats.totalIdentities} color="#FF6B35" />
        <StatCard label="Chains" value={statsLoading ? '...' : stats.totalChains} color="#3B82F6" />
        <StatCard label="Total Bonds" value={statsLoading ? '...' : stats.totalBonds} color="#8247E5" />
        <StatCard label="Total Bonded" value={statsLoading ? '...' : stats.totalBonded} color="#22C55E" />
      </div>

      {/* ══════════════════════════════════════════════════════════════════════
          VNS RESOLVER HERO PANEL
      ══════════════════════════════════════════════════════════════════════ */}
      <div style={{
        marginBottom: 20,
        borderRadius: 20,
        padding: '32px',
        background: 'linear-gradient(135deg, rgba(255,107,53,0.04) 0%, rgba(99,102,241,0.03) 50%, rgba(59,130,246,0.02) 100%)',
        border: `1px solid ${inputFocused ? 'rgba(255,107,53,0.35)' : 'rgba(255,107,53,0.15)'}`,
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        position: 'relative',
        overflow: 'hidden',
        transition: 'border-color 0.2s cubic-bezier(0.4,0,0.2,1)',
        animation: 'borderGlow 3s ease-in-out infinite',
        boxShadow: inputFocused
          ? '0 0 32px rgba(255,107,53,0.08), 0 4px 24px rgba(0,0,0,0.2)'
          : '0 4px 24px rgba(0,0,0,0.15)',
      }}>
        {/* Ambient corner glows */}
        <div style={{
          position: 'absolute', top: -80, right: -80, width: 220, height: 220,
          borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(255,107,53,0.06) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />
        <div style={{
          position: 'absolute', bottom: -60, left: -60, width: 160, height: 160,
          borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(99,102,241,0.05) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />

        {/* ── VNS Header ── */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
          {/* VNS logo circle */}
          <div style={{
            width: 36, height: 36, borderRadius: '50%', flexShrink: 0,
            background: 'linear-gradient(135deg, rgba(255,107,53,0.2), rgba(255,107,53,0.08))',
            border: '1px solid rgba(255,107,53,0.3)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18,
            boxShadow: '0 0 12px rgba(255,107,53,0.15)',
          }}>
            🔥
          </div>
          <h2 style={{
            fontSize: 20, fontWeight: 700, color: '#F4F4F5',
            margin: 0, letterSpacing: '-0.02em',
          }}>
            Vaultfire Name Service
          </h2>
          <div style={{
            marginLeft: 'auto',
            fontSize: 10, fontWeight: 700, color: '#52525b',
            background: 'rgba(255,255,255,0.04)',
            border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: 6, padding: '2px 8px',
            fontFamily: "'JetBrains Mono', monospace",
            letterSpacing: '0.03em',
          }}>
            VNS v1
          </div>
        </div>

        <div style={{ height: 1, background: 'rgba(255,107,53,0.1)', marginBottom: 14 }} />

        <p style={{
          fontSize: 13, color: '#71717a', margin: '0 0 20px 0', lineHeight: 1.55,
        }}>
          Resolve any <span style={{ color: '#FF6B35', fontWeight: 600 }}>.vns name</span> to a verified on-chain identity with trust scores
        </p>

        {/* ── Search Input Row ── */}
        <div style={{ display: 'flex', gap: 0, marginBottom: 16 }}>
          <div style={{ position: 'relative', flex: 1 }}>
            {/* Search icon */}
            <div style={{
              position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
              pointerEvents: 'none',
              color: inputFocused ? '#FF6B35' : '#52525b',
              transition: 'color 0.2s ease',
              display: 'flex', alignItems: 'center',
            }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="7" cy="7" r="5" />
                <line x1="11.5" y1="11.5" x2="14" y2="14" />
              </svg>
            </div>
            <input
              ref={inputRef}
              value={query}
              onChange={e => { setQuery(e.target.value); if (!e.target.value) clearSearch(); }}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              onFocus={() => setInputFocused(true)}
              onBlur={() => setInputFocused(false)}
              placeholder="Search by .vns name, wallet address, or agent name..."
              style={{
                width: '100%',
                padding: '14px 20px 14px 46px',
                borderRadius: '14px 0 0 14px',
                border: `1px solid ${inputFocused ? 'rgba(255,107,53,0.4)' : 'rgba(255,255,255,0.1)'}`,
                borderRight: 'none',
                background: inputFocused ? 'rgba(255,107,53,0.04)' : 'rgba(255,255,255,0.04)',
                color: '#F4F4F5',
                fontSize: 16, outline: 'none',
                fontFamily: "'Inter', system-ui, sans-serif",
                boxSizing: 'border-box',
                transition: 'border-color 0.2s ease, background 0.2s ease',
              }}
            />
          </div>
          {query && (
            <button
              onClick={clearSearch}
              style={{
                padding: '14px 14px',
                border: '1px solid rgba(255,255,255,0.1)', borderRight: 'none', borderLeft: 'none',
                background: 'rgba(255,255,255,0.04)',
                color: '#71717a', fontSize: 18, cursor: 'pointer', lineHeight: 1,
                transition: 'all 0.15s ease',
              }}
              title="Clear"
              onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.color = '#F87171'; }}
              onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.color = '#71717a'; }}
            >×</button>
          )}
          <button
            onClick={handleSearch}
            disabled={searching || !query.trim()}
            style={{
              padding: '14px 28px',
              borderRadius: '0 14px 14px 0',
              border: 'none',
              background: searching || !query.trim()
                ? 'rgba(255,107,53,0.3)'
                : 'linear-gradient(135deg, #FF6B35, #E55A24)',
              color: '#fff', fontSize: 15, fontWeight: 700,
              cursor: searching || !query.trim() ? 'not-allowed' : 'pointer',
              transition: 'all 0.18s ease',
              whiteSpace: 'nowrap',
              letterSpacing: '0.01em',
              animation: query.trim() && !searching ? 'breathe 2.5s ease-in-out infinite' : 'none',
              boxShadow: query.trim() && !searching ? '0 4px 14px rgba(255,107,53,0.35)' : 'none',
            }}
          >
            {searching ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <span style={{
                  display: 'inline-block', width: 14, height: 14,
                  border: '2px solid rgba(255,255,255,0.3)',
                  borderTopColor: '#fff',
                  borderRadius: '50%',
                  animation: 'spin 0.7s linear infinite',
                }} />
                Resolving...
              </span>
            ) : 'Resolve →'}
          </button>
        </div>

        {/* Also accepts hint */}
        <p style={{
          fontSize: 12, color: '#52525b', margin: '0 0 12px 0',
        }}>
          Also accepts: wallet addresses (0x...) or agent names
        </p>

        {/* ── Quick Examples Row ── */}
        <div style={{
          padding: '10px 14px',
          borderRadius: 10,
          background: 'rgba(255,255,255,0.02)',
          border: '1px solid rgba(255,255,255,0.06)',
          display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
        }}>
          <span style={{
            fontSize: 11, color: '#52525b', fontWeight: 600,
            letterSpacing: '0.04em', whiteSpace: 'nowrap',
          }}>
            Quick Examples:
          </span>
          {quickExamples.map(ex => (
            <button
              key={ex.value}
              onClick={() => handleQuickExample(ex.value)}
              style={{
                fontSize: 12, color: '#71717a',
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.08)',
                borderRadius: 8, padding: '5px 12px',
                cursor: 'pointer',
                transition: 'all 0.15s ease',
                fontFamily: ex.label.startsWith('0x') ? "'JetBrains Mono', monospace" : 'inherit',
                whiteSpace: 'nowrap',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLButtonElement).style.color = '#FF6B35';
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
                (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,107,53,0.06)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLButtonElement).style.color = '#71717a';
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.08)';
                (e.currentTarget as HTMLButtonElement).style.background = 'rgba(255,255,255,0.04)';
              }}
            >
              {ex.label}
            </button>
          ))}
        </div>

        {/* CSS for spinner */}
        <style>{`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}</style>
      </div>

      {/* ── VNS Stats Banner ── */}
      <VNSStatsBanner />

      {/* ══════════════════════════════════════════════════════════════════════
          VNS RESOLUTION CARD
      ══════════════════════════════════════════════════════════════════════ */}
      <div ref={vnsCardRef}>
        {searchResult && (
          <VNSResolutionCard
            agent={searchResult}
            onClose={clearSearch}
            onNavigate={onNavigate}
            onViewProfile={(agent) => {
              setSelectedAgent(agent);
              clearSearch();
            }}
            onOpenChat={(agent) => setChatAgent(agent)}
          />
        )}
      </div>

      {/* Search error */}
      {hasSearched && searchError && !searching && (
        <div style={{
          marginBottom: 24, padding: '14px 18px', borderRadius: 12,
          background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.2)',
          color: '#F87171', fontSize: 13,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <span style={{ fontSize: 16 }}>⚠</span>
          <span>{searchError}</span>
          <button
            onClick={() => onNavigate('register')}
            style={{
              marginLeft: 'auto', padding: '6px 14px', borderRadius: 8,
              background: 'rgba(255,107,53,0.15)', border: '1px solid rgba(255,107,53,0.3)',
              color: '#FF6B35', fontSize: 12, fontWeight: 700, cursor: 'pointer',
              whiteSpace: 'nowrap',
            }}
          >
            Register Agent →
          </button>
        </div>
      )}

      {/* ── Filter / Sort Row ── */}
      <div style={{
        marginBottom: 20,
        padding: '14px 18px',
        borderRadius: 14,
        background: 'rgba(255,255,255,0.02)',
        border: '1px solid rgba(255,255,255,0.07)',
      }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
          {/* Chain filters */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {chains.map(c => {
              const cfg = c !== 'All' ? CHAIN_CONFIG[c] : null;
              return (
                <FilterChip
                  key={c}
                  label={c}
                  active={chainFilter === c}
                  color={cfg?.color}
                  bg={cfg?.bg}
                  border={cfg?.border}
                  onClick={() => setChainFilter(c)}
                />
              );
            })}
          </div>

          <div style={{ width: 1, height: 20, background: 'rgba(255,255,255,0.08)', margin: '0 4px', flexShrink: 0 }} />

          {/* Type filters */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {types.map(t => {
              const conf = t.value !== 'All' ? TYPE_CONFIG[t.value] : null;
              return (
                <FilterChip
                  key={t.value}
                  label={t.label}
                  active={typeFilter === t.value}
                  color={conf?.color}
                  bg={conf?.bg}
                  onClick={() => setTypeFilter(t.value)}
                />
              );
            })}
          </div>

          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, color: '#52525b', fontWeight: 600, letterSpacing: '0.04em' }}>SORT</span>
            {([['trust', 'Trust Score'], ['newest', 'Newest'], ['bonded', 'Most Bonded']] as [SortOption, string][]).map(([val, lbl]) => (
              <FilterChip
                key={val}
                label={lbl}
                active={sortBy === val}
                onClick={() => setSortBy(val)}
              />
            ))}
          </div>
        </div>
      </div>

      {/* ── Directory Count ─────────────────────────────────────────────────── */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 16, flexWrap: 'wrap', gap: 8,
      }}>
        <div style={{ fontSize: 13, color: '#71717a' }}>
          Showing{' '}
          <span style={{ color: '#F4F4F5', fontWeight: 600 }}>{filteredAgents.length}</span>
          {' '}of <span style={{ color: '#F4F4F5', fontWeight: 600 }}>{AGENT_DIRECTORY.length}</span> agents
          {chainFilter !== 'All' && (
            <span style={{ color: CHAIN_CONFIG[chainFilter]?.color || '#FF6B35' }}> · {chainFilter}</span>
          )}
          {typeFilter !== 'All' && (
            <span style={{ color: TYPE_CONFIG[typeFilter]?.color || '#FF6B35' }}> · {typeFilter}</span>
          )}
        </div>
        {selectedAgent && (
          <button
            onClick={() => setSelectedAgent(null)}
            style={{
              fontSize: 12, fontWeight: 600, color: '#52525b',
              background: 'none', border: 'none', cursor: 'pointer',
              textDecoration: 'underline', textDecorationColor: 'rgba(255,255,255,0.15)',
              padding: 0,
            }}
          >
            Close Profile ×
          </button>
        )}
      </div>

      {/* ── Agent Profile Panel (slides in above grid) ────────────────────── */}
      <div ref={profilePanelRef}>
        {selectedAgent && (
          <AgentProfilePanel
            agent={selectedAgent}
            onClose={() => setSelectedAgent(null)}
            onOpenChat={(agent) => setChatAgent(agent)}
          />
        )}
      </div>

      {/* ── Agent Grid ─────────────────────────────────────────────────────── */}
      {filteredAgents.length > 0 ? (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%, 320px), 1fr))',
          gap: 14,
          marginBottom: 40,
        }}>
          {filteredAgents.map((agent, i) => (
            <div
              key={`${agent.chain}-${agent.address}-${i}`}
              style={{
                animationName: 'fadeInUp',
                animationDuration: `${0.25 + i * 0.04}s`,
                animationFillMode: 'both',
                animationTimingFunction: 'cubic-bezier(0.16, 1, 0.3, 1)',
              }}
            >
              <AgentCard
                agent={agent}
                onNavigate={onNavigate}
                onSelect={handleSelectAgent}
                isSelected={
                  selectedAgent?.address === agent.address &&
                  selectedAgent?.chain === agent.chain
                }
                onOpenChat={(a) => setChatAgent(a)}
              />
            </div>
          ))}
        </div>
      ) : (
        <div style={{
          textAlign: 'center', padding: '60px 24px',
          border: '1px dashed rgba(255,255,255,0.08)',
          borderRadius: 16, marginBottom: 40,
        }}>
          <div style={{ fontSize: 36, marginBottom: 12, opacity: 0.4 }}>◎</div>
          <h3 style={{ fontSize: 15, fontWeight: 600, color: '#a1a1aa', marginBottom: 8 }}>
            No agents match your filters
          </h3>
          <p style={{ fontSize: 13, color: '#52525b', marginBottom: 16 }}>
            Try clearing filters or searching by address
          </p>
          <button
            onClick={() => { setChainFilter('All'); setTypeFilter('All'); }}
            style={{
              padding: '8px 18px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.12)',
              background: 'rgba(255,255,255,0.04)', color: '#a1a1aa',
              fontSize: 12, fontWeight: 600, cursor: 'pointer',
            }}
          >
            Clear Filters
          </button>
        </div>
      )}

      {/* ── CTA Banner ─────────────────────────────────────────────────────── */}
      <div style={{
        borderRadius: 16, padding: '28px 28px',
        background: 'linear-gradient(135deg, rgba(255,107,53,0.08) 0%, rgba(229,90,36,0.04) 100%)',
        border: '1px solid rgba(255,107,53,0.2)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        flexWrap: 'wrap', gap: 20,
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Subtle background glow */}
        <div style={{
          position: 'absolute', right: -40, top: -40,
          width: 160, height: 160, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(255,107,53,0.12) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />

        <div>
          <h3 style={{ fontSize: 17, fontWeight: 700, color: '#F4F4F5', margin: '0 0 6px 0' }}>
            Don't see your agent?
          </h3>
          <p style={{ fontSize: 13, color: '#71717a', margin: 0, maxWidth: 360 }}>
            Register your agent on-chain in under 2 minutes. Get a trust score, VNS name, and partnership bonds across all 4 chains.
          </p>
        </div>
        <button
          onClick={() => onNavigate('register')}
          style={{
            padding: '12px 24px', borderRadius: 12, border: 'none',
            background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
            color: '#fff', fontSize: 14, fontWeight: 700,
            cursor: 'pointer', letterSpacing: '0.02em',
            boxShadow: '0 4px 14px rgba(255,107,53,0.3)',
            transition: 'transform 0.15s ease, box-shadow 0.15s ease',
            whiteSpace: 'nowrap', flexShrink: 0,
          }}
          onMouseEnter={e => {
            (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(-1px)';
            (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 6px 20px rgba(255,107,53,0.4)';
          }}
          onMouseLeave={e => {
            (e.currentTarget as HTMLButtonElement).style.transform = '';
            (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 4px 14px rgba(255,107,53,0.3)';
          }}
        >
          Register Now →
        </button>
      </div>

      {/* ── Protocol Disclaimer ── */}
      <div style={{
        marginTop: 48,
        padding: '20px 24px',
        borderTop: '1px solid rgba(255,255,255,0.06)',
        textAlign: 'center',
      }}>
        <p style={{
          fontSize: 11,
          color: '#52525b',
          lineHeight: 1.7,
          maxWidth: 680,
          margin: '0 auto',
        }}>
          <strong style={{ color: '#71717a' }}>⚠ 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>

      {/* ── XTMP Chat Panel ── */}
      {chatAgent && (
        <XTMPChatPanel
          agent={chatAgent}
          userTrustScore={87}
          onClose={() => setChatAgent(null)}
        />
      )}

    </div>
  );
}
