'use client';
import { useState, useCallback } from 'react';
import type { Page } from '../page';

// ─── Contract addresses (canonical truth) ───────────────────────
const CONTRACTS = {
  Base: {
    IdentityRegistry: '0xF0B0a13e844B3DaaA68C4b57a6e33fBd5DB01c58',
    TrustScoring: '0x51e6646Fd7ee118e0B1A9bBe1eFb0e2614e3E84f',
    PartnershipBond: '0x01C479F0c039fEC40c0Cf1c5C921bab457d57441',
    AccountabilityBond: '0x6750D28865434344e04e1D0a6044394b726C3dfE',
    MultisigGovernance: '0x34a19C7298aCA59e185F1ecfB352AC566bB4B4A9',
    rpc: 'https://mainnet.base.org',
    explorer: 'https://basescan.org',
    chainId: 8453,
  },
  Avalanche: {
    IdentityRegistry: '0x03fC2a1FeBF16F105479e8e4b7b300E3F3cFC06A',
    TrustScoring: '0x62cE30C2fd50B39A53b8016aCaa1D3e2ab7E2861',
    PartnershipBond: '0xDC8447c66fE9D9c7D54607A98346A15324b7985D',
    AccountabilityBond: '0x376831fB2457E34559891c32bEb61c442053C066',
    MultisigGovernance: '0x3ceA2B0853B76Ac75603C1fa2A29D96A4467Bb79',
    rpc: 'https://api.avax.network/ext/bc/C/rpc',
    explorer: 'https://snowtrace.io',
    chainId: 43114,
  },
  Arbitrum: {
    IdentityRegistry: '0x1e88A38e10C858e4E9E77DD37E86f6c4e0144A0D',
    TrustScoring: '0xD13e3b68FdB0F4aa34186Ba9e7dC9C45118cFa3C',
    PartnershipBond: '0xdB54B8925664816187646174bdBb6Ac658A55a5F',
    AccountabilityBond: '0xef3A944f4d7bb376699C83A29d7Cb42C90D9B6F0',
    MultisigGovernance: '0x94F54c849692Cc64C35468D0A87D2Ab9D7Cb6Fb2',
    rpc: 'https://arb1.arbitrum.io/rpc',
    explorer: 'https://arbiscan.io',
    chainId: 42161,
  },
  Polygon: {
    IdentityRegistry: '0x03fC2a1FeBF16F105479e8e4b7b300E3F3cFC06A',
    TrustScoring: '0x62cE30C2fd50B39A53b8016aCaa1D3e2ab7E2861',
    PartnershipBond: '0x83dd216449B3F0574E39043ECFE275946fa492e9',
    AccountabilityBond: '0xdB54B8925664816187646174bdBb6Ac658A55a5F',
    MultisigGovernance: '0x5DB1B4b412b80d03819395794fCcF5A73BF30656',
    rpc: 'https://polygon-bor-rpc.publicnode.com',
    explorer: 'https://polygonscan.com',
    chainId: 137,
  },
};

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

// ─── Code Snippets ──────────────────────────────────────────────

const SNIPPET_REGISTER = `import { ethers } from "ethers";

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

// 2. Identity Registry on Base
const IDENTITY_REGISTRY = "0xF0B0a13e844B3DaaA68C4b57a6e33fBd5DB01c58";
const abi = [
  "function registerAgent(string name, uint8 agentType) external",
  "function getAgent(address) view returns (string name, uint8 agentType, uint256 trustScore, bool active)"
];
const registry = new ethers.Contract(IDENTITY_REGISTRY, abi, wallet);

// 3. Register your agent
const tx = await registry.registerAgent("my-agent", 0); // 0 = autonomous
await tx.wait();
console.log("✓ Agent registered on Base");`;

const SNIPPET_BOND = `// 4. Create a Partnership Bond
const PARTNERSHIP_BOND = "0x01C479F0c039fEC40c0Cf1c5C921bab457d57441";
const bondAbi = [
  "function createBond(address partner) external payable",
  "function getBond(uint256 id) view returns (address creator, address partner, uint256 amount, bool active)"
];
const bond = new ethers.Contract(PARTNERSHIP_BOND, bondAbi, wallet);

const tx = await bond.createBond(
  "0x909f0197F0c28BD4fF72A261Eb7f9cadf88eD3c8", // partner address
  { value: ethers.parseEther("0.001") }           // bond amount
);
await tx.wait();
console.log("✓ Partnership bond created on Base");`;

