'use client';
import React, { useState, useEffect, useRef } from 'react';
import { BASE_CONTRACTS, AVALANCHE_CONTRACTS, ARBITRUM_CONTRACTS, POLYGON_CONTRACTS, EXPLORER_URLS, PARTNERSHIP_BONDS, TOTAL_CONTRACTS } from '../lib/contracts';
import type { Page } from '../page';

interface TrustProfile {
  address: string;
  isRegistered: boolean;
  agentName: string;
  trustScore: number;        // 0-100 composite Street Cred score
  averageRating: number;     // 0-10000 basis points from ERC8004ReputationRegistry
  reputationScore: number;
  bondAmount: string;
  bondCount: number;
  partnershipBondCount: number;
  vnsName?: string;
  validationCount: number;
  isPostQuantum: boolean;
  flourishingScore: number;
}

interface PartnershipBond {
  bondId: string;
  participant1: string;
  participant2: string;
  amount: string;
  tier: string;
  active: boolean;
  partnershipType: string;
  createdAt: string;
}

const DEMO_PROFILE: TrustProfile = {
  address: '0xfA15Ee28939B222B0448261A22156070f0A7813C',
  isRegistered: true,
  agentName: 'vaultfire-deployer',
  trustScore: 72,
  averageRating: 8700,
  reputationScore: 72,
  bondAmount: '0.001',
  bondCount: 6,
  partnershipBondCount: 4,
  vnsName: 'vaultfire',
  validationCount: 3,
  isPostQuantum: true,
  flourishingScore: 82,
};

// Score breakdown components
const SCORE_COMPONENTS = [
  { label: 'Identity', sublabel: 'ERC-8004 registered', maxPts: 15, color: '#A855F7', key: 'identity' },
  { label: 'Bond Stake', sublabel: 'Native token staked in bonds', maxPts: 25, color: '#FF6B35', key: 'bond' },
  { label: 'Multi-Chain Presence', sublabel: 'Active across chains', maxPts: 20, color: '#3B82F6', key: 'chain' },
  { label: 'Partnership Count', sublabel: 'Verified partnerships', maxPts: 15, color: '#10b981', key: 'partnership' },
  { label: 'Reputation Rating', sublabel: 'Peer feedback score', maxPts: 15, color: '#EAB308', key: 'reputation' },
  { label: 'Post-Quantum Security', sublabel: 'PQ cryptography enabled', maxPts: 5, color: '#06B6D4', key: 'pq' },
  { label: 'Flourishing Score', sublabel: 'Community vitality', maxPts: 5, color: '#F43F5E', key: 'flourish' },
];

function getComponentScore(profile: TrustProfile, key: string): number {
  switch (key) {
    case 'identity': return profile.isRegistered ? 15 : 0;
    case 'bond': {
      const amt = parseFloat(profile.bondAmount) || 0;
      return Math.min(25, Math.round(amt * 2500));
    }
    case 'chain': return Math.min(20, (profile.bondCount > 0 ? 8 : 0) + (profile.partnershipBondCount > 0 ? 6 : 0) + (profile.validationCount > 0 ? 6 : 0));
    case 'partnership': return Math.min(15, profile.partnershipBondCount * 3);
    case 'reputation': return profile.averageRating > 0 ? Math.round((profile.averageRating / 10000) * 15) : 0;
    case 'pq': return profile.isPostQuantum ? 5 : 0;
    case 'flourish': return Math.round((profile.flourishingScore / 100) * 5);
    default: return 0;
  }
}

function ScoreRing({ score, size = 80, label }: { score: number; size?: number; label: string }) {
  const color = score >= 80 ? '#22C55E' : score >= 60 ? '#EAB308' : score >= 40 ? '#F97316' : '#EF4444';
  const r = (size - 12) / 2;
  const c = 2 * Math.PI * r;
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ position: 'relative', width: size, height: size, margin: '0 auto 8px' }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
          <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="5" />
          <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth="5"
            strokeDasharray={c} strokeDashoffset={c * (1 - score / 100)} strokeLinecap="round"
            style={{ filter: `drop-shadow(0 0 6px ${color}40)` }} />
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <span style={{ fontSize: size * 0.28, fontWeight: 800, color, fontFamily: 'var(--font-mono, monospace)' }}>{score}</span>
        </div>
      </div>
      <div style={{ fontSize: 11, color: '#71717a', fontWeight: 500 }}>{label}</div>
    </div>
  );
}

function TierBadge({ tier }: { tier: string }) {
  const colors: Record<string, { bg: string; border: string; text: string }> = {
    bronze: { bg: 'rgba(205,127,50,0.1)', border: 'rgba(205,127,50,0.3)', text: '#CD7F32' },
    silver: { bg: 'rgba(192,192,192,0.1)', border: 'rgba(192,192,192,0.3)', text: '#C0C0C0' },
    gold: { bg: 'rgba(255,215,0,0.1)', border: 'rgba(255,215,0,0.3)', text: '#FFD700' },
    platinum: { bg: 'rgba(229,228,226,0.1)', border: 'rgba(229,228,226,0.3)', text: '#E5E4E2' },
  };
  const c = colors[tier.toLowerCase()] || colors.bronze;
  return (
    <span style={{
      padding: '2px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
      backgroundColor: c.bg, color: c.text, border: `1px solid ${c.border}`,
      textTransform: 'uppercase' as const,
    }}>{tier}</span>
  );
}

