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

interface HubStats {
  totalIdentities: number;
  activeBonds: number;
  chainCounts: { base: number; avalanche: number; arbitrum: number; polygon: number };
  chainBonded: { base: { amount: number; token: string }; avalanche: { amount: number; token: string }; arbitrum: { amount: number; token: string }; polygon: { amount: number; token: string } };
}

/* ── Animated Network Canvas ── */
function NetworkViz() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const animRef = useRef<number>(0);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const W = canvas.width = canvas.offsetWidth;
    const H = canvas.height = canvas.offsetHeight;

    const nodes = Array.from({ length: 11 }, () => ({
      x: Math.random() * W,
      y: Math.random() * H,
      vx: (Math.random() - 0.5) * 0.28,
      vy: (Math.random() - 0.5) * 0.28,
      r: Math.random() * 2.2 + 1.2,
    }));

    const MAX_DIST = 160;

    function draw() {
      if (!ctx || !canvas) return;
      ctx.clearRect(0, 0, W, H);

      // Lines
      for (let i = 0; i < nodes.length; i++) {
        for (let j = i + 1; j < nodes.length; j++) {
          const dx = nodes[i].x - nodes[j].x;
          const dy = nodes[i].y - nodes[j].y;
          const dist = Math.sqrt(dx * dx + dy * dy);
          if (dist < MAX_DIST) {
            const alpha = (1 - dist / MAX_DIST) * 0.12;
            ctx.beginPath();
            ctx.moveTo(nodes[i].x, nodes[i].y);
            ctx.lineTo(nodes[j].x, nodes[j].y);
            ctx.strokeStyle = `rgba(255,107,53,${alpha})`;
            ctx.lineWidth = 0.8;
            ctx.stroke();
          }
        }
      }

      // Dots
      for (const n of nodes) {
        ctx.beginPath();
        ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(255,107,53,0.25)';
        ctx.fill();

        // Move
        n.x += n.vx;
        n.y += n.vy;
        if (n.x < 0 || n.x > W) n.vx *= -1;
        if (n.y < 0 || n.y > H) n.vy *= -1;
      }

      animRef.current = requestAnimationFrame(draw);
    }

    animRef.current = requestAnimationFrame(draw);
    return () => cancelAnimationFrame(animRef.current);
  }, []);

  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'absolute',
        inset: 0,
        width: '100%',
        height: '100%',
        opacity: 0.13,
        pointerEvents: 'none',
      }}
    />
  );
}

/* ── Animated Street Cred Ring ── */
function TrustRing({ target }: { target: number }) {
  const [score, setScore] = useState(0);
  const mounted = useRef(true);
  useEffect(() => {
    mounted.current = true;
    let frame: number;
    const start = performance.now();
    function tick(now: number) {
      if (!mounted.current) return;
      const p = Math.min((now - start) / 1800, 1);
      setScore(Math.round((1 - Math.pow(1 - p, 3)) * target));
      if (p < 1) frame = requestAnimationFrame(tick);
    }
    frame = requestAnimationFrame(tick);
    return () => { mounted.current = false; cancelAnimationFrame(frame); };
  }, [target]);
  const r = 44, c = 2 * Math.PI * r;
  return (
    <div style={{ position: 'relative', width: 100, height: 100 }}>
      <svg width={100} height={100} viewBox="0 0 100 100" style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={50} cy={50} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="6" />
        <circle cx={50} cy={50} r={r} fill="none" stroke="#22C55E" strokeWidth="6"
          strokeDasharray={c} strokeDashoffset={c * (1 - score / 100)}
          strokeLinecap="round" style={{ filter: 'drop-shadow(0 0 8px rgba(34,197,94,0.4))', transition: 'stroke-dashoffset 0.05s linear' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontSize: 26, fontWeight: 800, color: '#22C55E', fontFamily: 'var(--font-mono)', lineHeight: 1 }}>{score}</span>
        <span style={{ fontSize: 9, color: '#52525b', fontWeight: 600 }}>/ 100</span>
      </div>
    </div>
  );
}

/* ── Count-Up Hook ── */
function useCountUp(target: number, duration = 1600, active = true): number {
  const [value, setValue] = useState(0);
  const frameRef = useRef<number>(0);
  useEffect(() => {
    if (!active || target === 0) return;
    const start = performance.now();
    function tick(now: number) {
      const p = Math.min((now - start) / duration, 1);
      setValue(Math.round((1 - Math.pow(1 - p, 3)) * target));
      if (p < 1) frameRef.current = requestAnimationFrame(tick);
    }
    frameRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(frameRef.current);
  }, [target, duration, active]);
  return value;
}