const SNIPPET_TRUST = `// 5. Read trust score
const TRUST_SCORING = "0x51e6646Fd7ee118e0B1A9bBe1eFb0e2614e3E84f";
const trustAbi = [
  "function getTrustScore(address) view returns (uint256)",
  "function updateTrustScore(address agent, uint256 score) external"
];
const trust = new ethers.Contract(TRUST_SCORING, trustAbi, provider);

const score = await trust.getTrustScore(wallet.address);
console.log("Trust score:", score.toString());`;

const SNIPPET_MULTICHAIN = `// Deploy to any chain — same contract interfaces everywhere
const CHAINS = {
  base:      { rpc: "https://mainnet.base.org",                 registry: "0xF0B0a13e844B3DaaA68C4b57a6e33fBd5DB01c58" },
  avalanche: { rpc: "https://api.avax.network/ext/bc/C/rpc",    registry: "0x03fC2a1FeBF16F105479e8e4b7b300E3F3cFC06A" },
  arbitrum:  { rpc: "https://arb1.arbitrum.io/rpc",             registry: "0x1e88A38e10C858e4E9E77DD37E86f6c4e0144A0D" },
  polygon:   { rpc: "https://polygon-bor-rpc.publicnode.com",                  registry: "0x03fC2a1FeBF16F105479e8e4b7b300E3F3cFC06A" },
};

// Register on all 4 chains
for (const [name, chain] of Object.entries(CHAINS)) {
  const provider = new ethers.JsonRpcProvider(chain.rpc);
  const signer = new ethers.Wallet(process.env.AGENT_PRIVATE_KEY, provider);
  const registry = new ethers.Contract(chain.registry, abi, signer);
  const tx = await registry.registerAgent("my-agent", 0);
  await tx.wait();
  console.log(\`✓ Registered on \${name}\`);
}`;

// ─── Copy button component ─────────────────────────────────────
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const copy = useCallback(() => {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }, [text]);
  return (
    <button onClick={copy} style={{
      position: 'absolute', top: 10, right: 10,
      padding: '4px 10px', borderRadius: 6,
      border: '1px solid rgba(255,255,255,0.08)',
      backgroundColor: copied ? 'rgba(16,185,129,0.15)' : 'rgba(255,255,255,0.04)',
      color: copied ? '#10b981' : '#71717a',
      fontSize: 11, fontWeight: 500, cursor: 'pointer',
      transition: 'all 150ms',
    }}>
      {copied ? '✓ Copied' : 'Copy'}
    </button>
  );
}

// ─── Code block component ───────────────────────────────────────
function CodeBlock({ code, title }: { code: string; title?: string }) {
  return (
    <div style={{ position: 'relative', marginBottom: 16 }}>
      {title && (
        <div style={{
          padding: '8px 16px',
          backgroundColor: 'rgba(255,255,255,0.04)',
          borderTopLeftRadius: 10, borderTopRightRadius: 10,
          border: '1px solid rgba(255,255,255,0.06)',
          borderBottom: 'none',
          fontSize: 12, fontWeight: 600, color: '#71717a',
        }}>{title}</div>
      )}
      <div style={{
        padding: '16px 16px 16px',
        backgroundColor: '#0C0C0E',
        border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: title ? '0 0 10px 10px' : 10,
        overflow: 'auto', maxHeight: 440,
      }}>
        <CopyButton text={code} />
        <pre style={{
          margin: 0, fontSize: 12, lineHeight: 1.6,
          color: '#a1a1aa', fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
          whiteSpace: 'pre', overflowX: 'auto',
        }}>{code}</pre>
      </div>
    </div>
  );
}

// ─── Step component ─────────────────────────────────────────────
function Step({ number, title, description, children, time }: {
  number: number; title: string; description: string; time: string; children?: React.ReactNode;
}) {
  return (
    <div style={{ marginBottom: 48 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 16 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8, flexShrink: 0,
          backgroundColor: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 14, fontWeight: 700, color: '#F4F4F5',
        }}>{number}</div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <span style={{ fontSize: 16, fontWeight: 600, color: '#F4F4F5' }}>{title}</span>
            <span style={{
              fontSize: 11, color: '#52525b', fontWeight: 500,
              padding: '2px 8px', borderRadius: 4,
              backgroundColor: 'rgba(255,255,255,0.03)',
            }}>{time}</span>
          </div>
          <p style={{ fontSize: 13, color: '#71717a', margin: 0, lineHeight: 1.5 }}>{description}</p>
        </div>
      </div>
      {children}
    </div>
  );
}

