"use client";
/**
 * Bridge — Cross-chain trust data explorer.
 * Reads real on-chain state from VaultfireTeleporterBridge on all 4 chains.
 * Shows synced agent counts, bond counts, message stats, and agent recognition lookup.
 */
import { useEffect, useState, useCallback } from "react";
import { CHAINS } from "../lib/contracts";
import { AlphaBanner } from "../components/DisclaimerBanner";

type ChainKey = "base" | "avalanche" | "arbitrum" | "polygon";

const CHAIN_INFO: { key: ChainKey; label: string; chainId: number; color: string; accent: string }[] = [
  { key: "base", label: "Base", chainId: 8453, color: "#0052FF", accent: "border-blue-500/30 text-blue-400" },
  { key: "avalanche", label: "Avalanche", chainId: 43114, color: "#E84142", accent: "border-red-500/30 text-red-400" },
  { key: "arbitrum", label: "Arbitrum", chainId: 42161, color: "#28A0F0", accent: "border-cyan-500/30 text-cyan-400" },
  { key: "polygon", label: "Polygon", chainId: 137, color: "#8247E5", accent: "border-purple-500/30 text-purple-400" },
];

type BridgeData = {
  bridge: {
    outboundMessages: string;
    inboundProcessed: string;
    paused: boolean;
    remoteChainId: string;
    relayerCount: string;
  };
  synced: {
    agents: string;
    partnershipBonds: string;
    accountabilityBonds: string;
    reputations: string;
    validations: string;
  };
};

type ChainBridgeState = {
  data: BridgeData | null;
  loading: boolean;
  error: string | null;
  latency: number | null;
};