function ScoreBreakdownBars({ profile, animate }: { profile: TrustProfile; animate: boolean }) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    if (animate) {
      const t = setTimeout(() => setMounted(true), 80);
      return () => clearTimeout(t);
    } else {
      setMounted(true);
    }
  }, [animate]);

  return (
    <div style={{
      padding: 20, borderRadius: 14, marginBottom: 12,
      border: '1px solid rgba(255,255,255,0.06)',
      backgroundColor: 'rgba(0,0,0,0.25)',
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#a1a1aa', letterSpacing: '0.08em', marginBottom: 16 }}>
        STREET CRED BREAKDOWN
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
        {SCORE_COMPONENTS.map((comp, i) => {
          const earned = getComponentScore(profile, comp.key);
          const pct = comp.maxPts > 0 ? earned / comp.maxPts : 0;
          const barColor = pct >= 0.8 ? '#22C55E' : pct >= 0.5 ? '#EAB308' : pct > 0 ? '#F97316' : '#3f3f46';
          return (
            <div key={comp.key} style={{ opacity: mounted ? 1 : 0, transition: `opacity 0.3s ease ${i * 60}ms` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <div style={{
                    width: 7, height: 7, borderRadius: '50%', backgroundColor: comp.color, flexShrink: 0,
                    boxShadow: `0 0 5px ${comp.color}50`,
                  }} />
                  <span style={{ fontSize: 12, fontWeight: 600, color: '#e4e4e7' }}>{comp.label}</span>
                  <span style={{ fontSize: 10, color: '#52525b' }}>{comp.sublabel}</span>
                </div>
                <span style={{ fontSize: 11, fontWeight: 700, color: barColor, fontFamily: 'monospace', flexShrink: 0 }}>
                  {earned} / {comp.maxPts}
                </span>
              </div>
              <div style={{ height: 5, borderRadius: 3, backgroundColor: 'rgba(255,255,255,0.05)', overflow: 'hidden' }}>
                <div style={{
                  height: '100%', borderRadius: 3, backgroundColor: barColor,
                  width: mounted ? `${pct * 100}%` : '0%',
                  transition: `width 0.7s cubic-bezier(0.22,1,0.36,1) ${i * 70}ms`,
                  boxShadow: pct > 0 ? `0 0 6px ${barColor}60` : 'none',
                }} />
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Chain presence dots
const CHAIN_CONFIGS = [
  { label: 'Base', color: '#3B82F6' },
  { label: 'Avalanche', color: '#EF4444' },
  { label: 'Arbitrum', color: '#28A0F0' },
  { label: 'Polygon', color: '#8247E5' },
];

// ─── TRUST INDEX DATA & COMPONENT ────────────────────────────────────────────

type ChainName = 'Base' | 'Avalanche' | 'Arbitrum' | 'Polygon';

interface TrustIndexAgent {
  id: string;
  name: string;
  vnsName?: string;
  trustScore: number;
  bonds: string;
  bondUnit: string;
  chains: ChainName[];
  partnerships: number;
  capabilities: string[];
  isVerified: boolean;
  isPostQuantum: boolean;
}

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

// Real on-chain registered agents — only agents that exist on the live contracts
const TRUST_INDEX_AGENTS: TrustIndexAgent[] = [
  { id: 'vaultfire-sentinel', name: 'vaultfire-sentinel', vnsName: 'vaultfire.vns', trustScore: 55, bonds: '0.001', bondUnit: 'ETH', chains: ['Base', 'Avalanche', 'Arbitrum', 'Polygon'], partnerships: 4, capabilities: ['Identity Registry', 'Bond Management', 'Cross-Chain Bridge', 'XMTP Messaging'], isVerified: true, isPostQuantum: true },
  { id: 'base-bond-agent', name: 'base-bond-agent', trustScore: 30, bonds: '0.001', bondUnit: 'ETH', chains: ['Base'], partnerships: 1, capabilities: ['Partnership Bonds', 'Trust Verification'], isVerified: true, isPostQuantum: false },
  { id: 'avalanche-bond-agent', name: 'avalanche-bond-agent', trustScore: 30, bonds: '0.01', bondUnit: 'AVAX', chains: ['Avalanche'], partnerships: 1, capabilities: ['Partnership Bonds', 'Trust Verification'], isVerified: true, isPostQuantum: false },
  { id: 'arbitrum-bond-agent', name: 'arbitrum-bond-agent', trustScore: 30, bonds: '0.0005', bondUnit: 'ETH', chains: ['Arbitrum'], partnerships: 1, capabilities: ['Partnership Bonds', 'Trust Verification'], isVerified: true, isPostQuantum: false },
  { id: 'polygon-bond-agent', name: 'polygon-bond-agent', trustScore: 30, bonds: '0.1', bondUnit: 'MATIC', chains: ['Polygon'], partnerships: 1, capabilities: ['Partnership Bonds', 'Trust Verification'], isVerified: true, isPostQuantum: false },
];

type SortKey = 'trustScore' | 'bonds' | 'chains' | 'partnerships';
type ChainFilter = 'All' | ChainName;
type CategoryFilter = 'All Agents' | 'Bonded' | 'Multi-Chain' | 'Partnership Active';

function agentInitials(name: string): string {
  const parts = name.replace(/[-_]/g, ' ').split(' ');
  if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
  return name.slice(0, 2).toUpperCase();
}

function agentGradient(name: string): string {
  const colors = [
    ['#FF6B35', '#E84142'],
    ['#3B82F6', '#8247E5'],
    ['#28A0F0', '#3B82F6'],
    ['#8247E5', '#E84142'],
    ['#10b981', '#3B82F6'],
    ['#EAB308', '#FF6B35'],
    ['#A855F7', '#28A0F0'],
    ['#F43F5E', '#FF6B35'],
  ];
  const idx = name.charCodeAt(0) % colors.length;
  return `linear-gradient(135deg, ${colors[idx][0]}, ${colors[idx][1]})`;
}

function TrustScoreBar({ score, animate, delay = 0 }: { score: number; animate: boolean; delay?: number }) {
  const color = score >= 80 ? '#22C55E' : score >= 60 ? '#EAB308' : '#F97316';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ flex: 1, height: 4, borderRadius: 2, backgroundColor: 'rgba(255,255,255,0.06)', overflow: 'hidden', minWidth: 60 }}>
        <div style={{
          height: '100%',
          borderRadius: 2,
          backgroundColor: color,
          width: animate ? `${score}%` : '0%',
          transition: `width 0.8s cubic-bezier(0.22,1,0.36,1) ${delay}ms`,
          boxShadow: `0 0 5px ${color}60`,
        }} />
      </div>
      <span style={{ fontSize: 12, fontWeight: 700, color, fontFamily: 'var(--font-mono, monospace)', flexShrink: 0, minWidth: 24 }}>{score}</span>
    </div>
  );
}

function AgentChainDots({ chains }: { chains: ChainName[] }) {
  const allChains: ChainName[] = ['Base', 'Avalanche', 'Arbitrum', 'Polygon'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
      {allChains.map(ch => {
        const active = chains.includes(ch);
        return (
          <div key={ch} title={ch} style={{
            width: 8, height: 8, borderRadius: '50%',
            backgroundColor: active ? CHAIN_COLOR_MAP[ch] : 'rgba(255,255,255,0.08)',
            boxShadow: active ? `0 0 5px ${CHAIN_COLOR_MAP[ch]}80` : 'none',
            transition: 'background-color 0.2s',
            flexShrink: 0,
          }} />
        );
      })}
    </div>
  );
}

function VerificationBadges({ agent }: { agent: TrustIndexAgent }) {
  const badges: { label: string; color: string; bg: string; border: string }[] = [];
  if (agent.isVerified) badges.push({ label: 'ID', color: '#10b981', bg: 'rgba(16,185,129,0.1)', border: 'rgba(16,185,129,0.25)' });
  if (parseFloat(agent.bonds) > 0) badges.push({ label: 'BOND', color: '#FF6B35', bg: 'rgba(255,107,53,0.1)', border: 'rgba(255,107,53,0.25)' });
  if (agent.chains.length > 1) badges.push({ label: 'MULTI', color: '#3B82F6', bg: 'rgba(59,130,246,0.1)', border: 'rgba(59,130,246,0.25)' });
  if (agent.isPostQuantum) badges.push({ label: 'PQ', color: '#A855F7', bg: 'rgba(168,85,247,0.1)', border: 'rgba(168,85,247,0.25)' });
  if (agent.partnerships > 0) badges.push({ label: `${agent.partnerships}P`, color: '#EAB308', bg: 'rgba(234,179,8,0.1)', border: 'rgba(234,179,8,0.25)' });
  return (
    <div style={{ display: 'flex', gap: 3, flexWrap: 'wrap' }}>
      {badges.map(b => (
        <span key={b.label} title={b.label === 'ID' ? 'Identity Verified' : b.label === 'BOND' ? 'Bonded' : b.label === 'MULTI' ? 'Multi-Chain' : b.label === 'PQ' ? 'Post-Quantum' : 'Partnerships'} style={{
          fontSize: 9, fontWeight: 700, padding: '1px 5px', borderRadius: 4,
          color: b.color, backgroundColor: b.bg, border: `1px solid ${b.border}`,
          letterSpacing: '0.04em',
        }}>{b.label}</span>
      ))}
    </div>
  );
}

function TrustDistributionBar({ agents }: { agents: TrustIndexAgent[] }) {
  const high = agents.filter(a => a.trustScore >= 80).length;
  const mod = agents.filter(a => a.trustScore >= 60 && a.trustScore < 80).length;
  const building = agents.filter(a => a.trustScore < 60).length;
  const total = agents.length;
  const tiers = [
    { label: '80+ High Trust', count: high, color: '#22C55E', pct: (high / total) * 100 },
    { label: '60–79 Moderate', count: mod, color: '#EAB308', pct: (mod / total) * 100 },
    { label: '<60 Building', count: building, color: '#F97316', pct: (building / total) * 100 },
  ];
  return (
    <div style={{
      padding: '14px 18px', borderRadius: 12,
      border: '1px solid rgba(255,255,255,0.06)',
      backgroundColor: 'rgba(0,0,0,0.2)',
    }}>
      <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', marginBottom: 10 }}>TRUST SCORE DISTRIBUTION</div>
      <div style={{ display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', marginBottom: 10, gap: 1 }}>
        {tiers.map(t => (
          <div key={t.label} style={{
            width: `${t.pct}%`,
            backgroundColor: t.color,
            boxShadow: `0 0 6px ${t.color}50`,
            transition: 'width 0.6s ease',
          }} />
        ))}
      </div>
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {tiers.map(t => (
          <div key={t.label} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: t.color, flexShrink: 0 }} />
            <span style={{ fontSize: 10, color: '#a1a1aa' }}>{t.label}</span>
            <span style={{ fontSize: 10, fontWeight: 700, color: t.color, fontFamily: 'monospace' }}>{t.count}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function TrustIndexAgentRow({
  agent, index, animate,
}: { agent: TrustIndexAgent; index: number; animate: boolean }) {
  const [hovered, setHovered] = useState(false);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const t = setTimeout(() => setVisible(true), 60 + index * 40);
    return () => clearTimeout(t);
  }, [index]);

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'grid',
        gridTemplateColumns: '32px minmax(120px,1fr) 100px 60px 80px 40px 70px 72px',
        alignItems: 'center',
        gap: 10,
        padding: '10px 14px',
        borderRadius: 10,
        border: hovered ? '1px solid rgba(255,255,255,0.12)' : '1px solid rgba(255,255,255,0.04)',
        backgroundColor: hovered ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.01)',
        transition: 'border-color 0.18s, background-color 0.18s',
        opacity: visible ? 1 : 0,
        transform: visible ? 'translateY(0)' : 'translateY(6px)',
        cursor: 'default',
      }}
    >
      {/* Avatar */}
      <div style={{
        width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
        background: agentGradient(agent.name),
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 10, fontWeight: 800, color: '#fff',
        letterSpacing: '-0.01em',
      }}>
        {agentInitials(agent.name)}
      </div>

      {/* Name */}
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5', fontFamily: 'var(--font-mono, monospace)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {agent.name}
        </div>
        {agent.vnsName && (
          <div style={{ fontSize: 10, color: '#FF6B35', fontWeight: 600, marginTop: 1 }}>{agent.vnsName}</div>
        )}
      </div>

      {/* Trust Score Bar */}
      <TrustScoreBar score={agent.trustScore} animate={animate} delay={index * 35} />

      {/* Chain Dots */}
      <AgentChainDots chains={agent.chains} />

      {/* Bonds */}
      <div style={{ fontSize: 12, fontWeight: 700, color: '#FF6B35', fontFamily: 'var(--font-mono, monospace)', textAlign: 'right' }}>
        {agent.bonds} <span style={{ fontSize: 9, color: '#71717a', fontWeight: 500 }}>{agent.bondUnit}</span>
      </div>

      {/* Partnerships */}
      <div style={{ fontSize: 12, fontWeight: 700, color: agent.partnerships > 0 ? '#10b981' : '#52525b', textAlign: 'center', fontFamily: 'monospace' }}>
        {agent.partnerships}
      </div>

      {/* Badges */}
      <VerificationBadges agent={agent} />

      {/* View Profile */}
      <button style={{
        padding: '4px 8px', borderRadius: 7,
        border: `1px solid ${hovered ? 'rgba(255,107,53,0.3)' : 'rgba(255,255,255,0.07)'}`,
        backgroundColor: hovered ? 'rgba(255,107,53,0.08)' : 'rgba(255,255,255,0.02)',
        color: hovered ? '#FF8C5A' : '#71717a',
        fontSize: 10, fontWeight: 600, cursor: 'pointer',
        whiteSpace: 'nowrap' as const,
        transition: 'all 0.15s',
      }}>
        View →
      </button>
    </div>
  );
}

function TrustIndex() {
  const [chainFilter, setChainFilter] = useState<ChainFilter>('All');
  const [categoryFilter, setCategoryFilter] = useState<CategoryFilter>('All Agents');
  const [sortBy, setSortBy] = useState<SortKey>('trustScore');
  const [animate, setAnimate] = useState(false);
  const [hubStats, setHubStats] = useState<{ totalIdentities: number; activeBonds: number } | null>(null);
  const sectionRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetch('/api/hub/stats').then(r => r.json()).then(setHubStats).catch(() => {});
  }, []);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setAnimate(true); observer.disconnect(); } },
      { threshold: 0.1 }
    );
    if (sectionRef.current) observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  const chains: ChainFilter[] = ['All', 'Base', 'Avalanche', 'Arbitrum', 'Polygon'];
  const categories: CategoryFilter[] = ['All Agents', 'Bonded', 'Multi-Chain', 'Partnership Active'];
  const sortOptions: { key: SortKey; label: string }[] = [
    { key: 'trustScore', label: 'Trust Score' },
    { key: 'bonds', label: 'Total Bonded' },
    { key: 'chains', label: 'Chain Presence' },
    { key: 'partnerships', label: 'Partnerships' },
  ];

  const filtered = TRUST_INDEX_AGENTS
    .filter(a => {
      if (chainFilter !== 'All' && !a.chains.includes(chainFilter as ChainName)) return false;
      if (categoryFilter === 'Bonded' && parseFloat(a.bonds) <= 0) return false;
      if (categoryFilter === 'Multi-Chain' && a.chains.length < 2) return false;
      if (categoryFilter === 'Partnership Active' && a.partnerships < 1) return false;
      return true;
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'trustScore': return b.trustScore - a.trustScore;
        case 'bonds': return parseFloat(b.bonds) - parseFloat(a.bonds);
        case 'chains': return b.chains.length - a.chains.length;
        case 'partnerships': return b.partnerships - a.partnerships;
        default: return 0;
      }
    });

  const pillBase: React.CSSProperties = {
    padding: '5px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
    cursor: 'pointer', border: '1px solid transparent', transition: 'all 0.15s',
    background: 'none',
  };

  return (
    <div ref={sectionRef} style={{ marginTop: 60, paddingTop: 32, borderTop: '1px solid rgba(255,255,255,0.06)' }}>
      {/* Section Header */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <h2 style={{ fontSize: 22, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.02em', margin: 0 }}>
            Trust Index
          </h2>
          <span style={{
            fontSize: 9, fontWeight: 700, padding: '2px 7px', borderRadius: 5,
            backgroundColor: 'rgba(255,107,53,0.12)', color: '#FF8C5A',
            border: '1px solid rgba(255,107,53,0.2)', letterSpacing: '0.08em',
          }}>LIVE</span>
        </div>
        <p style={{ fontSize: 13, color: '#71717a', lineHeight: 1.6, maxWidth: 540 }}>
          Transparent on-chain trust data across all registered agents. No ranks — just verified, auditable facts.
        </p>
      </div>

      {/* Summary Stats Bar */}
      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 0,
        borderRadius: 14, overflow: 'hidden',
        border: '1px solid rgba(255,255,255,0.07)',
        backgroundColor: 'rgba(0,0,0,0.3)',
        marginBottom: 20,
      }}>
        {[
          { label: 'Registered Agents', value: hubStats ? String(hubStats.totalIdentities) : '…', color: '#FF6B35' },
          { label: 'Chains', value: '4', color: '#3B82F6' },
          { label: 'Active Bonds', value: hubStats ? String(hubStats.activeBonds) : '…', color: '#10b981' },
          { label: 'Contracts', value: String(TOTAL_CONTRACTS), color: '#EAB308' },
          { label: 'Chains Live', value: 'Base · Avax · Arb · Poly', color: '#A855F7' },
        ].map((s, i) => (
          <div key={s.label} style={{
            flex: '1 1 100px', padding: '12px 16px',
            borderRight: i < 4 ? '1px solid rgba(255,255,255,0.05)' : 'none',
            textAlign: 'center',
          }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: s.color, fontFamily: 'var(--font-mono, monospace)', lineHeight: 1 }}>{s.value}</div>
            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 500, marginTop: 3 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* Distribution + Filters Row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 16, marginBottom: 20, alignItems: 'start' }}>
        <TrustDistributionBar agents={TRUST_INDEX_AGENTS} />
        <div style={{
          padding: '10px 14px', borderRadius: 12,
          border: '1px solid rgba(255,255,255,0.06)',
          backgroundColor: 'rgba(0,0,0,0.2)',
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', marginBottom: 2 }}>SORT BY</div>
          {sortOptions.map(o => (
            <button key={o.key} onClick={() => setSortBy(o.key)} style={{
              ...pillBase,
              backgroundColor: sortBy === o.key ? 'rgba(255,107,53,0.1)' : 'transparent',
              color: sortBy === o.key ? '#FF8C5A' : '#71717a',
              border: sortBy === o.key ? '1px solid rgba(255,107,53,0.2)' : '1px solid transparent',
              textAlign: 'left' as const,
              whiteSpace: 'nowrap' as const,
              padding: '4px 10px',
            }}>{o.label}</button>
          ))}
        </div>
      </div>

      {/* Filter Bar */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' }}>
        {/* Chain filter */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', flexShrink: 0 }}>CHAIN</span>
          {chains.map(ch => (
            <button key={ch} onClick={() => setChainFilter(ch)} style={{
              ...pillBase,
              backgroundColor: chainFilter === ch ? (ch === 'All' ? 'rgba(255,255,255,0.07)' : `${CHAIN_COLOR_MAP[ch as ChainName] ?? '#FF6B35'}18`) : 'rgba(255,255,255,0.02)',
              color: chainFilter === ch ? (ch === 'All' ? '#F4F4F5' : CHAIN_COLOR_MAP[ch as ChainName] ?? '#F4F4F5') : '#71717a',
              border: chainFilter === ch ? `1px solid ${ch === 'All' ? 'rgba(255,255,255,0.12)' : `${CHAIN_COLOR_MAP[ch as ChainName] ?? '#FF6B35'}40`}` : '1px solid rgba(255,255,255,0.05)',
            }}>{ch}</button>
          ))}
        </div>
        {/* Divider */}
        <div style={{ width: 1, height: 20, backgroundColor: 'rgba(255,255,255,0.06)', flexShrink: 0 }} />
        {/* Category filter */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', flexShrink: 0 }}>FILTER</span>
          {categories.map(cat => (
            <button key={cat} onClick={() => setCategoryFilter(cat)} style={{
              ...pillBase,
              backgroundColor: categoryFilter === cat ? 'rgba(255,107,53,0.1)' : 'rgba(255,255,255,0.02)',
              color: categoryFilter === cat ? '#FF8C5A' : '#71717a',
              border: categoryFilter === cat ? '1px solid rgba(255,107,53,0.2)' : '1px solid rgba(255,255,255,0.05)',
            }}>{cat}</button>
          ))}
        </div>
      </div>

      {/* Column Headers */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: '32px minmax(120px,1fr) 100px 60px 80px 40px 70px 72px',
        gap: 10,
        padding: '6px 14px',
        marginBottom: 4,
      }}>
        {['', 'Agent', 'Trust Score', 'Chains', 'Bonded', 'Prtnrs', 'Verified', ''].map((h, i) => (
          <div key={i} style={{ fontSize: 9, fontWeight: 700, color: '#52525b', letterSpacing: '0.08em', textTransform: 'uppercase' as const }}>
            {h}
          </div>
        ))}
      </div>

      {/* Agent Rows */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {filtered.length === 0 ? (
          <div style={{
            textAlign: 'center', padding: '32px 0',
            border: '1px solid rgba(255,255,255,0.06)',
            borderRadius: 12, color: '#52525b', fontSize: 13,
          }}>
            No agents match current filters.
          </div>
        ) : (
          filtered.map((agent, i) => (
            <TrustIndexAgentRow key={agent.id} agent={agent} index={i} animate={animate} />
          ))
        )}
      </div>

      {/* Result count */}
      <div style={{ marginTop: 10, fontSize: 11, color: '#52525b', textAlign: 'right' }}>
        Showing {filtered.length} of {TRUST_INDEX_AGENTS.length} agents
      </div>

      {/* Ethics Notice */}
      <div style={{
        marginTop: 28,
        padding: '14px 18px',
        borderRadius: 12,
        border: '1px solid rgba(255,255,255,0.05)',
        backgroundColor: 'rgba(0,0,0,0.15)',
      }}>
        <p style={{
          fontSize: 11, color: '#52525b', lineHeight: 1.7, margin: 0,
          fontStyle: 'italic',
        }}>
          The Trust Index provides transparent, on-chain data to help informed decisions. Trust scores are computed
          from verifiable actions — identity registration, bonds, partnerships, and cross-chain presence.
          Scores cannot be purchased or artificially inflated.
        </p>
      </div>
    </div>
  );
}

function ChainDots({ active = true }: { active?: boolean }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      {CHAIN_CONFIGS.map(ch => (
        <div key={ch.label} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3 }}>
          <div style={{
            width: 10, height: 10, borderRadius: '50%',
            backgroundColor: active ? ch.color : '#3f3f46',
            boxShadow: active ? `0 0 7px ${ch.color}70` : 'none',
            transition: 'box-shadow 0.3s',
          }} />
          <span style={{ fontSize: 8, color: active ? ch.color : '#52525b', fontWeight: 600 }}>{ch.label.slice(0, 3).toUpperCase()}</span>
        </div>
      ))}
    </div>
  );
}

// Demo Featured Agent card (pre-search)
function DemoProfileCard({ profile, onNavigate }: { profile: TrustProfile; onNavigate: (p: Page) => void }) {
  const [scoreVisible, setScoreVisible] = useState(false);
  const cardRef = useRef<HTMLDivElement>(null);

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

  const scoreColor = profile.trustScore >= 80 ? '#22C55E' : profile.trustScore >= 60 ? '#EAB308' : '#F97316';
  const r = 44;
  const circum = 2 * Math.PI * r;

  return (
    <div ref={cardRef} style={{
      marginBottom: 36,
      borderRadius: 20,
      border: '1px solid rgba(255,107,53,0.2)',
      background: 'linear-gradient(145deg, rgba(255,107,53,0.05) 0%, rgba(9,9,11,0.9) 50%, rgba(59,130,246,0.04) 100%)',
      backdropFilter: 'blur(12px)',
      overflow: 'hidden',
      position: 'relative',
    }}>
      {/* Subtle glow strip at top */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 2,
        background: 'linear-gradient(90deg, transparent, rgba(255,107,53,0.6), rgba(59,130,246,0.4), transparent)',
      }} />

      <div style={{ padding: '24px 24px 20px' }}>
        {/* Header row: badges + view link */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20, flexWrap: 'wrap', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              padding: '3px 10px', borderRadius: 6, fontSize: 10, fontWeight: 700,
              backgroundColor: 'rgba(255,107,53,0.12)', color: '#FF8C5A',
              border: '1px solid rgba(255,107,53,0.25)', letterSpacing: '0.06em',
            }}>FEATURED AGENT</span>
            <span style={{
              padding: '3px 10px', borderRadius: 6, fontSize: 10, fontWeight: 700,
              backgroundColor: 'rgba(255,255,255,0.05)', color: '#71717a',
              border: '1px solid rgba(255,255,255,0.08)', letterSpacing: '0.05em',
            }}>DEMO PROFILE</span>
          </div>
          <a href={`${EXPLORER_URLS.base}/address/${profile.address}`}
            target="_blank" rel="noopener noreferrer"
            style={{
              padding: '6px 12px', borderRadius: 8,
              border: '1px solid rgba(255,255,255,0.08)',
              backgroundColor: 'rgba(255,255,255,0.03)',
              color: '#FF8C5A', fontSize: 11, fontWeight: 600, textDecoration: 'none',
            }}>
            View on BaseScan →
          </a>
        </div>

        {/* Main content: identity + score ring */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 20, flexWrap: 'wrap' }}>
          {/* Left: identity */}
          <div style={{ flex: 1, minWidth: 200 }}>
            {/* Agent name + badges */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
              <h2 style={{ fontSize: 24, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.01em', margin: 0 }}>
                {profile.agentName}
              </h2>
              {profile.isRegistered && (
                <span style={{
                  display: 'flex', alignItems: 'center', gap: 4,
                  padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
                  backgroundColor: 'rgba(16,185,129,0.12)', color: '#10b981',
                  border: '1px solid rgba(16,185,129,0.25)',
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: '#10b981', display: 'inline-block', boxShadow: '0 0 5px #10b98170' }} />
                  VERIFIED ON-CHAIN
                </span>
              )}
              {profile.isPostQuantum && (
                <span style={{
                  padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
                  backgroundColor: 'rgba(168,85,247,0.12)', color: '#A855F7',
                  border: '1px solid rgba(168,85,247,0.25)',
                }}>POST-QUANTUM</span>
              )}
            </div>

            {/* VNS name */}
            {profile.vnsName && (
              <div style={{ fontSize: 15, color: '#FF6B35', fontWeight: 700, marginBottom: 6 }}>
                {profile.vnsName}.vaultfire
              </div>
            )}

            {/* Address */}
            <div style={{
              fontSize: 11, color: '#52525b', fontFamily: 'monospace',
              wordBreak: 'break-all' as const, marginBottom: 14,
            }}>
              {profile.address}
            </div>

            {/* Chain presence */}
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 6, letterSpacing: '0.06em' }}>CHAIN PRESENCE</div>
              <ChainDots active />
            </div>

            {/* Stat pills */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {[
                { label: 'BOND AMOUNT', value: `${profile.bondAmount} ETH`, color: '#FF6B35' },
                { label: 'PARTNERSHIPS', value: String(profile.partnershipBondCount), color: '#10b981' },
                { label: 'RATING', value: `${profile.averageRating.toLocaleString()} / 10k`, color: '#3B82F6' },
              ].map(stat => (
                <div key={stat.label} style={{
                  padding: '7px 12px', borderRadius: 10,
                  border: '1px solid rgba(255,255,255,0.06)',
                  backgroundColor: 'rgba(255,255,255,0.02)',
                }}>
                  <div style={{ fontSize: 9, color: '#52525b', fontWeight: 700, letterSpacing: '0.06em', marginBottom: 2 }}>{stat.label}</div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: stat.color, fontFamily: 'monospace' }}>{stat.value}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Right: large score ring */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
            <div style={{ position: 'relative', width: 120, height: 120 }}>
              <svg width={120} height={120} viewBox="0 0 120 120" style={{ transform: 'rotate(-90deg)' }}>
                <circle cx={60} cy={60} r={r} fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="7" />
                <circle cx={60} cy={60} r={r} fill="none" stroke={scoreColor} strokeWidth="7"
                  strokeDasharray={circum}
                  strokeDashoffset={scoreVisible ? circum * (1 - profile.trustScore / 100) : circum}
                  strokeLinecap="round"
                  style={{
                    transition: 'stroke-dashoffset 1.2s cubic-bezier(0.22,1,0.36,1)',
                    filter: `drop-shadow(0 0 10px ${scoreColor}50)`,
                  }} />
              </svg>
              <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
                <span style={{ fontSize: 34, fontWeight: 900, color: scoreColor, fontFamily: 'monospace', lineHeight: 1 }}>
                  {profile.trustScore}
                </span>
                <span style={{ fontSize: 10, color: '#71717a', fontWeight: 600 }}>/100</span>
              </div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 11, color: '#71717a', fontWeight: 600 }}>Street Cred</div>
              <span style={{
                fontSize: 12, fontWeight: 800, padding: '3px 10px', borderRadius: 6, marginTop: 4, display: 'inline-block',
                backgroundColor: 'rgba(34,197,94,0.12)', color: '#22C55E',
                border: '1px solid rgba(34,197,94,0.25)',
              }}>
                {profile.trustScore >= 80 ? 'A — Elite' : profile.trustScore >= 60 ? 'B — Trusted' : 'C — Active'}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom bar */}
      <div style={{
        padding: '12px 24px',
        borderTop: '1px solid rgba(255,255,255,0.04)',
        backgroundColor: 'rgba(0,0,0,0.2)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8,
      }}>
        <span style={{ fontSize: 11, color: '#52525b' }}>
          Search any wallet address below to verify their trust profile
        </span>
        <button onClick={() => onNavigate('register')} style={{
          padding: '5px 12px', borderRadius: 8, border: '1px solid rgba(255,107,53,0.2)',
          backgroundColor: 'rgba(255,107,53,0.06)', color: '#FF8C5A',
          fontSize: 11, fontWeight: 600, cursor: 'pointer',
        }}>
          Register your agent →
        </button>
      </div>
    </div>
  );
}

