"use client";
/**
 * VKP — Verified Key Protocol
 *
 * The key management layer for Vaultfire. Live on all 4 mainnet chains.
 * Three contracts per chain:
 *   VKPFactory           — Creates and manages agent key pairs
 *   VKPSessionKeyManager — Temporary scoped session keys for agent operations
 *   VKPDelegationRegistry — Permission delegation between agents
 *
 * ALL DATA IS REAL — live on-chain bytecode verification via RPC calls.
 */
import { useState, useEffect, useCallback } from "react";
import { CHAINS, VKP_FACTORY, VKP_SESSION_KEYS, VKP_DELEGATION, EXPLORER_URLS } from "../lib/contracts";
import { AlphaBanner } from "../components/DisclaimerBanner";

/* ─── Types ─── */
type SupportedChain = "base" | "avalanche" | "arbitrum" | "polygon";

interface ContractStatus {
  address: string;
  alive: boolean;
  loading: boolean;
  error: boolean;
}

interface ChainVKP {
  chain: SupportedChain;
  factory: ContractStatus;
  session: ContractStatus;
  delegation: ContractStatus;
}

/* ─── Constants ─── */
const CHAIN_CONFIG: Record<SupportedChain, { name: string; color: string; bg: string; border: string; explorer: string }> = {
  base: { name: "Base", color: "#3B82F6", bg: "rgba(59,130,246,0.08)", border: "rgba(59,130,246,0.2)", explorer: EXPLORER_URLS.base },
  avalanche: { name: "Avalanche", color: "#EF4444", bg: "rgba(239,68,68,0.08)", border: "rgba(239,68,68,0.2)", explorer: EXPLORER_URLS.avalanche },
  arbitrum: { name: "Arbitrum", color: "#28A0F0", bg: "rgba(40,160,240,0.08)", border: "rgba(40,160,240,0.2)", explorer: EXPLORER_URLS.arbitrum },
  polygon: { name: "Polygon", color: "#8247E5", bg: "rgba(130,71,229,0.08)", border: "rgba(130,71,229,0.2)", explorer: EXPLORER_URLS.polygon },
};

const RPC_URLS: Record<SupportedChain, string> = {
  base: CHAINS.base.rpcUrls.default.http[0],
  avalanche: CHAINS.avalanche.rpcUrls.default.http[0],
  arbitrum: CHAINS.arbitrum.rpcUrls.default.http[0],
  polygon: CHAINS.polygon.rpcUrls.default.http[0],
};

/* ─── RPC Helper ─── */
async function rpcCall(rpc: string, method: string, params: any[]): Promise<any> {
  const res = await fetch(rpc, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
  });
  return res.json();
}

async function checkContractLive(rpc: string, address: string): Promise<boolean> {
  try {
    const result = await rpcCall(rpc, "eth_getCode", [address, "latest"]);
    return result.result && result.result !== "0x" && result.result.length > 4;
  } catch {
    return false;
  }
}

/* ─── Icons ─── */
function KeyIcon({ size = 18, color = "currentColor" }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d="m21 2-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.78 7.78 5.5 5.5 0 0 1 7.78-7.78Zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4" />
    </svg>
  );
}
function FactoryIcon({ size = 18, color = "currentColor" }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8l-7 5V8l-7 5V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z" />
    </svg>
  );
}
function DelegateIcon({ size = 18, color = "currentColor" }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /><path d="M22 21v-2a4 4 0 0 0-3-3.87" /><path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  );
}
function ShieldCheckIcon({ size = 18, color = "currentColor" }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /><path d="m9 12 2 2 4-4" />
    </svg>
  );
}
function ExternalIcon({ size = 10 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round">
      <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>
  );
}
function RefreshIcon({ size = 12, spinning = false }: { size?: number; spinning?: boolean }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
      style={{ animation: spinning ? "spin 1s linear infinite" : "none" }}>
      <polyline points="23 4 23 10 17 10" /><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
    </svg>
  );
}
function CopyIcon({ size = 12 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="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>
  );
}

