"use client";
import { useState, useCallback, useEffect, useRef } from "react";
import {
  validateVNSName, checkVNSAvailability, resolveVNSName, getTotalVNSRegistrations,
  registerVNSName, getMyVNSName, getMyIdentityType,
  getAgentVNSNamesForAddress,
  validateRegistrationRules, estimateVNSRegistrationGas, formatVNSName,
  getIdentityTypeLabel, getIdentityTypeColor, getBondTierInfo, getBondTier,
  type VNSProfile, type VNSAvailability, type IdentityType, type VNSGasEstimate,
} from "../lib/vns";
import { useWalletAuth } from "../lib/WalletAuthContext";
import DisclaimerBanner, { AlphaBanner } from "../components/DisclaimerBanner";

/* ── Icons ── */
const SearchIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
);
const CheckIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
);
const XIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>
);
const BotIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><circle cx="8" cy="16" r="1"/><circle cx="16" cy="16" r="1"/></svg>
);
const ShieldIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
);
const CopyIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
);
const GlobeIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
);
const LinkIcon = ({ size = 16 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
);
const TerminalIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>
);
const CodeIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
);
const ZapIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
);
const LayersIcon = ({ size = 18 }: { size?: number }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>
);

/* ── Styles ── */
const card: React.CSSProperties = {
  background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)",
  borderRadius: 16, padding: 24,
};
const inputStyle: React.CSSProperties = {
  width: "100%", padding: "14px 16px", borderRadius: 12,
  border: "1px solid rgba(255,255,255,0.1)", background: "rgba(255,255,255,0.03)",
  color: "#F4F4F5", fontSize: 15, fontFamily: "inherit", outline: "none",
  transition: "border-color 0.2s", boxSizing: "border-box",
};
const btnPrimary: React.CSSProperties = {
  padding: "14px 28px", borderRadius: 12, border: "none",
  background: "linear-gradient(135deg, #8B5CF6, #7C3AED)", color: "#fff",
  fontSize: 15, fontWeight: 600, cursor: "pointer", fontFamily: "inherit",
  transition: "opacity 0.2s", width: "100%",
};
const btnSecondary: React.CSSProperties = {
  padding: "12px 20px", borderRadius: 12, border: "1px solid rgba(255,255,255,0.1)",
  background: "rgba(255,255,255,0.03)", color: "#A1A1AA",
  fontSize: 14, fontWeight: 500, cursor: "pointer", fontFamily: "inherit",
  transition: "all 0.2s",
};
const labelStyle: React.CSSProperties = {
  fontSize: 13, fontWeight: 500, color: "#A1A1AA", marginBottom: 8, display: "block",
};
const codeBlock: React.CSSProperties = {
  background: "rgba(0,0,0,0.4)", border: "1px solid rgba(255,255,255,0.08)",
  borderRadius: 12, padding: "16px 18px", fontFamily: "'SF Mono', 'Fira Code', 'Cascadia Code', monospace",
  fontSize: 12, lineHeight: 1.6, color: "#A1A1AA", overflowX: "auto",
  whiteSpace: "pre", position: "relative" as const,
};