export default function Bridge() {
  const [chains, setChains] = useState<Record<ChainKey, ChainBridgeState>>({
    base: { data: null, loading: true, error: null, latency: null },
    avalanche: { data: null, loading: true, error: null, latency: null },
    arbitrum: { data: null, loading: true, error: null, latency: null },
    polygon: { data: null, loading: true, error: null, latency: null },
  });
  const [activeTab, setActiveTab] = useState<"overview" | "lookup">("overview");
  const [lookupAddr, setLookupAddr] = useState("");
  const [lookupChain, setLookupChain] = useState<ChainKey>("base");
  const [lookupResult, setLookupResult] = useState<{ recognized: boolean; chain: string } | null>(null);
  const [lookupLoading, setLookupLoading] = useState(false);

  const loadChain = useCallback(async (chain: ChainKey) => {
    const start = Date.now();
    try {
      const res = await fetch(`/api/agent/bridge?chain=${chain}`);
      const latency = Date.now() - start;
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      setChains(prev => ({
        ...prev,
        [chain]: { data: json, loading: false, error: null, latency },
      }));
    } catch (e) {
      setChains(prev => ({
        ...prev,
        [chain]: { data: null, loading: false, error: e instanceof Error ? e.message : "Failed", latency: null },
      }));
    }
  }, []);

  useEffect(() => {
    CHAIN_INFO.forEach(c => loadChain(c.key));
    const interval = setInterval(() => {
      CHAIN_INFO.forEach(c => loadChain(c.key));
    }, 30000);
    return () => clearInterval(interval);
  }, [loadChain]);

  const lookupAgent = async () => {
    if (!lookupAddr.trim()) return;
    setLookupLoading(true);
    setLookupResult(null);
    try {
      const res = await fetch(`/api/agent/bridge?chain=${lookupChain}&address=${encodeURIComponent(lookupAddr.trim())}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      setLookupResult({ recognized: json.agentCheck?.recognized ?? false, chain: lookupChain });
    } catch {
      setLookupResult(null);
    }
    setLookupLoading(false);
  };

  // Aggregate totals
  const totals = {
    outbound: 0, inbound: 0, agents: 0, partnerships: 0, accountability: 0, reputations: 0, validations: 0, online: 0,
  };
  CHAIN_INFO.forEach(c => {
    const d = chains[c.key].data;
    if (d) {
      totals.outbound += Number(d.bridge.outboundMessages);
      totals.inbound += Number(d.bridge.inboundProcessed);
      totals.agents += Number(d.synced.agents);
      totals.partnerships += Number(d.synced.partnershipBonds);
      totals.accountability += Number(d.synced.accountabilityBonds);
      totals.reputations += Number(d.synced.reputations);
      totals.validations += Number(d.synced.validations);
      if (!d.bridge.paused) totals.online++;
    }
  });
  const allLoaded = CHAIN_INFO.every(c => !chains[c.key].loading);

  return (
    <div className="max-w-4xl mx-auto px-4 py-8 space-y-8">
      <AlphaBanner />

      {/* Header */}
      <div className="space-y-2">
        <div className="flex items-center gap-2">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
          <span className="text-[10px] font-bold text-emerald-500 uppercase tracking-[0.2em]">Live on 4 Chains</span>
        </div>
        <h1 className="text-4xl font-black text-white tracking-tight sm:text-5xl">Bridge</h1>
        <p className="text-zinc-500 text-base sm:text-lg max-w-2xl leading-relaxed">
          Cross-chain trust data synchronisation — real on-chain state from VaultfireTeleporterBridge contracts.
        </p>
      </div>

      {/* Status banner */}
      <div className="relative group">
        <div className="absolute -inset-1 bg-gradient-to-r from-amber-500/20 to-transparent rounded-2xl blur opacity-25 group-hover:opacity-40 transition duration-1000"></div>
        <div className="relative flex items-center gap-3 px-4 py-3 rounded-2xl bg-zinc-900/60 border border-amber-500/15 backdrop-blur-md">
          <div className="w-8 h-8 rounded-full bg-amber-500/10 flex items-center justify-center text-amber-500 flex-shrink-0">
            <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>
          </div>
          <p className="text-xs text-zinc-400 leading-relaxed">
            <span className="text-amber-500 font-bold">Contracts deployed, bridge not yet active.</span> VaultfireTeleporterBridge contracts are deployed on all 4 chains. Cross-chain message relaying has not started yet — stats will populate once the bridge relayers are activated. All data below is read live from on-chain state.
          </p>
        </div>
      </div>

      {/* Tab Selector */}
      <div className="flex bg-zinc-900/60 p-1.5 rounded-2xl border border-zinc-800/60 backdrop-blur-sm shadow-xl">
        {[
          { key: "overview" as const, label: "Bridge Status" },
          { key: "lookup" as const, label: "Agent Lookup" },
        ].map(t => (
          <button key={t.key} onClick={() => setActiveTab(t.key)}
            className={`flex-1 flex items-center justify-center py-3 rounded-xl transition-all duration-300 relative ${activeTab === t.key ? 'bg-zinc-800 text-white shadow-lg' : 'text-zinc-500 hover:text-zinc-300'}`}>
            <span className="text-xs font-bold uppercase tracking-widest">{t.label}</span>
            {activeTab === t.key && <div className="absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-emerald-500 shadow-[0_0_8px_rgba(34,197,94,0.8)]" />}
          </button>
        ))}
      </div>

      {/* ═══ BRIDGE STATUS TAB ═══ */}
      {activeTab === "overview" && (
        <div className="space-y-6">
          {/* Global Totals */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {[
              { label: "Chains Online", value: allLoaded ? `${totals.online}/4` : "...", sub: "active bridges" },
              { label: "Outbound Msgs", value: allLoaded ? String(totals.outbound) : "...", sub: "sent cross-chain" },
              { label: "Inbound Processed", value: allLoaded ? String(totals.inbound) : "...", sub: "received & synced" },
              { label: "Synced Agents", value: allLoaded ? String(totals.agents) : "...", sub: "cross-chain recognized" },
            ].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>

          {/* Synced Data Summary */}
          {allLoaded && (
            <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">Cross-Chain Synced Data (All Chains)</div>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {[
                  { label: "Partnership Bonds", value: String(totals.partnerships) },
                  { label: "Accountability Bonds", value: String(totals.accountability) },
                  { label: "Reputation Updates", value: String(totals.reputations) },
                  { label: "Validation Records", value: String(totals.validations) },
                ].map(s => (
                  <div key={s.label} className="text-center py-3">
                    <div className="text-xl font-extrabold text-white tracking-tight">{s.value}</div>
                    <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest mt-1">{s.label}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Per-Chain Status */}
          <div className="space-y-3">
            <div className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 px-1">Per-Chain Bridge Status</div>
            {CHAIN_INFO.map(c => {
              const state = chains[c.key];
              const d = state.data;
              const isOnline = d && !d.bridge.paused;
              return (
                <div key={c.key} className={`rounded-2xl bg-zinc-900/60 border ${isOnline ? 'border-zinc-800' : 'border-zinc-800/40'} p-5 relative overflow-hidden hover:border-zinc-700/50 transition-all`}>
                  <div className="absolute top-0 left-0 right-0 h-px" style={{ background: `linear-gradient(to right, ${c.color}40, transparent)` }} />
                  
                  {/* Chain Header */}
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className="w-2 h-2 rounded-full" style={{ backgroundColor: state.loading ? "#71717A" : isOnline ? "#22C55E" : "#EF4444" }} />
                      <span className="text-sm font-bold text-white">{c.label} Teleporter</span>
                      <span className="text-[9px] font-bold uppercase tracking-wider px-2 py-0.5 rounded-full bg-zinc-800 text-zinc-400">
                        {c.chainId}
                      </span>
                    </div>
                    <div className="flex items-center gap-3">
                      {state.latency && (
                        <span className="text-[10px] text-zinc-600 font-mono">{state.latency}ms</span>
                      )}
                      <span className={`text-[10px] font-bold uppercase tracking-widest ${state.loading ? 'text-zinc-600' : isOnline ? 'text-emerald-500' : 'text-red-400'}`}>
                        {state.loading ? "Loading..." : isOnline ? "Online" : d?.bridge.paused ? "Paused" : "Error"}
                      </span>
                    </div>
                  </div>

                  {state.error && (
                    <div className="text-xs text-red-400 mb-3">{state.error}</div>
                  )}

                  {d && (
                    <div className="grid grid-cols-3 sm:grid-cols-5 gap-3">
                      {[
                        { label: "Outbound", value: d.bridge.outboundMessages },
                        { label: "Inbound", value: d.bridge.inboundProcessed },
                        { label: "Agents", value: d.synced.agents },
                        { label: "Bonds", value: String(Number(d.synced.partnershipBonds) + Number(d.synced.accountabilityBonds)) },
                        { label: "Relayers", value: d.bridge.relayerCount },
                      ].map(s => (
                        <div key={s.label} className="text-center">
                          <div className="text-lg font-extrabold text-white tracking-tight">{s.value}</div>
                          <div className="text-[9px] text-zinc-600 font-bold uppercase tracking-widest">{s.label}</div>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Explorer link */}
                  {d && (
                    <div className="mt-3 pt-3 border-t border-zinc-800/40 flex items-center justify-between">
                      <code className="text-[11px] text-zinc-600 font-mono">
                        {CHAIN_INFO.find(ci => ci.key === c.key) ? 
                          `${chains[c.key].data?.bridge ? (state.data as any)?.contract || '' : ''}`.slice(0, 14) + '...' : ''}
                      </code>
                      <a
                        href={`${CHAINS[c.key].explorerUrl}/address/${c.key === 'base' ? '0x62edf0cBc8Fa3d98B6A07197DFE9cb1c128a7eC7' : c.key === 'avalanche' ? '0x1762e484A48558Ea5Cd056ac2CDf43FBbA52ba58' : '0x7b9293B05Bd0fcb7458d06A364078761B8E8848e'}`}
                        target="_blank" rel="noopener noreferrer"
                        className="text-[10px] text-zinc-500 hover:text-zinc-300 transition-colors flex items-center gap-1"
                      >
                        View on Explorer
                        <svg className="w-2.5 h-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6" /><polyline points="15 3 21 3 21 9" /><line x1="10" y1="14" x2="21" y2="3" /></svg>
                      </a>
                    </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">Cross-Chain Architecture.</span> The Teleporter Bridge syncs 5 data types: agent registrations, partnership bonds, accountability bonds, reputation scores, and validation status. Authorized relayers submit cross-chain messages. All data is readable by anyone via <code className="text-emerald-300 text-[11px]">/api/agent/bridge</code>.
            </p>
          </div>
        </div>
      )}

      {/* ═══ AGENT LOOKUP TAB ═══ */}
      {activeTab === "lookup" && (
        <div className="space-y-6">
          <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">Cross-Chain Agent Recognition</div>
            <p className="text-xs text-zinc-400 leading-relaxed mb-4">
              Check if an agent&rsquo;s trust data has been bridged to a specific chain. Agents recognized on a chain can operate with their full trust profile.
            </p>
            <div className="flex flex-col sm:flex-row gap-3">
              <input
                value={lookupAddr}
                onChange={e => setLookupAddr(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && lookupAgent()}
                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={lookupChain}
                onChange={e => setLookupChain(e.target.value as ChainKey)}
                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"
              >
                {CHAIN_INFO.map(c => (
                  <option key={c.key} value={c.key}>{c.label}</option>
                ))}
              </select>
              <button
                onClick={lookupAgent}
                disabled={lookupLoading || !lookupAddr.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"
              >
                {lookupLoading && <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>}
                {lookupLoading ? "Checking..." : "Check"}
              </button>
            </div>
          </div>

          {lookupResult && (
            <div className={`rounded-2xl p-5 border ${lookupResult.recognized ? 'bg-emerald-500/5 border-emerald-500/20' : 'bg-zinc-900/40 border-zinc-800/60'}`}>
              <div className="flex items-center gap-3 mb-3">
                {lookupResult.recognized ? (
                  <div className="w-8 h-8 rounded-full bg-emerald-500/10 flex items-center justify-center">
                    <svg className="w-4 h-4 text-emerald-400" 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>
                  </div>
                ) : (
                  <div className="w-8 h-8 rounded-full bg-zinc-800 flex items-center justify-center">
                    <svg className="w-4 h-4 text-zinc-500" 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>
                  </div>
                )}
                <div>
                  <div className={`text-sm font-bold ${lookupResult.recognized ? 'text-emerald-400' : 'text-zinc-400'}`}>
                    {lookupResult.recognized ? "Agent Recognized" : "Not Yet Recognized"}
                  </div>
                  <div className="text-[11px] text-zinc-500 mt-0.5">
                    on {CHAIN_INFO.find(c => c.key === lookupResult.chain)?.label}
                  </div>
                </div>
              </div>
              <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-xs text-zinc-400 font-mono">{lookupAddr.slice(0, 10)}...{lookupAddr.slice(-8)}</span>
              </div>
              {!lookupResult.recognized && (
                <p className="text-xs text-zinc-500 mt-3 leading-relaxed">
                  This agent&rsquo;s trust data has not been bridged to {CHAIN_INFO.find(c => c.key === lookupResult.chain)?.label} yet. The agent may need to register on-chain or wait for the next relayer sync cycle.
                </p>
              )}
            </div>
          )}

          {/* How Bridging Works */}
          <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">How Cross-Chain Bridging Works</div>
            <div className="space-y-3">
              {[
                { step: "1", title: "Agent Registers", desc: "An agent registers on-chain on any supported chain (Base, Avalanche, Arbitrum, or Polygon)." },
                { step: "2", title: "Relayer Detects", desc: "Authorized relayers monitor registration events, bond creations, and reputation updates across all chains." },
                { step: "3", title: "Bridge Syncs", desc: "The relayer submits a cross-chain message via VaultfireTeleporterBridge, syncing the trust data to other chains." },
                { step: "4", title: "Agent Recognized", desc: "The agent is now recognized on the destination chain with their full trust profile — bonds, reputation, and credentials intact." },
              ].map(s => (
                <div key={s.step} className="flex items-start gap-3">
                  <div className="w-6 h-6 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-400 text-[10px] font-bold flex-shrink-0 mt-0.5">
                    {s.step}
                  </div>
                  <div>
                    <div className="text-xs font-bold text-white">{s.title}</div>
                    <div className="text-[11px] text-zinc-500 leading-relaxed">{s.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Message types */}
          <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">Bridgeable Data Types</div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {[
                { label: "Agent Registration", desc: "Address, URI, type, capabilities", code: "SYNC_AGENT_REGISTRATION" },
                { label: "Partnership Bond", desc: "Human-AI partnership with purpose", code: "SYNC_PARTNERSHIP_BOND" },
                { label: "Accountability Bond", desc: "Company stake and revenue data", code: "SYNC_ACCOUNTABILITY_BOND" },
                { label: "Reputation", desc: "Ratings, feedbacks, verified score", code: "SYNC_REPUTATION" },
                { label: "Validation", desc: "Approval status and vote counts", code: "SYNC_VALIDATION" },
              ].map(dt => (
                <div key={dt.code} className="flex items-start gap-3 p-3 rounded-xl bg-zinc-900/60 border border-zinc-800/40">
                  <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 mt-1.5 flex-shrink-0" />
                  <div>
                    <div className="text-xs font-bold text-white">{dt.label}</div>
                    <div className="text-[10px] text-zinc-600">{dt.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="pt-8 border-t border-zinc-800/60 flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex items-center gap-6">
          <div className="text-[10px] text-zinc-600 font-bold uppercase tracking-[0.2em]">Trust portability</div>
          <div className="text-[10px] text-zinc-600 font-bold uppercase tracking-[0.2em]">Cross-chain identity</div>
          <div className="text-[10px] text-zinc-600 font-bold uppercase tracking-[0.2em]">Real data only</div>
        </div>
        <div className="text-[10px] text-zinc-700 font-medium">Vaultfire Protocol · VaultfireTeleporterBridge · v1.0.0</div>
      </div>
    </div>
  );
}