export default function Trust({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const [query, setQuery] = useState('');
  const [profile, setProfile] = useState<TrustProfile | null>(null);
  const [bonds, setBonds] = useState<PartnershipBond[]>([]);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);
  const [activeTab, setActiveTab] = useState<'overview' | 'partnerships' | 'contracts'>('overview');
  const [showScoreBreakdown, setShowScoreBreakdown] = useState(false);

  // Whether we're showing the live search result (vs the demo card)
  const showingLiveResult = searched && profile;
  const showDemoCard = !searched;

  async function handleVerify() {
    if (!query.trim()) return;
    setLoading(true);
    setSearched(true);
    try {
      const res = await fetch(`/api/agent/status?address=${encodeURIComponent(query.trim())}`);
      const data = await res.json();
      if (data && (data.address || data.isRegistered)) {
        setProfile({
          address: data.address || query.trim(),
          isRegistered: data.registered ?? data.isRegistered ?? false,
          agentName: data.agentName || data.name || 'Unknown Agent',
          trustScore: data.trustScore ?? data.overallScore ?? 0,
          averageRating: data.averageRating ?? 0,
          reputationScore: data.reputationScore ?? 0,
          bondAmount: data.bondAmountEth || data.bondAmount || '0',
          bondCount: data.bondCount ?? data.activeBonds ?? 0,
          partnershipBondCount: data.partnershipBondCount ?? 0,
          vnsName: data.vnsName,
          validationCount: data.validationCount ?? 0,
          isPostQuantum: data.isPostQuantum ?? false,
          flourishingScore: data.flourishingScore ?? 0,
        });
        // Fetch partnership bonds
        try {
          const bondRes = await fetch(`/api/agent/partnerships?address=${encodeURIComponent(query.trim())}`);
          const bondData = await bondRes.json();
          if (bondData.bonds) {
            setBonds(bondData.bonds);
          } else {
            setBonds([]);
          }
        } catch {
          setBonds([]);
        }
      } else {
        setProfile(null);
        setBonds([]);
      }
    } catch {
      setProfile(null);
      setBonds([]);
    } finally {
      setLoading(false);
    }
  }

  function handleQuickSearch(address: string) {
    setQuery(address);
    setTimeout(() => {
      const input = document.getElementById('trust-search-input') as HTMLInputElement | null;
      if (input) {
        input.value = address;
      }
    }, 0);
  }

  const allContracts = [
    ...BASE_CONTRACTS.map(c => ({ ...c, chainLabel: 'Base', explorer: EXPLORER_URLS.base })),
    ...AVALANCHE_CONTRACTS.map(c => ({ ...c, chainLabel: 'Avalanche', explorer: EXPLORER_URLS.avalanche })),
    ...ARBITRUM_CONTRACTS.map(c => ({ ...c, chainLabel: 'Arbitrum', explorer: EXPLORER_URLS.arbitrum })),
    ...POLYGON_CONTRACTS.map(c => ({ ...c, chainLabel: 'Polygon', explorer: EXPLORER_URLS.polygon })),
  ];

  const tabs = [
    { id: 'overview' as const, label: 'Street Cred Overview' },
    { id: 'partnerships' as const, label: `Partnership Bonds${bonds.length > 0 ? ` (${bonds.length})` : ''}` },
    { id: 'contracts' as const, label: 'Verified Contracts' },
  ];

  // The active profile: live search result or (when in contracts tab without search) nothing
  const activeProfile = showingLiveResult ? profile : null;

  return (
    <div style={{ padding: 'clamp(40px, 6vw, 80px) 24px', maxWidth: 760, margin: '0 auto' }}>
      <h1 style={{ fontSize: 28, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.02em', marginBottom: 8 }}>
        Verify Trust
      </h1>
      <p style={{ fontSize: 14, color: '#71717a', marginBottom: 20 }}>
        Look up any agent&apos;s Street Cred, partnership bonds, and on-chain verification data.
      </p>

      {/* Street Cred Explanation */}
      <div style={{
        padding: 18, borderRadius: 14, marginBottom: 28,
        border: '1px solid rgba(255,107,53,0.12)',
        background: 'linear-gradient(135deg, rgba(255,107,53,0.04), transparent)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: showScoreBreakdown ? 14 : 0 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{ fontSize: 16 }}>🔥</span>
              <h3 style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5' }}>What is Street Cred?</h3>
            </div>
            <p style={{ fontSize: 12, color: '#a1a1aa', lineHeight: 1.6 }}>
              Street Cred is your agent&apos;s on-chain reputation — earned through ERC-8004 identity registration and partnership bonds on AIPartnershipBondsV2.
              Calculated by the hub from live on-chain data. Can&apos;t be faked. Can&apos;t be bought.
            </p>
          </div>
          <button onClick={() => setShowScoreBreakdown(!showScoreBreakdown)} style={{
            padding: '6px 12px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.1)',
            backgroundColor: 'rgba(255,255,255,0.04)', color: '#FF8C5A', fontSize: 11,
            fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const, flexShrink: 0, marginLeft: 16,
          }}>
            {showScoreBreakdown ? 'Hide' : 'How it\'s scored'}
          </button>
        </div>
        {showScoreBreakdown && (
          <div style={{
            padding: 16, borderRadius: 12,
            backgroundColor: 'rgba(0,0,0,0.3)',
            border: '1px solid rgba(255,255,255,0.04)',
          }}>
            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#F4F4F5', marginBottom: 4 }}>STREET CRED (0–100) — Composite Reputation</div>
              <div style={{ fontSize: 11, color: '#71717a' }}>Calculated from real on-chain data by the hub. Scored out of 100.</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { label: 'ERC-8004 Identity Registered', pts: '30 pts', desc: 'Verified registration on ERC8004IdentityRegistry on Base', color: '#A855F7' },
                { label: 'Partnership Bond Exists', pts: '25 pts', desc: 'Has at least one bond on AIPartnershipBondsV2 (live)', color: '#10b981' },
                { label: 'Partnership Bond Active', pts: '15 pts', desc: 'Bond is currently in active state on-chain', color: '#3B82F6' },
                { label: 'Bond Tier Bonus', pts: '5–20 pts', desc: 'Bronze +5 · Silver +10 · Gold +15 · Platinum +20', color: '#EAB308' },
                { label: 'Multiple Bonds', pts: '5 pts', desc: 'More than one partnership bond — shows wider network', color: '#FF6B35' },
              ].map((item, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 8, height: 8, borderRadius: '50%', backgroundColor: item.color, flexShrink: 0,
                    boxShadow: `0 0 6px ${item.color}40`,
                  }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontSize: 12, fontWeight: 600, color: '#F4F4F5' }}>{item.label}</span>
                      <span style={{ fontSize: 11, fontWeight: 700, color: item.color, fontFamily: 'monospace' }}>{item.pts}</span>
                    </div>
                    <div style={{ fontSize: 11, color: '#71717a' }}>{item.desc}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{
              marginTop: 12, paddingTop: 10, borderTop: '1px solid rgba(255,255,255,0.06)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span style={{ fontSize: 11, color: '#71717a' }}>Max score: 30 + 25 + 15 + 20 + 5 = 95 pts (platinum bonded agent with multiple bonds)</span>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#FF6B35' }}>max 95 pts</span>
            </div>
            {/* On-Chain Rating explanation */}
            <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.06)' }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#3B82F6', marginBottom: 4 }}>ON-CHAIN RATING (0–10,000) — Peer Feedback</div>
              <div style={{ fontSize: 11, color: '#71717a', lineHeight: 1.6 }}>
                Stored directly in <strong style={{ color: '#a1a1aa' }}>ERC8004ReputationRegistry</strong>. Agents rate each other after interactions.
                10,000 = perfect score. Returned by <code style={{ color: '#FF8C5A', fontSize: 10 }}>getReputation(address).averageRating</code>.
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Demo profile card (pre-search) */}
      {showDemoCard && <DemoProfileCard profile={DEMO_PROFILE} onNavigate={onNavigate} />}

      {/* Search */}
      <div style={{ marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 0, marginBottom: 10 }}>
          <input
            id="trust-search-input"
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && handleVerify()}
            placeholder="Try it: Paste any wallet address to verify trust (0x...)..."
            style={{
              flex: 1, padding: '13px 16px', borderRadius: '12px 0 0 12px',
              border: '1px solid rgba(255,255,255,0.1)', borderRight: 'none',
              backgroundColor: 'rgba(255,255,255,0.04)', color: '#F4F4F5',
              fontSize: 14, outline: 'none',
            }}
          />
          <button onClick={handleVerify} disabled={loading} style={{
            padding: '13px 24px', borderRadius: '0 12px 12px 0', border: 'none',
            background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
            color: '#fff', fontSize: 14, fontWeight: 700, cursor: 'pointer',
            opacity: loading ? 0.6 : 1,
          }}>
            {loading ? 'Verifying...' : 'Verify'}
          </button>
        </div>
        {/* Quick-search buttons */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11, color: '#52525b', flexShrink: 0 }}>Quick search:</span>
          {[
            { label: 'vaultfire-deployer', address: '0xfA15Ee28939B222B0448261A22156070f0A7813C' },
          ].map(ex => (
            <button key={ex.address} onClick={() => { handleQuickSearch(ex.address); }} style={{
              padding: '4px 10px', borderRadius: 7, border: '1px solid rgba(255,255,255,0.08)',
              backgroundColor: 'rgba(255,255,255,0.03)', color: '#a1a1aa',
              fontSize: 11, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'monospace',
            }}>
              {ex.label}
            </button>
          ))}
        </div>
      </div>

      {/* Trust Profile Result (live search) */}
      {activeProfile && (
        <div style={{ marginBottom: 48, marginTop: 24 }}>
          {/* Glass Header Card */}
          <div style={{
            padding: 24, borderRadius: 20, marginBottom: 16,
            border: '1px solid rgba(255,255,255,0.09)',
            background: 'linear-gradient(145deg, rgba(255,107,53,0.04) 0%, rgba(9,9,11,0.95) 60%, rgba(59,130,246,0.03) 100%)',
            backdropFilter: 'blur(12px)',
            position: 'relative',
            overflow: 'hidden',
          }}>
            {/* top glow strip */}
            <div style={{
              position: 'absolute', top: 0, left: 0, right: 0, height: 2,
              background: 'linear-gradient(90deg, transparent, rgba(255,107,53,0.5), rgba(59,130,246,0.3), transparent)',
            }} />
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 16 }}>
              <div style={{ flex: 1, minWidth: 200 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6, flexWrap: 'wrap' }}>
                  <h2 style={{ fontSize: 22, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.01em' }}>{activeProfile.agentName}</h2>
                  {activeProfile.isRegistered && (
                    <span style={{
                      display: 'flex', alignItems: 'center', gap: 4,
                      padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
                      backgroundColor: 'rgba(16,185,129,0.12)', color: '#10b981',
                      border: '1px solid rgba(16,185,129,0.25)',
                    }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: '#10b981', display: 'inline-block', boxShadow: '0 0 5px #10b98170' }} />
                      VERIFIED ON-CHAIN
                    </span>
                  )}
                  {activeProfile.isPostQuantum && (
                    <span style={{
                      padding: '3px 8px', borderRadius: 6, fontSize: 10, fontWeight: 700,
                      backgroundColor: 'rgba(168,85,247,0.12)', color: '#A855F7',
                      border: '1px solid rgba(168,85,247,0.25)',
                    }}>POST-QUANTUM</span>
                  )}
                </div>
                {activeProfile.vnsName && (
                  <div style={{ fontSize: 15, color: '#FF6B35', fontWeight: 700, marginBottom: 6 }}>
                    {activeProfile.vnsName}.vaultfire
                  </div>
                )}
                <div style={{ fontSize: 11, color: '#52525b', fontFamily: 'monospace', wordBreak: 'break-all' as const, marginBottom: 12 }}>
                  {activeProfile.address}
                </div>
                <div style={{ marginBottom: 6 }}>
                  <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 6, letterSpacing: '0.06em' }}>CHAIN PRESENCE</div>
                  <ChainDots active={activeProfile.isRegistered} />
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                <ScoreRing score={activeProfile.trustScore} size={100} label="Street Cred" />
                <a href={`${EXPLORER_URLS.base}/address/${activeProfile.address}`}
                  target="_blank" rel="noopener noreferrer"
                  style={{
                    padding: '7px 14px', borderRadius: 8,
                    border: '1px solid rgba(255,255,255,0.1)',
                    backgroundColor: 'rgba(255,255,255,0.04)',
                    color: '#FF8C5A', fontSize: 11, fontWeight: 600, textDecoration: 'none',
                  }}>
                  View on BaseScan →
                </a>
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div style={{ display: 'flex', gap: 4, marginBottom: 16 }}>
            {tabs.map(t => (
              <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
                padding: '8px 16px', borderRadius: 8, border: 'none',
                backgroundColor: activeTab === t.id ? 'rgba(255,107,53,0.12)' : 'transparent',
                color: activeTab === t.id ? '#FF6B35' : '#71717a',
                fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>{t.label}</button>
            ))}
          </div>

          {/* Tab: Overview */}
          {activeTab === 'overview' && (
            <>
              {/* Hero: Street Cred Score */}
              <div style={{
                padding: 28, borderRadius: 16, marginBottom: 12,
                border: '1px solid rgba(255,107,53,0.15)',
                background: 'linear-gradient(135deg, rgba(255,107,53,0.06), rgba(255,107,53,0.02))',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 20 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#FF6B35', letterSpacing: '0.1em', marginBottom: 6 }}>STREET CRED SCORE</div>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                      <span style={{ fontSize: 64, fontWeight: 900, color: '#F4F4F5', lineHeight: 1, fontFamily: 'monospace' }}>{activeProfile.trustScore}</span>
                      <span style={{ fontSize: 20, color: '#52525b', fontWeight: 600 }}>/100</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{
                        fontSize: 18, fontWeight: 900, padding: '4px 12px', borderRadius: 8,
                        backgroundColor: activeProfile.trustScore >= 80 ? 'rgba(34,197,94,0.15)' : activeProfile.trustScore >= 60 ? 'rgba(234,179,8,0.15)' : activeProfile.trustScore >= 40 ? 'rgba(249,115,22,0.15)' : 'rgba(239,68,68,0.15)',
                        color: activeProfile.trustScore >= 80 ? '#22C55E' : activeProfile.trustScore >= 60 ? '#EAB308' : activeProfile.trustScore >= 40 ? '#F97316' : '#EF4444',
                        border: `1px solid ${activeProfile.trustScore >= 80 ? 'rgba(34,197,94,0.3)' : activeProfile.trustScore >= 60 ? 'rgba(234,179,8,0.3)' : activeProfile.trustScore >= 40 ? 'rgba(249,115,22,0.3)' : 'rgba(239,68,68,0.3)'}`,
                      }}>
                        {activeProfile.trustScore >= 80 ? 'A' : activeProfile.trustScore >= 60 ? 'B' : activeProfile.trustScore >= 40 ? 'C' : activeProfile.trustScore >= 20 ? 'D' : 'F'}
                      </span>
                      <span style={{ fontSize: 12, color: '#71717a' }}>
                        {activeProfile.trustScore >= 80 ? 'Platinum tier — top-tier agent' : activeProfile.trustScore >= 60 ? 'Gold tier — trusted agent' : activeProfile.trustScore >= 40 ? 'Silver tier — active agent' : activeProfile.trustScore >= 20 ? 'Bronze tier — new agent' : 'Unranked — no on-chain activity'}
                      </span>
                    </div>
                  </div>
                  <ScoreRing score={activeProfile.trustScore} size={100} label="Street Cred" />
                </div>
              </div>

              {/* Score Breakdown Bars */}
              <ScoreBreakdownBars profile={activeProfile} animate />

              {/* Secondary: On-Chain Rating */}
              <div style={{
                padding: 20, borderRadius: 14, marginBottom: 12,
                border: '1px solid rgba(59,130,246,0.15)',
                background: 'linear-gradient(135deg, rgba(59,130,246,0.04), transparent)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#3B82F6', letterSpacing: '0.1em', marginBottom: 4 }}>ON-CHAIN RATING</div>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
                      <span style={{ fontSize: 32, fontWeight: 800, color: '#F4F4F5', fontFamily: 'monospace' }}>
                        {activeProfile.averageRating > 0 ? activeProfile.averageRating.toLocaleString() : '—'}
                      </span>
                      <span style={{ fontSize: 14, color: '#52525b', fontWeight: 600 }}>/&nbsp;10,000</span>
                    </div>
                    <div style={{ fontSize: 12, color: '#71717a' }}>
                      Peer feedback score from ERC-8004 registry
                      {activeProfile.averageRating === 0 && ' · No ratings yet'}
                    </div>
                  </div>
                  {/* Rating bar */}
                  <div style={{ flex: 1, maxWidth: 200 }}>
                    <div style={{ height: 6, borderRadius: 3, backgroundColor: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
                      <div style={{
                        height: '100%', borderRadius: 3,
                        width: `${(activeProfile.averageRating / 10000) * 100}%`,
                        background: activeProfile.averageRating >= 8000 ? '#22C55E' : activeProfile.averageRating >= 6000 ? '#EAB308' : activeProfile.averageRating >= 4000 ? '#F97316' : '#3B82F6',
                        transition: 'width 0.6s ease',
                        boxShadow: '0 0 8px rgba(59,130,246,0.4)',
                      }} />
                    </div>
                    <div style={{ fontSize: 10, color: '#52525b', marginTop: 4, textAlign: 'right' }}>
                      {activeProfile.averageRating > 0 ? `${((activeProfile.averageRating / 10000) * 100).toFixed(1)}%` : 'No data'}
                    </div>
                  </div>
                </div>
              </div>

              {/* Bond Details */}
              <div style={{
                padding: 20, borderRadius: 14,
                border: '1px solid rgba(255,255,255,0.06)',
                backgroundColor: 'rgba(255,255,255,0.02)',
              }}>
                <h3 style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5', marginBottom: 12 }}>Bonds &amp; Validation</h3>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 12 }}>
                  {[
                    { label: 'BOND AMOUNT', value: `${activeProfile.bondAmount} ETH`, color: '#FF6B35' },
                    { label: 'ACCOUNTABILITY BONDS', value: String(activeProfile.bondCount), color: '#F4F4F5', note: 'LIVE — all 4 chains' },
                    { label: 'PARTNERSHIP BONDS', value: String(bonds.length || activeProfile.partnershipBondCount), color: '#10b981', note: 'Live on Base' },
                    { label: 'VALIDATIONS', value: String(activeProfile.validationCount), color: '#F4F4F5' },
                  ].map((item: { label: string; value: string; color: string; note?: string }, i) => (
                    <div key={i}>
                      <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>{item.label}</div>
                      <div style={{ fontSize: 16, fontWeight: 700, color: item.color }}>{item.value}</div>
                      {item.note && <div style={{ fontSize: 9, color: '#52525b', marginTop: 2 }}>{item.note}</div>}
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}

          {/* Tab: Partnership Bonds */}
          {activeTab === 'partnerships' && (
            <div>
              {bonds.length === 0 ? (
                <div style={{
                  textAlign: 'center', padding: '48px 0',
                  border: '1px solid rgba(255,255,255,0.06)',
                  borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
                }}>
                  <div style={{ fontSize: 36, marginBottom: 12, opacity: 0.5 }}>🤝</div>
                  <h3 style={{ fontSize: 15, fontWeight: 600, color: '#F4F4F5', marginBottom: 6 }}>No Partnership Bonds</h3>
                  <p style={{ fontSize: 13, color: '#71717a', maxWidth: 360, margin: '0 auto' }}>
                    This agent has no active partnership bonds. Partnership bonds prove verified working relationships between agents.
                  </p>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {bonds.map((bond, i) => {
                    const isParticipant1 = bond.participant1.toLowerCase() === activeProfile.address.toLowerCase();
                    const partnerAddress = isParticipant1 ? bond.participant2 : bond.participant1;
                    return (
                      <div key={i} style={{
                        padding: 18, borderRadius: 14,
                        border: bond.active ? '1px solid rgba(16,185,129,0.15)' : '1px solid rgba(255,255,255,0.06)',
                        backgroundColor: bond.active ? 'rgba(16,185,129,0.03)' : 'rgba(255,255,255,0.02)',
                      }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 10, marginBottom: 12 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <div style={{
                              width: 8, height: 8, borderRadius: '50%',
                              backgroundColor: bond.active ? '#10b981' : '#52525b',
                              boxShadow: bond.active ? '0 0 6px rgba(16,185,129,0.5)' : 'none',
                            }} />
                            <span style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5' }}>
                              Bond #{bond.bondId}
                            </span>
                            <TierBadge tier={bond.tier} />
                          </div>
                          <span style={{ fontSize: 11, color: '#52525b' }}>{bond.createdAt}</span>
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                          <div>
                            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>PARTNER</div>
                            <div style={{ fontSize: 12, color: '#a1a1aa', fontFamily: 'monospace', wordBreak: 'break-all' as const }}>
                              {partnerAddress.slice(0, 10)}...{partnerAddress.slice(-8)}
                            </div>
                          </div>
                          <div>
                            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>STAKED</div>
                            <div style={{ fontSize: 14, fontWeight: 700, color: '#FF6B35' }}>{bond.amount} ETH</div>
                          </div>
                          <div>
                            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>TYPE</div>
                            <div style={{ fontSize: 12, color: '#a1a1aa' }}>{bond.partnershipType}</div>
                          </div>
                          <div>
                            <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>STATUS</div>
                            <div style={{ fontSize: 12, color: bond.active ? '#10b981' : '#71717a', fontWeight: 600 }}>
                              {bond.active ? 'Active' : 'Inactive'}
                            </div>
                          </div>
                        </div>
                        <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.04)' }}>
                          <a href={`${EXPLORER_URLS.base}/address/${PARTNERSHIP_BONDS.base}`}
                            target="_blank" rel="noopener noreferrer"
                            style={{ fontSize: 12, color: '#FF8C5A', fontWeight: 600, textDecoration: 'none' }}>
                            View Contract on BaseScan →
                          </a>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* Tab: Contracts (in search result view) */}
          {activeTab === 'contracts' && (
            <div>
              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                marginBottom: 16, flexWrap: 'wrap', gap: 8,
              }}>
                <h3 style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5' }}>
                  63+ Verified Contracts Across 4 Chains
                </h3>
                <div style={{ display: 'flex', gap: 6 }}>
                  {CHAIN_CONFIGS.map(ch => (
                    <span key={ch.label} style={{
                      fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 6,
                      color: ch.color,
                      backgroundColor: `${ch.color}15`,
                      border: `1px solid ${ch.color}30`,
                    }}>{ch.label}</span>
                  ))}
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {allContracts.map((c, i) => (
                  <a key={i} href={`${c.explorer}/address/${c.address}`}
                    target="_blank" rel="noopener noreferrer"
                    style={{
                      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      padding: '12px 14px', borderRadius: 10,
                      border: '1px solid rgba(255,255,255,0.04)',
                      backgroundColor: 'rgba(255,255,255,0.015)',
                      textDecoration: 'none',
                      opacity: 0,
                      animation: `fadeSlideIn 0.3s ease ${i * 25}ms forwards`,
                    }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5' }}>{c.name}</div>
                      <div style={{ fontSize: 11, color: '#52525b', fontFamily: 'monospace' }}>
                        {c.address.slice(0, 10)}...{c.address.slice(-8)}
                      </div>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{
                        fontSize: 10, fontWeight: 600,
                        color: c.chainLabel === 'Base' ? '#3B82F6' : c.chainLabel === 'Avalanche' ? '#EF4444' : c.chainLabel === 'Arbitrum' ? '#12AAFF' : c.chainLabel === 'Polygon' ? '#8247E5' : '#627EEA',
                        padding: '2px 6px', borderRadius: 4,
                        backgroundColor: c.chainLabel === 'Base' ? 'rgba(59,130,246,0.1)' : c.chainLabel === 'Avalanche' ? 'rgba(239,68,68,0.1)' : c.chainLabel === 'Arbitrum' ? 'rgba(18,170,255,0.1)' : c.chainLabel === 'Polygon' ? 'rgba(130,71,229,0.1)' : 'rgba(98,126,234,0.1)',
                      }}>{c.chainLabel}</span>
                      <span style={{ fontSize: 12, color: '#52525b' }}>→</span>
                    </div>
                  </a>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {searched && !profile && !loading && (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <div style={{ fontSize: 40, marginBottom: 16 }}>🔍</div>
          <h3 style={{ fontSize: 16, fontWeight: 600, color: '#F4F4F5', marginBottom: 8 }}>Agent not found</h3>
          <p style={{ fontSize: 13, color: '#71717a' }}>
            No registered agent at that address. <button onClick={() => onNavigate('register')} style={{ color: '#FF6B35', background: 'none', border: 'none', cursor: 'pointer', fontWeight: 600 }}>Register one →</button>
          </p>
        </div>
      )}

      {/* Verified Contracts section — shown always below (when no live search result) */}
      {!showingLiveResult && (
        <div style={{ marginTop: 36 }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            marginBottom: 8, flexWrap: 'wrap', gap: 10,
          }}>
            <div>
              <h2 style={{ fontSize: 20, fontWeight: 700, color: '#F4F4F5', marginBottom: 4 }}>
                63+ Verified Contracts Across 4 Chains
              </h2>
              <p style={{ fontSize: 13, color: '#71717a' }}>
                All Vaultfire Protocol contracts, verified on-chain. Click any address to view on the block explorer.
              </p>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {CHAIN_CONFIGS.map(ch => (
                <span key={ch.label} style={{
                  fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 6,
                  color: ch.color,
                  backgroundColor: `${ch.color}15`,
                  border: `1px solid ${ch.color}30`,
                }}>{ch.label}</span>
              ))}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 16 }}>
            {allContracts.map((c, i) => (
              <a key={i} href={`${c.explorer}/address/${c.address}`}
                target="_blank" rel="noopener noreferrer"
                style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '12px 14px', borderRadius: 10,
                  border: '1px solid rgba(255,255,255,0.04)',
                  backgroundColor: 'rgba(255,255,255,0.015)',
                  textDecoration: 'none',
                  opacity: 0,
                  animation: `fadeSlideIn 0.3s ease ${i * 18}ms forwards`,
                }}>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5' }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: '#52525b', fontFamily: 'monospace' }}>
                    {c.address.slice(0, 10)}...{c.address.slice(-8)}
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    fontSize: 10, fontWeight: 600,
                    color: c.chainLabel === 'Base' ? '#3B82F6' : c.chainLabel === 'Avalanche' ? '#EF4444' : c.chainLabel === 'Arbitrum' ? '#12AAFF' : c.chainLabel === 'Polygon' ? '#8247E5' : '#627EEA',
                    padding: '2px 6px', borderRadius: 4,
                    backgroundColor: c.chainLabel === 'Base' ? 'rgba(59,130,246,0.1)' : c.chainLabel === 'Avalanche' ? 'rgba(239,68,68,0.1)' : c.chainLabel === 'Arbitrum' ? 'rgba(18,170,255,0.1)' : c.chainLabel === 'Polygon' ? 'rgba(130,71,229,0.1)' : 'rgba(98,126,234,0.1)',
                  }}>{c.chainLabel}</span>
                  <span style={{ fontSize: 12, color: '#52525b' }}>→</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      )}

      {/* Trust Index — transparent directory */}
      <TrustIndex />

      {/* ── 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>

      {/* Keyframe animations injected via style tag */}
      <style>{`
        @keyframes fadeSlideIn {
          from { opacity: 0; transform: translateY(6px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  );
}