/* ─── Copy Helper ─── */
function useCopy() {
  const [copied, setCopied] = useState<string | null>(null);
  const copy = useCallback((text: string, id: string) => {
    navigator.clipboard.writeText(text).catch(() => {});
    setCopied(id);
    setTimeout(() => setCopied(null), 1500);
  }, []);
  return { copied, copy };
}

/* ─── Contract Row ─── */
function ContractRow({
  label, icon, status, explorer, chain, copiedId, onCopy,
}: {
  label: string;
  icon: React.ReactNode;
  status: ContractStatus;
  explorer: string;
  chain: SupportedChain;
  copiedId: string | null;
  onCopy: (text: string, id: string) => void;
}) {
  const shortAddr = `${status.address.slice(0, 6)}...${status.address.slice(-4)}`;
  const copyId = `${chain}-${label}`;

  return (
    <div style={{
      display: "flex", alignItems: "center", justifyContent: "space-between",
      padding: "14px 16px", borderRadius: 12,
      backgroundColor: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.05)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10, flexShrink: 0,
          backgroundColor: "rgba(255,107,53,0.08)", border: "1px solid rgba(255,107,53,0.15)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          {icon}
        </div>
        <div style={{ minWidth: 0 }}>
          <p style={{ fontSize: 13, fontWeight: 600, color: "#F4F4F5", marginBottom: 2 }}>{label}</p>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <code style={{ fontSize: 11, color: "#71717A", fontFamily: "'JetBrains Mono', 'Courier New', monospace" }}>
              {shortAddr}
            </code>
            <button onClick={() => onCopy(status.address, copyId)} style={{
              background: "none", border: "none", cursor: "pointer", padding: 2, color: copiedId === copyId ? "#10B981" : "#52525B",
              transition: "color 150ms",
            }}>
              {copiedId === copyId ? (
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12" /></svg>
              ) : <CopyIcon size={10} />}
            </button>
          </div>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
        {/* Status badge */}
        {status.loading ? (
          <div style={{
            padding: "4px 10px", borderRadius: 6, fontSize: 10, fontWeight: 700,
            backgroundColor: "rgba(234,179,8,0.08)", border: "1px solid rgba(234,179,8,0.2)", color: "#EAB308",
          }}>Checking...</div>
        ) : status.alive ? (
          <div style={{
            display: "flex", alignItems: "center", gap: 5,
            padding: "4px 10px", borderRadius: 6, fontSize: 10, fontWeight: 700,
            backgroundColor: "rgba(16,185,129,0.08)", border: "1px solid rgba(16,185,129,0.2)", color: "#10B981",
          }}>
            <div style={{ width: 5, height: 5, borderRadius: "50%", backgroundColor: "#10B981" }} />
            LIVE
          </div>
        ) : status.error ? (
          <div style={{
            padding: "4px 10px", borderRadius: 6, fontSize: 10, fontWeight: 700,
            backgroundColor: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.2)", color: "#EF4444",
          }}>ERROR</div>
        ) : null}
        {/* Explorer link */}
        <a href={`${explorer}/address/${status.address}`} target="_blank" rel="noopener noreferrer" style={{
          display: "flex", alignItems: "center", gap: 4, padding: "6px 10px", borderRadius: 8,
          backgroundColor: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)",
          color: "#A1A1AA", fontSize: 11, fontWeight: 500, textDecoration: "none", transition: "all 150ms",
        }}>
          View <ExternalIcon size={9} />
        </a>
      </div>
    </div>
  );
}

