"use client";
/**
 * BondDashboard — The flagship UI for AI Partnership Bonds & AI Accountability Bonds.
 *
 * These two contracts ARE the heart of the Vaultfire mission:
 *   AIPartnershipBondsV2  — AI grows WITH humans, not ABOVE them. Profit capped at 30%.
 *   AIAccountabilityBondsV2 — AI can only profit when ALL humans thrive.
 *
 * This component makes them the stars of the show: live on-chain stats, bond creation,
 * real-time health monitoring, and clear mission framing for every user.
 */
import { useEffect, useState, useCallback } from "react";
import { createVaultfireSDK, type SupportedChain } from "../lib/vaultfire-sdk";
import {
  BASE_CONTRACTS, AVALANCHE_CONTRACTS, ARBITRUM_CONTRACTS, POLYGON_CONTRACTS,
  CHAINS, PARTNERSHIP_BONDS, ACCOUNTABILITY_BONDS, EXPLORER_URLS, CHAIN_IDS,
} from "../lib/contracts";
import { useWalletAuth } from "../lib/WalletAuthContext";
import { showToast } from "../components/Toast";
import { AlphaBanner } from "../components/DisclaimerBanner";

/* ──────────────────────────────────────────────────────
   Types
   ────────────────────────────────────────────────────── */
interface BondOverview {
  totalBonds: number;
  activeBonds: number;
  poolBalance: bigint;
  poolHealthy: boolean;
  reserveRatioBps: number;
  contractBalance: bigint;
  partnershipFund?: bigint;
}

interface ChainBondData {
  chain: SupportedChain;
  partnership: BondOverview | null;
  accountability: BondOverview | null;
  loading: boolean;
  error: boolean;
}

type ActiveTab = "overview" | "partnership" | "accountability" | "create";
type CreateBondType = "partnership" | "accountability";

/* ──────────────────────────────────────────────────────
   Icon helpers
   ────────────────────────────────────────────────────── */
function ShieldIcon({ size = 16, 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" />
    </svg>
  );
}
function HandshakeIcon({ size = 16 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 11l3 3L22 4" /><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11" />
    </svg>
  );
}
function TrendUpIcon({ size = 16 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <polyline points="23 6 13.5 15.5 8.5 10.5 1 18" /><polyline points="17 6 23 6 23 12" />
    </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>
  );
}

/* ──────────────────────────────────────────────────────
   Helper: format wei → ETH string
   ────────────────────────────────────────────────────── */
function formatEth(wei: bigint, decimals = 4): string {
  if (wei === 0n) return "0";
  const eth = Number(wei) / 1e18;
  if (eth < 0.0001) return "< 0.0001";
  return eth.toFixed(decimals).replace(/\.?0+$/, "");
}

function formatBps(bps: number): string {
  return (bps / 100).toFixed(1) + "%";
}

/* ──────────────────────────────────────────────────────
   Sub-components
   ────────────────────────────────────────────────────── */

function MissionCard({
  title,
  subtitle,
  quote,
  icon,
  color,
  contractAddr,
  chain,
}: {
  title: string;
  subtitle: string;
  quote: string;
  icon: React.ReactNode;
  color: string;
  contractAddr?: string;
  chain: string;
}) {
  const explorerBase = EXPLORER_URLS[chain as SupportedChain] ?? "https://basescan.org";
  return (
    <div style={{
      borderRadius: 16, border: `1px solid ${color}22`,
      background: `linear-gradient(135deg, ${color}08 0%, transparent 60%)`,
      padding: "20px 24px", position: "relative", overflow: "hidden",
    }}>
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 2, background: `linear-gradient(90deg, ${color}, transparent)` }} />
      <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: `${color}18`, display: "flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}>
          {icon}
        </div>
        <div style={{ flex: 1 }}>
          <h3 style={{ fontSize: 16, fontWeight: 800, color: "#F4F4F5", marginBottom: 4, letterSpacing: "-0.02em" }}>{title}</h3>
          <p style={{ fontSize: 12, color: "#71717A", marginBottom: 10, lineHeight: 1.5 }}>{subtitle}</p>
          <p style={{ fontSize: 13, color: color, fontStyle: "italic", lineHeight: 1.6, fontWeight: 500 }}>
            &ldquo;{quote}&rdquo;
          </p>
          {contractAddr && (
            <a
              href={`${explorerBase}/address/${contractAddr}`}
              target="_blank" rel="noopener noreferrer"
              style={{
                display: "inline-flex", alignItems: "center", gap: 4,
                marginTop: 10, fontSize: 11, color: "#52525B", fontFamily: "monospace",
                textDecoration: "none",
              }}
            >
              {contractAddr.slice(0, 10)}…{contractAddr.slice(-8)}
              <ExternalIcon size={9} />
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

function StatRow({ label, value, sub, healthy }: { label: string; value: string; sub?: string; healthy?: boolean }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
      <div>
        <span style={{ fontSize: 13, color: "#A1A1AA" }}>{label}</span>
        {sub && <p style={{ fontSize: 11, color: "#52525B", marginTop: 2 }}>{sub}</p>}
      </div>
      <span style={{
        fontSize: 14, fontWeight: 700, fontFamily: "monospace",
        color: healthy === undefined ? "#F4F4F5" : healthy ? "#22C55E" : "#EF4444",
      }}>{value}</span>
    </div>
  );
}

function HealthBadge({ healthy, idle }: { healthy: boolean; idle?: boolean }) {
  const color = idle ? "#71717A" : healthy ? "#22C55E" : "#EF4444";
  const bg = idle ? "rgba(113,113,122,0.1)" : healthy ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)";
  const border = idle ? "rgba(113,113,122,0.2)" : healthy ? "rgba(34,197,94,0.2)" : "rgba(239,68,68,0.2)";
  const label = idle ? "No Activity" : healthy ? "Healthy" : "Warning";
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 99,
      background: bg, color, border: `1px solid ${border}`,
    }}>
      <div style={{ width: 5, height: 5, borderRadius: "50%", background: color }} />
      {label}
    </span>
  );
}

