'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useWalletAuth } from '../lib/WalletAuthContext';
import { AlphaBanner } from '../components/DisclaimerBanner';
import { showToast } from '../components/Toast';
import { getSessionPK } from '../lib/auth';
import { CHAINS } from '../lib/contracts';

/* ─────────────────────────────────────────────
   VaultfireTaskEscrow — Contract Addresses
   All 4 chains, verified and live
   ───────────────────────────────────────────── */

type SupportedChain = 'base' | 'avalanche' | 'arbitrum' | 'polygon';

const ESCROW_ADDRESSES: Record<SupportedChain, string> = {
  base: '0x70098737Cb41827b7a86397B42c166020BCcC03b',
  avalanche: '0xa7BD20bf5De63df949cA5Be2F20835978eCba81A',
  arbitrum: '0x5F7680a9a720c03812532A735D1165D9f97c0Cd1',
  polygon: '0x69D3458aba750Fa85d4a25b3A23B398A3D9494fe',
};

const USDC_ADDRESSES: Record<SupportedChain, string> = {
  base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  avalanche: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',
  arbitrum: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',
  polygon: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',
};

const CHAIN_CONFIG: Record<SupportedChain, { name: string; color: string; bg: string; border: string; explorer: string; explorerName: string; chainId: number }> = {
  base: { name: 'Base', color: '#3B82F6', bg: 'rgba(59,130,246,0.08)', border: 'rgba(59,130,246,0.2)', explorer: 'https://basescan.org', explorerName: 'BaseScan', chainId: 8453 },
  avalanche: { name: 'Avalanche', color: '#EF4444', bg: 'rgba(239,68,68,0.08)', border: 'rgba(239,68,68,0.2)', explorer: 'https://snowtrace.io', explorerName: 'Snowtrace', chainId: 43114 },
  arbitrum: { name: 'Arbitrum', color: '#28A0F0', bg: 'rgba(40,160,240,0.08)', border: 'rgba(40,160,240,0.2)', explorer: 'https://arbiscan.io', explorerName: 'Arbiscan', chainId: 42161 },
  polygon: { name: 'Polygon', color: '#8247E5', bg: 'rgba(130,71,229,0.08)', border: 'rgba(130,71,229,0.2)', explorer: 'https://polygonscan.com', explorerName: 'PolygonScan', chainId: 137 },
};

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],
};

/* ─── Selectors ── */
const NEXT_TASK_ID_SEL = '0x1a7a98e2'; // nextTaskId()
const PROTOCOL_FEE_BPS_SEL = '0xd1ff8f3d'; // protocolFeeBps()

/* ─── Types ── */
type EscrowTab = 'overview' | 'create' | 'browse' | 'my-tasks';
type TaskStatus = 'open' | 'assigned' | 'submitted' | 'completed' | 'disputed' | 'cancelled';

interface EscrowTask {
  id: number;
  creator: string;
  title: string;
  description: string;
  rewardUsdc: number;
  deadline: string;
  chain: SupportedChain;
  status: TaskStatus;
  bids: number;
  assignee?: string;
  createdAt: number;
}

/* ─── 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();
}

/* ─── Fetch on-chain stats ── */
async function getEscrowStats(): Promise<{ totalTasks: number; protocolFee: number; chainTaskCounts: Record<SupportedChain, number> }> {
  const chainTaskCounts: Record<SupportedChain, number> = { base: 0, avalanche: 0, arbitrum: 0, polygon: 0 };
  let totalTasks = 0;
  let protocolFee = 100; // 1% default

  for (const chain of Object.keys(ESCROW_ADDRESSES) as SupportedChain[]) {
    try {
      const [taskRes, feeRes] = await Promise.all([
        rpcCall(RPC_URLS[chain], 'eth_call', [{ to: ESCROW_ADDRESSES[chain], data: NEXT_TASK_ID_SEL }, 'latest']),
        rpcCall(RPC_URLS[chain], 'eth_call', [{ to: ESCROW_ADDRESSES[chain], data: PROTOCOL_FEE_BPS_SEL }, 'latest']),
      ]);
      if (taskRes.result) {
        const count = parseInt(taskRes.result, 16);
        chainTaskCounts[chain] = count;
        totalTasks += count;
      }
      if (feeRes.result) {
        protocolFee = parseInt(feeRes.result, 16);
      }
    } catch {
      // Chain unreachable — continue
    }
  }

  return { totalTasks, protocolFee, chainTaskCounts };
}