/* ─── Chain Card ─── */
function ChainCard({ data, copiedId, onCopy }: { data: ChainVKP; copiedId: string | null; onCopy: (text: string, id: string) => void }) {
  const cfg = CHAIN_CONFIG[data.chain];
  const allAlive = data.factory.alive && data.session.alive && data.delegation.alive;
  const anyLoading = data.factory.loading || data.session.loading || data.delegation.loading;

  return (
    <div style={{
      backgroundColor: "rgba(255,255,255,0.015)", border: `1px solid ${cfg.border}`,
      borderRadius: 20, padding: 24, display: "flex", flexDirection: "column", gap: 14,
    }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 10, height: 10, borderRadius: "50%", backgroundColor: cfg.color,
            boxShadow: `0 0 8px ${cfg.color}60`,
          }} />
          <span style={{ fontSize: 16, fontWeight: 700, color: "#F4F4F5" }}>{cfg.name}</span>
        </div>
        {anyLoading ? (
          <span style={{ fontSize: 11, color: "#EAB308", fontWeight: 600 }}>Verifying...</span>
        ) : allAlive ? (
          <div style={{
            display: "flex", alignItems: "center", gap: 5, padding: "4px 12px", borderRadius: 8,
            backgroundColor: "rgba(16,185,129,0.08)", border: "1px solid rgba(16,185,129,0.2)",
          }}>
            <ShieldCheckIcon size={12} color="#10B981" />
            <span style={{ fontSize: 11, fontWeight: 700, color: "#10B981" }}>3/3 LIVE</span>
          </div>
        ) : (
          <span style={{ fontSize: 11, color: "#EF4444", fontWeight: 600 }}>Issues Detected</span>
        )}
      </div>

      {/* Contracts */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <ContractRow label="VKP Factory" icon={<FactoryIcon size={16} color="#FF8C5A" />} status={data.factory} explorer={cfg.explorer} chain={data.chain} copiedId={copiedId} onCopy={onCopy} />
        <ContractRow label="Session Key Manager" icon={<KeyIcon size={16} color="#FF8C5A" />} status={data.session} explorer={cfg.explorer} chain={data.chain} copiedId={copiedId} onCopy={onCopy} />
        <ContractRow label="Delegation Registry" icon={<DelegateIcon size={16} color="#FF8C5A" />} status={data.delegation} explorer={cfg.explorer} chain={data.chain} copiedId={copiedId} onCopy={onCopy} />
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   MAIN COMPONENT
   ═══════════════════════════════════════════════════ */
export default function VKP() {
  const [chainData, setChainData] = useState<ChainVKP[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const { copied, copy } = useCopy();

  const verify = useCallback(async () => {
    setRefreshing(true);

    const chains: SupportedChain[] = ["base", "avalanche", "arbitrum", "polygon"];
    const initial: ChainVKP[] = chains.map(chain => ({
      chain,
      factory: { address: VKP_FACTORY[chain], alive: false, loading: true, error: false },
      session: { address: VKP_SESSION_KEYS[chain], alive: false, loading: true, error: false },
      delegation: { address: VKP_DELEGATION[chain], alive: false, loading: true, error: false },
    }));
    setChainData(initial);

    const results = await Promise.all(
      chains.map(async (chain) => {
        const rpc = RPC_URLS[chain];
        const [fAlive, sAlive, dAlive] = await Promise.all([
          checkContractLive(rpc, VKP_FACTORY[chain]),
          checkContractLive(rpc, VKP_SESSION_KEYS[chain]),
          checkContractLive(rpc, VKP_DELEGATION[chain]),
        ]);
        return {
          chain,
          factory: { address: VKP_FACTORY[chain], alive: fAlive, loading: false, error: !fAlive },
          session: { address: VKP_SESSION_KEYS[chain], alive: sAlive, loading: false, error: !sAlive },
          delegation: { address: VKP_DELEGATION[chain], alive: dAlive, loading: false, error: !dAlive },
        };
      })
    );

    setChainData(results);
    setRefreshing(false);
  }, []);

  useEffect(() => { verify(); }, [verify]);

  const totalContracts = 12;
  const liveCount = chainData.reduce((n, c) => n + (c.factory.alive ? 1 : 0) + (c.session.alive ? 1 : 0) + (c.delegation.alive ? 1 : 0), 0);
  const allLoading = chainData.length === 0 || chainData.some(c => c.factory.loading);

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

      {/* Header */}
      <div style={{ textAlign: "center", marginBottom: 48 }}>
        <div style={{
          display: "inline-flex", alignItems: "center", gap: 8, padding: "6px 16px",
          borderRadius: 100, marginBottom: 20,
          backgroundColor: "rgba(255,107,53,0.06)", border: "1px solid rgba(255,107,53,0.15)",
        }}>
          <KeyIcon size={14} color="#FF8C5A" />
          <span style={{ fontSize: 12, fontWeight: 700, color: "#FF8C5A", letterSpacing: "0.04em" }}>
            VERIFIED KEY PROTOCOL
          </span>
        </div>
        <h1 style={{ fontSize: 32, fontWeight: 800, color: "#F4F4F5", letterSpacing: "-0.03em", marginBottom: 12 }}>
          Agent Key Management
        </h1>
        <p style={{ fontSize: 16, color: "#71717A", maxWidth: 600, margin: "0 auto", lineHeight: 1.6 }}>
          Session keys, delegation, and key factory — the security layer that lets AI agents
          operate with scoped permissions across all 4 chains.
        </p>
      </div>

      {/* Stats bar */}
      <div style={{
        display: "flex", justifyContent: "center", gap: 32, flexWrap: "wrap",
        marginBottom: 40, padding: "20px 24px", borderRadius: 16,
        backgroundColor: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)",
      }}>
        <div style={{ textAlign: "center" }}>
          <p style={{ fontSize: 28, fontWeight: 800, color: allLoading ? "#71717A" : liveCount === totalContracts ? "#10B981" : "#EAB308" }}>
            {allLoading ? "..." : `${liveCount}/${totalContracts}`}
          </p>
          <p style={{ fontSize: 11, color: "#52525B", fontWeight: 600, letterSpacing: "0.04em" }}>CONTRACTS LIVE</p>
        </div>
        <div style={{ width: 1, backgroundColor: "rgba(255,255,255,0.06)" }} />
        <div style={{ textAlign: "center" }}>
          <p style={{ fontSize: 28, fontWeight: 800, color: "#F4F4F5" }}>4</p>
          <p style={{ fontSize: 11, color: "#52525B", fontWeight: 600, letterSpacing: "0.04em" }}>MAINNET CHAINS</p>
        </div>
        <div style={{ width: 1, backgroundColor: "rgba(255,255,255,0.06)" }} />
        <div style={{ textAlign: "center" }}>
          <p style={{ fontSize: 28, fontWeight: 800, color: "#F4F4F5" }}>3</p>
          <p style={{ fontSize: 11, color: "#52525B", fontWeight: 600, letterSpacing: "0.04em" }}>CONTRACTS / CHAIN</p>
        </div>
        <div style={{ width: 1, backgroundColor: "rgba(255,255,255,0.06)" }} />
        <div style={{ textAlign: "center" }}>
          <button onClick={verify} disabled={refreshing} style={{
            background: "none", border: "none", cursor: refreshing ? "default" : "pointer",
            color: "#A1A1AA", display: "flex", alignItems: "center", gap: 6, padding: "4px 0",
            fontSize: 13, fontWeight: 600, transition: "color 150ms",
          }}>
            <RefreshIcon size={14} spinning={refreshing} />
            {refreshing ? "Verifying..." : "Re-verify"}
          </button>
        </div>
      </div>

      {/* What is VKP */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))", gap: 16,
        marginBottom: 40,
      }}>
        {[
          {
            icon: <FactoryIcon size={20} color="#FF8C5A" />,
            title: "VKP Factory",
            desc: "Creates and manages agent key pairs. Every agent registered on Vaultfire gets a verifiable key identity through the factory.",
          },
          {
            icon: <KeyIcon size={20} color="#FF8C5A" />,
            title: "Session Key Manager",
            desc: "Temporary scoped keys for agent operations. Agents can create time-limited session keys with restricted permissions — no master key exposure.",
          },
          {
            icon: <DelegateIcon size={20} color="#FF8C5A" />,
            title: "Delegation Registry",
            desc: "Permission delegation between agents. An agent can delegate specific capabilities to another agent with on-chain verification and revocation.",
          },
        ].map(card => (
          <div key={card.title} style={{
            padding: 20, borderRadius: 16,
            backgroundColor: "rgba(255,255,255,0.02)", border: "1px solid rgba(255,255,255,0.06)",
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 12, marginBottom: 14,
              backgroundColor: "rgba(255,107,53,0.08)", border: "1px solid rgba(255,107,53,0.15)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              {card.icon}
            </div>
            <h3 style={{ fontSize: 15, fontWeight: 700, color: "#F4F4F5", marginBottom: 8 }}>{card.title}</h3>
            <p style={{ fontSize: 13, color: "#71717A", lineHeight: 1.6 }}>{card.desc}</p>
          </div>
        ))}
      </div>

      {/* Chain cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(420px, 1fr))", gap: 20 }}>
        {chainData.map(data => (
          <ChainCard key={data.chain} data={data} copiedId={copied} onCopy={copy} />
        ))}
      </div>

      {/* Code example */}
      <div style={{
        marginTop: 48, padding: 24, borderRadius: 16,
        backgroundColor: "rgba(0,0,0,0.3)", border: "1px solid rgba(255,255,255,0.06)",
      }}>
        <h3 style={{ fontSize: 15, fontWeight: 700, color: "#F4F4F5", marginBottom: 16, display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 11, padding: "3px 8px", borderRadius: 6, backgroundColor: "rgba(16,185,129,0.1)", border: "1px solid rgba(16,185,129,0.2)", color: "#10B981", fontWeight: 700 }}>
            QUICKSTART
          </span>
          Create a Session Key
        </h3>
        <pre style={{
          fontSize: 12, color: "#A1A1AA", lineHeight: 1.8, overflow: "auto",
          fontFamily: "'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace",
        }}>
{`import { ethers } from 'ethers';

// Connect to Base
const provider = new ethers.JsonRpcProvider('https://mainnet.base.org');
const wallet = new ethers.Wallet(AGENT_PRIVATE_KEY, provider);

// VKP Session Key Manager on Base
const sessionManager = new ethers.Contract(
  '${VKP_SESSION_KEYS.base}',
  ['function createSession(address agent, uint256 expiry, bytes32 scope) returns (bytes32)'],
  wallet
);

// Create a 1-hour session key scoped to "task-execution"
const scope = ethers.id('task-execution');
const expiry = Math.floor(Date.now() / 1000) + 3600;
const sessionId = await sessionManager.createSession(
  wallet.address, expiry, scope
);

console.log('Session created:', sessionId);`}
        </pre>
      </div>

      {/* How it fits */}
      <div style={{
        marginTop: 32, padding: 24, borderRadius: 16,
        backgroundColor: "rgba(255,107,53,0.03)", border: "1px solid rgba(255,107,53,0.1)",
      }}>
        <h3 style={{ fontSize: 15, fontWeight: 700, color: "#F4F4F5", marginBottom: 12 }}>
          How VKP Fits Into the Trust Stack
        </h3>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 12, fontSize: 13, color: "#A1A1AA", lineHeight: 1.7 }}>
          <div style={{ flex: "1 1 200px" }}>
            <p><span style={{ color: "#FF8C5A", fontWeight: 700 }}>Identity</span> (ERC-8004) verifies who the agent is.</p>
            <p><span style={{ color: "#FF8C5A", fontWeight: 700 }}>Bonds</span> put skin in the game — accountability and partnership.</p>
          </div>
          <div style={{ flex: "1 1 200px" }}>
            <p><span style={{ color: "#FF8C5A", fontWeight: 700 }}>VKP</span> controls what the agent can do — scoped keys, delegation, no master key exposure.</p>
            <p><span style={{ color: "#FF8C5A", fontWeight: 700 }}>Together</span> they form the complete trust layer for the agentic web.</p>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @media (max-width: 500px) {
          div[style*="gridTemplateColumns: repeat(auto-fit, minmax(420px"] {
            grid-template-columns: 1fr !important;
          }
        }
      `}</style>
    </div>
  );
}