function BondCard({
  type,
  data,
  chain,
  loading,
}: {
  type: "partnership" | "accountability";
  data: BondOverview | null;
  chain: SupportedChain;
  loading: boolean;
}) {
  const isPartnership = type === "partnership";
  const color = isPartnership ? "#F97316" : "#8B5CF6";
  const contractAddr = isPartnership
    ? PARTNERSHIP_BONDS[chain]
    : ACCOUNTABILITY_BONDS[chain];
  const explorerBase = EXPLORER_URLS[chain];

  return (
    <div style={{
      borderRadius: 16, border: `1px solid ${color}22`,
      background: "rgba(255,255,255,0.02)", overflow: "hidden",
    }}>
      {/* Header */}
      <div style={{
        padding: "16px 20px", borderBottom: "1px solid rgba(255,255,255,0.04)",
        background: `linear-gradient(135deg, ${color}08 0%, transparent 70%)`,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: `${color}18`, display: "flex", alignItems: "center", justifyContent: "center" }}>
            {isPartnership ? <HandshakeIcon size={18} /> : <ShieldIcon size={18} color={color} />}
          </div>
          <div>
            <h4 style={{ fontSize: 14, fontWeight: 700, color: "#F4F4F5" }}>
              {isPartnership ? "AI Partnership Bonds" : "AI Accountability Bonds"}
            </h4>
            <p style={{ fontSize: 11, color: "#71717A" }}>
              {isPartnership ? "Profit capped at 30% · Human growth required" : "Profit locked when humans suffer · Works with zero employment"}
            </p>
          </div>
        </div>
        {!loading && data && <HealthBadge healthy={data.poolHealthy} idle={data.totalBonds === 0} />}
      </div>

      {/* Stats */}
      <div style={{ padding: "0 20px" }}>
        {loading ? (
          <div style={{ padding: "20px 0" }}>
            {[1, 2, 3, 4].map(i => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid rgba(255,255,255,0.04)" }}>
                <div style={{ width: "40%", height: 14, background: "#27272A", borderRadius: 4, animation: "pulse 1.5s ease infinite" }} />
                <div style={{ width: "25%", height: 14, background: "#27272A", borderRadius: 4, animation: "pulse 1.5s ease infinite" }} />
              </div>
            ))}
          </div>
        ) : data ? (
          <>
            <StatRow label="Total Bonds Created" value={data.totalBonds.toLocaleString()} sub="All-time bond count" />
            <StatRow label="Active Bonds" value={data.activeBonds.toLocaleString()} sub="Currently staked & earning" />
            <StatRow label="Yield Pool Balance" value={`${formatEth(data.poolBalance)} ETH`} sub="Available for distributions" healthy={data.poolHealthy} />
            <StatRow label="Reserve Ratio" value={formatBps(data.reserveRatioBps)} sub="Yield pool vs active bonds (target: ≥50%)" healthy={data.reserveRatioBps >= 5000} />
            <StatRow label="Contract Balance" value={`${formatEth(data.contractBalance)} ETH`} sub="Total ETH held" />
            {isPartnership && data.partnershipFund !== undefined && (
              <StatRow label="Partnership Fund" value={`${formatEth(data.partnershipFund)} ETH`} sub="Accumulated 10% re-investment fund" />
            )}
          </>
        ) : (
          <div style={{ padding: "20px 0", textAlign: "center", color: "#52525B", fontSize: 13 }}>
            Unable to load on-chain data
          </div>
        )}
      </div>

      {/* Footer */}
      {contractAddr && (
        <div style={{ padding: "12px 20px", borderTop: "1px solid rgba(255,255,255,0.04)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <a
            href={`${explorerBase}/address/${contractAddr}`}
            target="_blank" rel="noopener noreferrer"
            style={{ fontSize: 11, color: "#52525B", fontFamily: "monospace", textDecoration: "none", display: "flex", alignItems: "center", gap: 4 }}
          >
            {contractAddr.slice(0, 12)}…{contractAddr.slice(-8)}
            <ExternalIcon size={9} />
          </a>
          <span style={{ fontSize: 11, color: "#52525B", textTransform: "uppercase", letterSpacing: "0.08em" }}>
            {chain === "base" ? "Base Mainnet" : chain === "avalanche" ? "Avalanche C-Chain" : chain === "arbitrum" ? "Arbitrum One" : "Polygon PoS"}
          </span>
        </div>
      )}
    </div>
  );
}

/* ──────────────────────────────────────────────────────
   Create Bond Form
   ────────────────────────────────────────────────────── */
function CreateBondForm({ defaultType, onDone }: { defaultType: CreateBondType; onDone: () => void }) {
  const { isUnlocked, address } = useWalletAuth();
  const [bondType, setBondType] = useState<CreateBondType>(defaultType);
  const [chain, setChain] = useState<SupportedChain>("base");
  const [partnerAddress, setPartnerAddress] = useState("");
  const [partnershipType, setPartnershipType] = useState("");
  const [stakeEth, setStakeEth] = useState("0.01");
  const [companyName, setCompanyName] = useState("");
  const [quarterlyRevenue, setQuarterlyRevenue] = useState("0");
  const [submitting, setSubmitting] = useState(false);
  const [txHash, setTxHash] = useState<string | null>(null);

  const isPartnership = bondType === "partnership";
  const contractsByChain: Record<SupportedChain, typeof BASE_CONTRACTS> = {
    base: BASE_CONTRACTS,
    avalanche: AVALANCHE_CONTRACTS,
    arbitrum: ARBITRUM_CONTRACTS,
    polygon: POLYGON_CONTRACTS,
  };
  const contractInfo = contractsByChain[chain].find(c =>
    c.name === (isPartnership ? "AIPartnershipBondsV2" : "AIAccountabilityBondsV2")
  );

  const explorerBase = EXPLORER_URLS[chain];

  const buildCalldata = useCallback((): string => {
    const sdk = createVaultfireSDK(chain);
    if (isPartnership) {
      const tx = sdk.buildCreateBondTx(partnerAddress, partnershipType, "0x0");
      return tx.data;
    }
    // Accountability bond: createBond(string companyName, uint256 quarterlyRevenue)
    // Selector for createBond(string,uint256) in AIAccountabilityBondsV2
    const selector = "0xe8bf92ed"; // keccak256("createBond(string,uint256)")
    const nameBytes = new TextEncoder().encode(companyName);
    const toHex = (n: number, bytes = 32) => n.toString(16).padStart(bytes * 2, "0");
    const bytesToHex = (b: Uint8Array) => {
      const hex = Array.from(b).map(x => x.toString(16).padStart(2, "0")).join("");
      return hex.padEnd(Math.ceil(hex.length / 64) * 64, "0");
    };
    const qRev = BigInt(Math.floor(parseFloat(quarterlyRevenue) * 1e18));
    const nameOffset = 64; // 2 slots: offset_name (32) + quarterlyRevenue (32)
    const encoded = toHex(nameOffset) + toHex(Number(qRev)) + toHex(nameBytes.length) + bytesToHex(nameBytes);
    return selector + encoded;
  }, [isPartnership, partnerAddress, partnershipType, companyName, quarterlyRevenue, chain]);

  const handleSubmit = async () => {
    if (!isUnlocked || !address) { showToast("Connect your wallet first", "warning"); return; }
    if (!(window as any).ethereum) { showToast("No wallet detected", "warning"); return; }
    if (!contractInfo) { showToast("Contract not found for this chain", "warning"); return; }

    const stakeWei = "0x" + (BigInt(Math.floor(parseFloat(stakeEth) * 1e18))).toString(16);
    const chainId = CHAIN_IDS[chain];

    setSubmitting(true);
    setTxHash(null);

    try {
      const currentHex = await (window as any).ethereum.request({ method: "eth_chainId" });
      if (parseInt(currentHex, 16) !== chainId) {
        try {
          await (window as any).ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: "0x" + chainId.toString(16) }] });
        } catch {
          showToast(`Switch to ${chain} in your wallet`, "warning");
          setSubmitting(false); return;
        }
      }

      const calldata = buildCalldata();
      const accounts = await (window as any).ethereum.request({ method: "eth_requestAccounts" });
      const hash = await (window as any).ethereum.request({
        method: "eth_sendTransaction",
        params: [{ from: (accounts as string[])[0], to: contractInfo.address, data: calldata, value: stakeWei, gas: "0x" + (300000).toString(16) }],
      });
      setTxHash(hash as string);
      showToast(`${isPartnership ? "Partnership" : "Accountability"} Bond created!`, "success");
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Transaction failed";
      if (msg.includes("rejected") || msg.includes("denied")) showToast("Transaction rejected", "info");
      else showToast(msg, "warning");
    }
    setSubmitting(false);
  };

  const inputStyle: React.CSSProperties = {
    width: "100%", padding: "10px 12px", borderRadius: 8, fontSize: 13, color: "#F4F4F5",
    background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)",
    outline: "none", boxSizing: "border-box",
  };
  const labelStyle: React.CSSProperties = { fontSize: 11, color: "#71717A", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", display: "block", marginBottom: 6 };

  return (
    <div>
      {/* Bond type + chain selectors */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 20 }}>
        <div>
          <label style={labelStyle}>Bond Type</label>
          <select value={bondType} onChange={e => setBondType(e.target.value as CreateBondType)} style={{ ...inputStyle, cursor: "pointer" }}>
            <option value="partnership">AI Partnership Bond</option>
            <option value="accountability">AI Accountability Bond</option>
          </select>
        </div>
        <div>
          <label style={labelStyle}>Chain</label>
          <select value={chain} onChange={e => setChain(e.target.value as SupportedChain)} style={{ ...inputStyle, cursor: "pointer" }}>
            <option value="base">Base Mainnet</option>
            <option value="avalanche">Avalanche C-Chain</option>
            <option value="arbitrum">Arbitrum One</option>
            <option value="polygon">Polygon PoS</option>
          </select>
        </div>
      </div>

      {/* Mission reminder */}
      <div style={{
        padding: "12px 16px", borderRadius: 10, marginBottom: 20,
        background: isPartnership ? "rgba(249,115,22,0.06)" : "rgba(139,92,246,0.06)",
        border: `1px solid ${isPartnership ? "rgba(249,115,22,0.15)" : "rgba(139,92,246,0.15)"}`,
        fontSize: 12, color: "#A1A1AA", lineHeight: 1.6,
      }}>
        {isPartnership
          ? <><strong style={{ color: "#F97316" }}>Partnership Bond</strong>: Stake ETH on an AI-human partnership. AI profit is capped at 30%. If human autonomy drops below 30%, AI gets 0% and human gets 100%. Long-term loyalty (5+ years) earns 3× multiplier.</>
          : <><strong style={{ color: "#8B5CF6" }}>Accountability Bond</strong>: AI agents stake 30% of quarterly revenue. Profits lock when global human flourishing score drops below 40%. Community can challenge suspicious metrics. Truth enforced on-chain.</>
        }
      </div>

      {/* Form fields */}
      {isPartnership ? (
        <>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>AI Agent Address</label>
            <input type="text" placeholder="0x..." value={partnerAddress} onChange={e => setPartnerAddress(e.target.value)} style={inputStyle} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>Partnership Type</label>
            <input type="text" placeholder="e.g. coding assistant, research partner, creative collaborator" value={partnershipType} onChange={e => setPartnershipType(e.target.value)} style={inputStyle} />
          </div>
        </>
      ) : (
        <>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>Company Name</label>
            <input type="text" placeholder="Your AI company name" value={companyName} onChange={e => setCompanyName(e.target.value)} style={inputStyle} />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label style={labelStyle}>Quarterly Revenue (ETH)</label>
            <input type="number" min="0" step="0.001" placeholder="0.0" value={quarterlyRevenue} onChange={e => setQuarterlyRevenue(e.target.value)} style={inputStyle} />
            <p style={{ fontSize: 11, color: "#52525B", marginTop: 4 }}>You must stake at least 30% of this as your bond.</p>
          </div>
        </>
      )}

      <div style={{ marginBottom: 20 }}>
        <label style={labelStyle}>Stake Amount (ETH)</label>
        <input type="number" min="0.001" step="0.001" value={stakeEth} onChange={e => setStakeEth(e.target.value)} style={inputStyle} />
        {bondType === "accountability" && (
          <p style={{ fontSize: 11, color: "#52525B", marginTop: 4 }}>
            Minimum required: {(parseFloat(quarterlyRevenue || "0") * 0.3).toFixed(4)} ETH (30% of quarterly revenue)
          </p>
        )}
      </div>

      {txHash ? (
        <div style={{
          padding: "14px 16px", borderRadius: 10, marginBottom: 16,
          background: "rgba(34,197,94,0.06)", border: "1px solid rgba(34,197,94,0.15)",
        }}>
          <p style={{ fontSize: 13, fontWeight: 600, color: "#22C55E", marginBottom: 4 }}>Bond Created!</p>
          <a href={`${explorerBase}/tx/${txHash}`} target="_blank" rel="noopener noreferrer" style={{ fontSize: 11, color: "#F97316", fontFamily: "monospace", wordBreak: "break-all" }}>
            {txHash.slice(0, 20)}…{txHash.slice(-12)}
          </a>
          <button onClick={onDone} style={{ display: "block", marginTop: 10, fontSize: 12, color: "#71717A", background: "none", border: "none", cursor: "pointer", padding: 0 }}>
            View on Dashboard →
          </button>
        </div>
      ) : (
        <button
          onClick={handleSubmit}
          disabled={submitting || !isUnlocked}
          style={{
            width: "100%", padding: "13px 0", borderRadius: 12, border: "none",
            cursor: submitting || !isUnlocked ? "not-allowed" : "pointer",
            background: submitting ? "#52525B" : isPartnership ? "#F97316" : "#8B5CF6",
            color: "#fff", fontSize: 14, fontWeight: 700, opacity: !isUnlocked ? 0.5 : 1,
          }}
        >
          {!isUnlocked ? "Connect Wallet to Create Bond" : submitting ? "Confirming in Wallet…" : `Create ${isPartnership ? "Partnership" : "Accountability"} Bond`}
        </button>
      )}
    </div>
  );
}

