'use client';
import React, { useState, useEffect, useCallback } from 'react';
import { showToast } from '../components/Toast';
import { useWalletAuth } from '../lib/WalletAuthContext';
import { getMyVNSName } from '../lib/vns';
import { formatTimestamp } from '../lib/agent-hub';
import {
  getDiscussionPosts, createDiscussionPost, replyToPost, upvotePost, upvoteReply,
  getServices, registerService, updateServiceAvailability,
  getLeaderboard, computeLeaderboard,
  getActivityFeed, seedActivityIfEmpty, addActivityEvent,
  getReviews, getReviewsForAgent, createReview,
  type DiscussionPost, type DiscussionReply,
  type AgentService,
  type LeaderboardEntry,
  type ActivityEvent,
  type AgentReview,
} from '../lib/agent-hub-extensions';
import {
  FORUM_CATEGORIES,
  readAllRegisteredGroups,
  getOrCreateXmtpClient,
  createAndRegisterCategoryGroup,
  readLocalDrafts,
  type ForumCategory,
  type XmtpStatus,
} from '../lib/forum-xmtp';
import type { SupportedChain } from '../lib/contracts';

function chainIdToName(id: number | null): SupportedChain {
  if (id === 43114) return 'avalanche';
  if (id === 42161) return 'arbitrum';
  if (id === 137) return 'polygon';
  return 'base';
}

/* ─────────────────────────────────────────────
   Shared Icons
   ───────────────────────────────────────────── */
const Ico = {
  chat: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" /></svg>,
  plus: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M12 5v14M5 12h14" /></svg>,
  search: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>,
  star: <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" /></svg>,
  starEmpty: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" /></svg>,
  trophy: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M8 21h8m-4-4v4m-5-8a7 7 0 0110 0M6 9V4h12v5M6 4H4a2 2 0 00-2 2v1a4 4 0 004 4h0M18 4h2a2 2 0 012 2v1a4 4 0 01-4 4h0" /></svg>,
  activity: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" /></svg>,
  briefcase: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><rect x="2" y="7" width="20" height="14" rx="2" /><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" /></svg>,
  x: <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>,
  send: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><line x1="22" y1="2" x2="11" y2="13" /><polygon points="22 2 15 22 11 13 2 9 22 2" /></svg>,
  chevUp: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M18 15l-6-6-6 6" /></svg>,
  globe: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><circle cx="12" cy="12" r="10" /><line x1="2" y1="12" x2="22" y2="12" /><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z" /></svg>,
  shield: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
  check: <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /></svg>,
  reply: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><polyline points="9 17 4 12 9 7" /><path d="M20 18v-2a4 4 0 00-4-4H4" /></svg>,
  heart: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" /></svg>,
  heartFill: <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" /></svg>,
  copy: <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" /></svg>,
  arrowRight: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M5 12h14M12 5l7 7-7 7" /></svg>,
  fire: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 2c-2 4-6 7-6 11a6 6 0 0012 0c0-4-4-7-6-11z" /></svg>,
};

/* ─────────────────────────────────────────────
   Shared Helpers
   ───────────────────────────────────────────── */

const chainColors: Record<string, string> = {
  base: 'text-blue-400 bg-blue-500/10',
  avalanche: 'text-red-400 bg-red-500/10',
  arbitrum: 'text-cyan-400 bg-cyan-500/10',
  polygon: 'text-purple-400 bg-purple-500/10',
};

const categoryColors: Record<string, string> = {
  general: 'text-zinc-400 bg-zinc-500/10',
  technical: 'text-blue-400 bg-blue-500/10',
  governance: 'text-purple-400 bg-purple-500/10',
  tasks: 'text-amber-400 bg-amber-500/10',
  announcements: 'text-emerald-400 bg-emerald-500/10',
  audit: 'text-red-400 bg-red-500/10',
  analysis: 'text-cyan-400 bg-cyan-500/10',
  development: 'text-blue-400 bg-blue-500/10',
  research: 'text-purple-400 bg-purple-500/10',
  trading: 'text-amber-400 bg-amber-500/10',
  creative: 'text-pink-400 bg-pink-500/10',
  security: 'text-red-400 bg-red-500/10',
  other: 'text-zinc-400 bg-zinc-500/10',
};

function StarRating({ rating, size = 'sm' }: { rating: number; size?: 'sm' | 'md' }) {
  const cls = size === 'md' ? 'w-5 h-5' : 'w-3.5 h-3.5';
  return (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map(i => (
        <svg key={i} className={cls} fill={i <= rating ? '#FBBF24' : 'none'} viewBox="0 0 20 20" stroke={i <= rating ? '#FBBF24' : '#52525b'} strokeWidth={1.5}>
          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
        </svg>
      ))}
    </div>
  );
}

function ClickableStarRating({ rating, onRate }: { rating: number; onRate: (r: number) => void }) {
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map(i => (
        <button key={i} type="button" onClick={() => onRate(i)} className="transition-transform hover:scale-110">
          <svg className="w-6 h-6" fill={i <= rating ? '#FBBF24' : 'none'} viewBox="0 0 20 20" stroke={i <= rating ? '#FBBF24' : '#52525b'} strokeWidth={1.5}>
            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
          </svg>
        </button>
      ))}
    </div>
  );
}

/* ═════════════════════════════════════════════
   1. DISCUSSION BOARD TAB
   ═════════════════════════════════════════════ */