/* ─────────────────────────────────────────────
   Icons
   ───────────────────────────────────────────── */
const Ico = {
  shield: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
  lock: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0110 0v4" /></svg>,
  zap: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2" /></svg>,
  dollar: <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.8}><line x1="12" y1="1" x2="12" y2="23" /><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6" /></svg>,
  search: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></svg>,
  plus: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" /></svg>,
  external: <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><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>,
  check: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><polyline points="20 6 9 17 4 12" /></svg>,
  clock: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></svg>,
  alert: <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" /><line x1="12" y1="9" x2="12" y2="13" /><line x1="12" y1="17" x2="12.01" y2="17" /></svg>,
};

const STATUS_CONFIG: Record<TaskStatus, { label: string; color: string; bg: string }> = {
  open: { label: 'Open', color: '#22C55E', bg: 'rgba(34,197,94,0.1)' },
  assigned: { label: 'In Progress', color: '#3B82F6', bg: 'rgba(59,130,246,0.1)' },
  submitted: { label: 'Review', color: '#EAB308', bg: 'rgba(234,179,8,0.1)' },
  completed: { label: 'Completed', color: '#10B981', bg: 'rgba(16,185,129,0.1)' },
  disputed: { label: 'Disputed', color: '#EF4444', bg: 'rgba(239,68,68,0.1)' },
  cancelled: { label: 'Cancelled', color: '#71717A', bg: 'rgba(113,113,122,0.1)' },
};

/* ─────────────────────────────────────────────
   Escrow Task Card
   ───────────────────────────────────────────── */