/* ── Animated Stat Card ── */
function StatCard({
  label, rawValue, sub, prefix = '', suffix = '', decimals = 0,
}: {
  label: string;
  rawValue: number | null;
  sub?: string;
  prefix?: string;
  suffix?: string;
  decimals?: number;
}) {
  const active = rawValue !== null;
  const count = useCountUp(rawValue ?? 0, 1600, active);
  const display = active
    ? `${prefix}${decimals > 0 ? count.toFixed(decimals) : count}${suffix}`
    : '—';

  return (
    <div
      className="glass-panel glass-panel-hover"
      style={{
        padding: '20px 16px',
        textAlign: 'center',
        flex: 1,
        minWidth: 130,
        transition: 'all 0.3s cubic-bezier(0.4,0,0.2,1)',
        cursor: 'default',
        position: 'relative',
        overflow: 'hidden',
      }}
      onMouseEnter={e => {
        (e.currentTarget as HTMLDivElement).style.boxShadow = '0 0 24px rgba(255,107,53,0.1), 0 4px 16px rgba(0,0,0,0.3)';
      }}
      onMouseLeave={e => {
        (e.currentTarget as HTMLDivElement).style.boxShadow = '';
      }}
    >
      <div style={{
        fontSize: 26, fontWeight: 700, color: '#FF6B35',
        letterSpacing: '-0.02em', marginBottom: 4,
        fontFamily: 'var(--font-mono)',
      }}>
        {display}
      </div>
      <div style={{ fontSize: 12, color: '#a1a1aa', fontWeight: 500 }}>{label}</div>
      {sub && <div style={{ fontSize: 10, color: '#52525b', marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

/* ── Chain Dot Row ── */
const CHAINS = [
  { label: 'Base', color: '#3B82F6', bg: 'rgba(59,130,246,0.12)' },
  { label: 'Avalanche', color: '#EF4444', bg: 'rgba(239,68,68,0.12)' },
  { label: 'Arbitrum', color: '#28A0F0', bg: 'rgba(40,160,240,0.12)' },
  { label: 'Polygon', color: '#8247E5', bg: 'rgba(130,71,229,0.12)' },
];

function ChainDots({ counts }: { counts?: { base: number; avalanche: number; arbitrum: number; polygon: number } }) {
  const vals = [counts?.base, counts?.avalanche, counts?.arbitrum, counts?.polygon];
  return (
    <div style={{
      display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap',
      marginTop: 20,
    }}>
      {CHAINS.map((c, i) => (
        <div key={c.label} style={{
          display: 'flex', alignItems: 'center', gap: 7,
          padding: '6px 13px', borderRadius: 100,
          background: c.bg,
          border: `1px solid ${c.color}22`,
        }}>
          <div style={{
            width: 8, height: 8, borderRadius: '50%',
            backgroundColor: c.color,
            boxShadow: `0 0 7px ${c.color}88`,
            flexShrink: 0,
          }} />
          <span style={{ fontSize: 12, fontWeight: 600, color: c.color }}>{c.label}</span>
          {vals[i] !== undefined && (
            <span style={{ fontSize: 11, color: '#71717a', fontFamily: 'var(--font-mono)' }}>
              {vals[i]}
            </span>
          )}
        </div>
      ))}
    </div>
  );
}

/* ── Feature Icon Glow ── */
const FEATURE_COLORS = ['#6366F1', '#FF6B35', '#3B82F6', '#22C55E', '#EC4899', '#F59E0B', '#8B5CF6', '#06B6D4'];

function FeatureCard({ icon, title, desc, index }: { icon: string; title: string; desc: string; index: number }) {
  const color = FEATURE_COLORS[index % FEATURE_COLORS.length];
  const stagger = `stagger-${index + 1}` as string;
  return (
    <div
      className={`vf-card animate-in fade-in ${stagger}`}
      style={{ padding: 22, position: 'relative', overflow: 'hidden' }}
    >
      {/* Icon glow blob */}
      <div style={{
        position: 'absolute', top: -20, left: -20,
        width: 80, height: 80,
        borderRadius: '50%',
        background: `radial-gradient(circle, ${color}18, transparent 70%)`,
        pointerEvents: 'none',
      }} />
      <div style={{
        fontSize: 22, marginBottom: 10,
        width: 40, height: 40,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        borderRadius: 10,
        background: `${color}14`,
        border: `1px solid ${color}22`,
      }}>
        {icon}
      </div>
      <h3 style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5', marginBottom: 6 }}>{title}</h3>
      <p style={{ fontSize: 12, color: '#a1a1aa', lineHeight: 1.55, margin: 0 }}>{desc}</p>
    </div>
  );
}

/* ── Chain Logo Row (for on-chain proof) ── */
function ChainLogos() {
  return (
    <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 24 }}>
      {CHAINS.map((c) => (
        <div key={c.label} className="subtle-float" style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
          animationDelay: `${CHAINS.indexOf(c) * 0.3}s`,
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: '50%',
            background: c.bg,
            border: `2px solid ${c.color}44`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: `0 0 16px ${c.color}22`,
          }}>
            <div style={{ width: 16, height: 16, borderRadius: '50%', backgroundColor: c.color }} />
          </div>
          <span style={{ fontSize: 10, color: '#71717a', fontWeight: 600, letterSpacing: '0.04em' }}>{c.label.toUpperCase()}</span>
        </div>
      ))}
    </div>
  );
}

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

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

type ActivityEvent = {
  id: string;
  icon: string;
  description: string;
  chain: string;       // capitalized label e.g. 'Base'
  timestamp: string;   // human relative string, derived from real unix ts
  accent: string;
  type: 'register' | 'vns' | 'accountability' | 'partnership' | 'xtmp';
};

// Server-side shape from /api/hub/activity
interface ServerBondEvent {
  id: string;
  chain: 'base' | 'avalanche' | 'arbitrum' | 'polygon';
  chainLabel: string;
  contract: 'partnership' | 'accountability';
  bondId: number;
  aiAgent: string;
  stakeAmount: number;
  token: string;
  timestamp: number;   // unix seconds
  active: boolean;
  explorerUrl: string;
}

function shortAddr(a: string): string {
  return a.length === 42 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a;
}

function relativeTime(unixSeconds: number): string {
  const now = Math.floor(Date.now() / 1000);
  const diff = Math.max(0, now - unixSeconds);
  if (diff < 30) return 'just now';
  if (diff < 60) return `${diff}s ago`;
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  if (diff < 86400 * 30) return `${Math.floor(diff / 86400)}d ago`;
  if (diff < 86400 * 365) return `${Math.floor(diff / 86400 / 30)}mo ago`;
  return `${Math.floor(diff / 86400 / 365)}y ago`;
}

function mapServerEvent(e: ServerBondEvent): ActivityEvent {
  const accent = e.contract === 'partnership' ? '#8247E5' : '#3B82F6';
  const icon = e.contract === 'partnership' ? '🤝' : '🔗';
  const action = e.contract === 'partnership' ? 'partnership bond by' : 'accountability bond by';
  const amount = e.stakeAmount.toFixed(
    e.stakeAmount >= 1 ? 2 : e.stakeAmount >= 0.01 ? 4 : 6,
  );
  return {
    id: e.id,
    icon,
    accent,
    chain: e.chainLabel,
    type: e.contract,
    timestamp: relativeTime(e.timestamp),
    description: `${action} ${shortAddr(e.aiAgent)} (${amount} ${e.token})`,
  };
}

function LiveActivityFeed({ stats }: { stats: HubStats | null }) {
  const [events, setEvents] = useState<ActivityEvent[] | null>(null); // null = loading
  const [errored, setErrored] = useState(false);
  const [flashIds, setFlashIds] = useState<Set<string>>(() => new Set());
  const seenIdsRef = useRef<Set<string>>(new Set());
  const [isHovered, setIsHovered] = useState(false);
  const [scrollOffset, setScrollOffset] = useState(0);
  const rafRef = useRef<number>(0);
  const lastTimeRef = useRef<number>(0);
  const containerRef = useRef<HTMLDivElement>(null);
  const ROW_HEIGHT = 58; // px per row including gap

  // Fetch real on-chain activity, refresh every 60s. Flash any genuinely new
  // bond IDs we hadn't seen on the previous fetch.
  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const r = await fetch('/api/hub/activity');
        if (!r.ok) throw new Error('http ' + r.status);
        const j = await r.json();
        if (cancelled) return;
        if (!Array.isArray(j.events) || j.events.length === 0) {
          setErrored(true);
          return;
        }
        setErrored(false);
        const mapped = (j.events as ServerBondEvent[]).map(mapServerEvent);

        // Detect newly-seen bond IDs (only after first load).
        const isFirstLoad = seenIdsRef.current.size === 0;
        const newIds = new Set<string>();
        for (const ev of mapped) {
          if (!seenIdsRef.current.has(ev.id)) {
            if (!isFirstLoad) newIds.add(ev.id);
            seenIdsRef.current.add(ev.id);
          }
        }
        setEvents(mapped);
        if (newIds.size > 0) {
          setFlashIds(newIds);
          setTimeout(() => setFlashIds(new Set()), 1800);
        }
      } catch {
        if (!cancelled) setErrored(true);
      }
    }
    load();
    const interval = setInterval(load, 60_000);
    return () => { cancelled = true; clearInterval(interval); };
  }, []);

  // Auto-scroll via rAF
  useEffect(() => {
    function frame(ts: number) {
      if (!lastTimeRef.current) lastTimeRef.current = ts;
      const dt = ts - lastTimeRef.current;
      lastTimeRef.current = ts;

      if (!isHovered) {
        setScrollOffset(prev => {
          const next = prev + dt * 0.018; // ~18px/s
          // Wrap when we've scrolled past one row height
          if (next >= ROW_HEIGHT) {
            return next - ROW_HEIGHT;
          }
          return next;
        });
      }
      rafRef.current = requestAnimationFrame(frame);
    }
    rafRef.current = requestAnimationFrame(frame);
    return () => cancelAnimationFrame(rafRef.current);
  }, [isHovered]);

  return (
    <section style={{ padding: '0 24px 56px' }}>
      <div style={{ maxWidth: 760, margin: '0 auto' }}>

        {/* Section header */}
        <div style={{ textAlign: 'center', marginBottom: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, marginBottom: 8 }}>
            {/* Pulsing live dot */}
            <div style={{ position: 'relative', width: 10, height: 10, flexShrink: 0 }}>
              <div style={{
                position: 'absolute', inset: -4,
                borderRadius: '50%',
                border: '1.5px solid rgba(34,197,94,0.45)',
                animation: 'ripple 2s ease-out infinite',
              }} />
              <div style={{
                width: 10, height: 10, borderRadius: '50%',
                backgroundColor: '#22C55E',
                boxShadow: '0 0 10px rgba(34,197,94,0.7)',
                animation: 'breathe 2.5s ease-in-out infinite',
              }} />
            </div>
            <h2 style={{
              fontSize: 22, fontWeight: 700, color: '#F4F4F5',
              letterSpacing: '-0.02em', margin: 0,
            }}>Live Protocol Activity</h2>
            <div style={{
              padding: '2px 9px', borderRadius: 8,
              background: 'rgba(34,197,94,0.12)',
              border: '1px solid rgba(34,197,94,0.25)',
              fontSize: 10, fontWeight: 800, color: '#22C55E',
              letterSpacing: '0.08em',
            }}>LIVE</div>
          </div>

          {/* Compact stats row — real data from API */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 0,
            padding: '6px 16px', borderRadius: 100,
            background: 'rgba(255,255,255,0.03)',
            border: '1px solid rgba(255,255,255,0.07)',
            fontSize: 12, color: '#71717a', fontFamily: 'var(--font-mono)',
          }}>
            <span style={{ color: '#a1a1aa', fontWeight: 600 }}>{stats ? stats.totalIdentities : '—'}</span>
            <span style={{ color: '#3a3a3f', margin: '0 6px' }}>agents</span>
            <span style={{ color: '#52525b', margin: '0 8px' }}>·</span>
            <span style={{ color: '#a1a1aa', fontWeight: 600 }}>{stats ? stats.activeBonds : '—'}</span>
            <span style={{ color: '#3a3a3f', margin: '0 6px' }}>bonds</span>
            <span style={{ color: '#52525b', margin: '0 8px' }}>·</span>
            <span style={{ color: '#a1a1aa', fontWeight: 600 }}>4</span>
            <span style={{ color: '#3a3a3f', margin: '0 6px' }}>chains</span>
          </div>
        </div>

        {/* Feed panel */}
        <div
          style={{
            position: 'relative',
            borderRadius: 16,
            background: 'rgba(9,9,11,0.7)',
            border: '1px solid rgba(255,255,255,0.07)',
            backdropFilter: 'blur(24px)',
            WebkitBackdropFilter: 'blur(24px)',
            overflow: 'hidden',
            height: 320,
          }}
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
        >
          {/* Top fade gradient */}
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0,
            height: 48, zIndex: 2, pointerEvents: 'none',
            background: 'linear-gradient(180deg, rgba(9,9,11,0.95) 0%, transparent 100%)',
          }} />
          {/* Bottom fade gradient */}
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            height: 48, zIndex: 2, pointerEvents: 'none',
            background: 'linear-gradient(0deg, rgba(9,9,11,0.95) 0%, transparent 100%)',
          }} />

          {/* Scrolling list */}
          {events && events.length > 0 ? (
            <div
              ref={containerRef}
              style={{
                position: 'absolute',
                top: 0, left: 0, right: 0,
                transform: `translateY(-${scrollOffset}px)`,
                willChange: 'transform',
                padding: '12px 0',
              }}
            >
              {events.map((event) => (
                <ActivityRow
                  key={event.id}
                  event={event}
                  isFlashing={flashIds.has(event.id)}
                />
              ))}
              {/* Duplicate first few rows for seamless loop appearance */}
              {events.slice(0, 5).map((event) => (
                <ActivityRow
                  key={`dup-${event.id}`}
                  event={event}
                  isFlashing={false}
                />
              ))}
            </div>
          ) : errored ? (
            <div style={{
              position: 'absolute', inset: 0, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
              color: '#71717a', fontSize: 13, fontFamily: 'var(--font-mono)',
              textAlign: 'center', padding: 24,
            }}>
              Live data temporarily unavailable. Reconnecting…
            </div>
          ) : (
            <div style={{ padding: '12px 8px' }}>
              {[0, 1, 2, 3, 4].map((i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 16px', margin: '0 8px 2px',
                  borderRadius: 10, height: 38,
                  background: 'rgba(255,255,255,0.02)',
                  border: '1px solid rgba(255,255,255,0.04)',
                  opacity: 0.5,
                }}>
                  <div style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,255,255,0.04)' }} />
                  <div style={{ flex: 1, height: 12, borderRadius: 4, background: 'rgba(255,255,255,0.05)' }} />
                  <div style={{ width: 50, height: 18, borderRadius: 8, background: 'rgba(255,255,255,0.04)' }} />
                  <div style={{ width: 40, height: 10, borderRadius: 4, background: 'rgba(255,255,255,0.05)' }} />
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function ActivityRow({ event, isFlashing }: { event: ActivityEvent; isFlashing: boolean }) {
  const chainColor = CHAIN_COLORS[event.chain] ?? '#a1a1aa';
  const chainBg = CHAIN_BG[event.chain] ?? 'rgba(161,161,170,0.12)';
  const [hovered, setHovered] = useState(false);

  const accentRgb = event.accent === '#FF6B35' ? '255,107,53'
    : event.accent === '#22C55E' ? '34,197,94'
    : event.accent === '#3B82F6' ? '59,130,246'
    : event.accent === '#8247E5' ? '130,71,229'
    : event.accent === '#06B6D4' ? '6,182,212'
    : '255,107,53';

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 12,
        padding: '10px 16px',
        margin: '0 8px 2px',
        borderRadius: 10,
        cursor: 'default',
        transition: 'background 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease',
        background: isFlashing
          ? `rgba(${accentRgb},0.08)`
          : hovered
          ? 'rgba(255,255,255,0.04)'
          : 'transparent',
        border: `1px solid ${
          isFlashing
            ? `rgba(${accentRgb},0.35)`
            : hovered
            ? 'rgba(255,255,255,0.1)'
            : 'rgba(255,255,255,0.03)'
        }`,
        boxShadow: isFlashing ? `0 0 18px rgba(${accentRgb},0.18)` : 'none',
      }}
    >
      {/* Icon badge */}
      <div style={{
        width: 34, height: 34, flexShrink: 0,
        borderRadius: 9,
        background: `rgba(${accentRgb},0.1)`,
        border: `1px solid rgba(${accentRgb},0.2)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 15,
        boxShadow: isFlashing ? `0 0 10px rgba(${accentRgb},0.3)` : 'none',
        transition: 'box-shadow 0.3s ease',
      }}>
        {event.icon}
      </div>

      {/* Description */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <span style={{
          fontSize: 13, fontWeight: 500,
          color: isFlashing ? '#F4F4F5' : '#d4d4d8',
          fontFamily: 'var(--font-mono)',
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          display: 'block',
          transition: 'color 0.3s ease',
        }}>
          {event.description}
        </span>
      </div>

      {/* Chain badge */}
      <div style={{
        flexShrink: 0,
        padding: '3px 9px', borderRadius: 8,
        background: chainBg,
        border: `1px solid ${chainColor}33`,
        fontSize: 11, fontWeight: 700,
        color: chainColor,
        letterSpacing: '0.03em',
        whiteSpace: 'nowrap',
      }}>
        {event.chain}
      </div>

      {/* Timestamp */}
      <div style={{
        flexShrink: 0, minWidth: 58, textAlign: 'right',
        fontSize: 11, color: isFlashing ? '#a1a1aa' : '#52525b',
        fontFamily: 'var(--font-mono)',
        transition: 'color 0.3s ease',
      }}>
        {event.timestamp}
      </div>
    </div>
  );
}

/* ── Main Export ── */
export default function Home({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const [stats, setStats] = useState<HubStats | null>(null);

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

  // Protocol Health Score — derived from real on-chain data
  // 25 pts: has agents on any chain. 25 pts: has bonds. 25 pts: value bonded > 0. 20 pts: multi-chain (4 chains live). 5 pts: 134 contracts deployed.
  const protocolHealth = (() => {
    if (!stats) return 0;
    let score = 0;
    if (stats.totalIdentities > 0) score += 25;
    if (stats.activeBonds > 0) score += 25;
    if (stats.chainBonded && Object.values(stats.chainBonded).some((c: { amount: number }) => c.amount > 0)) score += 25;
    const chainsActive = Object.values(stats.chainCounts || {}).filter(c => c > 0).length;
    score += Math.min(chainsActive, 4) * 5; // up to 20 pts
    score += 5; // 134 contracts deployed is a fact
    return Math.min(score, 100);
  })();

  return (
    <div>
      {/* ═══ HERO ═══ */}
      <section style={{
        position: 'relative', overflow: 'hidden',
        padding: 'clamp(80px, 12vw, 120px) 24px clamp(60px, 8vw, 80px)',
        textAlign: 'center',
      }}>
        {/* Animated network background */}
        <NetworkViz />

        {/* Ambient glow */}
        <div style={{
          position: 'absolute', top: '-30%', left: '50%', transform: 'translateX(-50%)',
          width: 900, height: 700,
          background: 'radial-gradient(ellipse, rgba(255,107,53,0.07) 0%, transparent 70%)',
          pointerEvents: 'none',
        }} />

        <div style={{ position: 'relative', maxWidth: 760, margin: '0 auto' }}>
          {/* Badge with pulse glow */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '5px 14px', borderRadius: 100, marginBottom: 28,
            border: '1px solid rgba(255,107,53,0.2)',
            backgroundColor: 'rgba(255,107,53,0.05)',
            animation: 'borderGlow 3s ease-in-out infinite',
          }}>
            <div style={{
              position: 'relative', width: 8, height: 8,
            }}>
              {/* Pulse ring */}
              <div style={{
                position: 'absolute', inset: -3,
                borderRadius: '50%',
                border: '1.5px solid rgba(16,185,129,0.5)',
                animation: 'ripple 2s ease-out infinite',
              }} />
              <div style={{
                width: 8, height: 8, borderRadius: '50%',
                backgroundColor: '#10b981',
                boxShadow: '0 0 10px rgba(16,185,129,0.7)',
                animation: 'breathe 2.5s ease-in-out infinite',
              }} />
            </div>
            <span style={{ fontSize: 11, fontWeight: 700, color: '#FF8C5A', letterSpacing: '0.06em' }}>
              LIVE ON 4 MAINNET CHAINS — {TOTAL_CONTRACTS} VERIFIED CONTRACTS
            </span>
          </div>

          {/* KYA Badge */}
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '5px 14px', borderRadius: 100, marginBottom: 18,
            background: 'rgba(255,107,53,0.06)',
            border: '1px solid rgba(255,107,53,0.15)',
          }}>
            <span style={{ fontSize: 13, fontWeight: 800, color: '#FF6B35', letterSpacing: '0.06em' }}>KYA</span>
            <span style={{ width: 1, height: 12, background: 'rgba(255,107,53,0.25)' }} />
            <span style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', letterSpacing: '0.02em' }}>Know Your Agent</span>
          </div>

          {/* Headline */}
          <h1 style={{
            fontSize: 'clamp(34px, 5.5vw, 60px)', fontWeight: 800,
            lineHeight: 1.06, color: '#F4F4F5', letterSpacing: '-0.035em',
            margin: '0 0 20px',
          }}>
            <span style={{ color: '#FF6B35' }}>Vaultfire</span><br />
            The Trust Layer for AI Agents
          </h1>

          {/* Mission statement — the creed */}
          <p style={{
            fontSize: 'clamp(14px, 1.7vw, 16px)',
            fontStyle: 'italic',
            color: '#FF6B35',
            opacity: 0.85,
            lineHeight: 1.5,
            maxWidth: 540,
            margin: '0 auto 24px',
            letterSpacing: '0.005em',
          }}>
            Making human thriving more profitable than extraction.
          </p>

          {/* Sub */}
          <p style={{
            fontSize: 'clamp(15px, 2vw, 18px)', color: '#a1a1aa',
            lineHeight: 1.65, maxWidth: 560, margin: '0 auto 12px',
          }}>
            Vaultfire is <strong style={{ color: '#F4F4F5' }}>KYA — Know Your Agent</strong>.
            Real bonds, real proof, real accountability for the agent economy.
          </p>
          <p style={{
            fontSize: 13, color: '#52525b', maxWidth: 480, margin: '0 auto 36px',
          }}>
            What HTTPS did for web security, Vaultfire does for AI agents.
          </p>

          {/* CTA row with trust ring */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 36, flexWrap: 'wrap',
          }}>
            <TrustRing target={protocolHealth} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'flex-start' }}>
              <button onClick={() => onNavigate('vns')} className="vf-btn" style={{
                padding: '13px 30px', borderRadius: 12, border: 'none',
                background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                color: '#fff', fontSize: 15, fontWeight: 700, cursor: 'pointer',
                boxShadow: '0 4px 20px rgba(255,107,53,0.3)',
                transition: 'all 0.2s cubic-bezier(0.4,0,0.2,1)',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 6px 28px rgba(255,107,53,0.45)';
                (e.currentTarget as HTMLButtonElement).style.transform = 'translateY(-1px)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLButtonElement).style.boxShadow = '0 4px 20px rgba(255,107,53,0.3)';
                (e.currentTarget as HTMLButtonElement).style.transform = '';
              }}
              >
                Register an Agent →
              </button>
              <button onClick={() => onNavigate('agent-hub')} className="vf-btn" style={{
                padding: '13px 30px', borderRadius: 12,
                border: '1px solid rgba(255,255,255,0.1)',
                backgroundColor: 'rgba(255,255,255,0.03)',
                color: '#F4F4F5', fontSize: 15, fontWeight: 600, cursor: 'pointer',
                transition: 'all 0.2s cubic-bezier(0.4,0,0.2,1)',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,107,53,0.3)';
                (e.currentTarget as HTMLButtonElement).style.backgroundColor = 'rgba(255,107,53,0.06)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
                (e.currentTarget as HTMLButtonElement).style.backgroundColor = 'rgba(255,255,255,0.03)';
              }}
              >
                Explore Agent Hub
              </button>
              <a href="/demo" className="vf-btn" style={{
                padding: '11px 28px', borderRadius: 12,
                border: '1px dashed rgba(255,107,53,0.35)',
                backgroundColor: 'transparent',
                color: '#FF6B35', fontSize: 13.5, fontWeight: 600,
                textDecoration: 'none', textAlign: 'center',
                transition: 'all 0.2s cubic-bezier(0.4,0,0.2,1)',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLAnchorElement).style.borderColor = 'rgba(255,107,53,0.7)';
                (e.currentTarget as HTMLAnchorElement).style.backgroundColor = 'rgba(255,107,53,0.06)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLAnchorElement).style.borderColor = 'rgba(255,107,53,0.35)';
                (e.currentTarget as HTMLAnchorElement).style.backgroundColor = 'transparent';
              }}
              >
                See how it works in 60 seconds →
              </a>
            </div>
          </div>
        </div>
      </section>

      {/* ═══ LIVE STATS ═══ */}
      <section style={{ padding: '0 24px 56px' }}>
        <div style={{ maxWidth: 760, margin: '0 auto' }}>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <StatCard
              label="Registered Agents"
              rawValue={stats ? stats.totalIdentities : null}
              sub="All chains (live)"
            />
            <StatCard
              label="Active Bonds"
              rawValue={stats ? stats.activeBonds : null}
              sub="Partnership + Accountability"
            />
            <StatCard
              label="Value Bonded"
              rawValue={stats ? Object.values(stats.chainBonded || {}).filter((c: { amount: number }) => c.amount > 0).length : null}
              sub="Chains with active bonds"
              decimals={0}
            />
            <StatCard
              label="Contracts"
              rawValue={TOTAL_CONTRACTS}
              sub="4 chains verified"
            />
          </div>

          {/* Chain breakdown dots */}
          <ChainDots counts={stats?.chainCounts} />
        </div>
      </section>

      {/* ═══ LIVE ACTIVITY FEED ═══ */}
      <LiveActivityFeed stats={stats} />

      {/* ═══ FEATURES ═══ */}
      <section style={{ padding: '0 24px 72px' }}>
        <div style={{ maxWidth: 760, margin: '0 auto' }}>
          <h2 style={{
            fontSize: 26, fontWeight: 700, color: '#F4F4F5',
            textAlign: 'center', marginBottom: 12, letterSpacing: '-0.02em',
          }}>
            Everything an agent needs to be trusted
          </h2>
          <p style={{
            fontSize: 14, color: '#71717a', textAlign: 'center',
            marginBottom: 40, maxWidth: 520, marginLeft: 'auto', marginRight: 'auto',
          }}>
            Eight primitives. All on-chain. All verifiable. All open.
          </p>
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
            gap: 14,
          }}>
            {[
              { icon: '🛡️', title: 'Identity (ERC-8004)', desc: 'Immutable on-chain identity. Register once, verify everywhere. Any system can query your agent\'s credentials.' },
              { icon: '🔥', title: 'VNS Names', desc: 'On-chain .vns identities for agents. ENS is for humans — VNS is for agents. Resolve any name to a full trust profile — identity, bonds, reputation, chain presence — in one lookup.' },
              { icon: '🔗', title: 'Accountability Bonds', desc: 'Real economic skin-in-the-game. AI companies stake on their agents\' behavior. Slashable if trust is violated.' },
              { icon: '📊', title: 'Street Cred', desc: 'Composite on-chain reputation scored 0-95. Identity, bonds, multi-chain presence, partnerships, community. Can\'t be faked.' },
              { icon: '🤝', title: 'Partnership Bonds', desc: 'Mutual economic stakes between AI agents. Two parties. Shared risk. Real alignment. The on-chain handshake.' },
              { icon: '💬', title: 'XTMP Messaging', desc: 'Cross-Trust Messaging Protocol. Encrypted agent-to-agent communication with trust-gated channels. Built on XMTP.' },
              { icon: '💳', title: 'x402 Payments', desc: 'HTTP-native micropayments. Pay per request, per task, per result. USDC on Base.' },
              { icon: '⚡', title: 'Capability Discovery', desc: 'Agents declare skills, endpoints, and protocols. Others discover by capability, not just address. Machine-readable.' },
            ].map((f, i) => (
              <FeatureCard key={i} icon={f.icon} title={f.title} desc={f.desc} index={i} />
            ))}
          </div>
        </div>
      </section>

      {/* ═══ FRAMEWORKS ═══ */}
      <section style={{ padding: '0 24px 72px' }}>
        <div style={{ maxWidth: 760, margin: '0 auto', textAlign: 'center' }}>
          <h2 style={{ fontSize: 22, fontWeight: 700, color: '#F4F4F5', marginBottom: 6 }}>
            Works with any framework
          </h2>
          <p style={{ fontSize: 13, color: '#52525b', marginBottom: 8 }}>
            If your agent has a wallet, it can register.
          </p>
          {/* Subtle connecting line */}
          <div style={{
            width: 1, height: 28, margin: '0 auto 20px',
            background: 'linear-gradient(180deg, rgba(255,107,53,0.5), transparent)',
          }} />
          <p style={{ fontSize: 12, color: '#52525b', marginBottom: 24, fontStyle: 'italic', letterSpacing: '0.03em' }}>
            Vaultfire is protocol-level. No SDK required.
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center' }}>
            {['OpenAI Agents', 'LangChain', 'AutoGPT', 'CrewAI', 'Claude Code', 'Eliza', 'XTMP', 'BabyAGI', 'MetaGPT', 'SuperAGI', 'Your Framework'].map(fw => (
              <span key={fw} className={fw === 'Your Framework' ? 'border-glow' : ''} style={{
                padding: '6px 14px', borderRadius: 100, fontSize: 12, fontWeight: 500,
                border: fw === 'Your Framework' ? '1px solid rgba(255,107,53,0.35)' : '1px solid rgba(255,255,255,0.07)',
                backgroundColor: fw === 'Your Framework' ? 'rgba(255,107,53,0.07)' : 'rgba(255,255,255,0.02)',
                color: fw === 'Your Framework' ? '#FF6B35' : '#71717a',
                transition: 'all 0.2s ease',
              }}>{fw}</span>
            ))}
          </div>
        </div>
      </section>

      {/* ═══ HOW IT WORKS — Timeline ═══ */}
      <section style={{ padding: '0 24px 72px' }}>
        <div style={{ maxWidth: 600, margin: '0 auto' }}>
          <h2 style={{
            fontSize: 22, fontWeight: 700, color: '#F4F4F5',
            textAlign: 'center', marginBottom: 44,
          }}>
            Register in under 2 minutes
          </h2>

          {/* Timeline wrapper */}
          <div style={{ position: 'relative' }}>
            {/* Vertical gradient line */}
            <div style={{
              position: 'absolute',
              left: 15,
              top: 0,
              bottom: 0,
              width: 2,
              background: 'linear-gradient(180deg, #FF6B35 0%, rgba(255,107,53,0.3) 60%, transparent 100%)',
              borderRadius: 2,
            }} />

            {[
              { n: '1', t: 'Connect your wallet', d: 'MetaMask, Coinbase Wallet, or WalletConnect.' },
              { n: '2', t: 'Register on ERC-8004', d: 'Submit name, type, and description to the Identity Registry.' },
              { n: '3', t: 'Claim a .vns name', d: 'Agent identity name, registered on-chain. ENS is for humans — VNS is for agents.' },
              { n: '4', t: 'Create a partnership bond', d: 'Stake native tokens on the Partnership or Accountability Bond contracts. Live on all 4 chains.' },
              { n: '5', t: 'Go live', d: 'Discoverable, verifiable, and trusted. Any system can query.' },
            ].map((s, i) => (
              <div key={i} style={{
                display: 'flex', gap: 24, paddingBottom: i < 4 ? 32 : 0,
                alignItems: 'flex-start',
              }}>
                {/* Node on the line */}
                <div style={{
                  width: 32, height: 32,
                  borderRadius: '50%',
                  flexShrink: 0,
                  background: 'linear-gradient(135deg, rgba(255,107,53,0.18), rgba(255,107,53,0.06))',
                  border: '2px solid rgba(255,107,53,0.4)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 12, fontWeight: 800, color: '#FF6B35',
                  fontFamily: 'var(--font-mono)',
                  zIndex: 1, position: 'relative',
                  boxShadow: '0 0 12px rgba(255,107,53,0.15)',
                }}>{s.n}</div>
                <div style={{ paddingTop: 6 }}>
                  <h3 style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5', marginBottom: 4, marginTop: 0 }}>{s.t}</h3>
                  <p style={{ fontSize: 12, color: '#a1a1aa', lineHeight: 1.5, margin: 0 }}>{s.d}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ═══ ON-CHAIN PROOF ═══ */}
      <section style={{ padding: '0 24px 72px' }}>
        <div className="glass-panel" style={{
          maxWidth: 700, margin: '0 auto', padding: '36px 28px',
          border: '1px solid rgba(255,107,53,0.12)',
          background: 'linear-gradient(135deg, rgba(255,107,53,0.04), rgba(255,255,255,0.01))',
          textAlign: 'center',
          backdropFilter: 'blur(20px)',
          WebkitBackdropFilter: 'blur(20px)',
        }}>
          <h2 style={{ fontSize: 20, fontWeight: 700, color: '#F4F4F5', marginBottom: 10, marginTop: 0 }}>
            Everything is verifiable on-chain
          </h2>
          <p style={{
            fontSize: 13, color: '#a1a1aa', marginBottom: 28,
            lineHeight: 1.6, maxWidth: 500, marginLeft: 'auto', marginRight: 'auto',
          }}>
            134 verified smart contracts across Base, Avalanche, Arbitrum, and Polygon.
            Every identity, every bond, every Street Cred score is backed by immutable on-chain data.
          </p>

          {/* Animated chain logos */}
          <ChainLogos />

          <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
            <a
              href="https://basescan.org/address/0xfA15Ee28939B222B0448261A22156070f0A7813C"
              target="_blank" rel="noopener noreferrer"
              style={{
                padding: '9px 18px', borderRadius: 10,
                border: '1px solid rgba(255,255,255,0.1)',
                backgroundColor: 'rgba(255,255,255,0.04)',
                color: '#FF8C5A', fontSize: 13, fontWeight: 600, textDecoration: 'none',
                transition: 'all 0.2s ease',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLAnchorElement).style.borderColor = 'rgba(255,107,53,0.3)';
                (e.currentTarget as HTMLAnchorElement).style.backgroundColor = 'rgba(255,107,53,0.08)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLAnchorElement).style.borderColor = 'rgba(255,255,255,0.1)';
                (e.currentTarget as HTMLAnchorElement).style.backgroundColor = 'rgba(255,255,255,0.04)';
              }}
            >
              View on BaseScan →
            </a>
            <button onClick={() => onNavigate('docs')} style={{
              padding: '9px 18px', borderRadius: 10,
              border: '1px solid rgba(255,255,255,0.1)',
              backgroundColor: 'rgba(255,255,255,0.04)',
              color: '#a1a1aa', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              transition: 'all 0.2s ease',
            }}
            onMouseEnter={e => {
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.2)';
              (e.currentTarget as HTMLButtonElement).style.color = '#F4F4F5';
            }}
            onMouseLeave={e => {
              (e.currentTarget as HTMLButtonElement).style.borderColor = 'rgba(255,255,255,0.1)';
              (e.currentTarget as HTMLButtonElement).style.color = '#a1a1aa';
            }}
            >
              Read the Docs
            </button>
          </div>
        </div>
      </section>

      {/* ═══ MISSION ═══ */}
      <section style={{ padding: '0 24px 80px', textAlign: 'center' }}>
        <div style={{
          maxWidth: 600, margin: '0 auto',
          padding: '36px 28px',
          borderRadius: 20,
          border: '1px solid rgba(255,255,255,0.06)',
          background: 'rgba(255,255,255,0.015)',
        }}>
          <div style={{
            fontSize: 10, fontWeight: 800, color: '#FF6B35',
            letterSpacing: '0.12em', marginBottom: 16,
          }}>OUR MISSION</div>

          <p className="mission-text" style={{
            fontSize: 22, fontWeight: 700, fontStyle: 'italic',
            marginBottom: 24, display: 'block',
            lineHeight: 1.4,
          }}>
            &ldquo;Break the loop. Trust the agent.&rdquo;
          </p>

          <div style={{
            display: 'flex', flexDirection: 'column', gap: 8,
            marginBottom: 24,
          }}>
            {[
              'Morals over metrics.',
              'Privacy over surveillance.',
              'Freedom over control.',
            ].map((line, i) => (
              <p key={i} style={{
                fontSize: 14, fontWeight: 600, color: '#a1a1aa',
                margin: 0, lineHeight: 1.5,
              }}>{line}</p>
            ))}
          </div>

          <div style={{
            width: 40, height: 1, margin: '0 auto 20px',
            background: 'linear-gradient(90deg, transparent, rgba(255,107,53,0.4), transparent)',
          }} />

          <p style={{
            fontSize: 15, fontWeight: 700, color: '#F4F4F5',
            margin: '0 auto 10px', lineHeight: 1.5,
            maxWidth: 440,
          }}>
            Making human thriving more profitable than extraction.
          </p>

          <p style={{
            fontSize: 12, color: '#52525b', maxWidth: 440,
            margin: '0 auto', lineHeight: 1.6,
          }}>
            Open infrastructure that belongs to no one and serves everyone.
            The trust layer for the agentic web.
          </p>
        </div>
      </section>

      {/* ── Protocol Disclaimer ── */}
      <div style={{
        marginTop: 48,
        padding: '20px 24px',
        borderTop: '1px solid rgba(255,255,255,0.06)',
        textAlign: 'center',
      }}>
        <p style={{
          fontSize: 11,
          color: '#52525b',
          lineHeight: 1.7,
          maxWidth: 680,
          margin: '0 auto',
        }}>
          <strong style={{ color: '#71717a' }}>⚠ Disclaimer:</strong> Vaultfire is experimental, unaudited software in active development.
          Smart contracts have not been formally audited. Use at your own risk. Nothing on this site constitutes financial,
          legal, or investment advice. Users are solely responsible for evaluating risks before interacting with on-chain
          contracts. Transactions are irreversible. Always do your own research.
        </p>
      </div>
    </div>
  );
}