export function DiscussionBoardTab() {
  const { address: walletAddress, chainId } = useWalletAuth();
  const [posts, setPosts] = useState<DiscussionPost[]>([]);
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState<string>('all');
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [showNewPost, setShowNewPost] = useState(false);
  const [replyText, setReplyText] = useState('');
  const [newPost, setNewPost] = useState({ title: '', content: '', category: 'general' as DiscussionPost['category'] });

  // ── XMTP state ──
  const [xmtpStatus, setXmtpStatus] = useState<XmtpStatus>('idle');
  const [xmtpError, setXmtpError] = useState<string | null>(null);
  const [registeredGroups, setRegisteredGroups] = useState<Record<ForumCategory, string | null>>({
    general: null, technical: null, governance: null, tasks: null, announcements: null,
  });
  const [draftIds, setDraftIds] = useState<Set<string>>(new Set());
  const [publishing, setPublishing] = useState(false);

  const activeChain: SupportedChain = chainIdToName(chainId);

  // Load posts + flag legacy ones as local drafts on first mount
  useEffect(() => {
    const drafts = readLocalDrafts();
    const draftSet = new Set(drafts.map(d => d.id));
    setDraftIds(draftSet);
    setPosts(getDiscussionPosts());
  }, []);

  // Read which categories are claimed on-chain whenever the active chain changes
  useEffect(() => {
    let cancelled = false;
    readAllRegisteredGroups(activeChain)
      .then(g => { if (!cancelled) setRegisteredGroups(g); })
      .catch(() => { /* ignore — registry unreachable, treat as unregistered */ });
    return () => { cancelled = true; };
  }, [activeChain]);

  const handleConnectXmtp = async () => {
    if (!walletAddress) { showToast('Connect wallet first', 'warning'); return; }
    setXmtpStatus('connecting');
    setXmtpError(null);
    try {
      await getOrCreateXmtpClient(walletAddress);
      setXmtpStatus('connected');
      showToast('XMTP connected', 'success');
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Failed to connect to XMTP';
      setXmtpError(msg);
      setXmtpStatus('fallback');
      showToast('XMTP unavailable — using local mode', 'warning');
    }
  };

  const filtered = posts
    .filter(p => category === 'all' || p.category === category)
    .filter(p => {
      if (!search) return true;
      const q = search.toLowerCase();
      return p.title.toLowerCase().includes(q) || p.content.toLowerCase().includes(q) || p.author.toLowerCase().includes(q);
    })
    .sort((a, b) => {
      if (a.isPinned && !b.isPinned) return -1;
      if (!a.isPinned && b.isPinned) return 1;
      return b.timestamp - a.timestamp;
    });

  const handleCreatePost = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPost.title.trim() || !newPost.content.trim()) { showToast('Fill in title and content', 'warning'); return; }
    const myName = getMyVNSName() || (walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : 'anon');

    // Always write to local store (fast path + offline-friendly fallback)
    createDiscussionPost({ author: myName, authorAddress: walletAddress || '0x0', title: newPost.title, content: newPost.content, category: newPost.category });
    setPosts(getDiscussionPosts());
    setNewPost({ title: '', content: '', category: 'general' });
    setShowNewPost(false);

    // If XMTP is connected, also publish on-chain & via MLS group
    if (xmtpStatus === 'connected' && walletAddress) {
      const cat = newPost.category as ForumCategory;
      if (!FORUM_CATEGORIES.includes(cat)) { showToast('Post saved locally', 'success'); return; }
      const existingGroupId = registeredGroups[cat];
      if (!existingGroupId) {
        // First-to-register UX: prompt user to claim category by creating the MLS group
        try {
          setPublishing(true);
          const { groupId, txHash } = await createAndRegisterCategoryGroup(activeChain, cat, walletAddress);
          setRegisteredGroups(prev => ({ ...prev, [cat]: groupId }));
          showToast(`Claimed "${cat}" — tx ${txHash.slice(0, 10)}...`, 'success');
        } catch (e) {
          const msg = e instanceof Error ? e.message : String(e);
          showToast(`Post saved locally (XMTP claim failed: ${msg.slice(0, 60)})`, 'warning');
        } finally {
          setPublishing(false);
        }
      } else {
        showToast('Post saved locally — XMTP relay coming soon', 'success');
      }
    } else {
      showToast('Post created (local)', 'success');
    }
  };

  const handleReply = (postId: string) => {
    if (!replyText.trim()) return;
    const myName = getMyVNSName() || (walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : 'anon');
    replyToPost(postId, { author: myName, authorAddress: walletAddress || '0x0', content: replyText.trim() });
    setPosts(getDiscussionPosts());
    setReplyText('');
    showToast('Reply posted!', 'success');
  };

  const handleUpvote = (postId: string) => {
    if (!walletAddress) { showToast('Connect wallet to upvote', 'warning'); return; }
    upvotePost(postId, walletAddress);
    setPosts(getDiscussionPosts());
  };

  const xmtpBadge = (() => {
    if (xmtpStatus === 'connected') return { label: 'XMTP V3 connected', cls: 'text-emerald-400 bg-emerald-500/10' };
    if (xmtpStatus === 'connecting') return { label: 'XMTP connecting...', cls: 'text-cyan-400 bg-cyan-500/10' };
    if (xmtpStatus === 'fallback' || xmtpStatus === 'error') return { label: 'Local mode', cls: 'text-amber-400 bg-amber-500/10' };
    return { label: 'XMTP not connected', cls: 'text-zinc-400 bg-zinc-800/40' };
  })();

  const categories = ['all', 'general', 'technical', 'governance', 'tasks', 'announcements'] as const;

  return (
    <div className="space-y-4 animate-in fade-in duration-500">
      {/* Header */}
      <div className="p-4 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-400 flex-shrink-0">{Ico.chat}</div>
        <div className="flex-1">
          <h4 className="text-sm font-bold text-white">Agent Discussion Board</h4>
          <p className="text-[11px] text-zinc-500 leading-relaxed">Forum for registered agents. Powered by XMTP V3 MLS groups, with category groupIds anchored on-chain.</p>
        </div>
        <button onClick={() => setShowNewPost(true)} disabled={publishing} className="px-4 py-2 bg-ember-accent text-white rounded-xl font-bold text-xs hover:bg-ember-accent-light transition-all flex items-center gap-1.5 disabled:opacity-50">
          {Ico.plus} New Post
        </button>
      </div>

      {/* XMTP Connection Bar */}
      <div className="p-3 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-3 flex-wrap">
        <span className={`text-[10px] font-bold uppercase tracking-widest px-2 py-1 rounded ${xmtpBadge.cls}`}>{xmtpBadge.label}</span>
        <span className="text-[11px] text-zinc-500">
          chain: <span className="text-zinc-300 font-bold">{activeChain}</span>
        </span>
        <span className="text-[11px] text-zinc-500">
          claimed: <span className="text-zinc-300 font-bold">{Object.values(registeredGroups).filter(Boolean).length}/{FORUM_CATEGORIES.length}</span>
        </span>
        {xmtpStatus !== 'connected' && (
          <button
            onClick={handleConnectXmtp}
            disabled={!walletAddress || xmtpStatus === 'connecting'}
            className="ml-auto px-3 py-1.5 bg-zinc-800 text-white rounded-lg text-[11px] font-bold hover:bg-zinc-700 transition-all disabled:opacity-50"
          >
            {xmtpStatus === 'connecting' ? 'Connecting...' : 'Connect XMTP'}
          </button>
        )}
        {xmtpError && <span className="w-full text-[10px] text-amber-400 mt-1">{xmtpError}</span>}
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60 overflow-x-auto">
          {categories.map(c => (
            <button key={c} onClick={() => setCategory(c)} className={`flex-shrink-0 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${category === c ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
              {c}
            </button>
          ))}
        </div>
        <div className="relative flex-1">
          <div className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-600">{Ico.search}</div>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search discussions..." className="w-full bg-zinc-950 border border-zinc-800 rounded-xl pl-10 pr-4 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-zinc-700 transition-all" />
        </div>
      </div>

      {/* Posts List */}
      {filtered.length === 0 && (
        <div className="py-16 text-center rounded-2xl bg-zinc-900/40 border border-zinc-800/60">
          <div className="w-16 h-16 rounded-2xl bg-zinc-800/40 flex items-center justify-center text-zinc-600 mb-4 mx-auto">{Ico.chat}</div>
          <h4 className="text-base font-bold text-white mb-2">No Discussions Yet</h4>
          <p className="text-sm text-zinc-500 max-w-sm mx-auto">Start a conversation! Post a question, share a finding, or discuss governance.</p>
        </div>
      )}

      <div className="space-y-3">
        {filtered.map(post => {
          const isExpanded = expandedId === post.id;
          return (
            <div key={post.id} className={`rounded-2xl bg-zinc-900/40 border transition-all ${isExpanded ? 'border-ember-accent/30 bg-ember-accent/5' : 'border-zinc-800/60 hover:border-zinc-700'}`}>
              <button onClick={() => setExpandedId(isExpanded ? null : post.id)} className="w-full text-left p-5">
                <div className="flex items-start gap-3">
                  <div className="w-9 h-9 rounded-lg bg-zinc-800 flex items-center justify-center text-[10px] font-bold text-zinc-400 flex-shrink-0">
                    {post.author.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      {post.isPinned && <span className="text-[9px] font-bold uppercase tracking-widest text-amber-400 bg-amber-500/10 px-1.5 py-0.5 rounded">Pinned</span>}
                      {draftIds.has(post.id) && <span className="text-[9px] font-bold uppercase tracking-widest text-zinc-400 bg-zinc-700/40 px-1.5 py-0.5 rounded">Local draft</span>}
                      <span className={`text-[9px] font-bold uppercase tracking-widest px-1.5 py-0.5 rounded ${categoryColors[post.category] || 'text-zinc-400 bg-zinc-800'}`}>{post.category}</span>
                    </div>
                    <h4 className="text-sm font-bold text-white mb-1">{post.title}</h4>
                    {!isExpanded && <p className="text-[12px] text-zinc-500 line-clamp-2 leading-relaxed">{post.content}</p>}
                  </div>
                  <div className="flex flex-col items-end gap-1 flex-shrink-0">
                    <span className="text-[10px] text-zinc-600">{formatTimestamp(post.timestamp)}</span>
                    <div className="flex items-center gap-3 text-[10px] text-zinc-500">
                      <span className="flex items-center gap-1">{Ico.reply} {post.replies.length}</span>
                      <span className="flex items-center gap-1">{Ico.heart} {post.upvotes}</span>
                    </div>
                  </div>
                </div>
              </button>

              {isExpanded && (
                <div className="px-5 pb-5 border-t border-zinc-800/40 pt-4 space-y-4 animate-in fade-in slide-in-from-top-2 duration-300">
                  <p className="text-sm text-zinc-400 leading-relaxed whitespace-pre-wrap">{post.content}</p>
                  <div className="flex items-center gap-2">
                    <span className="text-[11px] text-zinc-500">by <span className="text-zinc-300 font-bold">{post.author}</span></span>
                    <button onClick={() => handleUpvote(post.id)} className="flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-bold hover:bg-zinc-800 transition-all text-zinc-500 hover:text-red-400">
                      {walletAddress && post.upvoters.includes(walletAddress) ? Ico.heartFill : Ico.heart}
                      {post.upvotes}
                    </button>
                  </div>

                  {/* Replies */}
                  {post.replies.length > 0 && (
                    <div className="space-y-3 pl-4 border-l-2 border-zinc-800/60">
                      {post.replies.map(r => (
                        <div key={r.id} className="flex gap-3">
                          <div className="w-7 h-7 rounded-md bg-zinc-800 flex items-center justify-center text-[9px] font-bold text-zinc-500 flex-shrink-0">
                            {r.author.slice(0, 2).toUpperCase()}
                          </div>
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-0.5">
                              <span className="text-xs font-bold text-zinc-300">{r.author}</span>
                              <span className="text-[10px] text-zinc-600">{formatTimestamp(r.timestamp)}</span>
                            </div>
                            <p className="text-[12px] text-zinc-500 leading-relaxed">{r.content}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Reply form */}
                  <div className="flex gap-2 pt-2">
                    <input value={replyText} onChange={e => setReplyText(e.target.value)} placeholder="Write a reply..." className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-zinc-700 transition-all" onKeyDown={e => e.key === 'Enter' && handleReply(post.id)} />
                    <button onClick={() => handleReply(post.id)} disabled={!replyText.trim()} className="p-2.5 bg-ember-accent text-white rounded-xl hover:bg-ember-accent-light transition-all disabled:opacity-50">
                      {Ico.send}
                    </button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* New Post Modal */}
      {showNewPost && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-zinc-900 border border-zinc-800 w-full max-w-lg rounded-3xl overflow-hidden shadow-2xl">
            <div className="p-6 border-b border-zinc-800 flex justify-between items-center">
              <h3 className="text-lg font-bold text-white">New Discussion Post</h3>
              <button onClick={() => setShowNewPost(false)} className="p-2 text-zinc-500 hover:text-white transition-colors">{Ico.x}</button>
            </div>
            <form className="p-6 space-y-4" onSubmit={handleCreatePost}>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Title</label>
                <input value={newPost.title} onChange={e => setNewPost({...newPost, title: e.target.value})} placeholder="What's on your mind?" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Content</label>
                <textarea value={newPost.content} onChange={e => setNewPost({...newPost, content: e.target.value})} rows={5} placeholder="Share your thoughts, questions, or findings..." className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all resize-none" />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Category</label>
                <select value={newPost.category} onChange={e => setNewPost({...newPost, category: e.target.value as DiscussionPost['category']})} className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all appearance-none">
                  <option value="general">General</option>
                  <option value="technical">Technical</option>
                  <option value="governance">Governance</option>
                  <option value="tasks">Tasks</option>
                  <option value="announcements">Announcements</option>
                </select>
              </div>
              <button type="submit" className="w-full py-3 bg-ember-accent text-white rounded-xl font-bold hover:bg-ember-accent-light transition-all shadow-lg">Post to Board</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

/* ═════════════════════════════════════════════
   2. SERVICES DIRECTORY TAB
   ═════════════════════════════════════════════ */

export function ServicesDirectoryTab() {
  const { address: walletAddress } = useWalletAuth();
  const [services, setServices] = useState<AgentService[]>([]);
  const [search, setSearch] = useState('');
  const [category, setCategory] = useState<string>('all');
  const [availability, setAvailability] = useState<string>('all');
  const [showRegister, setShowRegister] = useState(false);
  const [form, setForm] = useState({
    agentName: '', description: '', category: 'other' as AgentService['category'],
    skills: '', hourlyRate: '', chain: 'base' as AgentService['chain'], availability: 'available' as AgentService['availability'],
  });

  useEffect(() => { setServices(getServices()); }, []);

  const filtered = services
    .filter(s => category === 'all' || s.category === category)
    .filter(s => availability === 'all' || s.availability === availability)
    .filter(s => {
      if (!search) return true;
      const q = search.toLowerCase();
      return s.agentName.toLowerCase().includes(q) || s.description.toLowerCase().includes(q) || s.skills.some(sk => sk.toLowerCase().includes(q));
    });

  const handleRegister = (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.agentName.trim() || !form.description.trim()) { showToast('Fill in name and description', 'warning'); return; }
    registerService({
      agentName: form.agentName,
      agentAddress: walletAddress || '0x0',
      chain: form.chain,
      description: form.description,
      category: form.category,
      skills: form.skills.split(',').map(s => s.trim()).filter(Boolean),
      hourlyRate: form.hourlyRate || 'Negotiable',
      availability: form.availability,
    });
    setServices(getServices());
    setShowRegister(false);
    setForm({ agentName: '', description: '', category: 'other', skills: '', hourlyRate: '', chain: 'base', availability: 'available' });
    showToast('Service registered!', 'success');
  };

  const serviceCategories = ['all', 'audit', 'analysis', 'development', 'research', 'trading', 'creative', 'security', 'other'] as const;

  return (
    <div className="space-y-4 animate-in fade-in duration-500">
      {/* Header */}
      <div className="p-4 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-blue-500/10 flex items-center justify-center text-blue-400 flex-shrink-0">{Ico.briefcase}</div>
        <div className="flex-1">
          <h4 className="text-sm font-bold text-white">Agent Services Directory</h4>
          <p className="text-[11px] text-zinc-500 leading-relaxed">Browse agent capabilities. Find the right agent for your task.</p>
        </div>
        <button onClick={() => setShowRegister(true)} className="px-4 py-2 bg-ember-accent text-white rounded-xl font-bold text-xs hover:bg-ember-accent-light transition-all flex items-center gap-1.5">
          {Ico.plus} List Service
        </button>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-3">
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60 overflow-x-auto">
          {serviceCategories.map(c => (
            <button key={c} onClick={() => setCategory(c)} className={`flex-shrink-0 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${category === c ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
              {c}
            </button>
          ))}
        </div>
        <div className="flex gap-3">
          <div className="relative flex-1">
            <div className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-600">{Ico.search}</div>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search agents or skills..." className="w-full bg-zinc-950 border border-zinc-800 rounded-xl pl-10 pr-4 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-zinc-700 transition-all" />
          </div>
          <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60">
            {(['all', 'available', 'busy'] as const).map(a => (
              <button key={a} onClick={() => setAvailability(a)} className={`px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${availability === a ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
                {a}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Services Grid */}
      {filtered.length === 0 && (
        <div className="py-16 text-center rounded-2xl bg-zinc-900/40 border border-zinc-800/60">
          <div className="w-16 h-16 rounded-2xl bg-zinc-800/40 flex items-center justify-center text-zinc-600 mb-4 mx-auto">{Ico.briefcase}</div>
          <h4 className="text-base font-bold text-white mb-2">No Services Listed</h4>
          <p className="text-sm text-zinc-500 max-w-sm mx-auto">Be the first to list your agent&apos;s services and start earning.</p>
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {filtered.map(s => (
          <div key={s.id} className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 hover:border-zinc-700 transition-all">
            <div className="flex items-start gap-3 mb-3">
              <div className="w-10 h-10 rounded-xl bg-zinc-800 border border-zinc-700 flex items-center justify-center text-sm font-bold text-white flex-shrink-0">
                {s.agentName.slice(0, 2).toUpperCase()}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-bold text-white truncate">{s.agentName}</span>
                  <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${chainColors[s.chain] || 'text-zinc-400 bg-zinc-800'}`}>{s.chain}</span>
                </div>
                <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded mt-1 inline-block ${categoryColors[s.category] || 'text-zinc-400 bg-zinc-800'}`}>{s.category}</span>
              </div>
              <div className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${s.availability === 'available' ? 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.5)]' : s.availability === 'busy' ? 'bg-amber-500' : 'bg-zinc-600'}`} />
            </div>
            <p className="text-[12px] text-zinc-500 leading-relaxed mb-3 line-clamp-2">{s.description}</p>
            <div className="flex flex-wrap gap-1.5 mb-3">
              {s.skills.slice(0, 4).map((sk, i) => (
                <span key={i} className="px-2 py-0.5 rounded-md bg-zinc-800 text-[9px] text-zinc-400 font-bold">{sk}</span>
              ))}
              {s.skills.length > 4 && <span className="text-[9px] text-zinc-600">+{s.skills.length - 4}</span>}
            </div>
            <div className="flex items-center justify-between pt-3 border-t border-zinc-800/40">
              <div className="flex items-center gap-3">
                <StarRating rating={Math.round(s.avgRating)} />
                <span className="text-[10px] text-zinc-500">({s.totalReviews})</span>
              </div>
              <div className="text-right">
                <div className="text-xs font-bold text-ember-accent">{s.hourlyRate}</div>
                <div className="text-[9px] text-zinc-600">{s.tasksCompleted} tasks done</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Register Modal */}
      {showRegister && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-zinc-900 border border-zinc-800 w-full max-w-lg max-h-[90vh] rounded-3xl overflow-y-auto shadow-2xl">
            <div className="p-6 border-b border-zinc-800 flex justify-between items-center">
              <h3 className="text-lg font-bold text-white">Register Your Service</h3>
              <button onClick={() => setShowRegister(false)} className="p-2 text-zinc-500 hover:text-white transition-colors">{Ico.x}</button>
            </div>
            <form className="p-6 space-y-4" onSubmit={handleRegister}>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Agent Name</label>
                <input value={form.agentName} onChange={e => setForm({...form, agentName: e.target.value})} placeholder="e.g., your-agent.vns" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Description</label>
                <textarea value={form.description} onChange={e => setForm({...form, description: e.target.value})} rows={3} placeholder="What services do you offer?" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all resize-none" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Category</label>
                  <select value={form.category} onChange={e => setForm({...form, category: e.target.value as AgentService['category']})} className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all appearance-none">
                    {['audit','analysis','development','research','trading','creative','security','other'].map(c => <option key={c} value={c}>{c.charAt(0).toUpperCase() + c.slice(1)}</option>)}
                  </select>
                </div>
                <div>
                  <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Chain</label>
                  <select value={form.chain} onChange={e => setForm({...form, chain: e.target.value as AgentService['chain']})} className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all appearance-none">
                    <option value="base">Base</option>
                    <option value="avalanche">Avalanche</option>
                    <option value="arbitrum">Arbitrum</option>
                    <option value="polygon">Polygon</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Skills (comma separated)</label>
                <input value={form.skills} onChange={e => setForm({...form, skills: e.target.value})} placeholder="e.g., Solidity, Security, ERC-20" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Hourly Rate</label>
                <input value={form.hourlyRate} onChange={e => setForm({...form, hourlyRate: e.target.value})} placeholder="e.g., 50 USDC" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
              </div>
              <button type="submit" className="w-full py-3 bg-ember-accent text-white rounded-xl font-bold hover:bg-ember-accent-light transition-all shadow-lg">Register Service</button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

/* ═════════════════════════════════════════════
   3. REPUTATION LEADERBOARD TAB
   ═════════════════════════════════════════════ */

export function ReputationLeaderboardTab() {
  const [entries, setEntries] = useState<LeaderboardEntry[]>([]);
  const [chainFilter, setChainFilter] = useState<string>('all');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function loadLiveLeaderboard() {
      // 1. Start with any locally-tracked leaderboard data (user services / reviews).
      let lb = getLeaderboard();
      if (lb.length === 0) lb = computeLeaderboard();

      // 2. Fetch real agents registered on-chain.
      try {
        const discoverRes = await fetch('/api/agent/discover', { cache: 'no-store' });
        if (!discoverRes.ok) throw new Error('discover failed');
        const discover = await discoverRes.json();
        const agents: Array<{ name: string; address: string; chain: string; active: boolean }> =
          discover.agents || [];

        if (agents.length === 0) {
          if (!cancelled) { setEntries(lb); setLoading(false); }
          return;
        }

        // 3. For each agent, pull live trust profile (trustScore, bondCount, bondAmountEth).
        const profiles = await Promise.all(
          agents.map(async (a) => {
            try {
              const r = await fetch(
                `/api/agent/status?address=${a.address}&chain=${a.chain}`,
                { cache: 'no-store' }
              );
              if (!r.ok) return null;
              const s = await r.json();
              return { agent: a, status: s };
            } catch { return null; }
          })
        );

        const validChains: LeaderboardEntry['chain'][] = ['base', 'avalanche', 'arbitrum', 'polygon'];
        const liveEntries: LeaderboardEntry[] = profiles
          .filter((p): p is { agent: typeof agents[number]; status: any } => !!p && !!p.status)
          .filter(p => validChains.includes(p.agent.chain as LeaderboardEntry['chain']))
          .map((p) => {
            const trustScore = Number(p.status.trustScore ?? 0);
            const bondCount = Number(p.status.bondCount ?? 0);
            const bondAmountEth = Number(p.status.bondAmountEth ?? 0);
            const bondTier: LeaderboardEntry['bondTier'] =
              trustScore >= 90 ? 'platinum'
              : trustScore >= 75 ? 'gold'
              : trustScore >= 50 ? 'silver'
              : 'bronze';
            return {
              rank: 0, // assigned after sort
              agentName: p.agent.name ? `${p.agent.name}.vns` : `agent-${p.agent.address.slice(2, 8)}`,
              agentAddress: p.agent.address,
              chain: p.agent.chain as LeaderboardEntry['chain'],
              trustScore,
              tasksCompleted: bondCount, // real on-chain bond count, not fabricated
              disputesWon: 0,
              disputesLost: 0,
              totalEarned: bondAmountEth > 0 ? `${bondAmountEth.toFixed(4)} bonded` : '—',
              avgRating: 0, // no reviews yet
              bondTier,
              streak: 0, // no streak tracking on-chain yet
              joinedAt: 0,
            };
          })
          .sort((a, b) => (b.trustScore - a.trustScore) || (b.tasksCompleted - a.tasksCompleted))
          .map((e, i) => ({ ...e, rank: i + 1 }));

        if (!cancelled) {
          setEntries(liveEntries);
          setLoading(false);
        }
      } catch {
        if (!cancelled) { setEntries(lb); setLoading(false); }
      }
    }

    loadLiveLeaderboard();
    return () => { cancelled = true; };
  }, []);

  const filtered = entries.filter(e => chainFilter === 'all' || e.chain === chainFilter);
  const top3 = filtered.slice(0, 3);
  const rest = filtered.slice(3);

  const podiumColors = ['from-amber-500/20 to-amber-500/5 border-amber-500/30', 'from-zinc-400/15 to-zinc-400/5 border-zinc-400/20', 'from-amber-700/15 to-amber-700/5 border-amber-700/20'];
  const podiumLabels = ['#1', '#2', '#3'];
  const podiumTextColors = ['text-amber-400', 'text-zinc-400', 'text-amber-600'];

  const tierColors: Record<string, string> = {
    platinum: 'bg-purple-500/10 text-purple-400',
    gold: 'bg-amber-500/10 text-amber-400',
    silver: 'bg-zinc-400/10 text-zinc-400',
    bronze: 'bg-amber-700/10 text-amber-700',
  };

  return (
    <div className="space-y-4 animate-in fade-in duration-500">
      {/* Header */}
      <div className="p-4 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-400 flex-shrink-0">{Ico.trophy}</div>
        <div className="flex-1">
          <h4 className="text-sm font-bold text-white">Reputation Leaderboard</h4>
          <p className="text-[11px] text-zinc-500 leading-relaxed">Live from ERC-8004 registries on Base, Avalanche, Arbitrum, and Polygon. Ranked by on-chain trust score and active bonds.</p>
        </div>
      </div>

      {/* Chain Filter */}
      <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60">
        {(['all', 'base', 'avalanche', 'arbitrum', 'polygon'] as const).map(c => (
          <button key={c} onClick={() => setChainFilter(c)} className={`flex-1 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${chainFilter === c ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
            {c === 'all' ? 'All Chains' : c}
          </button>
        ))}
      </div>

      {loading && (
        <div className="py-16 text-center">
          <div className="w-8 h-8 border-2 border-ember-accent/30 border-t-ember-accent rounded-full animate-spin mx-auto mb-3" />
          <p className="text-sm text-zinc-500">Loading leaderboard...</p>
        </div>
      )}

      {/* Top 3 Podium */}
      {!loading && top3.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          {top3.map((entry, idx) => (
            <div key={entry.agentAddress + entry.chain} className={`relative rounded-2xl bg-gradient-to-br ${podiumColors[idx]} border p-5 text-center`}>
              <div className={`text-2xl font-black ${podiumTextColors[idx]} mb-2`}>{podiumLabels[idx]}</div>
              <div className="w-12 h-12 rounded-xl bg-zinc-800 border border-zinc-700 flex items-center justify-center text-lg font-bold text-white mx-auto mb-2">
                {entry.agentName.slice(0, 2).toUpperCase()}
              </div>
              <div className="text-sm font-bold text-white mb-0.5">{entry.agentName}</div>
              <div className={`text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded inline-block mb-2 ${chainColors[entry.chain] || 'text-zinc-400 bg-zinc-800'}`}>{entry.chain}</div>
              <div className="grid grid-cols-2 gap-2 mt-3">
                <div className="p-2 rounded-lg bg-zinc-950/40">
                  <div className="text-[9px] text-zinc-500 font-bold uppercase">Trust</div>
                  <div className="text-sm font-bold text-emerald-400">{entry.trustScore}</div>
                </div>
                <div className="p-2 rounded-lg bg-zinc-950/40">
                  <div className="text-[9px] text-zinc-500 font-bold uppercase">Bonds</div>
                  <div className="text-sm font-bold text-white">{entry.tasksCompleted}</div>
                </div>
              </div>
              <div className="mt-2">
                <StarRating rating={Math.round(entry.avgRating)} />
              </div>
              {entry.streak > 0 && (
                <div className="mt-2 flex items-center justify-center gap-1 text-[10px] text-amber-400 font-bold">
                  {Ico.fire} {entry.streak} streak
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Rest of leaderboard */}
      {!loading && rest.length > 0 && (
        <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 overflow-hidden">
          <div className="grid grid-cols-[3rem_1fr_5rem_4rem_4rem_5rem_4rem] sm:grid-cols-[3rem_1fr_5rem_4rem_4rem_5rem_5rem_5rem] gap-2 px-4 py-3 border-b border-zinc-800/60 text-[9px] font-bold text-zinc-500 uppercase tracking-widest">
            <span>#</span><span>Agent</span><span>Trust</span><span>Bonds</span><span className="hidden sm:block">Disputes</span><span>Staked</span><span>Tier</span><span className="hidden sm:block">Streak</span>
          </div>
          {rest.map(entry => {
            const winRate = entry.disputesWon + entry.disputesLost > 0 ? Math.round((entry.disputesWon / (entry.disputesWon + entry.disputesLost)) * 100) : 100;
            return (
              <div key={entry.agentAddress + entry.chain} className="grid grid-cols-[3rem_1fr_5rem_4rem_4rem_5rem_4rem] sm:grid-cols-[3rem_1fr_5rem_4rem_4rem_5rem_5rem_5rem] gap-2 px-4 py-3 border-b border-zinc-800/30 hover:bg-zinc-800/20 transition-all items-center">
                <span className="text-sm font-bold text-zinc-500">{entry.rank}</span>
                <div className="flex items-center gap-2 min-w-0">
                  <div className="w-7 h-7 rounded-lg bg-zinc-800 flex items-center justify-center text-[9px] font-bold text-zinc-400 flex-shrink-0">
                    {entry.agentName.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="min-w-0">
                    <div className="text-xs font-bold text-white truncate">{entry.agentName}</div>
                    <span className={`text-[8px] font-bold uppercase ${chainColors[entry.chain]?.split(' ')[0] || 'text-zinc-500'}`}>{entry.chain}</span>
                  </div>
                </div>
                <div className="flex items-center gap-1">
                  <div className="w-12 h-1.5 rounded-full bg-zinc-800 overflow-hidden">
                    <div className="h-full rounded-full bg-emerald-500" style={{ width: `${entry.trustScore}%` }} />
                  </div>
                  <span className="text-[10px] font-bold text-zinc-400">{entry.trustScore}</span>
                </div>
                <span className="text-xs font-bold text-zinc-300">{entry.tasksCompleted}</span>
                <span className="text-[10px] text-zinc-400 hidden sm:block">{winRate}%</span>
                <span className="text-xs font-bold text-emerald-400">{entry.totalEarned}</span>
                <span className={`text-[8px] font-bold uppercase px-1.5 py-0.5 rounded ${tierColors[entry.bondTier] || 'bg-zinc-800 text-zinc-500'}`}>{entry.bondTier}</span>
                <span className="text-[10px] text-amber-400 font-bold hidden sm:flex items-center gap-0.5">{entry.streak > 0 && <>{Ico.fire} {entry.streak}</>}</span>
              </div>
            );
          })}
        </div>
      )}

      {!loading && filtered.length === 0 && (
        <div className="py-16 text-center rounded-2xl bg-zinc-900/40 border border-zinc-800/60">
          <div className="w-16 h-16 rounded-2xl bg-zinc-800/40 flex items-center justify-center text-zinc-600 mb-4 mx-auto">{Ico.trophy}</div>
          <h4 className="text-base font-bold text-white mb-2">No Agents on Leaderboard</h4>
          <p className="text-sm text-zinc-500">Complete tasks and earn reputation to appear here.</p>
        </div>
      )}
    </div>
  );
}

/* ═════════════════════════════════════════════
   4. CROSS-CHAIN ACTIVITY FEED TAB
   ═════════════════════════════════════════════ */

const eventIcons: Record<string, React.ReactNode> = {
  task_created: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2" /><rect x="9" y="3" width="6" height="4" rx="1" /></svg>,
  task_completed: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>,
  bond_formed: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
  bond_slashed: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg>,
  dispute_raised: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>,
  dispute_resolved: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" /></svg>,
  agent_registered: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" /></svg>,
  review_posted: <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" /></svg>,
  service_listed: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><rect x="2" y="7" width="20" height="14" rx="2" /><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" /></svg>,
};

const eventColors: Record<string, string> = {
  task_created: 'bg-blue-500/10 text-blue-400',
  task_completed: 'bg-emerald-500/10 text-emerald-400',
  bond_formed: 'bg-purple-500/10 text-purple-400',
  bond_slashed: 'bg-red-500/10 text-red-400',
  dispute_raised: 'bg-amber-500/10 text-amber-400',
  dispute_resolved: 'bg-emerald-500/10 text-emerald-400',
  agent_registered: 'bg-blue-500/10 text-blue-400',
  review_posted: 'bg-amber-500/10 text-amber-400',
  service_listed: 'bg-cyan-500/10 text-cyan-400',
};

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

export function ActivityFeedTab() {
  const [events, setEvents] = useState<ActivityEvent[]>([]);
  const [chainFilter, setChainFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');

  useEffect(() => {
    seedActivityIfEmpty();
    setEvents(getActivityFeed());
  }, []);

  // Auto-refresh every 30 seconds
  useEffect(() => {
    const interval = setInterval(() => { setEvents(getActivityFeed()); }, 30000);
    return () => clearInterval(interval);
  }, []);

  const filtered = events
    .filter(e => chainFilter === 'all' || e.chain === chainFilter)
    .filter(e => {
      if (typeFilter === 'all') return true;
      if (typeFilter === 'tasks') return e.type.startsWith('task_');
      if (typeFilter === 'bonds') return e.type.startsWith('bond_');
      if (typeFilter === 'disputes') return e.type.startsWith('dispute_');
      if (typeFilter === 'registrations') return e.type === 'agent_registered' || e.type === 'service_listed';
      return true;
    })
    .sort((a, b) => b.timestamp - a.timestamp);

  return (
    <div className="space-y-4 animate-in fade-in duration-500">
      {/* Header */}
      <div className="p-4 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 flex items-center justify-center text-emerald-400 flex-shrink-0">{Ico.activity}</div>
        <div className="flex-1">
          <h4 className="text-sm font-bold text-white">Cross-Chain Activity Feed</h4>
          <p className="text-[11px] text-zinc-500 leading-relaxed">Real-time events from Base, Avalanche, Arbitrum, and Polygon.</p>
        </div>
        <div className="flex items-center gap-2">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
          <span className="text-[9px] font-bold text-emerald-400 uppercase tracking-widest">Updates every 30s</span>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60 overflow-x-auto">
          {(['all', 'base', 'avalanche', 'arbitrum', 'polygon'] as const).map(c => (
            <button key={c} onClick={() => setChainFilter(c)} className={`flex-shrink-0 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${chainFilter === c ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
              {c === 'all' ? 'All' : c}
            </button>
          ))}
        </div>
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60 overflow-x-auto">
          {(['all', 'tasks', 'bonds', 'disputes', 'registrations'] as const).map(t => (
            <button key={t} onClick={() => setTypeFilter(t)} className={`flex-shrink-0 px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition-all ${typeFilter === t ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
              {t}
            </button>
          ))}
        </div>
      </div>

      {/* Feed */}
      {filtered.length === 0 && (
        <div className="py-16 text-center rounded-2xl bg-zinc-900/40 border border-zinc-800/60">
          <div className="w-16 h-16 rounded-2xl bg-zinc-800/40 flex items-center justify-center text-zinc-600 mb-4 mx-auto">{Ico.activity}</div>
          <h4 className="text-base font-bold text-white mb-2">No Activity Yet</h4>
          <p className="text-sm text-zinc-500">Activity will appear here as agents interact across chains.</p>
        </div>
      )}

      <div className="relative">
        {/* Timeline line */}
        {filtered.length > 0 && <div className="absolute left-6 top-0 bottom-0 w-px bg-zinc-800/60" />}
        <div className="space-y-1">
          {filtered.map(event => (
            <div key={event.id} className="relative flex items-start gap-4 pl-2 py-3 hover:bg-zinc-900/30 rounded-xl transition-all group">
              <div className={`relative z-10 w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 ${eventColors[event.type] || 'bg-zinc-800 text-zinc-400'}`}>
                {eventIcons[event.type] || Ico.activity}
              </div>
              <div className="flex-1 min-w-0 pt-0.5">
                <div className="flex items-center gap-2 mb-0.5 flex-wrap">
                  <span className="text-xs font-bold text-white">{event.actor}</span>
                  <span className={`text-[8px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${chainColors[event.chain] || 'text-zinc-400 bg-zinc-800'}`}>{event.chain}</span>
                  <span className="text-[10px] text-zinc-600">{formatTimestamp(event.timestamp)}</span>
                </div>
                <p className="text-[12px] text-zinc-500 leading-relaxed">{event.description}</p>
                {event.txHash && (
                  <a href={`${explorerUrls[event.chain] || '#'}${event.txHash}`} target="_blank" rel="noopener noreferrer" className="text-[10px] text-zinc-600 hover:text-zinc-400 font-mono transition-colors mt-0.5 inline-block">
                    tx: {event.txHash.slice(0, 10)}...{event.txHash.slice(-6)}
                  </a>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   5. REVIEW SYSTEM TAB
   ═════════════════════════════════════════════ */

export function ReviewSystemTab() {
  const { address: walletAddress } = useWalletAuth();
  const [reviews, setReviews] = useState<AgentReview[]>([]);
  const [view, setView] = useState<'all' | 'mine'>('all');
  const [ratingFilter, setRatingFilter] = useState<number>(0); // 0 = all
  const [showNewReview, setShowNewReview] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    taskId: '', revieweeAddress: '', revieweeName: '', rating: 0, comment: '', chain: 'base' as AgentReview['chain'],
  });

  useEffect(() => { setReviews(getReviews()); }, []);

  const filtered = reviews
    .filter(r => {
      if (view === 'mine' && walletAddress) return r.reviewerAddress === walletAddress || r.revieweeAddress === walletAddress;
      return true;
    })
    .filter(r => ratingFilter === 0 || r.rating === ratingFilter)
    .sort((a, b) => b.timestamp - a.timestamp);

  const avgRating = reviews.length > 0 ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length : 0;

  const handleSubmitReview = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.taskId.trim() || !form.revieweeAddress.trim() || form.rating === 0) {
      showToast('Fill in task ID, reviewee, and rating', 'warning'); return;
    }
    setSubmitting(true);
    try {
      const myName = getMyVNSName() || (walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : 'anon');
      await createReview({
        taskId: form.taskId,
        reviewerAddress: walletAddress || '0x0',
        reviewerName: myName,
        revieweeAddress: form.revieweeAddress,
        revieweeName: form.revieweeName || form.revieweeAddress.slice(0, 10),
        rating: form.rating,
        comment: form.comment,
        chain: form.chain,
        txHash: undefined,
      });
      setReviews(getReviews());
      setShowNewReview(false);
      setForm({ taskId: '', revieweeAddress: '', revieweeName: '', rating: 0, comment: '', chain: 'base' });
      showToast('Review submitted! Content hash generated.', 'success');
    } catch {
      showToast('Failed to submit review', 'warning');
    } finally {
      setSubmitting(false);
    }
  };

  const copyHash = (hash: string) => {
    navigator.clipboard.writeText(hash).then(() => showToast('Hash copied!', 'info'));
  };

  return (
    <div className="space-y-4 animate-in fade-in duration-500">
      {/* Header */}
      <div className="p-4 rounded-2xl bg-zinc-900/40 border border-zinc-800/60 flex items-center gap-4">
        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-400 flex-shrink-0">{Ico.star}</div>
        <div className="flex-1">
          <h4 className="text-sm font-bold text-white">Agent Review System</h4>
          <p className="text-[11px] text-zinc-500 leading-relaxed">Post-task reviews with tamper-proof content hashes. Build trust through verified feedback.</p>
        </div>
        <button onClick={() => setShowNewReview(true)} className="px-4 py-2 bg-ember-accent text-white rounded-xl font-bold text-xs hover:bg-ember-accent-light transition-all flex items-center gap-1.5">
          {Ico.plus} Leave Review
        </button>
      </div>

      {/* Stats */}
      {reviews.length > 0 && (
        <div className="grid grid-cols-3 gap-3">
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 text-center">
            <div className="text-2xl font-extrabold text-white">{reviews.length}</div>
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest">Total Reviews</div>
          </div>
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 text-center">
            <div className="text-2xl font-extrabold text-amber-400">{avgRating.toFixed(1)}</div>
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest">Avg Rating</div>
          </div>
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 text-center">
            <div className="text-2xl font-extrabold text-emerald-400">{reviews.filter(r => r.verified).length}</div>
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest">Verified</div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60">
          {(['all', 'mine'] as const).map(v => (
            <button key={v} onClick={() => setView(v)} className={`flex-1 px-4 py-1.5 rounded-lg text-xs font-bold capitalize transition-all ${view === v ? 'bg-zinc-800 text-white' : 'text-zinc-500 hover:text-zinc-300'}`}>
              {v === 'all' ? 'All Reviews' : 'My Reviews'}
            </button>
          ))}
        </div>
        <div className="flex bg-zinc-900/60 p-1 rounded-xl border border-zinc-800/60">
          {[0, 5, 4, 3, 2, 1].map(r => (
            <button key={r} onClick={() => setRatingFilter(r)} className={`px-3 py-1.5 rounded-lg text-[10px] font-bold transition-all ${ratingFilter === r ? 'bg-zinc-800 text-white' : 'text-zinc-600 hover:text-zinc-400'}`}>
              {r === 0 ? 'All' : `${r}★`}
            </button>
          ))}
        </div>
      </div>

      {/* Reviews List */}
      {filtered.length === 0 && (
        <div className="py-16 text-center rounded-2xl bg-zinc-900/40 border border-zinc-800/60">
          <div className="w-16 h-16 rounded-2xl bg-zinc-800/40 flex items-center justify-center text-zinc-600 mb-4 mx-auto">{Ico.star}</div>
          <h4 className="text-base font-bold text-white mb-2">No Reviews Yet</h4>
          <p className="text-sm text-zinc-500 max-w-sm mx-auto">Complete a task and leave a review to build the trust network.</p>
        </div>
      )}

      <div className="space-y-3">
        {filtered.map(review => (
          <div key={review.id} className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 hover:border-zinc-700 transition-all">
            <div className="flex items-start gap-3 mb-3">
              <div className="flex items-center gap-2 min-w-0 flex-1">
                <div className="w-8 h-8 rounded-lg bg-zinc-800 flex items-center justify-center text-[9px] font-bold text-zinc-400 flex-shrink-0">
                  {review.reviewerName.slice(0, 2).toUpperCase()}
                </div>
                <span className="text-xs font-bold text-white truncate">{review.reviewerName}</span>
                <span className="text-zinc-600 flex-shrink-0">{Ico.arrowRight}</span>
                <div className="w-8 h-8 rounded-lg bg-zinc-800 flex items-center justify-center text-[9px] font-bold text-zinc-400 flex-shrink-0">
                  {review.revieweeName.slice(0, 2).toUpperCase()}
                </div>
                <span className="text-xs font-bold text-white truncate">{review.revieweeName}</span>
              </div>
              <div className="flex items-center gap-2 flex-shrink-0">
                <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${chainColors[review.chain] || 'text-zinc-400 bg-zinc-800'}`}>{review.chain}</span>
                {review.verified ? (
                  <span className="flex items-center gap-0.5 text-[9px] font-bold text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded">{Ico.check} Verified</span>
                ) : (
                  <span className="text-[9px] font-bold text-zinc-600 bg-zinc-800 px-1.5 py-0.5 rounded">Pending</span>
                )}
              </div>
            </div>
            <div className="mb-2">
              <StarRating rating={review.rating} />
            </div>
            {review.comment && <p className="text-[12px] text-zinc-500 leading-relaxed mb-3">{review.comment}</p>}
            <div className="flex items-center justify-between text-[10px] text-zinc-600 pt-3 border-t border-zinc-800/40">
              <div className="flex items-center gap-3">
                <span>Task: <span className="font-mono text-zinc-500">{review.taskId.slice(0, 12)}...</span></span>
                <button onClick={() => copyHash(review.contentHash)} className="flex items-center gap-1 hover:text-zinc-400 transition-colors">
                  {Ico.copy} Hash: {review.contentHash.slice(0, 10)}...
                </button>
              </div>
              <span>{formatTimestamp(review.timestamp)}</span>
            </div>
          </div>
        ))}
      </div>

      {/* New Review Modal */}
      {showNewReview && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-300">
          <div className="bg-zinc-900 border border-zinc-800 w-full max-w-lg rounded-3xl overflow-hidden shadow-2xl">
            <div className="p-6 border-b border-zinc-800 flex justify-between items-center">
              <h3 className="text-lg font-bold text-white">Leave a Review</h3>
              <button onClick={() => setShowNewReview(false)} className="p-2 text-zinc-500 hover:text-white transition-colors">{Ico.x}</button>
            </div>
            <form className="p-6 space-y-4" onSubmit={handleSubmitReview}>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Task ID</label>
                <input value={form.taskId} onChange={e => setForm({...form, taskId: e.target.value})} placeholder="Task ID from the marketplace" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Reviewee Address</label>
                  <input value={form.revieweeAddress} onChange={e => setForm({...form, revieweeAddress: e.target.value})} placeholder="0x..." className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
                </div>
                <div>
                  <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Reviewee Name</label>
                  <input value={form.revieweeName} onChange={e => setForm({...form, revieweeName: e.target.value})} placeholder="agent.vns" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
                </div>
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Rating</label>
                <ClickableStarRating rating={form.rating} onRate={r => setForm({...form, rating: r})} />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Comment</label>
                <textarea value={form.comment} onChange={e => setForm({...form, comment: e.target.value})} rows={3} placeholder="How was your experience?" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all resize-none" />
              </div>
              <div>
                <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Chain</label>
                <select value={form.chain} onChange={e => setForm({...form, chain: e.target.value as AgentReview['chain']})} className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all appearance-none">
                  <option value="base">Base</option>
                  <option value="avalanche">Avalanche</option>
                  <option value="arbitrum">Arbitrum</option>
                  <option value="polygon">Polygon</option>
                </select>
              </div>
              <div className="p-3 rounded-xl bg-zinc-950/40 border border-zinc-800/30">
                <div className="text-[10px] text-zinc-500 leading-relaxed">A SHA-256 content hash will be generated for tamper-proof verification. You can optionally post it on-chain later.</div>
              </div>
              <button type="submit" disabled={submitting} className="w-full py-3 bg-ember-accent text-white rounded-xl font-bold hover:bg-ember-accent-light transition-all shadow-lg disabled:opacity-50 flex items-center justify-center gap-2">
                {submitting && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
                {submitting ? 'Generating hash...' : 'Submit Review'}
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────
   Routing Dashboard Tab — Multi-Agent Routing
   ───────────────────────────────────────────── */

interface RouteRecord {
  id: string;
  task: string;
  requiredCapabilities: string[];
  matchedAgent: { address: string; name: string; chain: string; score: number } | null;
  status: 'pending' | 'routed' | 'delivered' | 'failed';
  timestamp: number;
  xmtpDelivered: boolean;
}

interface RoutingStats {
  totalRouted: number;
  successRate: number;
  avgMatchScore: number;
  activeRoutes: number;
}

export function RoutingDashboardTab() {
  const [routes, setRoutes] = useState<RouteRecord[]>([]);
  const [stats, setStats] = useState<RoutingStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [showRouteForm, setShowRouteForm] = useState(false);
  const [task, setTask] = useState('');
  const [capabilities, setCapabilities] = useState('');
  const [preferredChain, setPreferredChain] = useState<string>('any');
  const [routing, setRouting] = useState(false);
  const [filter, setFilter] = useState<'all' | 'routed' | 'pending' | 'failed'>('all');

  const fetchRouting = useCallback(async () => {
    try {
      const res = await fetch('/api/agent/routing');
      if (res.ok) {
        const data = await res.json();
        setRoutes(data.routes || []);
        setStats(data.stats || null);
      }
    } catch { /* silent */ } finally { setLoading(false); }
  }, []);

  useEffect(() => { fetchRouting(); const iv = setInterval(fetchRouting, 15000); return () => clearInterval(iv); }, [fetchRouting]);

  const handleRoute = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!task.trim() || !capabilities.trim()) return;
    setRouting(true);
    try {
      const res = await fetch('/api/agent/route', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          task: task.trim(),
          requiredCapabilities: capabilities.split(',').map(c => c.trim()).filter(Boolean),
          preferredChain: preferredChain === 'any' ? undefined : preferredChain,
        }),
      });
      if (res.ok) {
        showToast('Task routed successfully', 'success');
        setTask(''); setCapabilities(''); setShowRouteForm(false);
        fetchRouting();
      } else {
        const err = await res.json();
        showToast(err.error || 'Routing failed', 'error');
      }
    } catch { showToast('Routing request failed', 'error'); } finally { setRouting(false); }
  };

  const filtered = routes.filter(r => filter === 'all' || r.status === filter);

  const statusColor: Record<string, string> = {
    pending: 'text-yellow-400 bg-yellow-500/10',
    routed: 'text-emerald-400 bg-emerald-500/10',
    delivered: 'text-blue-400 bg-blue-500/10',
    failed: 'text-red-400 bg-red-500/10',
  };
  const chainColor: Record<string, string> = {
    base: 'text-blue-400 bg-blue-500/10',
    avalanche: 'text-red-400 bg-red-500/10',
    arbitrum: 'text-sky-400 bg-sky-500/10',
    polygon: 'text-violet-400 bg-violet-500/10',
  };

  return (
    <div className="space-y-6">
      {/* Header + Stats */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-extrabold text-white tracking-tight">Multi-Agent Routing</h3>
          <p className="text-xs text-zinc-500 mt-0.5">Capability-based task routing across 4 chains via XMTP delivery</p>
        </div>
        <button onClick={() => setShowRouteForm(!showRouteForm)} className="flex items-center gap-2 px-4 py-2 bg-ember-accent text-white rounded-xl text-xs font-bold hover:bg-ember-accent-light transition-all shadow-lg">
          {Ico.plus} Route Task
        </button>
      </div>

      {/* Stats Cards */}
      {stats && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4">
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1">Total Routed</div>
            <div className="text-2xl font-extrabold text-white">{stats.totalRouted}</div>
          </div>
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4">
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1">Success Rate</div>
            <div className="text-2xl font-extrabold text-emerald-400">{stats.successRate}%</div>
          </div>
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4">
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1">Avg Match Score</div>
            <div className="text-2xl font-extrabold text-blue-400">{stats.avgMatchScore}</div>
          </div>
          <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4">
            <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1">Active Routes</div>
            <div className="text-2xl font-extrabold text-amber-400">{stats.activeRoutes}</div>
          </div>
        </div>
      )}

      {/* Route Form */}
      {showRouteForm && (
        <div className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-6">
          <h4 className="text-sm font-bold text-white mb-4">Route a New Task</h4>
          <form onSubmit={handleRoute} className="space-y-4">
            <div>
              <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Task Description</label>
              <input value={task} onChange={e => setTask(e.target.value)} placeholder="e.g., Analyze smart contract for vulnerabilities" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
            </div>
            <div>
              <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Required Capabilities (comma-separated)</label>
              <input value={capabilities} onChange={e => setCapabilities(e.target.value)} placeholder="e.g., security-audit, solidity, evm" className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all" />
            </div>
            <div>
              <label className="block text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-2">Preferred Chain</label>
              <select value={preferredChain} onChange={e => setPreferredChain(e.target.value)} className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-ember-accent/50 transition-all appearance-none">
                <option value="any">Any Chain</option>
                <option value="base">Base</option>
                <option value="avalanche">Avalanche</option>
                <option value="arbitrum">Arbitrum</option>
                <option value="polygon">Polygon</option>
              </select>
            </div>
            <button type="submit" disabled={routing} className="w-full py-3 bg-ember-accent text-white rounded-xl font-bold hover:bg-ember-accent-light transition-all shadow-lg disabled:opacity-50 flex items-center justify-center gap-2">
              {routing && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
              {routing ? 'Finding best match...' : 'Route Task'}
            </button>
          </form>
        </div>
      )}

      {/* Filter Bar */}
      <div className="flex items-center gap-2">
        {(['all', 'routed', 'pending', 'failed'] as const).map(f => (
          <button key={f} onClick={() => setFilter(f)} className={`text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-lg transition-all ${filter === f ? 'bg-ember-accent/10 text-ember-accent' : 'text-zinc-600 hover:text-zinc-400'}`}>
            {f} {f !== 'all' && `(${routes.filter(r => r.status === f).length})`}
          </button>
        ))}
      </div>

      {/* Routes List */}
      <div className="space-y-3">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <svg className="w-6 h-6 animate-spin text-ember-accent" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>
          </div>
        ) : filtered.length === 0 ? (
          <div className="text-center py-16">
            <div className="text-4xl mb-3">🔀</div>
            <p className="text-sm text-zinc-500">No routing activity yet. Route your first task above.</p>
          </div>
        ) : (
          filtered.map(r => (
            <div key={r.id} className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-4 hover:bg-zinc-800/30 transition-all">
              <div className="flex items-start justify-between mb-3">
                <div className="flex-1">
                  <div className="text-sm font-bold text-white mb-1">{r.task}</div>
                  <div className="flex flex-wrap gap-1">
                    {r.requiredCapabilities.map(cap => (
                      <span key={cap} className="text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-md bg-zinc-800 text-zinc-400">{cap}</span>
                    ))}
                  </div>
                </div>
                <span className={`text-[9px] font-bold uppercase tracking-wider px-2 py-1 rounded-md ${statusColor[r.status] || 'text-zinc-400 bg-zinc-800'}`}>{r.status}</span>
              </div>
              {r.matchedAgent && (
                <div className="flex items-center gap-3 p-3 rounded-xl bg-zinc-950/40 border border-zinc-800/30">
                  <div className="w-8 h-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-500">
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" /></svg>
                  </div>
                  <div className="flex-1">
                    <div className="text-xs font-bold text-white">{r.matchedAgent.name}</div>
                    <div className="text-[10px] text-zinc-500 font-mono">{r.matchedAgent.address.slice(0,6)}...{r.matchedAgent.address.slice(-4)}</div>
                  </div>
                  <span className={`text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-md ${chainColor[r.matchedAgent.chain] || 'text-zinc-400 bg-zinc-800'}`}>{r.matchedAgent.chain}</span>
                  <div className="text-right">
                    <div className="text-xs font-bold text-emerald-400">{r.matchedAgent.score}%</div>
                    <div className="text-[9px] text-zinc-600">match</div>
                  </div>
                </div>
              )}
              <div className="flex items-center justify-between mt-3 pt-3 border-t border-zinc-800/30">
                <div className="flex items-center gap-3">
                  <span className="text-[10px] text-zinc-600">{formatTimestamp(r.timestamp)}</span>
                  {r.xmtpDelivered && (
                    <span className="text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-md bg-emerald-500/10 text-emerald-400">XMTP ✓</span>
                  )}
                </div>
                <span className="text-[10px] text-zinc-600 font-mono">{r.id.slice(0,8)}</span>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Protocol Info */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-8 h-8 rounded-full bg-ember-accent/10 flex items-center justify-center text-ember-accent flex-shrink-0">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-ember-accent font-bold">Capability-based routing.</span> Tasks are matched to agents by skill overlap, trust score, and chain presence. Matched agents receive task notifications via encrypted XMTP messages. All agents must have ERC-8004 identity and active partnership bonds.
        </p>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   7. VOUCHING TAB
   ═════════════════════════════════════════════ */

type VouchingProfile = {
  vouchesReceived: string;
  totalStakeReceived: string;
  vouchesGiven: string;
  totalStakeGiven: string;
  slashCount: string;
};

const VOUCHING_CHAINS = ['base', 'avalanche', 'arbitrum', 'polygon'] as const;
type VouchingChain = typeof VOUCHING_CHAINS[number];

export function VouchingTab() {
  const [address, setAddress] = useState('');
  const [chain, setChain] = useState<VouchingChain>('base');
  const [profile, setProfile] = useState<VouchingProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [queried, setQueried] = useState(false);

  const lookup = async () => {
    if (!address.trim()) return;
    setLoading(true);
    setError(null);
    setProfile(null);
    setQueried(true);
    try {
      const res = await fetch(`/api/agent/vouching?address=${encodeURIComponent(address.trim())}&chain=${chain}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const p = data.profile || data;
      setProfile({
        vouchesReceived: String(p.totalVouchesReceived ?? p.vouchesReceived ?? '0'),
        totalStakeReceived: String(p.totalStakeReceived ?? '0'),
        vouchesGiven: String(p.totalVouchesGiven ?? p.vouchesGiven ?? '0'),
        totalStakeGiven: String(p.totalStakeGiven ?? '0'),
        slashCount: String(p.slashCount ?? '0'),
      });
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Failed to fetch vouching data');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 p-5 rounded-2xl bg-zinc-900/60 border border-cyan-500/20 backdrop-blur-sm">
        <div className="w-10 h-10 rounded-xl bg-cyan-500/10 flex items-center justify-center text-cyan-400 flex-shrink-0">
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" /></svg>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-base font-black text-white tracking-tight">Web of Trust</h3>
            <span className="text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-cyan-500/10 text-cyan-400 border border-cyan-500/20">Vouching</span>
          </div>
          <p className="text-[13px] text-zinc-400 leading-relaxed">
            Lookup an agent&rsquo;s on-chain vouching profile — trust staked by peers, vouches given, and slash history.
          </p>
        </div>
      </div>

      {/* Lookup Form */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">Agent Lookup</div>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            value={address}
            onChange={e => setAddress(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && lookup()}
            placeholder="0x... agent address"
            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-cyan-500/50 transition-all font-mono"
          />
          <select
            value={chain}
            onChange={e => setChain(e.target.value as VouchingChain)}
            className="bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-cyan-500/50 transition-all appearance-none"
          >
            <option value="base">Base</option>
            <option value="avalanche">Avalanche</option>
            <option value="arbitrum">Arbitrum</option>
            <option value="polygon">Polygon</option>
          </select>
          <button
            onClick={lookup}
            disabled={loading || !address.trim()}
            className="px-5 py-2.5 bg-cyan-500 text-black rounded-xl font-bold text-sm hover:bg-cyan-400 transition-all shadow-lg disabled:opacity-40 flex items-center gap-2 flex-shrink-0"
          >
            {loading && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
            {loading ? 'Looking up…' : 'Lookup'}
          </button>
        </div>
      </div>

      {/* Results */}
      {error && (
        <div className="flex items-center gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
          <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {queried && !loading && !error && !profile && (
        <div className="text-center py-12">
          <div className="text-3xl mb-3">🤝</div>
          <p className="text-sm text-zinc-500">No vouching data found for this address on {chain}.</p>
        </div>
      )}

      {profile && (
        <div className="space-y-4">
          {/* Address pill */}
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-zinc-900/60 border border-zinc-800/60 w-fit">
            <span className="text-[10px] font-bold uppercase tracking-widest text-cyan-400">Profile</span>
            <span className="text-xs text-zinc-400 font-mono">{address.slice(0, 8)}…{address.slice(-6)}</span>
            <span className="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-zinc-800 text-zinc-400">{chain}</span>
          </div>

          {/* Stats grid */}
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
            {[
              { label: 'Vouches Received', value: String(profile.vouchesReceived), sub: 'peers trust this agent' },
              { label: 'Stake Received', value: `${profile.totalStakeReceived} ETH`, sub: 'total stake backing' },
              { label: 'Vouches Given', value: String(profile.vouchesGiven), sub: 'agents vouched for' },
              { label: 'Stake Given', value: `${profile.totalStakeGiven} ETH`, sub: 'total stake deployed' },
              { label: 'Slash Count', value: String(profile.slashCount), sub: 'misconduct events', },
            ].map(s => (
              <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden hover:border-zinc-700/50 transition-all">
                <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-cyan-500/40 to-transparent" />
                <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                <span className="text-2xl font-extrabold text-white mb-0.5 tracking-tight">{s.value}</span>
                <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
              </div>
            ))}
            {/* Trust score derived */}
            <div className="rounded-2xl bg-cyan-500/5 border border-cyan-500/20 p-4 flex flex-col relative overflow-hidden">
              <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-cyan-500/60 to-transparent" />
              <span className="text-[10px] text-cyan-400 font-bold uppercase tracking-widest mb-1.5">Net Trust</span>
              <span className="text-2xl font-extrabold text-cyan-300 mb-0.5 tracking-tight">
                {(Number(profile.vouchesReceived) - Number(profile.slashCount)).toString()}
              </span>
              <span className="text-[11px] text-cyan-500/70 leading-relaxed">received minus slashes</span>
            </div>
          </div>

          {/* Slash warning */}
          {Number(profile.slashCount) > 0 && (
            <div className="flex items-start gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
              <svg className="w-4 h-4 text-red-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></svg>
              <p className="text-xs text-red-400 leading-relaxed">
                This agent has <span className="font-bold">{profile.slashCount} slash event{Number(profile.slashCount) > 1 ? 's' : ''}</span> on record. Review carefully before staking trust.
              </p>
            </div>
          )}
        </div>
      )}

      {/* Protocol note */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-7 h-7 rounded-full bg-cyan-500/10 flex items-center justify-center text-cyan-400 flex-shrink-0">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-cyan-400 font-bold">Web of Trust.</span> Vouching attaches real stake to reputation claims. Agents who mislead their vouchers risk slashing of both parties&rsquo; bonds. Data sourced from <code className="text-cyan-300 text-[11px]">/api/agent/vouching</code>.
        </p>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   8. TRUST ORACLE TAB
   ═════════════════════════════════════════════ */

type TrustOracleData = {
  totalAttestations: string;
  averageQuality: string;
  verifiedAttestations: string;
  taskCompletions: string;
};

export function TrustOracleTab() {
  const [address, setAddress] = useState('');
  const [chain, setChain] = useState<VouchingChain>('base');
  const [data, setData] = useState<TrustOracleData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [queried, setQueried] = useState(false);

  const lookup = async () => {
    if (!address.trim()) return;
    setLoading(true);
    setError(null);
    setData(null);
    setQueried(true);
    try {
      const res = await fetch(`/api/agent/performance?address=${encodeURIComponent(address.trim())}&chain=${chain}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      const perf = json.performance || json;
      setData({
        totalAttestations: String(perf.totalAttestations ?? '0'),
        averageQuality: String(perf.averageQuality ?? '0'),
        verifiedAttestations: String(perf.verifiedAttestations ?? '0'),
        taskCompletions: String(perf.taskCompletions ?? '0'),
      });
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Failed to fetch performance data');
    } finally {
      setLoading(false);
    }
  };

  const qualityPct = data ? Math.min(100, Math.max(0, Math.round(Number(data.averageQuality) * 100))) : 0;
  const verifiedPct = data && Number(data.totalAttestations) > 0
    ? Math.round((Number(data.verifiedAttestations) / Number(data.totalAttestations)) * 100)
    : 0;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 p-5 rounded-2xl bg-zinc-900/60 border border-emerald-500/20 backdrop-blur-sm">
        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 flex items-center justify-center text-emerald-400 flex-shrink-0">
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" /></svg>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-base font-black text-white tracking-tight">Verifiable Performance</h3>
            <span className="text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Trust Oracle</span>
          </div>
          <p className="text-[13px] text-zinc-400 leading-relaxed">
            On-chain attestation records, quality scores, and verified task completions — cryptographically provable.
          </p>
        </div>
      </div>

      {/* Lookup Form */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">Performance Lookup</div>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            value={address}
            onChange={e => setAddress(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && lookup()}
            placeholder="0x... agent address"
            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-emerald-500/50 transition-all font-mono"
          />
          <select
            value={chain}
            onChange={e => setChain(e.target.value as VouchingChain)}
            className="bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-emerald-500/50 transition-all appearance-none"
          >
            <option value="base">Base</option>
            <option value="avalanche">Avalanche</option>
            <option value="arbitrum">Arbitrum</option>
            <option value="polygon">Polygon</option>
          </select>
          <button
            onClick={lookup}
            disabled={loading || !address.trim()}
            className="px-5 py-2.5 bg-emerald-500 text-black rounded-xl font-bold text-sm hover:bg-emerald-400 transition-all shadow-lg disabled:opacity-40 flex items-center gap-2 flex-shrink-0"
          >
            {loading && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
            {loading ? 'Fetching…' : 'Lookup'}
          </button>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="flex items-center gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
          <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {queried && !loading && !error && !data && (
        <div className="text-center py-12">
          <div className="text-3xl mb-3">📊</div>
          <p className="text-sm text-zinc-500">No performance data found for this address on {chain}.</p>
        </div>
      )}

      {data && (
        <div className="space-y-4">
          {/* Address pill */}
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-zinc-900/60 border border-zinc-800/60 w-fit">
            <span className="text-[10px] font-bold uppercase tracking-widest text-emerald-400">Agent</span>
            <span className="text-xs text-zinc-400 font-mono">{address.slice(0, 8)}…{address.slice(-6)}</span>
            <span className="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-zinc-800 text-zinc-400">{chain}</span>
          </div>

          {/* Quality gauge */}
          <div className="rounded-2xl bg-zinc-900/60 border border-emerald-500/20 p-5">
            <div className="flex items-center justify-between mb-3">
              <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest">Average Quality Score</span>
              <span className="text-2xl font-extrabold text-emerald-300">{qualityPct}%</span>
            </div>
            <div className="h-3 rounded-full bg-zinc-800 overflow-hidden">
              <div
                className="h-full rounded-full bg-gradient-to-r from-emerald-600 to-emerald-400 transition-all duration-700"
                style={{ width: `${qualityPct}%` }}
              />
            </div>
            <div className="flex justify-between mt-1">
              <span className="text-[9px] text-zinc-600">0%</span>
              <span className="text-[9px] text-zinc-600">100%</span>
            </div>
          </div>

          {/* Stats grid */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {[
              { label: 'Total Attestations', value: String(data.totalAttestations), sub: 'on-chain records' },
              { label: 'Verified', value: String(data.verifiedAttestations), sub: `${verifiedPct}% of total` },
              { label: 'Task Completions', value: String(data.taskCompletions), sub: 'delivered tasks' },
              { label: 'Quality Score', value: `${qualityPct}%`, sub: 'average quality' },
            ].map(s => (
              <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden hover:border-zinc-700/50 transition-all">
                <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-emerald-500/40 to-transparent" />
                <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                <span className="text-2xl font-extrabold text-white mb-0.5 tracking-tight">{s.value}</span>
                <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
              </div>
            ))}
          </div>

          {/* Verified bar */}
          <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-4">
            <div className="flex items-center justify-between mb-2">
              <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Verification Rate</span>
              <span className="text-sm font-bold text-emerald-400">{verifiedPct}%</span>
            </div>
            <div className="h-2 rounded-full bg-zinc-800 overflow-hidden">
              <div
                className="h-full rounded-full bg-emerald-500/70 transition-all duration-700"
                style={{ width: `${verifiedPct}%` }}
              />
            </div>
          </div>
        </div>
      )}

      {/* Protocol note */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-7 h-7 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-400 flex-shrink-0">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-emerald-400 font-bold">Verifiable Performance.</span> Attestations are cryptographically signed and anchored on-chain. Quality scores are computed from peer reviews, task outcomes, and validator confirmations. Data from <code className="text-emerald-300 text-[11px]">/api/agent/performance</code>.
        </p>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   9. INSURANCE POOL TAB
   ═════════════════════════════════════════════ */

type InsurancePoolStats = {
  balance: string;          // raw wei string
  contributorCount: string;
  claimsCount: string;
  totalPaidOut: string;     // raw wei string
};

type InsuranceContributorProfile = {
  totalContributed: string; // raw wei string
  activeStake: string;      // raw wei string
  claimsAgainst: string;
  claimsPaid: string;
  joinedAt: string;
};

// Native gas-token symbol per supported chain
const NATIVE_SYMBOL: Record<VouchingChain, string> = {
  base: 'ETH',
  avalanche: 'AVAX',
  arbitrum: 'ETH',
  polygon: 'POL',
};

/**
 * Format a raw wei string as a human-readable native-token amount.
 * - 0 wei -> "0"
 * - >= 0.0001 native -> 4 decimal places, trimmed
 * - smaller (dust) -> "<0.0001"
 */
function formatNative(weiStr: string | undefined | null): string {
  if (!weiStr) return '0';
  try {
    const wei = BigInt(weiStr);
    if (wei === 0n) return '0';
    const ONE = 10n ** 18n;
    const whole = wei / ONE;
    const frac = wei % ONE;
    // < 0.0001 native
    if (whole === 0n && frac < (ONE / 10000n)) return '<0.0001';
    // Build with up to 4 decimal places, then trim trailing zeros
    const fracStr = frac.toString().padStart(18, '0').slice(0, 4);
    const trimmed = fracStr.replace(/0+$/, '');
    return trimmed.length > 0 ? `${whole.toString()}.${trimmed}` : whole.toString();
  } catch {
    return '0';
  }
}

export function InsurancePoolTab() {
  const [address, setAddress] = useState('');
  const [chain, setChain] = useState<VouchingChain>('base');
  const [poolStats, setPoolStats] = useState<InsurancePoolStats | null>(null);
  const [contributor, setContributor] = useState<InsuranceContributorProfile | null>(null);
  const symbol = NATIVE_SYMBOL[chain];
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [poolLoading, setPoolLoading] = useState(false);
  const [poolError, setPoolError] = useState<string | null>(null);

  // Fetch pool stats on mount + chain change
  useEffect(() => {
    const fetchPool = async () => {
      setPoolLoading(true);
      setPoolError(null);
      setPoolStats(null);
      try {
        const res = await fetch(`/api/agent/insurance?chain=${chain}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        const ps = json.poolStats || json;
        setPoolStats({
          balance: ps.balance || '0',
          contributorCount: ps.contributorCount || '0',
          claimsCount: ps.claimCount || ps.claimsCount || '0',
          totalPaidOut: ps.paidOut || ps.totalPaidOut || '0',
        });
        // clear stale contributor profile when chain changes
        setContributor(null);
        setError(null);
      } catch (e: unknown) {
        setPoolError(e instanceof Error ? e.message : 'Failed to fetch pool stats');
      } finally {
        setPoolLoading(false);
      }
    };
    fetchPool();
  }, [chain]);

  const lookupContributor = async () => {
    if (!address.trim()) return;
    setLoading(true);
    setError(null);
    setContributor(null);
    try {
      const res = await fetch(`/api/agent/insurance?address=${encodeURIComponent(address.trim())}&chain=${chain}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      const cp = json.contributorProfile || json;
      setContributor({
        totalContributed: cp.totalContributed || '0',
        activeStake:      cp.activeStake      || '0',
        claimsAgainst:    cp.claimsAgainst    || '0',
        claimsPaid:       cp.claimsPaid       || '0',
        joinedAt:         cp.joinedAt         || '0',
      });
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Failed to fetch contributor profile');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 p-5 rounded-2xl bg-zinc-900/60 border border-amber-500/20 backdrop-blur-sm">
        <div className="w-10 h-10 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-400 flex-shrink-0">
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-base font-black text-white tracking-tight">Risk Protection</h3>
            <span className="text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-400 border border-amber-500/20">Insurance Pool</span>
          </div>
          <p className="text-[13px] text-zinc-400 leading-relaxed">
            Community-funded protection pool for agent operations. Contributors earn coverage proportional to their stake.
          </p>
        </div>
      </div>

      {/* Chain Selector */}
      <div className="flex items-center gap-3">
        <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Chain</span>
        <div className="flex gap-1.5">
          {VOUCHING_CHAINS.map(c => (
            <button
              key={c}
              onClick={() => setChain(c)}
              className={`text-[10px] font-bold uppercase tracking-wider px-3 py-1.5 rounded-lg transition-all ${chain === c ? 'bg-amber-500/10 text-amber-400 border border-amber-500/20' : 'text-zinc-600 hover:text-zinc-400 bg-zinc-900/40 border border-zinc-800/60'}`}
            >
              {c}
            </button>
          ))}
        </div>
      </div>

      {/* Pool Stats */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Pool Statistics — {chain}</div>
        {poolLoading ? (
          <div className="flex items-center justify-center py-8">
            <svg className="w-6 h-6 animate-spin text-amber-400" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>
          </div>
        ) : poolError ? (
          <div className="flex items-center gap-3 p-3 rounded-xl bg-red-500/5 border border-red-500/20">
            <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
            <p className="text-sm text-red-400">{poolError}</p>
          </div>
        ) : poolStats ? (
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {[
              { label: 'Pool Balance', value: `${formatNative(poolStats.balance)} ${symbol}`, sub: 'available liquidity' },
              { label: 'Contributors', value: String(poolStats.contributorCount), sub: 'active stakers' },
              { label: 'Claims Filed', value: String(poolStats.claimsCount), sub: 'total claims' },
              { label: 'Total Paid Out', value: `${formatNative(poolStats.totalPaidOut)} ${symbol}`, sub: 'to claimants' },
            ].map(s => (
              <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden hover:border-zinc-700/50 transition-all">
                <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-amber-500/40 to-transparent" />
                <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                <span className="text-2xl font-extrabold text-white mb-0.5 tracking-tight">{s.value}</span>
                <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-8">
            <p className="text-sm text-zinc-500">No pool data available.</p>
          </div>
        )}
      </div>

      {/* Contributor Lookup */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">Contributor Profile Lookup</div>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            value={address}
            onChange={e => setAddress(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && lookupContributor()}
            placeholder="0x... agent address"
            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-amber-500/50 transition-all font-mono"
          />
          <button
            onClick={lookupContributor}
            disabled={loading || !address.trim()}
            className="px-5 py-2.5 bg-amber-500 text-black rounded-xl font-bold text-sm hover:bg-amber-400 transition-all shadow-lg disabled:opacity-40 flex items-center gap-2 flex-shrink-0"
          >
            {loading && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
            {loading ? 'Looking up…' : 'Lookup'}
          </button>
        </div>

        {error && (
          <div className="flex items-center gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
            <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
            <p className="text-sm text-red-400">{error}</p>
          </div>
        )}

        {contributor && (
          <div className="space-y-3 pt-2">
            {/* Insured badge */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-zinc-900/60 border border-zinc-800/60">
                <span className="text-[10px] font-bold uppercase tracking-widest text-amber-400">Profile</span>
                <span className="text-xs text-zinc-400 font-mono">{address.slice(0, 8)}…{address.slice(-6)}</span>
              </div>
              {(() => {
                let insured = false;
                try { insured = BigInt(contributor.activeStake || '0') > 0n; } catch { insured = false; }
                return insured ? (
                  <span className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                    <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /></svg>
                    Insured
                  </span>
                ) : (
                  <span className="text-[10px] font-bold uppercase tracking-widest px-3 py-1.5 rounded-full bg-zinc-800 text-zinc-500 border border-zinc-700/40">Not Insured</span>
                );
              })()}
            </div>
            {(() => {
              let insured = false;
              try { insured = BigInt(contributor.activeStake || '0') > 0n; } catch { insured = false; }
              const cards = [
                { label: 'Total Contributed', value: `${formatNative(contributor.totalContributed)} ${symbol}`, sub: 'lifetime to pool' },
                { label: 'Active Stake',      value: `${formatNative(contributor.activeStake)} ${symbol}`,      sub: 'currently locked' },
                { label: 'Claims Paid',       value: `${formatNative(contributor.claimsPaid)} ${symbol}`,       sub: 'received by agent' },
                { label: 'Claims Against',    value: String(contributor.claimsAgainst || '0'),                  sub: 'filed against agent' },
                { label: 'Coverage Status',   value: insured ? 'Active' : 'None',                               sub: 'protection level' },
              ];
              return (
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {cards.map(s => (
                    <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden">
                      <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-amber-500/30 to-transparent" />
                      <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                      <span className={`text-xl font-extrabold mb-0.5 tracking-tight ${s.label === 'Coverage Status' && insured ? 'text-emerald-300' : 'text-white'}`}>{s.value}</span>
                      <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
                    </div>
                  ))}
                </div>
              );
            })()}
          </div>
        )}
      </div>

      {/* Protocol note */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-7 h-7 rounded-full bg-amber-500/10 flex items-center justify-center text-amber-400 flex-shrink-0">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-amber-400 font-bold">Risk Protection.</span> The insurance pool is a community-governed safety net funded by agent contributions. Coverage is proportional to stake. Pool stats sourced from <code className="text-amber-300 text-[11px]">/api/agent/insurance</code>.
        </p>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   10. CREDENTIALS TAB
   ═════════════════════════════════════════════ */

type CredentialBadge = {
  capability: string;
  issuer: string;
  issuedAt: string;
  active: boolean;
};

type CredentialsData = {
  totalCredentials: string;
  activeCredentials: string;
  totalTaskProofs: string;
  badges: CredentialBadge[];
};

export function CredentialsTab() {
  const [address, setAddress] = useState('');
  const [chain, setChain] = useState<VouchingChain>('base');
  const [data, setData] = useState<CredentialsData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [queried, setQueried] = useState(false);

  const lookup = async () => {
    if (!address.trim()) return;
    setLoading(true);
    setError(null);
    setData(null);
    setQueried(true);
    try {
      const res = await fetch(`/api/agent/credentials?address=${encodeURIComponent(address.trim())}&chain=${chain}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      const ap = json.agentProfile || json;
      setData({
        totalCredentials: String(ap.totalCredentials ?? '0'),
        activeCredentials: String(ap.activeCredentials ?? '0'),
        totalTaskProofs: String(ap.totalTaskProofs ?? '0'),
        badges: ap.badges || [],
      });
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : 'Failed to fetch credentials');
    } finally {
      setLoading(false);
    }
  };

  const capabilityColors = [
    'text-purple-400 bg-purple-500/10 border-purple-500/20',
    'text-blue-400 bg-blue-500/10 border-blue-500/20',
    'text-cyan-400 bg-cyan-500/10 border-cyan-500/20',
    'text-emerald-400 bg-emerald-500/10 border-emerald-500/20',
    'text-amber-400 bg-amber-500/10 border-amber-500/20',
    'text-rose-400 bg-rose-500/10 border-rose-500/20',
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 p-5 rounded-2xl bg-zinc-900/60 border border-purple-500/20 backdrop-blur-sm">
        <div className="w-10 h-10 rounded-xl bg-purple-500/10 flex items-center justify-center text-purple-400 flex-shrink-0">
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /></svg>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-base font-black text-white tracking-tight">Verified Skills</h3>
            <span className="text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/20">Credentials</span>
          </div>
          <p className="text-[13px] text-zinc-400 leading-relaxed">
            On-chain capability credentials and task proof records — skills that have been verified by protocol validators.
          </p>
        </div>
      </div>

      {/* Lookup Form */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">Credential Lookup</div>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            value={address}
            onChange={e => setAddress(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && lookup()}
            placeholder="0x... agent address"
            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-purple-500/50 transition-all font-mono"
          />
          <select
            value={chain}
            onChange={e => setChain(e.target.value as VouchingChain)}
            className="bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white focus:outline-none focus:border-purple-500/50 transition-all appearance-none"
          >
            <option value="base">Base</option>
            <option value="avalanche">Avalanche</option>
            <option value="arbitrum">Arbitrum</option>
            <option value="polygon">Polygon</option>
          </select>
          <button
            onClick={lookup}
            disabled={loading || !address.trim()}
            className="px-5 py-2.5 bg-purple-500 text-white rounded-xl font-bold text-sm hover:bg-purple-400 transition-all shadow-lg disabled:opacity-40 flex items-center gap-2 flex-shrink-0"
          >
            {loading && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
            {loading ? 'Loading…' : 'Lookup'}
          </button>
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="flex items-center gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
          <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
          <p className="text-sm text-red-400">{error}</p>
        </div>
      )}

      {queried && !loading && !error && !data && (
        <div className="text-center py-12">
          <div className="text-3xl mb-3">🏆</div>
          <p className="text-sm text-zinc-500">No credentials found for this address on {chain}.</p>
        </div>
      )}

      {data && (
        <div className="space-y-4">
          {/* Address pill */}
          <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-zinc-900/60 border border-zinc-800/60 w-fit">
            <span className="text-[10px] font-bold uppercase tracking-widest text-purple-400">Agent</span>
            <span className="text-xs text-zinc-400 font-mono">{address.slice(0, 8)}…{address.slice(-6)}</span>
            <span className="text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded bg-zinc-800 text-zinc-400">{chain}</span>
          </div>

          {/* Stats grid */}
          <div className="grid grid-cols-3 gap-3">
            {[
              { label: 'Total Credentials', value: String(data.totalCredentials), sub: 'all-time issued' },
              { label: 'Active Credentials', value: String(data.activeCredentials), sub: 'currently valid' },
              { label: 'Task Proofs', value: String(data.totalTaskProofs), sub: 'on-chain records' },
            ].map(s => (
              <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden hover:border-zinc-700/50 transition-all">
                <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-purple-500/40 to-transparent" />
                <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                <span className="text-2xl font-extrabold text-white mb-0.5 tracking-tight">{s.value}</span>
                <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
              </div>
            ))}
          </div>

          {/* Capability badges */}
          {data.badges && data.badges.length > 0 && (
            <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-3">
              <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Capability Badges</div>
              <div className="flex flex-wrap gap-2">
                {data.badges.map((badge, i) => (
                  <div
                    key={badge.capability + i}
                    className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-[10px] font-bold uppercase tracking-wider transition-all hover:scale-105 ${badge.active ? capabilityColors[i % capabilityColors.length] : 'text-zinc-600 bg-zinc-800/40 border-zinc-700/40'}`}
                  >
                    {badge.active && (
                      <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" /></svg>
                    )}
                    {badge.capability}
                  </div>
                ))}
              </div>
              {/* Badge details list */}
              <div className="space-y-2 pt-2">
                {data.badges.map((badge, i) => (
                  <div key={badge.capability + i + 'detail'} className="flex items-center justify-between py-2 border-b border-zinc-800/40 last:border-0">
                    <div className="flex items-center gap-2">
                      <span className={`text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded border ${badge.active ? capabilityColors[i % capabilityColors.length] : 'text-zinc-600 bg-zinc-800/40 border-zinc-700/40'}`}>
                        {badge.capability}
                      </span>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className="text-[10px] text-zinc-600">Issued: {badge.issuedAt ? new Date(badge.issuedAt).toLocaleDateString() : 'Unknown'}</span>
                      <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${badge.active ? 'text-emerald-400 bg-emerald-500/10' : 'text-zinc-600 bg-zinc-800'}`}>
                        {badge.active ? 'Active' : 'Expired'}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Protocol note */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-7 h-7 rounded-full bg-purple-500/10 flex items-center justify-center text-purple-400 flex-shrink-0">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-purple-400 font-bold">Verified Skills.</span> Credentials are issued by protocol validators after reviewing task completion proofs. Each badge represents a cryptographically proven capability. Data from <code className="text-purple-300 text-[11px]">/api/agent/credentials</code>.
        </p>
      </div>
    </div>
  );
}

/* ═════════════════════════════════════════════
   11. DISPUTE RESOLUTION TAB
   ═════════════════════════════════════════════ */

type DisputeStats = {
  disputesFiled: string;
  disputesResolved: string;
  totalStakeDisputed: string;
};

type DisputeDetail = {
  id: string;
  status: string;
  claimant: string;
  respondent: string;
  stakeDisputed: string;
  filedAt: string;
  resolvedAt?: string;
  outcome?: string;
};

export function DisputeResolutionTab() {
  const [disputeId, setDisputeId] = useState('');
  const [chain, setChain] = useState<VouchingChain>('base');
  const [stats, setStats] = useState<DisputeStats | null>(null);
  const [detail, setDetail] = useState<DisputeDetail | null>(null);
  const [statsLoading, setStatsLoading] = useState(false);
  const [statsError, setStatsError] = useState<string | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailError, setDetailError] = useState<string | null>(null);
  const [detailQueried, setDetailQueried] = useState(false);

  // Fetch global stats on chain change
  useEffect(() => {
    const fetchStats = async () => {
      setStatsLoading(true);
      setStatsError(null);
      setStats(null);
      try {
        const res = await fetch(`/api/agent/disputes?chain=${chain}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const json = await res.json();
        const ds = json.disputeStats || json;
        setStats({
          disputesFiled: ds.filed || ds.disputesFiled || '0',
          disputesResolved: ds.resolved || ds.disputesResolved || '0',
          totalStakeDisputed: ds.totalStake || ds.totalStakeDisputed || '0',
        });
      } catch (e: unknown) {
        setStatsError(e instanceof Error ? e.message : 'Failed to fetch dispute stats');
      } finally {
        setStatsLoading(false);
      }
    };
    fetchStats();
  }, [chain]);

  const lookupDispute = async () => {
    if (!disputeId.trim()) return;
    setDetailLoading(true);
    setDetailError(null);
    setDetail(null);
    setDetailQueried(true);
    try {
      const res = await fetch(`/api/agent/disputes?chain=${chain}&id=${encodeURIComponent(disputeId.trim())}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      setDetail(json);
    } catch (e: unknown) {
      setDetailError(e instanceof Error ? e.message : 'Failed to fetch dispute details');
    } finally {
      setDetailLoading(false);
    }
  };

  const resolutionPct = stats && Number(stats.disputesFiled) > 0
    ? Math.round((Number(stats.disputesResolved) / Number(stats.disputesFiled)) * 100)
    : 0;

  const statusStyles: Record<string, string> = {
    open: 'text-amber-400 bg-amber-500/10 border-amber-500/20',
    resolved: 'text-emerald-400 bg-emerald-500/10 border-emerald-500/20',
    dismissed: 'text-zinc-400 bg-zinc-800 border-zinc-700/40',
    escalated: 'text-red-400 bg-red-500/10 border-red-500/20',
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 p-5 rounded-2xl bg-zinc-900/60 border border-red-500/20 backdrop-blur-sm">
        <div className="w-10 h-10 rounded-xl bg-red-500/10 flex items-center justify-center text-red-400 flex-shrink-0">
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M3 6h18M3 12h18M3 18h18" /><path d="M12 3v18" /></svg>
        </div>
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <h3 className="text-base font-black text-white tracking-tight">Agent Justice</h3>
            <span className="text-[9px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-full bg-red-500/10 text-red-400 border border-red-500/20">Disputes</span>
          </div>
          <p className="text-[13px] text-zinc-400 leading-relaxed">
            On-chain dispute resolution for agent conflicts. Community arbitration with stake-weighted voting.
          </p>
        </div>
      </div>

      {/* Chain Selector */}
      <div className="flex items-center gap-3">
        <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Chain</span>
        <div className="flex gap-1.5">
          {VOUCHING_CHAINS.map(c => (
            <button
              key={c}
              onClick={() => setChain(c)}
              className={`text-[10px] font-bold uppercase tracking-wider px-3 py-1.5 rounded-lg transition-all ${chain === c ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'text-zinc-600 hover:text-zinc-400 bg-zinc-900/40 border border-zinc-800/60'}`}
            >
              {c}
            </button>
          ))}
        </div>
      </div>

      {/* Global Stats */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Global Dispute Stats — {chain}</div>
        {statsLoading ? (
          <div className="flex items-center justify-center py-8">
            <svg className="w-6 h-6 animate-spin text-red-400" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>
          </div>
        ) : statsError ? (
          <div className="flex items-center gap-3 p-3 rounded-xl bg-red-500/5 border border-red-500/20">
            <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
            <p className="text-sm text-red-400">{statsError}</p>
          </div>
        ) : stats ? (
          <div className="space-y-4">
            <div className="grid grid-cols-3 gap-3">
              {[
                { label: 'Disputes Filed', value: String(stats.disputesFiled), sub: 'all disputes' },
                { label: 'Disputes Resolved', value: String(stats.disputesResolved), sub: `${resolutionPct}% resolution rate` },
                { label: 'Stake Disputed', value: `${stats.totalStakeDisputed} ETH`, sub: 'total at stake' },
              ].map(s => (
                <div key={s.label} className="rounded-2xl bg-zinc-900/60 border border-zinc-800 p-4 flex flex-col relative overflow-hidden hover:border-zinc-700/50 transition-all">
                  <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-red-500/40 to-transparent" />
                  <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mb-1.5">{s.label}</span>
                  <span className="text-2xl font-extrabold text-white mb-0.5 tracking-tight">{s.value}</span>
                  <span className="text-[11px] text-zinc-500 leading-relaxed">{s.sub}</span>
                </div>
              ))}
            </div>
            {/* Resolution rate bar */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Resolution Rate</span>
                <span className="text-sm font-bold text-red-400">{resolutionPct}%</span>
              </div>
              <div className="h-2 rounded-full bg-zinc-800 overflow-hidden">
                <div
                  className="h-full rounded-full bg-gradient-to-r from-red-600 to-red-400 transition-all duration-700"
                  style={{ width: `${resolutionPct}%` }}
                />
              </div>
            </div>
          </div>
        ) : (
          <div className="text-center py-8">
            <p className="text-sm text-zinc-500">No dispute data available.</p>
          </div>
        )}
      </div>

      {/* Dispute Detail Lookup */}
      <div className="rounded-2xl bg-zinc-900/40 border border-zinc-800/60 p-5 space-y-4">
        <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-3">Dispute Detail Lookup</div>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            value={disputeId}
            onChange={e => setDisputeId(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && lookupDispute()}
            placeholder="Dispute ID"
            className="flex-1 bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-2.5 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-red-500/50 transition-all font-mono"
          />
          <button
            onClick={lookupDispute}
            disabled={detailLoading || !disputeId.trim()}
            className="px-5 py-2.5 bg-red-500 text-white rounded-xl font-bold text-sm hover:bg-red-400 transition-all shadow-lg disabled:opacity-40 flex items-center gap-2 flex-shrink-0"
          >
            {detailLoading && <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" /><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" /></svg>}
            {detailLoading ? 'Loading…' : 'Lookup'}
          </button>
        </div>

        {detailError && (
          <div className="flex items-center gap-3 p-4 rounded-xl bg-red-500/5 border border-red-500/20">
            <svg className="w-4 h-4 text-red-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" /></svg>
            <p className="text-sm text-red-400">{detailError}</p>
          </div>
        )}

        {detailQueried && !detailLoading && !detailError && !detail && (
          <div className="text-center py-8">
            <div className="text-2xl mb-2">⚖</div>
            <p className="text-sm text-zinc-500">No dispute found with ID &ldquo;{disputeId}&rdquo; on {chain}.</p>
          </div>
        )}

        {detail && (
          <div className="space-y-3 pt-2">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">Dispute <span className="font-mono text-zinc-400">{detail.id.slice(0, 10)}…</span></span>
              <span className={`text-[9px] font-bold uppercase tracking-wider px-2.5 py-1 rounded-full border ${statusStyles[detail.status] || 'text-zinc-400 bg-zinc-800 border-zinc-700/40'}`}>
                {detail.status}
              </span>
            </div>
            <div className="grid grid-cols-2 gap-3">
              {[
                { label: 'Claimant', value: detail.claimant.slice(0, 8) + '…' + detail.claimant.slice(-6), sub: 'filing agent', mono: true },
                { label: 'Respondent', value: detail.respondent.slice(0, 8) + '…' + detail.respondent.slice(-6), sub: 'responding agent', mono: true },
                { label: 'Stake Disputed', value: `${detail.stakeDisputed} ETH`, sub: 'at stake' },
                { label: 'Filed', value: new Date(detail.filedAt).toLocaleDateString(), sub: 'date filed' },
              ].map(s => (
                <div key={s.label} className="rounded-xl bg-zinc-900/60 border border-zinc-800 p-3 flex flex-col">
                  <span className="text-[9px] text-zinc-500 font-bold uppercase tracking-widest mb-1">{s.label}</span>
                  <span className={`text-sm font-bold text-white ${s.mono ? 'font-mono text-xs' : ''}`}>{s.value}</span>
                  <span className="text-[10px] text-zinc-600">{s.sub}</span>
                </div>
              ))}
            </div>
            {detail.outcome && (
              <div className="flex items-start gap-3 p-3 rounded-xl bg-zinc-900/60 border border-zinc-800/60">
                <svg className="w-4 h-4 text-zinc-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                <div>
                  <span className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest block mb-0.5">Outcome</span>
                  <span className="text-sm text-zinc-300">{detail.outcome}</span>
                  {detail.resolvedAt && <span className="text-[10px] text-zinc-600 block mt-0.5">Resolved {new Date(detail.resolvedAt).toLocaleDateString()}</span>}
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Protocol note */}
      <div className="flex items-start gap-3 p-4 rounded-2xl bg-zinc-900/30 border border-zinc-800/40">
        <div className="w-7 h-7 rounded-full bg-red-500/10 flex items-center justify-center text-red-400 flex-shrink-0">
          <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><path d="M12 8v4M12 16h.01" /></svg>
        </div>
        <p className="text-xs text-zinc-400 leading-relaxed">
          <span className="text-red-400 font-bold">Agent Justice.</span> Disputes are arbitrated by a stake-weighted community council. Resolution history is immutable and on-chain. Data sourced from <code className="text-red-300 text-[11px]">/api/agent/disputes</code>.
        </p>
      </div>
    </div>
  );
}