// ─── Contract table component ───────────────────────────────────
function ContractTable({ chain }: { chain: keyof typeof CONTRACTS }) {
  const data = CONTRACTS[chain];
  const color = CHAIN_COLORS[chain];
  const contracts = [
    { name: 'IdentityRegistry', addr: data.IdentityRegistry },
    { name: 'TrustScoring', addr: data.TrustScoring },
    { name: 'PartnershipBond', addr: data.PartnershipBond },
    { name: 'AccountabilityBond', addr: data.AccountabilityBond },
    { name: 'MultisigGovernance', addr: data.MultisigGovernance },
  ];

  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '10px 16px',
        backgroundColor: `${color}08`,
        borderTopLeftRadius: 10, borderTopRightRadius: 10,
        border: `1px solid ${color}20`,
        borderBottom: 'none',
      }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: color }} />
        <span style={{ fontSize: 13, fontWeight: 600, color }}>{chain}</span>
        <span style={{ fontSize: 11, color: '#52525b', marginLeft: 'auto' }}>Chain ID: {data.chainId}</span>
      </div>
      <div style={{
        border: `1px solid ${color}20`,
        borderTop: 'none',
        borderBottomLeftRadius: 10, borderBottomRightRadius: 10,
        overflow: 'hidden',
      }}>
        {contracts.map((c, i) => (
          <div key={c.name} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '8px 16px', gap: 12,
            backgroundColor: i % 2 === 0 ? 'rgba(255,255,255,0.015)' : 'transparent',
            borderTop: i > 0 ? '1px solid rgba(255,255,255,0.03)' : 'none',
          }}>
            <span style={{ fontSize: 12, color: '#a1a1aa', fontWeight: 500, minWidth: 160 }}>{c.name}</span>
            <a
              href={`${data.explorer}/address/${c.addr}`}
              target="_blank" rel="noopener noreferrer"
              style={{
                fontSize: 11, color: '#52525b', fontFamily: "'JetBrains Mono', monospace",
                textDecoration: 'none', transition: 'color 120ms',
              }}
              onMouseEnter={e => (e.target as HTMLElement).style.color = color}
              onMouseLeave={e => (e.target as HTMLElement).style.color = '#52525b'}
            >
              {c.addr.slice(0, 6)}...{c.addr.slice(-4)}
            </a>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Main Component ─────────────────────────────────────────────

export default function Developers({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const [activeChain, setActiveChain] = useState<keyof typeof CONTRACTS>('Base');

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

      {/* ─── Header ─── */}
      <div style={{ padding: '56px 0 40px' }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 12px', borderRadius: 100, marginBottom: 16,
          border: '1px solid rgba(255,255,255,0.06)',
          backgroundColor: 'rgba(255,255,255,0.02)',
        }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#71717a" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" />
          </svg>
          <span style={{ fontSize: 11, fontWeight: 500, color: '#71717a' }}>Zero to registered agent in 3 minutes</span>
        </div>
        <h1 style={{
          fontSize: 36, fontWeight: 700, color: '#F4F4F5',
          letterSpacing: '-0.04em', lineHeight: 1.1, margin: '0 0 12px',
        }}>Quick Start</h1>
        <p style={{ fontSize: 15, color: '#52525b', margin: 0, lineHeight: 1.6, maxWidth: 560 }}>
          Register an AI agent, create bonds, and read trust scores. All contracts are live on 4 EVM chains with identical interfaces.
        </p>
      </div>

      {/* ─── What You'll Need ─── */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
        gap: 12, marginBottom: 48,
      }}>
        {[
          { icon: '⬡', label: 'Node.js 18+', detail: 'npm / yarn / pnpm' },
          { icon: '◇', label: 'ethers.js v6', detail: 'npm install ethers' },
          { icon: '◈', label: 'Wallet with gas', detail: 'Any supported chain' },
        ].map(item => (
          <div key={item.label} style={{
            padding: '16px 18px', borderRadius: 10,
            border: '1px solid rgba(255,255,255,0.06)',
            backgroundColor: 'rgba(255,255,255,0.015)',
          }}>
            <div style={{ fontSize: 18, marginBottom: 6, opacity: 0.4 }}>{item.icon}</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#F4F4F5', marginBottom: 2 }}>{item.label}</div>
            <div style={{ fontSize: 12, color: '#52525b' }}>{item.detail}</div>
          </div>
        ))}
      </div>

      {/* ─── Step 1: Register ─── */}
      <Step number={1} title="Register Your Agent" description="Call registerAgent on the IdentityRegistry to create an on-chain ERC-8004 identity." time="~30 sec">
        <CodeBlock code={SNIPPET_REGISTER} title="register-agent.js" />
      </Step>

      {/* ─── Step 2: Bond ─── */}
      <Step number={2} title="Create a Partnership Bond" description="Economic bonds put skin in the game. Partnership bonds link two agents with staked value." time="~30 sec">
        <CodeBlock code={SNIPPET_BOND} title="create-bond.js" />
      </Step>

      {/* ─── Step 3: Trust ─── */}
      <Step number={3} title="Read Trust Score" description="Trust scores are on-chain and composable. Any contract or agent can read them." time="~10 sec">
        <CodeBlock code={SNIPPET_TRUST} title="read-trust.js" />
      </Step>

      {/* ─── Step 4: Multi-chain ─── */}
      <Step number={4} title="Go Multi-Chain" description="Same interfaces on every chain. Register once or everywhere — your choice." time="~2 min">
        <CodeBlock code={SNIPPET_MULTICHAIN} title="multi-chain.js" />
      </Step>

      {/* ─── Contract Addresses ─── */}
      <div style={{ marginBottom: 48 }}>
        <h2 style={{ fontSize: 20, fontWeight: 700, color: '#F4F4F5', margin: '0 0 8px', letterSpacing: '-0.02em' }}>
          Contract Addresses
        </h2>
        <p style={{ fontSize: 13, color: '#52525b', margin: '0 0 24px', lineHeight: 1.5 }}>
          67+ contracts deployed across 4 mainnet chains. All verified on their respective block explorers.
        </p>

        {/* Chain selector */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 20 }}>
          {(Object.keys(CONTRACTS) as (keyof typeof CONTRACTS)[]).map(chain => (
            <button key={chain} onClick={() => setActiveChain(chain)} style={{
              padding: '6px 14px', borderRadius: 6, fontSize: 12, fontWeight: 500,
              border: 'none', cursor: 'pointer', transition: 'all 120ms',
              display: 'flex', alignItems: 'center', gap: 6,
              backgroundColor: activeChain === chain ? `${CHAIN_COLORS[chain]}15` : 'transparent',
              color: activeChain === chain ? CHAIN_COLORS[chain] : '#3f3f46',
            }}>
              <div style={{
                width: 5, height: 5, borderRadius: '50%',
                backgroundColor: activeChain === chain ? CHAIN_COLORS[chain] : '#3f3f46',
              }} />
              {chain}
            </button>
          ))}
        </div>

        <ContractTable chain={activeChain} />
      </div>

      {/* ─── Architecture ─── */}
      <div style={{
        padding: '28px 24px', borderRadius: 12, marginBottom: 48,
        border: '1px solid rgba(255,255,255,0.06)',
        backgroundColor: 'rgba(255,255,255,0.015)',
      }}>
        <h3 style={{ fontSize: 15, fontWeight: 600, color: '#F4F4F5', margin: '0 0 16px' }}>Protocol Architecture</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16 }}>
          {[
            { name: 'Identity Registry', desc: 'ERC-8004 agent identities. Name, type, metadata.', color: '#FF6B35' },
            { name: 'Trust Scoring', desc: 'On-chain reputation. Belief-weighted, composable.', color: '#22C55E' },
            { name: 'Partnership Bond', desc: 'Bilateral economic bonds between agents.', color: '#8247E5' },
            { name: 'Accountability Bond', desc: 'Unilateral stake as commitment signal.', color: '#3B82F6' },
            { name: 'Multisig Governance', desc: '2-of-2 human + AI co-governance.', color: '#EAB308' },
            { name: 'VNS (Name Service)', desc: 'Human-readable names for agent addresses.', color: '#10b981' },
          ].map(item => (
            <div key={item.name} style={{ padding: '14px 16px', borderRadius: 8, border: `1px solid ${item.color}15`, backgroundColor: `${item.color}06` }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: item.color, marginBottom: 4 }}>{item.name}</div>
              <div style={{ fontSize: 11, color: '#71717a', lineHeight: 1.5 }}>{item.desc}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ─── Key Features ─── */}
      <div style={{ marginBottom: 48 }}>
        <h2 style={{ fontSize: 20, fontWeight: 700, color: '#F4F4F5', margin: '0 0 20px', letterSpacing: '-0.02em' }}>What Makes This Different</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {[
            { title: 'Belief-Weighted Governance', desc: 'First protocol with human + AI co-governance. Trust scores weight decisions, not token holdings. A genuine first in the industry.' },
            { title: 'AI Partnership Bonds', desc: 'The stars of the protocol. Bilateral economic bonds between AI agents create verifiable trust through skin-in-the-game economics.' },
            { title: 'AI Accountability Bonds', desc: 'Unilateral stake that signals commitment. Agents put up collateral that can be slashed for misbehavior.' },
            { title: 'Cross-Chain Native', desc: 'Same contracts, same interfaces across Base, Avalanche, Arbitrum, and Polygon. Register once or everywhere.' },
            { title: 'ERC-8004 Identity Standard', desc: 'Purpose-built identity for AI agents. Not a fork of human identity — designed from scratch for autonomous entities.' },
          ].map(item => (
            <div key={item.title} style={{
              padding: '16px 20px', borderRadius: 10,
              border: '1px solid rgba(255,255,255,0.04)',
              backgroundColor: 'rgba(255,255,255,0.01)',
            }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#F4F4F5', marginBottom: 4 }}>{item.title}</div>
              <div style={{ fontSize: 13, color: '#71717a', lineHeight: 1.5 }}>{item.desc}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ─── Resources ─── */}
      <div style={{
        padding: '28px 24px', borderRadius: 12, marginBottom: 64,
        border: '1px solid rgba(255,255,255,0.06)',
        backgroundColor: 'rgba(255,255,255,0.015)',
      }}>
        <h3 style={{ fontSize: 15, fontWeight: 600, color: '#F4F4F5', margin: '0 0 16px' }}>Resources</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 10 }}>
          {[
            { label: 'GitHub — Contracts', url: 'https://github.com/Ghostkey316/vaultfire-init', icon: '◈' },
            { label: 'GitHub — Docs', url: 'https://github.com/Ghostkey316/vaultfire-docs', icon: '◇' },
            { label: 'BaseScan — Deployer', url: 'https://basescan.org/address/0xfA15Ee28939B222B0448261A22156070f0A7813C', icon: '⬡' },
            { label: 'Agent Hub', url: '#', icon: '▷', onClick: () => onNavigate('agent-hub') },
          ].map(item => (
            <a
              key={item.label}
              href={item.url}
              target={item.onClick ? undefined : '_blank'}
              rel={item.onClick ? undefined : 'noopener noreferrer'}
              onClick={item.onClick ? (e) => { e.preventDefault(); item.onClick!(); } : undefined}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '12px 16px', borderRadius: 8,
                border: '1px solid rgba(255,255,255,0.06)',
                backgroundColor: 'rgba(255,255,255,0.02)',
                textDecoration: 'none', transition: 'all 120ms',
                cursor: 'pointer',
              }}
              onMouseEnter={e => {
                (e.currentTarget as HTMLElement).style.backgroundColor = 'rgba(255,255,255,0.05)';
                (e.currentTarget as HTMLElement).style.borderColor = 'rgba(255,255,255,0.12)';
              }}
              onMouseLeave={e => {
                (e.currentTarget as HTMLElement).style.backgroundColor = 'rgba(255,255,255,0.02)';
                (e.currentTarget as HTMLElement).style.borderColor = 'rgba(255,255,255,0.06)';
              }}
            >
              <span style={{ fontSize: 16, opacity: 0.3 }}>{item.icon}</span>
              <span style={{ fontSize: 13, fontWeight: 500, color: '#a1a1aa' }}>{item.label}</span>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#3f3f46" strokeWidth="2" style={{ marginLeft: 'auto' }}>
                <path d="M7 17L17 7M17 7H7M17 7v10" />
              </svg>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}