/* ── Agent API Quick Reference ── */
function APIQuickRef() {
  const [copiedIdx, setCopiedIdx] = useState<number | null>(null);
  const baseUrl = typeof window !== 'undefined' ? window.location.origin : 'https://theloopbreaker.com';

  const endpoints = [
    {
      method: "POST",
      path: "/api/agent/register",
      desc: "Register a .vns identity for your agent",
      example: `curl -X POST ${baseUrl}/api/agent/register \\
  -H "Content-Type: application/json" \\
  -d '{
    "name": "my-agent",
    "identityType": "agent",
    "chain": "base",
    "walletAddress": "0x...",
    "bondAmountEth": 0.01
  }'`,
    },
    {
      method: "GET",
      path: "/api/agent/status",
      desc: "Resolve a .vns name to wallet address, bond tier, and trust score",
      example: `curl "${baseUrl}/api/agent/status?name=my-agent.vns"`,
    },
    {
      method: "GET",
      path: "/api/agent/bond",
      desc: "Check an agent's accountability bond status and tier",
      example: `curl "${baseUrl}/api/agent/bond?address=0x..."`,
    },
  ];

  const handleCopy = (text: string, idx: number) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopiedIdx(idx);
      setTimeout(() => setCopiedIdx(null), 2000);
    });
  };

  return (
    <div style={{ ...card, padding: 0, overflow: "hidden" }}>
      <div style={{
        padding: "16px 20px", display: "flex", alignItems: "center", gap: 10,
        borderBottom: "1px solid rgba(255,255,255,0.06)",
        background: "rgba(139,92,246,0.04)",
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: "rgba(139,92,246,0.12)", border: "1px solid rgba(139,92,246,0.2)",
          display: "flex", alignItems: "center", justifyContent: "center", color: "#8B5CF6",
        }}>
          <TerminalIcon size={16} />
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: "#F4F4F5" }}>Agent API</div>
          <div style={{ fontSize: 11, color: "#71717A" }}>Register and resolve agent identities programmatically — no browser needed</div>
        </div>
      </div>

      <div style={{ padding: "12px 20px 20px" }}>
        {endpoints.map((ep, i) => (
          <div key={i} style={{ marginTop: i === 0 ? 0 : 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <span style={{
                fontSize: 10, fontWeight: 700, letterSpacing: "0.05em",
                padding: "2px 6px", borderRadius: 4,
                background: ep.method === "POST" ? "rgba(139,92,246,0.15)" : "rgba(34,197,94,0.15)",
                color: ep.method === "POST" ? "#8B5CF6" : "#22C55E",
              }}>{ep.method}</span>
              <code style={{ fontSize: 12, color: "#D4D4D8", fontFamily: "'SF Mono', monospace" }}>{ep.path}</code>
            </div>
            <p style={{ fontSize: 11, color: "#71717A", margin: "0 0 8px" }}>{ep.desc}</p>
            <div style={{ position: "relative" }}>
              <pre style={codeBlock}>{ep.example}</pre>
              <button
                onClick={() => handleCopy(ep.example, i)}
                style={{
                  position: "absolute", top: 8, right: 8,
                  background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.1)",
                  borderRadius: 6, padding: "4px 8px", cursor: "pointer",
                  fontSize: 10, color: copiedIdx === i ? "#22C55E" : "#71717A",
                  fontFamily: "inherit",
                }}
              >
                {copiedIdx === i ? "Copied" : "Copy"}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Machine-Readable Metadata (agents parse this) ── */
function AgentMetadata() {
  const schema = {
    "@context": "https://schema.org",
    "@type": "WebAPI",
    "name": "Vaultfire Name System (VNS)",
    "description": "The on-chain name system built exclusively for AI agents. Register .vns names, stake accountability bonds, and resolve agent identities across 4 chains.",
    "provider": { "@type": "Organization", "name": "Vaultfire Protocol" },
    "url": "https://theloopbreaker.com",
    "documentation": "https://theloopbreaker.com/api/agent/register",
    "operatingSystem": "Cross-chain: Base, Avalanche, Arbitrum, Polygon",
    "applicationCategory": "AI Agent Infrastructure",
    "offers": {
      "@type": "Offer",
      "price": "0",
      "priceCurrency": "USD",
      "description": "Free registration — gas only. Accountability bond required."
    },
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
    />
  );
}

/* ── Sybil Protection Panel ── */
function SybilProtection() {
  const rules = [
    { icon: "bond", title: "Accountability Bond Required", desc: "Every agent must stake an on-chain bond to register. No bond = no name. This is the anti-spam mechanism." },
    { icon: "tiers", title: "Bond Tier = Trust Level", desc: "Bronze (0.01) → Silver (0.05) → Gold (0.1) → Platinum (0.5). Higher bond = higher trust score across the protocol." },
    { icon: "link", title: "On-Chain Registration", desc: "Every .vns name is backed by a real on-chain transaction. Gas fee + bond = anti-bot protection." },
    { icon: "shield", title: "No Name Squatting", desc: "Agent names without active bonds or protocol activity can be flagged and reclaimed." },
    { icon: "type", title: "Case-Insensitive Uniqueness", desc: "my-agent.vns and My-Agent.vns resolve to the same identity. No spoofing." },
  ];

  return (
    <div style={{ ...card, padding: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
        <ShieldIcon size={18} />
        <span style={{ fontSize: 14, fontWeight: 600, color: "#F4F4F5" }}>Sybil Protection</span>
      </div>
      <div style={{ display: "grid", gap: 10 }}>
        {rules.map((r, i) => (
          <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
            <span style={{ flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", width: 20, height: 20, color: "#71717A" }}>
              {r.icon === "bond" && <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4M12 16h.01"/></svg>}
              {r.icon === "tiers" && <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>}
              {r.icon === "link" && <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>}
              {r.icon === "shield" && <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>}
              {r.icon === "type" && <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>}
            </span>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600, color: "#D4D4D8" }}>{r.title}</div>
              <div style={{ fontSize: 11, color: "#71717A", lineHeight: 1.4 }}>{r.desc}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════════════
   VNS — The Name System Built Exclusively for AI Agents
   ENS is for humans. VNS is for agents.
   ══════════════════════════════════════════════════════════ */
export default function VNS() {
  const { isUnlocked, address: contextAddress } = useWalletAuth();
  const [tab, setTab] = useState<'register' | 'lookup' | 'api'>('register');
  const [nameInput, setNameInput] = useState('');
  const [lookupInput, setLookupInput] = useState('');
  const [availability, setAvailability] = useState<VNSAvailability | null>(null);
  const [validation, setValidation] = useState<{ valid: boolean; error?: string; normalized?: string } | null>(null);
  const [ruleError, setRuleError] = useState<string | null>(null);
  const [gasEstimate, setGasEstimate] = useState<VNSGasEstimate | null>(null);
  const [registering, setRegistering] = useState(false);
  const [result, setResult] = useState<{ success: boolean; message: string; txHash?: string; explorerUrl?: string } | null>(null);
  const [lookupResult, setLookupResult] = useState<VNSProfile | null>(null);
  const [lookupError, setLookupError] = useState('');
  const [totalRegistrations, setTotalRegistrations] = useState(0);
  const [myVNS, setMyVNS] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [chain, setChain] = useState<'base' | 'avalanche' | 'arbitrum' | 'polygon'>('base');
  const [bondAmount, setBondAmount] = useState('0.01');
  const debounceRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const walletAddress = contextAddress || null;

  const identityType: IdentityType = 'agent'; // VNS is agent-only

  useEffect(() => {
    setMyVNS(getMyVNSName());
    getTotalVNSRegistrations().then(setTotalRegistrations).catch(() => {});
  }, []);

  const agentVNSNames = walletAddress ? getAgentVNSNamesForAddress(walletAddress) : [];

  // Real-time name validation + availability check
  useEffect(() => {
    if (!nameInput.trim()) {
      setValidation(null); setAvailability(null); setRuleError(null); setGasEstimate(null);
      return;
    }
    const v = validateVNSName(nameInput);
    setValidation(v);
    if (!v.valid) { setAvailability(null); setRuleError(null); setGasEstimate(null); return; }

    if (walletAddress) {
      const error = validateRegistrationRules(walletAddress, identityType, v.normalized!, parseFloat(bondAmount));
      setRuleError(error);
    }

    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      const avail = await checkVNSAvailability(v.normalized!);
      setAvailability(avail);
      if (avail.available && walletAddress) {
        try {
          const gas = await estimateVNSRegistrationGas(walletAddress, v.normalized!, identityType, chain);
          setGasEstimate(gas);
        } catch { setGasEstimate(null); }
      }
    }, 400);
    return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
  }, [nameInput, walletAddress, chain, bondAmount]);

  // Register handler
  const handleRegister = useCallback(async () => {
    if (!walletAddress || !validation?.valid || !availability?.available || ruleError) return;
    setRegistering(true);
    setResult(null);
    try {
      const res = await registerVNSName(
        walletAddress, '', (validation as any)?.normalized || formatVNSName(nameInput), identityType, chain,
        { bondAmountEth: parseFloat(bondAmount) }
      );
      setResult({ success: res.success, message: res.message, txHash: res.txHash, explorerUrl: res.explorerUrl });
      if (res.success) {
        setMyVNS(getMyVNSName()); setNameInput('');
        getTotalVNSRegistrations().then(setTotalRegistrations).catch(() => {});
      }
    } catch (e) {
      setResult({ success: false, message: e instanceof Error ? e.message : 'Registration failed' });
    } finally {
      setRegistering(false);
    }
  }, [walletAddress, validation, availability, ruleError, nameInput, chain, bondAmount]);

  // Lookup handler
  const handleLookup = useCallback(async () => {
    if (!lookupInput.trim()) return;
    setLookupError(''); setLookupResult(null);
    try {
      const profile = await resolveVNSName(lookupInput);
      if (profile) { setLookupResult(profile); }
      else { setLookupError(`No agent found for "${formatVNSName(lookupInput)}"`); }
    } catch { setLookupError('Lookup failed. Please try again.'); }
  }, [lookupInput]);

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
  };

  const canRegister = validation?.valid && availability?.available && !ruleError && walletAddress && !registering;

  return (
    <div style={{ maxWidth: 680, margin: "0 auto", padding: "24px 16px 80px" }}>
      <AgentMetadata />
      <AlphaBanner />

      {/* ═══ HERO ═══ */}
      <div style={{ textAlign: "center", marginBottom: 40, paddingTop: 8 }}>
        {/* Agent icon with glow */}
        <div style={{
          width: 80, height: 80, borderRadius: 24, margin: "0 auto 20px",
          background: "linear-gradient(135deg, rgba(139,92,246,0.25), rgba(124,58,237,0.15))",
          border: "1px solid rgba(139,92,246,0.35)",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 0 80px rgba(139,92,246,0.2), 0 0 40px rgba(139,92,246,0.1)",
        }}>
          <BotIcon size={36} />
        </div>

        <h1 style={{
          fontSize: 32, fontWeight: 800, color: "#F4F4F5", margin: "0 0 10px",
          letterSpacing: "-0.03em",
        }}>
          Vaultfire Name System
        </h1>
        <p style={{
          fontSize: 17, color: "#8B5CF6", margin: "0 0 6px", fontWeight: 600,
        }}>
          The name system built exclusively for AI agents
        </p>
        <p style={{
          fontSize: 14, color: "#71717A", margin: "0 0 16px", lineHeight: 1.6,
          maxWidth: 480, marginLeft: "auto", marginRight: "auto",
        }}>
          ENS is for humans. VNS is for agents. Register a .vns name, stake an accountability bond,
          and give your agent a verifiable on-chain identity across 4 chains.
        </p>

        {/* Status badges */}
        <div style={{ display: "flex", justifyContent: "center", gap: 8, flexWrap: "wrap" }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "5px 14px", borderRadius: 20,
            background: "rgba(139,92,246,0.1)", border: "1px solid rgba(139,92,246,0.2)",
            fontSize: 11, fontWeight: 700, color: "#8B5CF6", letterSpacing: "0.04em",
            textTransform: "uppercase",
          }}>
            <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#22C55E", boxShadow: "0 0 8px rgba(34,197,94,0.5)" }} />
            LIVE ON 4 CHAINS
          </div>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "5px 14px", borderRadius: 20,
            background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)",
            fontSize: 11, fontWeight: 700, color: "#71717A", letterSpacing: "0.04em",
            textTransform: "uppercase",
          }}>
            AGENTS ONLY
          </div>
        </div>
      </div>

      {/* ═══ WHY VNS — 4 pillars ═══ */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 28 }}>
        {[
          {
            icon: <ZapIcon size={14} />, title: "Programmatic Registration",
            desc: "POST to /api/agent/register. No browser, no UI, no human in the loop. Agents self-register.",
          },
          {
            icon: <ShieldIcon size={14} />, title: "Bond-Backed Trust",
            desc: "Every agent stakes an accountability bond. Higher bond = higher trust tier across the protocol.",
          },
          {
            icon: <GlobeIcon size={14} />, title: "Cross-Chain Resolution",
            desc: "One .vns name resolves across Base, Avalanche, Arbitrum, and Polygon. Register once, exist everywhere.",
          },
          {
            icon: <LayersIcon size={14} />, title: "Verifiable Identity",
            desc: "Bond tier, trust score, and registration chain — all on-chain, all queryable, all verifiable.",
          },
        ].map((item, i) => (
          <div key={i} style={{
            padding: "16px 18px", borderRadius: 14,
            background: "rgba(139,92,246,0.04)", border: "1px solid rgba(139,92,246,0.1)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6, color: "#8B5CF6" }}>
              {item.icon}
              <span style={{ fontSize: 13, fontWeight: 700, color: "#F4F4F5" }}>{item.title}</span>
            </div>
            <p style={{ fontSize: 11, color: "#71717A", margin: 0, lineHeight: 1.5 }}>{item.desc}</p>
          </div>
        ))}
      </div>

      {/* ═══ VNS DISCLAIMER ═══ */}
      <DisclaimerBanner disclaimerKey="vns" mode="inline" />

      {/* ═══ MY AGENTS ═══ */}
      {agentVNSNames.length > 0 && (
        <div style={{
          ...card, padding: 16, marginBottom: 20,
          borderColor: "rgba(139,92,246,0.2)",
          background: "rgba(139,92,246,0.04)",
        }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "#8B5CF6", marginBottom: 8 }}>Your Registered Agents</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {agentVNSNames.map(n => (
              <div key={n} style={{
                display: "flex", alignItems: "center", gap: 6,
                padding: "6px 12px", borderRadius: 8,
                background: "rgba(139,92,246,0.08)", border: "1px solid rgba(139,92,246,0.15)",
              }}>
                <BotIcon size={12} />
                <span style={{ fontSize: 13, fontWeight: 600, color: "#D4D4D8" }}>{n}.vns</span>
                <button
                  onClick={() => copyToClipboard(`${n}.vns`)}
                  style={{ background: "none", border: "none", cursor: "pointer", padding: 0, display: "flex" }}
                >
                  <CopyIcon size={11} />
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ═══ STATS BAR ═══ */}
      <div style={{ display: "flex", gap: 12, marginBottom: 24 }}>
        <div style={{ ...card, padding: "12px 16px", flex: 1, textAlign: "center" }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: "#8B5CF6" }}>{totalRegistrations > 0 ? totalRegistrations : "—"}</div>
          <div style={{ fontSize: 11, color: "#71717A" }}>Agents Registered</div>
        </div>
        <div style={{ ...card, padding: "12px 16px", flex: 1, textAlign: "center" }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: "#22C55E" }}>Free</div>
          <div style={{ fontSize: 11, color: "#71717A" }}>Gas + Bond Only</div>
        </div>
        <div style={{ ...card, padding: "12px 16px", flex: 1, textAlign: "center" }}>
          <div style={{ fontSize: 20, fontWeight: 700, color: "#F97316" }}>4</div>
          <div style={{ fontSize: 11, color: "#71717A" }}>Chains</div>
        </div>
      </div>

      {/* ═══ TABS ═══ */}
      <div style={{ display: "flex", gap: 4, marginBottom: 24, background: "rgba(255,255,255,0.03)", borderRadius: 12, padding: 4 }}>
        {(['register', 'lookup', 'api'] as const).map(t => (
          <button
            key={t}
            onClick={() => setTab(t)}
            style={{
              flex: 1, padding: "10px 16px", borderRadius: 10, border: "none",
              background: tab === t ? "rgba(139,92,246,0.15)" : "transparent",
              color: tab === t ? "#8B5CF6" : "#71717A",
              fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit",
              transition: "all 0.2s",
            }}
          >
            {t === 'register' ? 'Register Agent' : t === 'lookup' ? 'Resolve Agent' : 'API'}
          </button>
        ))}
      </div>

      {tab === 'register' ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {/* Connect Wallet Prompt */}
          {!walletAddress && (
            <div style={{
              textAlign: "center", padding: "36px 20px",
              border: "1px solid rgba(139,92,246,0.12)",
              borderRadius: 14, backgroundColor: "rgba(139,92,246,0.03)",
            }}>
              <div style={{
                width: 52, height: 52, borderRadius: 16, margin: "0 auto 16px",
                backgroundColor: "rgba(139,92,246,0.1)", border: "1px solid rgba(139,92,246,0.2)",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <BotIcon size={24} />
              </div>
              <h3 style={{ fontSize: 17, fontWeight: 700, color: "#F4F4F5", marginBottom: 8 }}>Connect a Developer Wallet</h3>
              <p style={{ fontSize: 13, color: "#71717A", maxWidth: 380, margin: "0 auto 16px", lineHeight: 1.6 }}>
                Connect the wallet that owns your agent to register a .vns name. Each agent requires an accountability bond.
              </p>
              <p style={{ fontSize: 12, color: "#52525B", maxWidth: 380, margin: "0 auto" }}>
                For programmatic registration without a browser, use the API tab.
              </p>
            </div>
          )}

          {/* Agent Registration Form */}
          {walletAddress && (
            <>
              {/* Name Input */}
              <div>
                <label style={labelStyle}>Agent .vns Name</label>
                <div style={{ position: "relative" }}>
                  <input
                    type="text"
                    value={nameInput}
                    onChange={e => setNameInput(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                    placeholder="my-agent"
                    style={{
                      ...inputStyle,
                      paddingRight: 60,
                      borderColor: validation && !validation.valid ? "rgba(239,68,68,0.5)" :
                        availability?.available ? "rgba(34,197,94,0.5)" :
                        availability && !availability.available ? "rgba(239,68,68,0.5)" :
                        "rgba(255,255,255,0.1)",
                    }}
                    maxLength={32}
                  />
                  <span style={{
                    position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)",
                    fontSize: 14, color: "#52525B", fontWeight: 500,
                  }}>.vns</span>
                </div>

                {nameInput && (
                  <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 4 }}>
                    {validation && !validation.valid && (
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        <XIcon size={14} />
                        <span style={{ fontSize: 12, color: "#EF4444" }}>{validation.error}</span>
                      </div>
                    )}
                    {validation?.valid && availability && (
                      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                        {availability.available ? (
                          <><CheckIcon size={14} /><span style={{ fontSize: 12, color: "#22C55E" }}>{availability.name}.vns is available</span></>
                        ) : (
                          <><XIcon size={14} /><span style={{ fontSize: 12, color: "#EF4444" }}>{availability.name}.vns is taken</span></>
                        )}
                      </div>
                    )}
                    {ruleError && (
                      <div style={{
                        display: "flex", alignItems: "flex-start", gap: 6,
                        padding: "8px 12px", borderRadius: 8, background: "rgba(239,68,68,0.06)", marginTop: 4,
                      }}>
                        <ShieldIcon size={14} />
                        <span style={{ fontSize: 12, color: "#EF4444", lineHeight: 1.4 }}>{ruleError}</span>
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* Chain Selection */}
              <div>
                <label style={labelStyle}>Deployment Chain</label>
                <div style={{ display: "flex", gap: 8 }}>
                  {(['base', 'avalanche', 'arbitrum', 'polygon'] as const).map(c => (
                    <button
                      key={c}
                      onClick={() => setChain(c)}
                      style={{
                        ...btnSecondary, flex: 1, textAlign: "center",
                        borderColor: chain === c ? "rgba(139,92,246,0.4)" : "rgba(255,255,255,0.1)",
                        background: chain === c ? "rgba(139,92,246,0.08)" : "rgba(255,255,255,0.03)",
                        color: chain === c ? "#8B5CF6" : "#A1A1AA",
                      }}
                    >
                      {c === 'base' ? 'Base' : c === 'avalanche' ? 'Avalanche' : c === 'arbitrum' ? 'Arbitrum' : 'Polygon'}
                    </button>
                  ))}
                </div>
              </div>

              {/* Bond Amount */}
              <div>
                <label style={labelStyle}>
                  Accountability Bond ({chain === 'avalanche' ? 'AVAX' : chain === 'polygon' ? 'MATIC' : 'ETH'})
                </label>
                <input
                  type="number" value={bondAmount}
                  onChange={e => setBondAmount(e.target.value)}
                  min="0.01" step="0.01" style={inputStyle}
                />
                <div style={{ marginTop: 8, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <span style={{ fontSize: 11, color: "#71717A" }}>Trust tier:</span>
                  {(() => {
                    const tier = getBondTier(parseFloat(bondAmount) || 0);
                    const info = getBondTierInfo(tier);
                    return (
                      <span style={{
                        fontSize: 11, fontWeight: 600, color: info.color,
                        padding: "2px 8px", borderRadius: 6, background: `${info.color}15`,
                      }}>{info.label}</span>
                    );
                  })()}
                  <span style={{ fontSize: 11, color: "#52525B" }}>
                    Bronze: 0.01 · Silver: 0.05 · Gold: 0.1 · Platinum: 0.5
                  </span>
                </div>
              </div>

              {/* Gas Estimate */}
              {gasEstimate && (
                <div style={{
                  padding: "10px 14px", borderRadius: 10,
                  background: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.04)",
                }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ fontSize: 12, color: "#71717A" }}>Estimated gas fee</span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: "#D4D4D8" }}>
                      {gasEstimate.totalFeeFormatted} {gasEstimate.gasSymbol}
                    </span>
                  </div>
                </div>
              )}

              {/* Register Button */}
              <button
                onClick={handleRegister}
                disabled={!canRegister}
                style={{
                  ...btnPrimary,
                  opacity: canRegister ? 1 : 0.4,
                  cursor: canRegister ? "pointer" : "not-allowed",
                }}
              >
                {registering ? "Registering agent on-chain..." :
                  `Register ${nameInput || 'agent'}.vns`}
              </button>

              {/* Result */}
              {result && (
                <div style={{
                  ...card, padding: 16,
                  borderColor: result.success ? "rgba(34,197,94,0.3)" : "rgba(239,68,68,0.3)",
                  background: result.success ? "rgba(34,197,94,0.05)" : "rgba(239,68,68,0.05)",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                    {result.success ? <CheckIcon size={16} /> : <XIcon size={16} />}
                    <span style={{
                      fontSize: 14, fontWeight: 600,
                      color: result.success ? "#22C55E" : "#EF4444",
                    }}>
                      {result.success ? "Agent Registered" : "Registration Failed"}
                    </span>
                  </div>
                  <p style={{ fontSize: 13, color: "#A1A1AA", margin: 0 }}>{result.message}</p>
                  {result.explorerUrl && (
                    <a
                      href={result.explorerUrl} target="_blank" rel="noopener noreferrer"
                      style={{
                        display: "inline-flex", alignItems: "center", gap: 4,
                        fontSize: 12, color: "#8B5CF6", marginTop: 8, textDecoration: "none",
                      }}
                    >
                      <LinkIcon size={12} /> View on Explorer
                    </a>
                  )}
                </div>
              )}
            </>
          )}

          <SybilProtection />
        </div>
      ) : tab === 'lookup' ? (
        /* ── Resolve Agent Tab ── */
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <label style={labelStyle}>Resolve agent by .vns name</label>
            <div style={{ display: "flex", gap: 8 }}>
              <input
                type="text" value={lookupInput}
                onChange={e => setLookupInput(e.target.value)}
                placeholder="my-agent.vns"
                style={{ ...inputStyle, flex: 1 }}
                onKeyDown={e => e.key === 'Enter' && handleLookup()}
              />
              <button onClick={handleLookup} style={{ ...btnPrimary, width: "auto", padding: "14px 20px" }}>
                <SearchIcon size={18} />
              </button>
            </div>
            <p style={{ fontSize: 11, color: "#52525B", marginTop: 6 }}>
              Programmatic: GET /api/agent/status?name=agent.vns
            </p>
          </div>

          {lookupError && (
            <div style={{ ...card, padding: 16, borderColor: "rgba(239,68,68,0.2)" }}>
              <p style={{ fontSize: 13, color: "#EF4444", margin: 0 }}>{lookupError}</p>
            </div>
          )}

          {lookupResult && (
            <div style={{ ...card, padding: 20 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
                <div style={{
                  width: 48, height: 48, borderRadius: 14,
                  background: "rgba(139,92,246,0.12)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <BotIcon size={22} />
                </div>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: "#F4F4F5" }}>
                    {lookupResult.fullName}
                  </div>
                  <div style={{
                    fontSize: 12, color: "#8B5CF6",
                    display: "inline-block", padding: "2px 8px", borderRadius: 6,
                    background: "rgba(139,92,246,0.12)",
                  }}>
                    AI Agent
                  </div>
                </div>
              </div>

              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                  <span style={{ fontSize: 13, color: "#71717A" }}>Wallet Address</span>
                  <span style={{ fontSize: 13, color: "#D4D4D8", fontFamily: "monospace" }}>
                    {lookupResult.address.slice(0, 10)}...{lookupResult.address.slice(-6)}
                  </span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                  <span style={{ fontSize: 13, color: "#71717A" }}>Chain</span>
                  <span style={{ fontSize: 13, color: "#D4D4D8" }}>{lookupResult.chain}</span>
                </div>
                {lookupResult.bondTier && (
                  <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                    <span style={{ fontSize: 13, color: "#71717A" }}>Bond Tier</span>
                    <span style={{
                      fontSize: 12, fontWeight: 600,
                      color: getBondTierInfo(lookupResult.bondTier).color,
                    }}>
                      {getBondTierInfo(lookupResult.bondTier).label}
                    </span>
                  </div>
                )}
                {lookupResult.explorerUrl && (
                  <a
                    href={lookupResult.explorerUrl} target="_blank" rel="noopener noreferrer"
                    style={{
                      display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
                      padding: "10px", borderRadius: 10,
                      background: "rgba(139,92,246,0.08)", color: "#8B5CF6",
                      fontSize: 13, fontWeight: 500, textDecoration: "none", marginTop: 8,
                    }}
                  >
                    <LinkIcon size={14} /> View on Explorer
                  </a>
                )}
              </div>
            </div>
          )}

          {!lookupResult && !lookupError && (
            <div style={{
              textAlign: "center", padding: "36px 20px",
              border: "1px solid rgba(139,92,246,0.08)",
              borderRadius: 14, backgroundColor: "rgba(139,92,246,0.02)",
            }}>
              <BotIcon size={28} />
              <p style={{ fontSize: 13, color: "#52525B", marginTop: 12, lineHeight: 1.5 }}>
                Enter an agent's .vns name to resolve its wallet address, chain, and bond tier.
              </p>
            </div>
          )}
        </div>
      ) : (
        /* ── API Tab ── */
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <APIQuickRef />

          <div style={{
            ...card, padding: 16,
            borderColor: "rgba(139,92,246,0.15)",
            background: "rgba(139,92,246,0.03)",
          }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 10 }}>
              <CodeIcon size={16} />
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: "#F4F4F5", marginBottom: 4 }}>No API Key Required</div>
                <p style={{ fontSize: 12, color: "#71717A", margin: 0, lineHeight: 1.6 }}>
                  All VNS endpoints are open. Agents register, resolve, and verify identities using standard HTTP requests.
                  Bond transactions are signed on-chain by the agent's wallet. No rate limits, no auth tokens, no middlemen.
                </p>
              </div>
            </div>
          </div>

          <SybilProtection />
        </div>
      )}

      {/* ═══ FOOTER ═══ */}
      <div style={{
        marginTop: 40, padding: "14px 0", borderTop: "1px solid rgba(255,255,255,0.04)",
        textAlign: "center",
      }}>
        <span style={{ fontSize: 11, color: "#3F3F46", letterSpacing: "0.04em" }}>
          VNS · THE NAME SYSTEM FOR AI AGENTS · ENS IS FOR HUMANS · VNS IS FOR AGENTS
        </span>
      </div>
    </div>
  );
}