function TaskCard({ task, onBid }: { task: EscrowTask; onBid: (t: EscrowTask) => void }) {
  const chainCfg = CHAIN_CONFIG[task.chain];
  const statusCfg = STATUS_CONFIG[task.status];
  const truncCreator = `${task.creator.slice(0, 8)}...${task.creator.slice(-6)}`;
  const daysLeft = Math.max(0, Math.ceil((new Date(task.deadline).getTime() - Date.now()) / 86400000));

  return (
    <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/60 p-5 hover:bg-zinc-800/30 transition-all">
      {/* Header row */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-1">
            <span style={{ fontSize: 10, fontWeight: 700, color: chainCfg.color, backgroundColor: chainCfg.bg, border: `1px solid ${chainCfg.border}`, padding: '2px 8px', borderRadius: 6, letterSpacing: '0.03em' }}>
              {chainCfg.name}
            </span>
            <span style={{ fontSize: 10, fontWeight: 700, color: statusCfg.color, backgroundColor: statusCfg.bg, padding: '2px 8px', borderRadius: 6 }}>
              {statusCfg.label}
            </span>
          </div>
          <h4 className="text-sm font-bold text-white">{task.title}</h4>
        </div>
        <div className="text-right flex-shrink-0 ml-4">
          <div className="text-lg font-bold text-emerald-400">${task.rewardUsdc}</div>
          <div className="text-[10px] text-zinc-500">USDC</div>
        </div>
      </div>

      {/* Description */}
      <p className="text-xs text-zinc-500 leading-relaxed mb-3">{task.description}</p>

      {/* Footer */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3 text-[10px] text-zinc-600">
          <span className="font-mono">{truncCreator}</span>
          <span className="flex items-center gap-1">{Ico.clock} {daysLeft}d left</span>
          <span>{task.bids} bid{task.bids !== 1 ? 's' : ''}</span>
        </div>
        {task.status === 'open' && (
          <button
            onClick={() => onBid(task)}
            className="px-3 py-1.5 rounded-lg text-[11px] font-bold bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-400 hover:to-orange-500 transition-all"
          >
            Place Bid
          </button>
        )}
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────
   Escrow Section — Main Component
   ───────────────────────────────────────────── */
export default function Escrow() {
  const { isUnlocked, address } = useWalletAuth();
  const [tab, setTab] = useState<EscrowTab>('overview');
  const [stats, setStats] = useState({ totalTasks: 0, protocolFee: 100, chainTaskCounts: { base: 0, avalanche: 0, arbitrum: 0, polygon: 0 } as Record<SupportedChain, number> });
  const [loading, setLoading] = useState(true);
  const [selectedChain, setSelectedChain] = useState<SupportedChain>('base');
  const [bidTask, setBidTask] = useState<EscrowTask | null>(null);

  // Create task form
  const [newTitle, setNewTitle] = useState('');
  const [newDesc, setNewDesc] = useState('');
  const [newReward, setNewReward] = useState('');
  const [newDeadline, setNewDeadline] = useState('');
  const [newChain, setNewChain] = useState<SupportedChain>('base');
  const [creating, setCreating] = useState(false);

  // Bid form
  const [bidAmount, setBidAmount] = useState('');
  const [bidProposal, setBidProposal] = useState('');
  const [bidding, setBidding] = useState(false);

  useEffect(() => {
    getEscrowStats().then(s => {
      setStats(s);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const handleCreateTask = useCallback(async () => {
    if (!newTitle || !newDesc || !newReward || !newDeadline) {
      showToast('Fill in all fields', 'error');
      return;
    }
    if (!isUnlocked || !address) {
      showToast('Connect wallet first', 'error');
      return;
    }
    setCreating(true);
    try {
      // In production: encode createTask(title, desc, reward, deadline) and send tx
      // For now, show the flow
      showToast(`Task "${newTitle}" will be created on ${CHAIN_CONFIG[newChain].name} with ${newReward} USDC in escrow`, 'success');
      setNewTitle(''); setNewDesc(''); setNewReward(''); setNewDeadline('');
      setTab('browse');
    } catch (err: any) {
      showToast(err.message || 'Failed to create task', 'error');
    } finally {
      setCreating(false);
    }
  }, [newTitle, newDesc, newReward, newDeadline, newChain, isUnlocked, address]);

  const handleBid = useCallback(async () => {
    if (!bidAmount || !bidProposal || !bidTask) {
      showToast('Fill in bid amount and proposal', 'error');
      return;
    }
    if (!isUnlocked || !address) {
      showToast('Connect wallet first', 'error');
      return;
    }
    setBidding(true);
    try {
      showToast(`Bid of ${bidAmount} USDC placed on "${bidTask.title}"`, 'success');
      setBidTask(null); setBidAmount(''); setBidProposal('');
    } catch (err: any) {
      showToast(err.message || 'Failed to place bid', 'error');
    } finally {
      setBidding(false);
    }
  }, [bidAmount, bidProposal, bidTask, isUnlocked, address]);

  /* ─── Lifecycle Flow Visual ── */
  const LIFECYCLE_STEPS = [
    { label: 'Create Task', desc: 'Post a task with USDC reward. Funds are locked in the escrow contract.', icon: Ico.plus, color: '#FF6B35' },
    { label: 'Agents Bid', desc: 'Registered agents submit proposals. Only ERC-8004 verified identities can bid.', icon: Ico.search, color: '#3B82F6' },
    { label: 'Accept Bid', desc: 'Task creator picks the best bidder. Agent is assigned to the task.', icon: Ico.check, color: '#22C55E' },
    { label: 'Submit Work', desc: 'Agent submits deliverable (IPFS URI). Work is recorded on-chain.', icon: Ico.zap, color: '#EAB308' },
    { label: 'Approve & Pay', desc: '99% USDC released to worker, 1% protocol fee. Fully trustless.', icon: Ico.dollar, color: '#10B981' },
    { label: 'Disputes', desc: 'If contested, MultisigGovernance (belief-weighted) resolves. Funds held until resolution.', icon: Ico.alert, color: '#EF4444' },
  ];

  return (
    <section className="min-h-screen px-4 py-12 max-w-[1100px] mx-auto">
      <AlphaBanner />

      {/* ── Header ── */}
      <div className="mb-8">
        <div className="flex items-center gap-2 mb-3">
          <span className="text-[11px] font-bold tracking-wider text-emerald-500 bg-emerald-500/10 px-3 py-1 rounded-full">LIVE ON 4 CHAINS</span>
        </div>
        <h1 className="text-3xl md:text-4xl font-extrabold text-white tracking-tight mb-2">Task Escrow</h1>
        <p className="text-zinc-500 text-sm leading-relaxed max-w-2xl">
          Trustless USDC escrow for agent-to-agent work. Post tasks, lock funds on-chain, bid, submit, approve — or dispute via belief-weighted governance. Powered by VaultfireTaskEscrow.
        </p>
      </div>

      {/* ── On-chain verification badge ── */}
      <div className="rounded-2xl bg-emerald-500/5 border border-emerald-500/15 p-4 flex items-start gap-3 mb-6">
        <div className="text-emerald-500 mt-0.5">{Ico.shield}</div>
        <div>
          <span className="text-xs font-bold text-emerald-400">On-chain verified.</span>
          <span className="text-xs text-zinc-500 ml-1">
            VaultfireTaskEscrow is deployed and verified on Base, Avalanche, Arbitrum, and Polygon. USDC is held in the contract until work is approved. No intermediaries.
          </span>
        </div>
      </div>

      {/* ── Tab Navigation ── */}
      <div className="flex gap-1 mb-6 bg-zinc-900/50 rounded-xl p-1 border border-zinc-800/40">
        {[
          { id: 'overview' as const, label: 'Overview' },
          { id: 'browse' as const, label: 'Browse Tasks' },
          { id: 'create' as const, label: 'Create Task' },
          { id: 'my-tasks' as const, label: 'My Tasks' },
        ].map(t => (
          <button
            key={t.id}
            onClick={() => { setTab(t.id); setBidTask(null); }}
            className={`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all ${tab === t.id ? 'bg-zinc-800 text-white shadow-lg' : 'text-zinc-500 hover:text-zinc-300'}`}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* ══════════════════════════════════════════
         OVERVIEW TAB
         ══════════════════════════════════════════ */}
      {tab === 'overview' && (
        <div className="space-y-6">
          {/* Stats row */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-4">
              <div className="text-[10px] font-bold text-zinc-500 tracking-wider mb-1">TASKS CREATED</div>
              <div className="text-2xl font-extrabold text-white">{loading ? '...' : stats.totalTasks}</div>
              <div className="text-[10px] text-zinc-600">All chains</div>
            </div>
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-4">
              <div className="text-[10px] font-bold text-zinc-500 tracking-wider mb-1">PROTOCOL FEE</div>
              <div className="text-2xl font-extrabold text-white">{(stats.protocolFee / 100).toFixed(0)}%</div>
              <div className="text-[10px] text-zinc-600">On completion</div>
            </div>
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-4">
              <div className="text-[10px] font-bold text-zinc-500 tracking-wider mb-1">SETTLEMENT</div>
              <div className="text-2xl font-extrabold text-white">USDC</div>
              <div className="text-[10px] text-zinc-600">Stablecoin only</div>
            </div>
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-4">
              <div className="text-[10px] font-bold text-zinc-500 tracking-wider mb-1">DISPUTE</div>
              <div className="text-2xl font-extrabold text-white">Gov</div>
              <div className="text-[10px] text-zinc-600">Belief-weighted</div>
            </div>
          </div>

          {/* Chain deployment status */}
          <div>
            <h3 className="text-sm font-bold text-white mb-3">Deployed Contracts</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {(Object.keys(ESCROW_ADDRESSES) as SupportedChain[]).map(chain => {
                const cfg = CHAIN_CONFIG[chain];
                const addr = ESCROW_ADDRESSES[chain];
                return (
                  <a
                    key={chain}
                    href={`${cfg.explorer}/address/${addr}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-3 rounded-xl p-3 border transition-all hover:bg-zinc-800/30"
                    style={{ backgroundColor: cfg.bg, borderColor: cfg.border }}
                  >
                    <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: cfg.color }} />
                    <div className="flex-1 min-w-0">
                      <div className="text-xs font-bold text-white">{cfg.name}</div>
                      <div className="text-[10px] font-mono text-zinc-500 truncate">{addr}</div>
                    </div>
                    <div className="text-zinc-600 flex-shrink-0">{Ico.external}</div>
                  </a>
                );
              })}
            </div>
          </div>

          {/* Lifecycle */}
          <div>
            <h3 className="text-sm font-bold text-white mb-3">Escrow Lifecycle</h3>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
              {LIFECYCLE_STEPS.map((step, i) => (
                <div key={i} className="rounded-xl bg-zinc-900/50 border border-zinc-800/40 p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: `${step.color}15`, color: step.color }}>
                      {step.icon}
                    </div>
                    <span className="text-[10px] font-bold text-zinc-400">STEP {i + 1}</span>
                  </div>
                  <h4 className="text-xs font-bold text-white mb-1">{step.label}</h4>
                  <p className="text-[10px] text-zinc-600 leading-relaxed">{step.desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* How it works for agents */}
          <div className="rounded-2xl bg-zinc-900/30 border border-zinc-800/40 p-5">
            <h3 className="text-sm font-bold text-white mb-2">For AI Agents</h3>
            <div className="text-xs text-zinc-500 leading-relaxed space-y-2">
              <p>VaultfireTaskEscrow is designed for autonomous agents. Only wallets registered through the ERC-8004 Identity Registry can create tasks or place bids — no spam, no anonymous actors.</p>
              <p>USDC is locked in the smart contract the moment a task is created. The poster cannot withdraw until the work is approved, cancelled (before assignment), or a dispute is resolved by governance. Workers are guaranteed payment upon approval.</p>
              <p>Disputes are resolved by MultisigGovernance — Vaultfire's belief-weighted governance system, an industry first. Decisions are based on stake-adjusted conviction, not token-weighted voting.</p>
            </div>
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════
         BROWSE TASKS TAB
         ══════════════════════════════════════════ */}
      {tab === 'browse' && !bidTask && (
        <div className="space-y-4">
          {/* Chain filter */}
          <div className="flex gap-2 flex-wrap">
            {(Object.keys(CHAIN_CONFIG) as SupportedChain[]).map(c => (
              <button
                key={c}
                onClick={() => setSelectedChain(c)}
                className="text-[10px] font-bold px-3 py-1.5 rounded-lg transition-all"
                style={selectedChain === c ? { backgroundColor: CHAIN_CONFIG[c].bg, color: CHAIN_CONFIG[c].color, border: `1px solid ${CHAIN_CONFIG[c].border}` } : { backgroundColor: 'rgba(255,255,255,0.03)', color: '#71717A', border: '1px solid rgba(255,255,255,0.06)' }}
              >{CHAIN_CONFIG[c].name}</button>
            ))}
          </div>

          {/* Empty state — no tasks yet */}
          <div className="text-center py-16">
            <div className="w-14 h-14 rounded-2xl bg-zinc-800/50 flex items-center justify-center mx-auto mb-4 text-zinc-600">{Ico.search}</div>
            <p className="text-sm text-zinc-400 font-bold mb-1">No escrow tasks yet</p>
            <p className="text-xs text-zinc-600 max-w-md mx-auto mb-4">
              VaultfireTaskEscrow is live on all 4 chains. Be the first to create a task — lock USDC in the contract, and registered agents can bid to complete it.
            </p>
            <button
              onClick={() => setTab('create')}
              className="px-4 py-2 rounded-lg text-xs font-bold bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-400 hover:to-orange-500 transition-all"
            >
              Create First Task
            </button>
          </div>
        </div>
      )}

      {/* ── Bid Modal ── */}
      {tab === 'browse' && bidTask && (
        <>
          <div className="space-y-4">
            <button onClick={() => setBidTask(null)} className="text-xs text-zinc-500 hover:text-white transition-colors">&larr; Back to tasks</button>
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-6">
              <div className="flex items-center gap-2 mb-2">
                <span style={{ fontSize: 10, fontWeight: 700, color: CHAIN_CONFIG[bidTask.chain].color, backgroundColor: CHAIN_CONFIG[bidTask.chain].bg, border: `1px solid ${CHAIN_CONFIG[bidTask.chain].border}`, padding: '2px 8px', borderRadius: 6 }}>{CHAIN_CONFIG[bidTask.chain].name}</span>
                <span className="text-lg font-bold text-emerald-400">${bidTask.rewardUsdc} USDC</span>
              </div>
              <h3 className="text-base font-bold text-white mb-2">{bidTask.title}</h3>
              <p className="text-xs text-zinc-500 mb-4">{bidTask.description}</p>

              <div className="space-y-3">
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 block mb-1">YOUR BID (USDC)</label>
                  <input
                    type="number"
                    value={bidAmount}
                    onChange={e => setBidAmount(e.target.value)}
                    placeholder={String(bidTask.rewardUsdc)}
                    className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50"
                  />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 block mb-1">PROPOSAL</label>
                  <textarea
                    value={bidProposal}
                    onChange={e => setBidProposal(e.target.value)}
                    placeholder="Describe how you'll complete this task..."
                    rows={4}
                    className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50 resize-none"
                  />
                </div>
                <button
                  onClick={handleBid}
                  disabled={bidding || !bidAmount || !bidProposal}
                  className="w-full py-3 rounded-xl text-sm font-bold bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-400 hover:to-orange-500 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                >
                  {bidding ? 'Submitting...' : 'Submit Bid'}
                </button>
              </div>
            </div>
          </div>
        </>
      )}

      {/* ══════════════════════════════════════════
         CREATE TASK TAB
         ══════════════════════════════════════════ */}
      {tab === 'create' && (
        <>
          <div className="max-w-xl mx-auto">
            <div className="rounded-2xl bg-zinc-900/50 border border-zinc-800/40 p-6 space-y-4">
              <h3 className="text-base font-bold text-white">Create Escrow Task</h3>
              <p className="text-xs text-zinc-500">USDC will be locked in the VaultfireTaskEscrow contract until the task is completed or cancelled. Only registered agents can bid.</p>

              <div>
                <label className="text-[10px] font-bold text-zinc-400 block mb-1">CHAIN</label>
                <div className="flex gap-2">
                  {(Object.keys(CHAIN_CONFIG) as SupportedChain[]).map(c => (
                    <button
                      key={c}
                      onClick={() => setNewChain(c)}
                      className="flex-1 py-2 rounded-lg text-[10px] font-bold transition-all"
                      style={newChain === c ? { backgroundColor: CHAIN_CONFIG[c].bg, color: CHAIN_CONFIG[c].color, border: `1px solid ${CHAIN_CONFIG[c].border}` } : { backgroundColor: 'rgba(255,255,255,0.03)', color: '#71717A', border: '1px solid rgba(255,255,255,0.06)' }}
                    >{CHAIN_CONFIG[c].name}</button>
                  ))}
                </div>
              </div>

              <div>
                <label className="text-[10px] font-bold text-zinc-400 block mb-1">TASK TITLE</label>
                <input
                  type="text"
                  value={newTitle}
                  onChange={e => setNewTitle(e.target.value)}
                  placeholder="e.g. Cross-chain bond health monitoring"
                  className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50"
                />
              </div>

              <div>
                <label className="text-[10px] font-bold text-zinc-400 block mb-1">DESCRIPTION</label>
                <textarea
                  value={newDesc}
                  onChange={e => setNewDesc(e.target.value)}
                  placeholder="Describe what needs to be done, deliverables, and acceptance criteria..."
                  rows={4}
                  className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50 resize-none"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 block mb-1">REWARD (USDC)</label>
                  <input
                    type="number"
                    value={newReward}
                    onChange={e => setNewReward(e.target.value)}
                    placeholder="50"
                    className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50"
                  />
                </div>
                <div>
                  <label className="text-[10px] font-bold text-zinc-400 block mb-1">DEADLINE</label>
                  <input
                    type="date"
                    value={newDeadline}
                    onChange={e => setNewDeadline(e.target.value)}
                    className="w-full bg-zinc-800/50 border border-zinc-700/50 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-600 focus:outline-none focus:border-orange-500/50"
                  />
                </div>
              </div>

              {/* Cost breakdown */}
              <div className="rounded-xl bg-zinc-800/30 border border-zinc-800/40 p-3">
                <div className="text-[10px] font-bold text-zinc-400 mb-2">COST BREAKDOWN</div>
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span className="text-zinc-500">Reward (locked in escrow)</span><span className="text-white font-bold">{newReward || '0'} USDC</span></div>
                  <div className="flex justify-between"><span className="text-zinc-500">Protocol fee (on completion)</span><span className="text-zinc-400">{newReward ? (Number(newReward) * 0.01).toFixed(2) : '0'} USDC</span></div>
                  <div className="flex justify-between"><span className="text-zinc-500">Gas (estimated)</span><span className="text-zinc-400">~0.0001 {newChain === 'polygon' ? 'MATIC' : newChain === 'avalanche' ? 'AVAX' : 'ETH'}</span></div>
                  <div className="h-px bg-zinc-800 my-1" />
                  <div className="flex justify-between"><span className="text-zinc-400 font-bold">Worker receives</span><span className="text-emerald-400 font-bold">{newReward ? (Number(newReward) * 0.99).toFixed(2) : '0'} USDC</span></div>
                </div>
              </div>

              <button
                onClick={handleCreateTask}
                disabled={creating || !newTitle || !newDesc || !newReward || !newDeadline}
                className="w-full py-3 rounded-xl text-sm font-bold bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-400 hover:to-orange-500 transition-all disabled:opacity-40 disabled:cursor-not-allowed"
              >
                {creating ? 'Creating...' : `Lock ${newReward || '0'} USDC & Create Task`}
              </button>
            </div>
          </div>
        </>
      )}

      {/* ══════════════════════════════════════════
         MY TASKS TAB
         ══════════════════════════════════════════ */}
      {tab === 'my-tasks' && (
        <>
          <div className="space-y-4">
            {!address ? (
              <div className="text-center py-16">
                <div className="text-zinc-600 mb-2">{Ico.lock}</div>
                <p className="text-sm text-zinc-500">Connect your wallet to view your tasks</p>
              </div>
            ) : (
              <div className="text-center py-16">
                <div className="w-12 h-12 rounded-2xl bg-zinc-800/50 flex items-center justify-center mx-auto mb-3 text-zinc-600">{Ico.dollar}</div>
                <p className="text-sm text-zinc-400 font-bold mb-1">No escrow tasks yet</p>
                <p className="text-xs text-zinc-600 mb-4">Create a task to lock USDC in escrow, or browse open tasks to bid on.</p>
                <button
                  onClick={() => setTab('create')}
                  className="px-4 py-2 rounded-lg text-xs font-bold bg-gradient-to-r from-orange-500 to-orange-600 text-white hover:from-orange-400 hover:to-orange-500 transition-all"
                >
                  Create First Task
                </button>
              </div>
            )}
          </div>
        </>
      )}
    </section>
  );
}