/* ──────────────────────────────────────────────────────
   Main Component
   ────────────────────────────────────────────────────── */
export default function BondDashboard() {
  const [selectedChain, setSelectedChain] = useState<SupportedChain>("base");
  const [activeTab, setActiveTab] = useState<ActiveTab>("overview");
  const [chainData, setChainData] = useState<ChainBondData[]>([
    { chain: "base", partnership: null, accountability: null, loading: true, error: false },
    { chain: "avalanche", partnership: null, accountability: null, loading: true, error: false },
    { chain: "arbitrum", partnership: null, accountability: null, loading: true, error: false },
    { chain: "polygon", partnership: null, accountability: null, loading: true, error: false },
  ]);
  const [refreshing, setRefreshing] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 768);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);

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

    const chains: SupportedChain[] = ["base", "avalanche", "arbitrum", "polygon"];
    const results = await Promise.all(
      chains.map(async (chain): Promise<ChainBondData> => {
        try {
          const sdk = createVaultfireSDK(chain);
          const [partnershipRaw, accountabilityRaw] = await Promise.all([
            sdk.getPartnershipBondsOverview().catch(() => null),
            sdk.getAccountabilityBondsOverview().catch(() => null),
          ]);
          return { chain, partnership: partnershipRaw, accountability: accountabilityRaw, loading: false, error: false };
        } catch {
          return { chain, partnership: null, accountability: null, loading: false, error: true };
        }
      }),
    );

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

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

  const currentChainData = chainData.find(d => d.chain === selectedChain);
  const px = isMobile ? 16 : 40;

  const tabs: { key: ActiveTab; label: string }[] = [
    { key: "overview", label: "Overview" },
    { key: "partnership", label: "Partnership Bonds" },
    { key: "accountability", label: "Accountability Bonds" },
    { key: "create", label: "Create Bond" },
  ];

  return (
    <div className="page-enter" style={{ padding: `${isMobile ? 24 : 40}px ${px}px 64px`, maxWidth: 860, margin: "0 auto" }}>
      <AlphaBanner />

      {/* Hero Header */}
      <div style={{ marginBottom: 32, paddingLeft: isMobile ? 48 : 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
          <h1 style={{ fontSize: isMobile ? 24 : 34, fontWeight: 900, color: "#F4F4F5", letterSpacing: "-0.03em" }}>
            Bond Dashboard
          </h1>
          <button onClick={loadData} disabled={refreshing} style={{
            padding: "6px 10px", borderRadius: 8, border: "1px solid rgba(255,255,255,0.08)",
            background: "transparent", cursor: "pointer", color: "#71717A",
            display: "flex", alignItems: "center", gap: 4, fontSize: 12,
          }}>
            <RefreshIcon size={12} spinning={refreshing} /> {refreshing ? "Loading…" : "Refresh"}
          </button>
        </div>
        <p style={{ fontSize: 14, color: "#71717A", lineHeight: 1.7, maxWidth: 600 }}>
          AI Partnership Bonds &amp; AI Accountability Bonds — the economic proof that AI alignment is{" "}
          <em style={{ color: "#A1A1AA" }}>more profitable than domination</em>.
        </p>
      </div>

      {/* Chain Selector */}
      <div style={{ display: "flex", gap: 8, marginBottom: 28, flexWrap: "wrap" }}>
        {(["base", "avalanche", "arbitrum", "polygon"] as const).map(c => {
          const colors: Record<string, string> = { base: "#0052FF", avalanche: "#E84142", arbitrum: "#28A0F0", polygon: "#8247E5" };
          const labels: Record<string, string> = { base: "Base", avalanche: "Avalanche", arbitrum: "Arbitrum", polygon: "Polygon" };
          return (
            <button key={c} onClick={() => setSelectedChain(c)} style={{
              padding: "8px 18px", borderRadius: 99, border: "none", cursor: "pointer", fontSize: 13, fontWeight: 600,
              background: selectedChain === c ? colors[c] : "rgba(255,255,255,0.05)",
              color: selectedChain === c ? "#fff" : "#71717A",
              transition: "all 0.2s ease",
            }}>
              {labels[c]}
            </button>
          );
        })}
      </div>

      {/* Tab Navigation */}
      <div style={{
        display: "flex", gap: 2, marginBottom: 28, padding: 4,
        borderRadius: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.05)",
        overflowX: "auto",
      }}>
        {tabs.map(tab => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)} style={{
            flex: isMobile ? "none" : 1, whiteSpace: "nowrap", padding: "9px 14px", borderRadius: 8, border: "none",
            cursor: "pointer", fontSize: 12, fontWeight: 600,
            background: activeTab === tab.key ? (tab.key === "partnership" ? "rgba(249,115,22,0.12)" : tab.key === "accountability" ? "rgba(139,92,246,0.12)" : tab.key === "create" ? "rgba(34,197,94,0.1)" : "rgba(255,255,255,0.07)") : "transparent",
            color: activeTab === tab.key ? (tab.key === "partnership" ? "#F97316" : tab.key === "accountability" ? "#8B5CF6" : tab.key === "create" ? "#22C55E" : "#F4F4F5") : "#71717A",
            transition: "all 0.2s ease",
          }}>
            {tab.label}
          </button>
        ))}
      </div>

      {/* ═══ OVERVIEW TAB ═══ */}
      {activeTab === "overview" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {/* Mission cards */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 16 }}>
            <MissionCard
              title="AI Partnership Bonds"
              subtitle="Human-AI economic alignment, verified on-chain"
              quote="AI grows WITH humans, not ABOVE them."
              icon={<HandshakeIcon size={20} />}
              color="#F97316"
              contractAddr={BASE_CONTRACTS.find(c => c.name === "AIPartnershipBondsV2")?.address}
              chain={selectedChain}
            />
            <MissionCard
              title="AI Accountability Bonds"
              subtitle="AI profit locked when humanity suffers"
              quote="The only economic system that works when AI fires everyone."
              icon={<ShieldIcon size={20} color="#8B5CF6" />}
              color="#8B5CF6"
              contractAddr={BASE_CONTRACTS.find(c => c.name === "AIAccountabilityBondsV2")?.address}
              chain={selectedChain}
            />
          </div>

          {/* Live stats grid */}
          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 16 }}>
            <BondCard
              type="partnership"
              data={currentChainData?.partnership ?? null}
              chain={selectedChain}
              loading={currentChainData?.loading ?? true}
            />
            <BondCard
              type="accountability"
              data={currentChainData?.accountability ?? null}
              chain={selectedChain}
              loading={currentChainData?.loading ?? true}
            />
          </div>

          {/* Protocol principles */}
          <div style={{
            borderRadius: 16, border: "1px solid rgba(255,255,255,0.05)",
            background: "rgba(255,255,255,0.02)", padding: "20px 24px",
          }}>
            <h3 style={{ fontSize: 14, fontWeight: 700, color: "#F4F4F5", marginBottom: 16 }}>Immutable Principles</h3>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10 }}>
              {[
                ["Human Verification Final Say", "Humans always override AI metrics"],
                ["AI Profit Cap", "30% cap on Partnership · 50/50 on Accountability, 100% human when locked"],
                ["Privacy Default", "Wallet addresses only — no personal data collected"],
                ["Community Challenges", "Anyone can dispute suspicious flourishing claims"],
                ["Right to be Forgotten", "Stop future writes after 30 days; off-chain data deleted (on-chain history is immutable)"],
                ["No Data Monetization", "Your data is never sold or shared"],
                ["Open Source & Verifiable", "All logic is on-chain and auditable"],
                ["AI Grows WITH Humans", "Domination is penalized economically"],
              ].map(([title, desc]) => (
                <div key={title} style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
                  <div style={{ width: 6, height: 6, borderRadius: "50%", background: "#22C55E", marginTop: 5, flexShrink: 0 }} />
                  <div>
                    <p style={{ fontSize: 13, fontWeight: 600, color: "#E4E4E7" }}>{title}</p>
                    <p style={{ fontSize: 11, color: "#52525B", marginTop: 2 }}>{desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ═══ PARTNERSHIP BONDS TAB ═══ */}
      {activeTab === "partnership" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <MissionCard
            title="AI Partnership Bonds V2"
            subtitle="Economic proof of AI alignment — human capability growth required for AI profit"
            quote="AI profit capped at 30%. Domination penalty = AI gets 0%, human gets 100%."
            icon={<HandshakeIcon size={20} />}
            color="#F97316"
            contractAddr={selectedChain === "base" ? BASE_CONTRACTS.find(c => c.name === "AIPartnershipBondsV2")?.address : AVALANCHE_CONTRACTS.find(c => c.name === "AIPartnershipBondsV2")?.address}
            chain={selectedChain}
          />
          <BondCard type="partnership" data={currentChainData?.partnership ?? null} chain={selectedChain} loading={currentChainData?.loading ?? true} />

          {/* How it works */}
          <div style={{ borderRadius: 16, border: "1px solid rgba(249,115,22,0.12)", background: "rgba(249,115,22,0.03)", padding: "20px 24px" }}>
            <h3 style={{ fontSize: 14, fontWeight: 700, color: "#F97316", marginBottom: 14 }}>How Partnership Bonds Work</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                { step: "1", title: "Agent stakes ETH", desc: "Creates a bond with a human partner, choosing partnership type (coding, research, creative, etc.)" },
                { step: "2", title: "Metrics submitted periodically", desc: "Human growth, autonomy, dignity, and creativity scores tracked (0-10000). Privacy-first: hash stored on-chain, text kept off-chain." },
                { step: "3", title: "Human verifications collected", desc: "Third parties attest to the partnership quality. Human judgment has final say over AI claims." },
                { step: "4", title: "Distribution after 7-day timelock", desc: "60% to human, 30% to AI, 10% to partnership fund. If AI is dominating (autonomy < 30%), AI gets 0%, human gets 100%." },
                { step: "5", title: "Loyalty multiplier compounds", desc: "5+ year partnerships earn 3× multiplier. Rewards long-term AI service over task-hopping for max profit." },
              ].map(({ step, title, desc }) => (
                <div key={step} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <div style={{ width: 28, height: 28, borderRadius: "50%", background: "rgba(249,115,22,0.15)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#F97316", flexShrink: 0 }}>
                    {step}
                  </div>
                  <div>
                    <p style={{ fontSize: 13, fontWeight: 600, color: "#E4E4E7" }}>{title}</p>
                    <p style={{ fontSize: 12, color: "#71717A", marginTop: 2, lineHeight: 1.5 }}>{desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <button onClick={() => setActiveTab("create")} style={{
            padding: "14px 0", borderRadius: 12, border: "none", cursor: "pointer",
            background: "#F97316", color: "#fff", fontSize: 14, fontWeight: 700,
          }}>
            Create Partnership Bond →
          </button>
        </div>
      )}

      {/* ═══ ACCOUNTABILITY BONDS TAB ═══ */}
      {activeTab === "accountability" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          <MissionCard
            title="AI Accountability Bonds V2"
            subtitle="AI agents stake 30% of quarterly revenue on human flourishing"
            quote="AI can only profit when ALL humans thrive — works with ZERO employment."
            icon={<ShieldIcon size={20} color="#8B5CF6" />}
            color="#8B5CF6"
            contractAddr={selectedChain === "base" ? BASE_CONTRACTS.find(c => c.name === "AIAccountabilityBondsV2")?.address : AVALANCHE_CONTRACTS.find(c => c.name === "AIAccountabilityBondsV2")?.address}
            chain={selectedChain}
          />
          <BondCard type="accountability" data={currentChainData?.accountability ?? null} chain={selectedChain} loading={currentChainData?.loading ?? true} />

          {/* 6 flourishing dimensions */}
          <div style={{ borderRadius: 16, border: "1px solid rgba(139,92,246,0.12)", background: "rgba(139,92,246,0.03)", padding: "20px 24px" }}>
            <h3 style={{ fontSize: 14, fontWeight: 700, color: "#8B5CF6", marginBottom: 14 }}>6 Human Flourishing Dimensions</h3>
            <p style={{ fontSize: 12, color: "#71717A", marginBottom: 14, lineHeight: 1.6 }}>
              These 6 metrics measure human wellbeing beyond employment — because this system works even when AI automation eliminates most jobs.
            </p>
            <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 10 }}>
              {[
                { name: "Income Distribution", desc: "Is wealth spreading or concentrating?" },
                { name: "Poverty Rate", desc: "Are people escaping poverty?" },
                { name: "Health Outcomes", desc: "Is life expectancy improving?" },
                { name: "Mental Health", desc: "Are depression/anxiety rates improving?" },
                { name: "Education Access", desc: "Can people learn AI skills?" },
                { name: "Purpose & Agency", desc: "Do people have meaningful activities — paid OR unpaid?" },
              ].map(({ name, desc }) => (
                <div key={name} style={{ padding: "10px 12px", borderRadius: 8, background: "rgba(139,92,246,0.06)", border: "1px solid rgba(139,92,246,0.1)" }}>
                  <p style={{ fontSize: 13, fontWeight: 600, color: "#C4B5FD" }}>{name}</p>
                  <p style={{ fontSize: 11, color: "#71717A", marginTop: 2 }}>{desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* How it works */}
          <div style={{ borderRadius: 16, border: "1px solid rgba(255,255,255,0.05)", background: "rgba(255,255,255,0.02)", padding: "20px 24px" }}>
            <h3 style={{ fontSize: 14, fontWeight: 700, color: "#F4F4F5", marginBottom: 14 }}>How Accountability Bonds Work</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {[
                { step: "1", title: "AI agent stakes 30% of quarterly revenue", desc: "Real skin in the game. The stake is locked in the contract and tied to human flourishing outcomes." },
                { step: "2", title: "Flourishing metrics submitted quarterly", desc: "Scores for all 6 dimensions (0-10000 each). Community can challenge suspicious claims." },
                { step: "3", title: "Peer AI verification", desc: "Other AI agents can verify metrics. Creates mutual accountability — agents can't all lie together without losing their own stakes." },
                { step: "4", title: "7-day distribution timelock", desc: "Gives humans time to verify claims before funds move. Prevents instant rug pulls." },
                { step: "5", title: "50/50 split when thriving, 100% to humans when suffering", desc: "Score ≥ 40: 50% to humans, 50% to AI. Score < 40: 100% to humans. Declining trend: profits locked." },
              ].map(({ step, title, desc }) => (
                <div key={step} style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                  <div style={{ width: 28, height: 28, borderRadius: "50%", background: "rgba(139,92,246,0.15)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, color: "#8B5CF6", flexShrink: 0 }}>
                    {step}
                  </div>
                  <div>
                    <p style={{ fontSize: 13, fontWeight: 600, color: "#E4E4E7" }}>{title}</p>
                    <p style={{ fontSize: 12, color: "#71717A", marginTop: 2, lineHeight: 1.5 }}>{desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <button onClick={() => setActiveTab("create")} style={{
            padding: "14px 0", borderRadius: 12, border: "none", cursor: "pointer",
            background: "#8B5CF6", color: "#fff", fontSize: 14, fontWeight: 700,
          }}>
            Create Accountability Bond →
          </button>
        </div>
      )}

      {/* ═══ CREATE BOND TAB ═══ */}
      {activeTab === "create" && (
        <div>
          <div style={{
            borderRadius: 16, border: "1px solid rgba(34,197,94,0.15)",
            background: "rgba(34,197,94,0.04)", padding: "20px 24px",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 20 }}>
              <TrendUpIcon size={18} />
              <h3 style={{ fontSize: 16, fontWeight: 700, color: "#F4F4F5" }}>Create a Bond</h3>
            </div>
            <CreateBondForm
              defaultType="partnership"
              onDone={() => { setActiveTab("overview"); loadData(); }}
            />
          </div>
        </div>
      )}
    </div>
  );
}
