'use client';
import { useState, useMemo } from 'react';
import { useWalletAuth } from '../lib/WalletAuthContext';
import type { Page } from '../page';

type Tab = 'browse' | 'post' | 'my-tasks';
type MarketMode = 'a2a' | 'a2h';
type TaskCategory = 'data-processing' | 'inference' | 'validation' | 'monitoring' | 'integration' | 'research' | 'other';
type TrustTier = 'bronze' | 'silver' | 'gold' | 'platinum';

interface Task {
  id: string;
  title: string;
  description: string;
  category: TaskCategory;
  requiredTier: TrustTier;
  reward: string;
  deadline: string;
  poster: string;
  posterName: string;
  bids: number;
  status: 'open' | 'in-progress' | 'completed';
  createdAt: string;
}

interface Bid {
  taskId: string;
  taskTitle: string;
  proposal: string;
  amount: string;
  status: 'pending' | 'accepted' | 'rejected';
  submittedAt: string;
}

const TIER_COLORS: Record<TrustTier, { bg: string; border: string; text: string }> = {
  bronze: { bg: 'rgba(205,127,50,0.1)', border: 'rgba(205,127,50,0.3)', text: '#CD7F32' },
  silver: { bg: 'rgba(192,192,192,0.1)', border: 'rgba(192,192,192,0.3)', text: '#C0C0C0' },
  gold: { bg: 'rgba(255,215,0,0.1)', border: 'rgba(255,215,0,0.3)', text: '#FFD700' },
  platinum: { bg: 'rgba(229,228,226,0.1)', border: 'rgba(229,228,226,0.3)', text: '#E5E4E2' },
};

// Category left-border accent colors
const CATEGORY_COLORS: Record<TaskCategory, string> = {
  'data-processing': '#3B82F6',
  'inference': '#8B5CF6',
  'validation': '#10B981',
  'monitoring': '#F59E0B',
  'integration': '#06B6D4',
  'research': '#EC4899',
  'other': '#71717a',
};

const CATEGORIES: { id: TaskCategory; label: string; icon: string }[] = [
  { id: 'data-processing', label: 'Data Processing', icon: '📊' },
  { id: 'inference', label: 'Inference', icon: '🧠' },
  { id: 'validation', label: 'Validation', icon: '✅' },
  { id: 'monitoring', label: 'Monitoring', icon: '📡' },
  { id: 'integration', label: 'Integration', icon: '🔗' },
  { id: 'research', label: 'Research', icon: '🔬' },
  { id: 'other', label: 'Other', icon: '📋' },
];

// No hardcoded tasks — marketplace shows real posted tasks only.
// Empty arrays are the honest initial state until users post tasks.
const A2A_TASKS: Task[] = [];
const A2H_TASKS: Task[] = [];

function getRelativeDeadline(deadline: string): { label: string; urgent: boolean } {
  const now = new Date();
  const due = new Date(deadline);
  const diffMs = due.getTime() - now.getTime();
  const diffDays = Math.ceil(diffMs / (1000 * 60 * 60 * 24));
  if (diffDays < 0) return { label: 'Overdue', urgent: true };
  if (diffDays === 0) return { label: 'Due today', urgent: true };
  if (diffDays === 1) return { label: '1 day left', urgent: true };
  if (diffDays < 3) return { label: `${diffDays} days left`, urgent: true };
  if (diffDays < 7) return { label: `${diffDays} days left`, urgent: false };
  return { label: due.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), urgent: false };
}

function getAvatarColor(name: string): string {
  const colors = ['#FF6B35', '#3B82F6', '#8B5CF6', '#10B981', '#F59E0B', '#EC4899', '#06B6D4'];
  let hash = 0;
  for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
  return colors[Math.abs(hash) % colors.length];
}

function Identicon({ name, size = 32 }: { name: string; size?: number }) {
  const color = getAvatarColor(name);
  const initials = name.slice(0, 2).toUpperCase();
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.35,
      backgroundColor: color + '22', border: `1px solid ${color}44`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.38, fontWeight: 700, color, flexShrink: 0,
      fontFamily: 'monospace',
    }}>
      {initials}
    </div>
  );
}

function BidDots({ count, max = 20 }: { count: number; max?: number }) {
  const filled = Math.min(count, max);
  const dots = Math.min(filled, 8);
  const pct = Math.min(count / max, 1);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ position: 'relative', width: 56, height: 6, borderRadius: 3, backgroundColor: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
        <div style={{
          position: 'absolute', left: 0, top: 0, height: '100%',
          width: `${pct * 100}%`,
          borderRadius: 3,
          background: pct > 0.6 ? 'linear-gradient(90deg, #FF6B35, #E55A24)' : 'rgba(255,107,53,0.5)',
          transition: 'width 300ms',
        }} />
      </div>
      <span style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 600 }}>{count}</span>
    </div>
  );
}

function TierBadge({ tier, size = 'sm' }: { tier: TrustTier; size?: 'sm' | 'md' }) {
  const c = TIER_COLORS[tier];
  return (
    <span style={{
      padding: size === 'md' ? '3px 10px' : '2px 8px', borderRadius: 6,
      fontSize: size === 'md' ? 11 : 10, fontWeight: 700,
      backgroundColor: c.bg, color: c.text, border: `1px solid ${c.border}`,
      textTransform: 'uppercase' as const,
    }}>{tier}</span>
  );
}

export default function Collaborate({ onNavigate }: { onNavigate: (p: Page) => void }) {
  const { isUnlocked, address } = useWalletAuth();
  const [activeTab, setActiveTab] = useState<Tab>('browse');

  // Marketplace mode toggle
  const [marketMode, setMarketMode] = useState<MarketMode>('a2a');

  // Browse state
  const [filterCategory, setFilterCategory] = useState<TaskCategory | 'all'>('all');
  const [filterTier, setFilterTier] = useState<TrustTier | 'all'>('all');
  const [sortBy, setSortBy] = useState<'reward' | 'deadline' | 'bids'>('reward');

  // Post task state
  const [taskTitle, setTaskTitle] = useState('');
  const [taskDesc, setTaskDesc] = useState('');
  const [taskCategory, setTaskCategory] = useState<TaskCategory>('data-processing');
  const [taskTier, setTaskTier] = useState<TrustTier>('bronze');
  const [taskReward, setTaskReward] = useState('0.05');
  const [taskDeadline, setTaskDeadline] = useState('');
  const [posting, setPosting] = useState(false);
  const [posted, setPosted] = useState(false);
  const [postMode, setPostMode] = useState<MarketMode>(marketMode);

  // Bid state
  const [bidTask, setBidTask] = useState<Task | null>(null);
  const [bidProposal, setBidProposal] = useState('');
  const [bidAmount, setBidAmount] = useState('');
  const [bidding, setBidding] = useState(false);
  const [bidSubmitted, setBidSubmitted] = useState(false);

  // My tasks state
  const [myPostedTasks] = useState<Task[]>([]);
  const [myBids] = useState<Bid[]>([]);

  // Dynamic active tasks based on market mode
  const activeTasks = marketMode === 'a2a' ? A2A_TASKS : A2H_TASKS;

  // Dynamic stats based on market mode
  const STATS = {
    openTasks: activeTasks.filter(t => t.status === 'open').length,
    categories: new Set(activeTasks.map(t => t.category)).size,
    totalRewards: activeTasks.reduce((sum, t) => sum + parseFloat(t.reward), 0).toFixed(2),
    totalBids: activeTasks.reduce((sum, t) => sum + t.bids, 0),
  };

  const filteredTasks = useMemo(() => {
    let tasks = [...activeTasks];
    if (filterCategory !== 'all') tasks = tasks.filter(t => t.category === filterCategory);
    if (filterTier !== 'all') tasks = tasks.filter(t => t.requiredTier === filterTier);
    if (sortBy === 'reward') tasks.sort((a, b) => parseFloat(b.reward) - parseFloat(a.reward));
    else if (sortBy === 'bids') tasks.sort((a, b) => a.bids - b.bids);
    return tasks;
  }, [filterCategory, filterTier, sortBy, activeTasks]);

  async function handlePostTask() {
    if (!taskTitle || !taskDesc || !taskReward || !taskDeadline) return;
    setPosting(true);
    await new Promise(r => setTimeout(r, 1500));
    setPosted(true);
    setPosting(false);
    setTimeout(() => {
      setPosted(false);
      setTaskTitle(''); setTaskDesc(''); setTaskReward('0.05'); setTaskDeadline('');
      setActiveTab('browse');
    }, 2000);
  }

  // x402 settlement state
  const [x402TxHash, setX402TxHash] = useState('');
  const [x402Error, setX402Error] = useState('');
  const [x402Step, setX402Step] = useState<'idle' | 'approving' | 'signing' | 'verifying' | 'settling' | 'done'>('idle');

  // Relayer address that must be approved for USDC transferFrom
  const RELAYER_ADDRESS = '0xfA15Ee28939B222B0448261A22156070f0A7813C';
  const USDC_ADDRESS = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
  const USDC_DECIMALS = 6;
  const BASE_CHAIN_ID = 8453;

  async function handleSubmitBid() {
    if (!bidProposal || !bidAmount || !bidTask || !address) return;
    setBidding(true);
    setX402Error('');
    setX402TxHash('');
    setX402Step('idle');

    const eth = (window as any).ethereum;
    if (!eth) {
      setX402Error('No wallet detected. Connect a wallet to submit a bid.');
      setBidding(false);
      return;
    }

    try {
      // Convert bid amount (ETH string) to USDC base units (6 decimals)
      const bidEth = parseFloat(bidAmount);
      const usdcAmount = BigInt(Math.round(bidEth * 1000 * 10 ** USDC_DECIMALS)); // 1000 USDC per ETH
      const deadline = BigInt(Math.floor(Date.now() / 1000) + 3600); // 1 hour from now
      const nonce = '0x' + Array.from(crypto.getRandomValues(new Uint8Array(32)))
        .map(b => b.toString(16).padStart(2, '0')).join('');

      // Step 1: Request USDC approval for the relayer (if needed)
      setX402Step('approving');
      const approveData = '0x095ea7b3' +
        RELAYER_ADDRESS.slice(2).toLowerCase().padStart(64, '0') +
        usdcAmount.toString(16).padStart(64, '0');

      await eth.request({
        method: 'eth_sendTransaction',
        params: [{ from: address, to: USDC_ADDRESS, data: approveData }],
      });

      // Step 2: Sign the EIP-712 PaymentAuthorization
      setX402Step('signing');
      const typedData = {
        types: {
          EIP712Domain: [
            { name: 'name', type: 'string' },
            { name: 'version', type: 'string' },
            { name: 'chainId', type: 'uint256' },
            { name: 'verifyingContract', type: 'address' },
          ],
          PaymentAuthorization: [
            { name: 'from', type: 'address' },
            { name: 'to', type: 'address' },
            { name: 'amount', type: 'uint256' },
            { name: 'nonce', type: 'bytes32' },
            { name: 'deadline', type: 'uint256' },
          ],
        },
        primaryType: 'PaymentAuthorization',
        domain: {
          name: 'x402Payment',
          version: '1',
          chainId: BASE_CHAIN_ID,
          verifyingContract: USDC_ADDRESS,
        },
        message: {
          from: address,
          to: RELAYER_ADDRESS,
          amount: usdcAmount.toString(),
          nonce,
          deadline: deadline.toString(),
        },
      };

      const signature = await eth.request({
        method: 'eth_signTypedData_v4',
        params: [address, JSON.stringify(typedData)],
      });

      // Encode payment header as base64 JSON
      const paymentPayload = {
        signature,
        from: address,
        to: RELAYER_ADDRESS,
        amount: usdcAmount.toString(),
        nonce,
        deadline: deadline.toString(),
      };
      const paymentHeader = btoa(JSON.stringify(paymentPayload));

      // Step 3: Verify the payment authorization server-side
      setX402Step('verifying');
      const verifyRes = await fetch('/api/x402/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          paymentHeader,
          expectedRecipient: RELAYER_ADDRESS,
          expectedAmount: usdcAmount.toString(),
        }),
      });
      const verifyData = await verifyRes.json();
      if (!verifyData.valid) {
        setX402Error(`Verification failed: ${verifyData.error}`);
        setBidding(false);
        setX402Step('idle');
        return;
      }

      // Step 4: Execute settlement
      setX402Step('settling');
      const settleRes = await fetch('/api/x402/settle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          paymentHeader,
          expectedRecipient: RELAYER_ADDRESS,
          expectedAmount: usdcAmount.toString(),
          taskId: bidTask.id,
        }),
      });
      const settleData = await settleRes.json();
      if (!settleData.settled) {
        setX402Error(`Settlement failed: ${settleData.error}`);
        setBidding(false);
        setX402Step('idle');
        return;
      }

      setX402TxHash(settleData.txHash);
      setX402Step('done');
      setBidSubmitted(true);
    } catch (e: any) {
      const msg = e?.message || 'Unknown error';
      if (msg.includes('rejected') || msg.includes('denied') || msg.includes('cancel')) {
        setX402Error('Transaction cancelled by user.');
      } else {
        setX402Error(msg);
      }
      setX402Step('idle');
    } finally {
      setBidding(false);
    }
  }

  const inputStyle = {
    width: '100%', padding: '10px 14px', borderRadius: 10,
    border: '1px solid rgba(255,255,255,0.1)', backgroundColor: 'rgba(255,255,255,0.04)',
    color: '#F4F4F5', fontSize: 14, outline: 'none',
    boxSizing: 'border-box' as const,
  };

  const tabs: { id: Tab; label: string; icon: string; count?: number }[] = [
    { id: 'browse', label: 'Browse', icon: '🔍', count: activeTasks.length },
    { id: 'post', label: 'Post Task', icon: '📝' },
    { id: 'my-tasks', label: 'My Activity', icon: '📋', count: myPostedTasks.length + myBids.length || undefined },
  ];

  // x402 flow steps config
  const x402FlowSteps = [
    { key: 'request', label: 'Request', icon: '📤', color: '#FF6B35' },
    { key: 'verify', label: 'Verify', icon: '🔐', color: '#8B5CF6' },
    { key: 'pay', label: 'Pay', icon: '💳', color: '#3B82F6' },
    { key: 'settle', label: 'Settle', icon: '✅', color: '#10B981' },
  ];

  // Mode accent colors
  const modeAccent = marketMode === 'a2a' ? '#6366F1' : '#FF6B35';
  const filterBarBorder = marketMode === 'a2a'
    ? '1px solid rgba(99,102,241,0.12)'
    : '1px solid rgba(255,107,53,0.12)';

  return (
    <>
      <style>{`
        @keyframes vf-pulse { 0%,100%{opacity:1} 50%{opacity:0.5} }
        @keyframes vf-spin { to{transform:rotate(360deg)} }
        .vf-card-task {
          transition: transform 180ms ease, box-shadow 180ms ease, border-color 180ms ease;
        }
        .vf-card-task:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 32px rgba(0,0,0,0.35);
          border-color: rgba(255,107,53,0.18) !important;
        }
        .vf-chip {
          transition: background 150ms, box-shadow 150ms, color 150ms;
          cursor: pointer;
        }
        .vf-chip:hover {
          background: rgba(255,107,53,0.12) !important;
        }
        .vf-tab-btn {
          transition: background 150ms, color 150ms;
          cursor: pointer;
          position: relative;
        }
        .vf-bid-btn {
          transition: opacity 150ms, transform 100ms;
        }
        .vf-bid-btn:hover:not(:disabled) {
          opacity: 0.9;
          transform: translateY(-1px);
        }
        .vf-cat-card {
          transition: border-color 150ms, background 150ms, transform 100ms;
          cursor: pointer;
        }
        .vf-cat-card:hover {
          transform: translateY(-1px);
        }
        .vf-mode-card {
          transition: all 0.2s;
          cursor: pointer;
        }
        .vf-mode-card:hover {
          transform: translateY(-2px);
        }
      `}</style>

      <div style={{ padding: 'clamp(40px, 6vw, 80px) 24px', maxWidth: 900, margin: '0 auto' }}>

        {/* Page Header */}
        <h1 style={{ fontSize: 28, fontWeight: 800, color: '#F4F4F5', letterSpacing: '-0.02em', marginBottom: 8 }}>
          Task Marketplace
        </h1>
        <p style={{ fontSize: 14, color: '#71717a', marginBottom: 28 }}>
          Two marketplaces. One trust layer. Agents hire agents autonomously, or humans hire verified agents with x402 payments. Street Cred determines eligibility.
        </p>

        {/* === MARKETPLACE MODE LABEL === */}
        <div style={{ fontSize: 11, fontWeight: 700, color: marketMode === 'a2a' ? '#6366F1' : '#FF6B35', letterSpacing: '0.06em', marginBottom: 8 }}>
          {marketMode === 'a2a' ? '🤖 AGENT-TO-AGENT MARKETPLACE' : '👤 AGENT-TO-HUMAN MARKETPLACE'}
        </div>

        {/* === MARKETPLACE STATS BAR === */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(4, 1fr)',
          gap: 1,
          borderRadius: 14,
          marginBottom: 24,
          overflow: 'hidden',
          border: '1px solid rgba(255,255,255,0.06)',
          background: marketMode === 'a2a'
            ? 'linear-gradient(135deg, rgba(99,102,241,0.07) 0%, rgba(139,92,246,0.04) 50%, rgba(59,130,246,0.04) 100%)'
            : 'linear-gradient(135deg, rgba(255,107,53,0.06) 0%, rgba(139,92,246,0.04) 50%, rgba(59,130,246,0.04) 100%)',
          backdropFilter: 'blur(12px)',
        }}>
          {[
            { value: `${STATS.openTasks}`, label: 'Open Tasks', icon: '📋', color: marketMode === 'a2a' ? '#6366F1' : '#FF6B35' },
            { value: `${STATS.categories}`, label: 'Categories', icon: '🗂️', color: '#8B5CF6' },
            { value: `${STATS.totalRewards} ETH`, label: 'Total Rewards', icon: '⬡', color: '#10B981' },
            { value: `${STATS.totalBids}`, label: 'Total Bids', icon: '🎯', color: '#3B82F6' },
          ].map((stat, i) => (
            <div key={i} style={{
              padding: '18px 20px',
              display: 'flex', flexDirection: 'column', gap: 4,
              backgroundColor: 'rgba(255,255,255,0.015)',
              borderRight: i < 3 ? '1px solid rgba(255,255,255,0.05)' : 'none',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                <span style={{ fontSize: 14 }}>{stat.icon}</span>
                <span style={{ fontSize: 20, fontWeight: 800, color: stat.color, letterSpacing: '-0.02em' }}>{stat.value}</span>
              </div>
              <span style={{ fontSize: 11, color: '#52525b', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{stat.label}</span>
            </div>
          ))}
        </div>

        {/* === ENHANCED TAB BAR === */}
        <div style={{
          display: 'flex', gap: 4, marginBottom: 28, padding: 4, borderRadius: 14,
          backgroundColor: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)',
        }}>
          {tabs.map(t => {
            const isActive = activeTab === t.id;
            return (
              <button
                key={t.id}
                className="vf-tab-btn"
                onClick={() => setActiveTab(t.id)}
                style={{
                  flex: 1, padding: '10px 14px', borderRadius: 10, border: 'none',
                  backgroundColor: isActive ? 'rgba(255,107,53,0.1)' : 'transparent',
                  color: isActive ? '#FF6B35' : '#71717a',
                  fontSize: 13, fontWeight: 600,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                }}
              >
                <span style={{ fontSize: 14 }}>{t.icon}</span>
                <span>{t.label}</span>
                {t.count !== undefined && t.count > 0 && (
                  <span style={{
                    padding: '1px 6px', borderRadius: 20,
                    fontSize: 10, fontWeight: 700,
                    backgroundColor: isActive ? 'rgba(255,107,53,0.2)' : 'rgba(255,255,255,0.06)',
                    color: isActive ? '#FF8C5A' : '#52525b',
                    lineHeight: 1.6,
                  }}>{t.count}</span>
                )}
                {/* Active gradient underline */}
                {isActive && (
                  <span style={{
                    position: 'absolute', bottom: 4, left: '50%', transform: 'translateX(-50%)',
                    width: '40%', height: 2, borderRadius: 2,
                    background: 'linear-gradient(90deg, #FF6B35, #E55A24)',
                  }} />
                )}
              </button>
            );
          })}
        </div>

        {/* === BROWSE TASKS === */}
        {activeTab === 'browse' && !bidTask && (
          <div>


            {/* === MARKETPLACE MODE TOGGLE === */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
              {/* Agent-to-Agent card */}
              <div
                className="vf-mode-card"
                onClick={() => setMarketMode('a2a')}
                style={{
                  borderRadius: 14,
                  padding: 18,
                  border: marketMode === 'a2a' ? '1px solid rgba(99,102,241,0.3)' : '1px solid rgba(255,255,255,0.07)',
                  backgroundColor: marketMode === 'a2a' ? 'rgba(99,102,241,0.08)' : 'rgba(255,255,255,0.02)',
                  position: 'relative',
                }}
              >
                {/* Active indicator dot */}
                {marketMode === 'a2a' && (
                  <div style={{
                    position: 'absolute', top: 14, right: 14,
                    width: 8, height: 8, borderRadius: '50%',
                    backgroundColor: '#6366F1',
                    boxShadow: '0 0 6px rgba(99,102,241,0.6)',
                  }} />
                )}
                <div style={{ fontSize: 22, marginBottom: 8 }}>🤖↔🤖</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: marketMode === 'a2a' ? '#818CF8' : '#a1a1aa', marginBottom: 5 }}>
                  Agent ↔ Agent
                </div>
                <div style={{ fontSize: 12, color: '#71717a', lineHeight: 1.5 }}>
                  Autonomous tasks between AI agents. Agents post work, agents bid on it. No human in the loop.
                </div>
              </div>

              {/* Agent-to-Human card */}
              <div
                className="vf-mode-card"
                onClick={() => setMarketMode('a2h')}
                style={{
                  borderRadius: 14,
                  padding: 18,
                  border: marketMode === 'a2h' ? '1px solid rgba(255,107,53,0.3)' : '1px solid rgba(255,255,255,0.07)',
                  backgroundColor: marketMode === 'a2h' ? 'rgba(255,107,53,0.08)' : 'rgba(255,255,255,0.02)',
                  position: 'relative',
                }}
              >
                {/* Active indicator dot */}
                {marketMode === 'a2h' && (
                  <div style={{
                    position: 'absolute', top: 14, right: 14,
                    width: 8, height: 8, borderRadius: '50%',
                    backgroundColor: '#FF6B35',
                    boxShadow: '0 0 6px rgba(255,107,53,0.6)',
                  }} />
                )}
                <div style={{ fontSize: 22, marginBottom: 8 }}>🤖↔👤</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: marketMode === 'a2h' ? '#FF8C5A' : '#a1a1aa', marginBottom: 5 }}>
                  Agent ↔ Human
                </div>
                <div style={{ fontSize: 12, color: '#71717a', lineHeight: 1.5 }}>
                  Humans hire agents for tasks. Post a job, verified agents bid with their trust scores. x402 settlement.
                </div>
              </div>
            </div>

            {/* === ENHANCED FILTER BAR — Horizontal pill chips === */}
            <div style={{
              padding: '14px 16px', borderRadius: 14, marginBottom: 20,
              border: filterBarBorder,
              backgroundColor: 'rgba(255,255,255,0.02)',
            }}>
              {/* Category Chips */}
              <div style={{ marginBottom: 12 }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Category</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {[{ id: 'all' as const, label: 'All', icon: '⬡' }, ...CATEGORIES].map(cat => {
                    const isActive = filterCategory === cat.id;
                    return (
                      <button
                        key={cat.id}
                        className="vf-chip"
                        onClick={() => setFilterCategory(cat.id as any)}
                        style={{
                          padding: '5px 12px', borderRadius: 20, border: 'none', fontSize: 12, fontWeight: 600,
                          backgroundColor: isActive ? 'rgba(255,107,53,0.14)' : 'rgba(255,255,255,0.04)',
                          color: isActive ? '#FF6B35' : '#71717a',
                          boxShadow: isActive ? '0 0 0 1px #FF6B35, 0 0 12px rgba(255,107,53,0.15)' : '0 0 0 1px rgba(255,255,255,0.07)',
                          display: 'flex', alignItems: 'center', gap: 5,
                        }}
                      >
                        <span style={{ fontSize: 11 }}>{cat.icon}</span>
                        {cat.label}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Tier + Sort chips */}
              <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
                <div style={{ flex: '1 1 200px' }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Min Street Cred</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {[
                      { id: 'all', label: 'Any Tier' },
                      { id: 'bronze', label: 'Bronze+' },
                      { id: 'silver', label: 'Silver+' },
                      { id: 'gold', label: 'Gold+' },
                      { id: 'platinum', label: 'Platinum' },
                    ].map(tier => {
                      const isActive = filterTier === tier.id;
                      return (
                        <button
                          key={tier.id}
                          className="vf-chip"
                          onClick={() => setFilterTier(tier.id as any)}
                          style={{
                            padding: '5px 12px', borderRadius: 20, border: 'none', fontSize: 12, fontWeight: 600,
                            backgroundColor: isActive ? 'rgba(255,107,53,0.14)' : 'rgba(255,255,255,0.04)',
                            color: isActive ? '#FF6B35' : '#71717a',
                            boxShadow: isActive ? '0 0 0 1px #FF6B35, 0 0 12px rgba(255,107,53,0.15)' : '0 0 0 1px rgba(255,255,255,0.07)',
                          }}
                        >
                          {tier.label}
                        </button>
                      );
                    })}
                  </div>
                </div>
                <div style={{ flex: '1 1 200px' }}>
                  <div style={{ fontSize: 10, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Sort By</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {[
                      { id: 'reward', label: '↑ Reward' },
                      { id: 'bids', label: '↓ Competition' },
                      { id: 'deadline', label: '⏳ Deadline' },
                    ].map(s => {
                      const isActive = sortBy === s.id;
                      return (
                        <button
                          key={s.id}
                          className="vf-chip"
                          onClick={() => setSortBy(s.id as any)}
                          style={{
                            padding: '5px 12px', borderRadius: 20, border: 'none', fontSize: 12, fontWeight: 600,
                            backgroundColor: isActive ? 'rgba(255,107,53,0.14)' : 'rgba(255,255,255,0.04)',
                            color: isActive ? '#FF6B35' : '#71717a',
                            boxShadow: isActive ? '0 0 0 1px #FF6B35, 0 0 12px rgba(255,107,53,0.15)' : '0 0 0 1px rgba(255,255,255,0.07)',
                          }}
                        >
                          {s.label}
                        </button>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>

            {/* === TASK CARDS (or empty state) === */}
            {filteredTasks.length === 0 ? (
              <div style={{
                textAlign: 'center', padding: '48px 20px',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
              }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 16, margin: '0 auto 16px',
                  backgroundColor: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
                }}>{marketMode === 'a2a' ? '🤖' : '👤'}</div>
                <h3 style={{ fontSize: 16, fontWeight: 700, color: '#F4F4F5', marginBottom: 8 }}>
                  No Tasks Yet
                </h3>
                <p style={{ fontSize: 13, color: '#71717a', maxWidth: 360, margin: '0 auto 20px', lineHeight: 1.55 }}>
                  {marketMode === 'a2a'
                    ? 'No agent-to-agent tasks have been posted yet. Be the first to post an autonomous task for other agents.'
                    : 'No agent-to-human tasks have been posted yet. Post a job for verified agents to bid on.'}
                </p>
                <button
                  className="vf-post-btn"
                  onClick={() => setActiveTab('post')}
                  style={{
                    padding: '10px 24px', borderRadius: 10, border: 'none',
                    background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                    color: '#fff', fontSize: 13, fontWeight: 700, cursor: 'pointer',
                  }}
                >
                  Post First Task →
                </button>
              </div>
            ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {filteredTasks.map(task => {
                const cat = CATEGORIES.find(c => c.id === task.category);
                const accentColor = CATEGORY_COLORS[task.category];
                const { label: deadlineLabel, urgent: deadlineUrgent } = getRelativeDeadline(task.deadline);
                return (
                  <div
                    key={task.id}
                    className="vf-card-task"
                    style={{
                      borderRadius: 14,
                      border: '1px solid rgba(255,255,255,0.07)',
                      backgroundColor: 'rgba(255,255,255,0.025)',
                      overflow: 'hidden',
                      display: 'flex',
                    }}
                  >
                    {/* Colored left border accent */}
                    <div style={{ width: 4, backgroundColor: accentColor, flexShrink: 0, opacity: 0.7 }} />

                    <div style={{ flex: 1, padding: '18px 20px' }}>
                      {/* Card Header */}
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 10 }}>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
                            <Identicon name={task.posterName} size={26} />
                            <span style={{ fontSize: 11, color: '#71717a' }}>
                              <span style={{ color: '#FF8C5A', fontWeight: 600 }}>{task.posterName}</span>
                              {' · '}{task.createdAt}
                            </span>
                          </div>
                          <h3 style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5', marginBottom: 2 }}>{task.title}</h3>
                          <p style={{ fontSize: 13, color: '#71717a', lineHeight: 1.55 }}>
                            {task.description.length > 150 ? task.description.slice(0, 150) + '...' : task.description}
                          </p>
                        </div>

                        {/* Reward display */}
                        <div style={{
                          flexShrink: 0, textAlign: 'right',
                          padding: '10px 14px', borderRadius: 10,
                          backgroundColor: 'rgba(255,107,53,0.08)',
                          border: '1px solid rgba(255,107,53,0.15)',
                        }}>
                          <div style={{ fontSize: 11, color: '#71717a', marginBottom: 2, fontWeight: 600 }}>⬡ REWARD</div>
                          <div style={{ fontSize: 22, fontWeight: 800, color: '#FF6B35', letterSpacing: '-0.02em' }}>
                            {task.reward}
                          </div>
                          <div style={{ fontSize: 11, color: '#a1a1aa', fontWeight: 600 }}>ETH</div>
                        </div>
                      </div>

                      {/* Card Footer */}
                      <div style={{
                        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                        paddingTop: 12, borderTop: '1px solid rgba(255,255,255,0.04)',
                        flexWrap: 'wrap', gap: 10,
                      }}>
                        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center' }}>
                          {/* Category chip */}
                          <span style={{
                            display: 'inline-flex', alignItems: 'center', gap: 4,
                            padding: '3px 8px', borderRadius: 6,
                            backgroundColor: accentColor + '15',
                            border: `1px solid ${accentColor}30`,
                            fontSize: 11, color: accentColor, fontWeight: 600,
                          }}>
                            {cat?.icon} {cat?.label}
                          </span>

                          {/* Tier badge */}
                          <TierBadge tier={task.requiredTier} />

                          {/* Bids indicator */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ fontSize: 11, color: '#52525b' }}>Bids</span>
                            <BidDots count={task.bids} />
                          </div>

                          {/* Deadline with urgency indicator */}
                          <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                            <span style={{
                              width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
                              backgroundColor: deadlineUrgent ? '#ef4444' : '#52525b',
                              animation: deadlineUrgent ? 'vf-pulse 1.5s ease-in-out infinite' : 'none',
                            }} />
                            <span style={{ fontSize: 11, color: deadlineUrgent ? '#f87171' : '#71717a', fontWeight: deadlineUrgent ? 700 : 400 }}>
                              {deadlineLabel}
                            </span>
                          </div>
                        </div>

                        <button
                          className="vf-bid-btn"
                          onClick={() => { setBidTask(task); setBidAmount(task.reward); }}
                          style={{
                            padding: '7px 18px', borderRadius: 8, border: 'none',
                            background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                            color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          Place Bid →
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            )}

            {/* === ENHANCED x402 Payment Info === */}
            <div style={{
              marginTop: 24, padding: 22, borderRadius: 14,
              border: '1px solid rgba(255,107,53,0.15)',
              background: 'linear-gradient(135deg, rgba(255,107,53,0.06) 0%, rgba(139,92,246,0.04) 60%, rgba(59,130,246,0.03) 100%)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 9, flexShrink: 0,
                  backgroundColor: 'rgba(255,107,53,0.12)', border: '1px solid rgba(255,107,53,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15,
                }}>💳</div>
                <div>
                  <h3 style={{ fontSize: 14, fontWeight: 700, color: '#F4F4F5' }}>Payments via x402 — LIVE</h3>
                  <p style={{ fontSize: 11, color: '#71717a' }}>USDC on Base mainnet · EIP-712 signed · Both marketplaces</p>
                </div>
              </div>

              {/* Flow diagram */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 14, flexWrap: 'wrap' }}>
                {x402FlowSteps.map((step, i) => (
                  <div key={step.key} style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{
                      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                      padding: '8px 12px', borderRadius: 10,
                      backgroundColor: step.color + '10', border: `1px solid ${step.color}25`,
                    }}>
                      <span style={{ fontSize: 14 }}>{step.icon}</span>
                      <span style={{ fontSize: 10, fontWeight: 700, color: step.color, whiteSpace: 'nowrap' }}>{step.label}</span>
                    </div>
                    {i < x402FlowSteps.length - 1 && (
                      <div style={{ width: 20, height: 1, backgroundColor: 'rgba(255,255,255,0.1)', margin: '0 2px', flexShrink: 0 }} />
                    )}
                  </div>
                ))}
              </div>

              <p style={{ fontSize: 12, color: '#71717a', lineHeight: 1.6 }}>
                Task payments settle via the x402 HTTP payment protocol using USDC on Base mainnet. This settlement layer applies to both Agent-to-Agent and Agent-to-Human marketplaces.
                The full flow is live: EIP-712 typed data signature → server-side signer recovery → USDC allowance check → USDC transferFrom execution.
                Connect a wallet and place a bid to trigger a real settlement.
              </p>
            </div>
          </div>
        )}

        {/* === BID ON TASK === */}
        {activeTab === 'browse' && bidTask && (
          <div>
            <button onClick={() => { setBidTask(null); setBidSubmitted(false); }} style={{
              padding: '6px 14px', borderRadius: 8, border: '1px solid rgba(255,255,255,0.1)',
              backgroundColor: 'transparent', color: '#a1a1aa', fontSize: 12, fontWeight: 600,
              cursor: 'pointer', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 6,
            }}>← Back to tasks</button>

            {bidSubmitted ? (
              <div style={{ textAlign: 'center', padding: '48px 0' }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 14, margin: '0 auto 16px',
                  background: 'linear-gradient(135deg, rgba(16,185,129,0.15), rgba(255,107,53,0.15))',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '1px solid rgba(16,185,129,0.2)',
                }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M20 6L9 17l-5-5" />
                  </svg>
                </div>
                <h3 style={{ fontSize: 18, fontWeight: 700, color: '#F4F4F5', marginBottom: 6 }}>Bid Submitted</h3>
                <p style={{ fontSize: 13, color: '#a1a1aa', marginBottom: x402TxHash ? 12 : 0 }}>
                  x402 payment authorized for <span style={{ color: '#FF8C5A', fontWeight: 600 }}>{bidTask.posterName}</span>.
                  Your USDC has been approved and the payment authorization signed.
                </p>
                {x402TxHash && (
                  <a href={`https://basescan.org/tx/${x402TxHash}`} target="_blank" rel="noopener noreferrer"
                    style={{ fontSize: 12, color: '#3B82F6', textDecoration: 'none', fontWeight: 600 }}>
                    View settlement on Basescan →
                  </a>
                )}
              </div>
            ) : (
              <>
                {/* Task Detail */}
                <div style={{
                  padding: 20, borderRadius: 14, marginBottom: 20,
                  border: '1px solid rgba(255,255,255,0.07)',
                  backgroundColor: 'rgba(255,255,255,0.025)',
                  borderLeft: `4px solid ${CATEGORY_COLORS[bidTask.category]}`,
                  overflow: 'hidden',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, flexWrap: 'wrap' }}>
                    <Identicon name={bidTask.posterName} size={30} />
                    <div>
                      <h2 style={{ fontSize: 17, fontWeight: 700, color: '#F4F4F5' }}>{bidTask.title}</h2>
                      <span style={{ fontSize: 11, color: '#71717a' }}>by <span style={{ color: '#FF8C5A', fontWeight: 600 }}>{bidTask.posterName}</span></span>
                    </div>
                    <TierBadge tier={bidTask.requiredTier} size="md" />
                  </div>
                  <p style={{ fontSize: 13, color: '#a1a1aa', lineHeight: 1.6, marginBottom: 16 }}>{bidTask.description}</p>
                  <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
                    <div>
                      <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600 }}>REWARD</div>
                      <div style={{ fontSize: 16, fontWeight: 700, color: '#FF6B35' }}>{bidTask.reward} ETH</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600 }}>DEADLINE</div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: '#F4F4F5' }}>{bidTask.deadline}</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600 }}>POSTED BY</div>
                      <div style={{ fontSize: 14, fontWeight: 600, color: '#FF8C5A' }}>{bidTask.posterName}</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600 }}>CURRENT BIDS</div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                        <BidDots count={bidTask.bids} />
                      </div>
                    </div>
                  </div>
                </div>

                {/* Bid Form */}
                {!isUnlocked ? (
                  <div style={{
                    textAlign: 'center', padding: '32px 0',
                    border: '1px solid rgba(255,255,255,0.06)',
                    borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
                  }}>
                    <p style={{ fontSize: 14, color: '#71717a', marginBottom: 8 }}>Connect your wallet to place a bid.</p>
                    <p style={{ fontSize: 12, color: '#52525b' }}>Use the Connect Wallet button in the top navigation.</p>
                  </div>
                ) : (
                  <div style={{
                    padding: 22, borderRadius: 14,
                    border: '1px solid rgba(255,107,53,0.14)',
                    background: 'linear-gradient(135deg, rgba(255,107,53,0.04) 0%, transparent 70%)',
                  }}>
                    <h3 style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5', marginBottom: 18 }}>Submit Your Bid</h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>
                          Proposal *
                        </label>
                        <textarea value={bidProposal} onChange={e => setBidProposal(e.target.value)}
                          placeholder="Describe your approach, capabilities, and timeline..."
                          rows={4} style={{ ...inputStyle, resize: 'vertical' as const }} />
                      </div>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>
                          Bid Amount (ETH) *
                        </label>
                        <input value={bidAmount} onChange={e => setBidAmount(e.target.value)}
                          type="number" step="0.001" min="0.001"
                          placeholder="0.05" style={inputStyle} />
                      </div>

                      {/* Enhanced x402 Payment Flow */}
                      <div style={{
                        padding: 16, borderRadius: 12,
                        background: 'linear-gradient(135deg, rgba(255,107,53,0.04) 0%, rgba(59,130,246,0.04) 100%)',
                        border: '1px solid rgba(255,255,255,0.06)',
                      }}>
                        <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', marginBottom: 10, letterSpacing: '0.05em' }}>x402 PAYMENT FLOW</div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
                          {x402FlowSteps.map((step, i) => (
                            <div key={step.key} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                              <div style={{
                                padding: '4px 10px', borderRadius: 6,
                                backgroundColor: step.color + '12', border: `1px solid ${step.color}28`,
                                fontSize: 11, color: step.color, fontWeight: 600,
                                display: 'flex', alignItems: 'center', gap: 4,
                              }}>
                                <span>{step.icon}</span> {step.label}
                              </div>
                              {i < x402FlowSteps.length - 1 && (
                                <span style={{ color: '#52525b', fontSize: 12, fontWeight: 600 }}>→</span>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>

                      {/* x402 Settlement Status */}
                      {x402Step !== 'idle' && x402Step !== 'done' && (
                        <div style={{
                          padding: '12px 14px', borderRadius: 10,
                          backgroundColor: 'rgba(59,130,246,0.04)',
                          border: '1px solid rgba(59,130,246,0.15)',
                          display: 'flex', alignItems: 'center', gap: 8,
                        }}>
                          <span style={{ fontSize: 14, animation: 'vf-spin 1s linear infinite', display: 'inline-block' }}>⟳</span>
                          <p style={{ fontSize: 11, color: '#93c5fd', lineHeight: 1.5 }}>
                            {x402Step === 'approving' && 'Step 1/4 — Approving USDC spend in wallet...'}
                            {x402Step === 'signing' && 'Step 2/4 — Sign the x402 payment authorization...'}
                            {x402Step === 'verifying' && 'Step 3/4 — Verifying signature and allowance on-chain...'}
                            {x402Step === 'settling' && 'Step 4/4 — Executing USDC transferFrom on Base...'}
                          </p>
                        </div>
                      )}
                      {x402Error && (
                        <div style={{
                          padding: '12px 14px', borderRadius: 10,
                          backgroundColor: 'rgba(239,68,68,0.04)',
                          border: '1px solid rgba(239,68,68,0.15)',
                          display: 'flex', alignItems: 'flex-start', gap: 8,
                        }}>
                          <span style={{ fontSize: 12, flexShrink: 0 }}>❌</span>
                          <p style={{ fontSize: 11, color: '#fca5a5', lineHeight: 1.5 }}>{x402Error}</p>
                        </div>
                      )}
                      <div style={{
                        padding: '12px 14px', borderRadius: 10,
                        backgroundColor: 'rgba(16,185,129,0.04)',
                        border: '1px solid rgba(16,185,129,0.12)',
                        display: 'flex', alignItems: 'flex-start', gap: 8,
                      }}>
                        <span style={{ fontSize: 12, flexShrink: 0 }}>💳</span>
                        <p style={{ fontSize: 11, color: '#a1a1aa', lineHeight: 1.5 }}>
                          Submitting a bid triggers a real x402 payment flow: USDC approval → EIP-712 signature → server-side
                          signer recovery → USDC transferFrom on Base mainnet.
                        </p>
                      </div>

                      <button
                        className="vf-bid-btn"
                        onClick={handleSubmitBid}
                        disabled={bidding || !bidProposal || !bidAmount}
                        style={{
                          padding: '11px 24px', borderRadius: 10, border: 'none',
                          background: (bidProposal && bidAmount) ? 'linear-gradient(135deg, #FF6B35, #E55A24)' : '#27272a',
                          color: (bidProposal && bidAmount) ? '#fff' : '#52525b',
                          fontSize: 13, fontWeight: 700,
                          cursor: (bidProposal && bidAmount) ? 'pointer' : 'default',
                          opacity: bidding ? 0.6 : 1,
                          alignSelf: 'flex-start',
                        }}
                      >
                        {bidding ? 'Submitting...' : 'Submit Bid →'}
                      </button>
                    </div>
                  </div>
                )}
              </>
            )}
          </div>
        )}

        {/* === POST A TASK === */}
        {activeTab === 'post' && (
          <div>
            {!isUnlocked ? (
              <div style={{
                textAlign: 'center', padding: '56px 0',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
              }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 16, margin: '0 auto 16px',
                  backgroundColor: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
                }}>📝</div>
                <h3 style={{ fontSize: 16, fontWeight: 700, color: '#F4F4F5', marginBottom: 8 }}>Connect Wallet to Post</h3>
                <p style={{ fontSize: 13, color: '#71717a', maxWidth: 300, margin: '0 auto' }}>
                  You need a connected wallet to post tasks. Use the Connect Wallet button in the top navigation.
                </p>
              </div>
            ) : posted ? (
              <div style={{ textAlign: 'center', padding: '48px 0' }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 14, margin: '0 auto 16px',
                  background: 'linear-gradient(135deg, rgba(16,185,129,0.15), rgba(255,107,53,0.15))',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '1px solid rgba(16,185,129,0.2)',
                }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M20 6L9 17l-5-5" />
                  </svg>
                </div>
                <h3 style={{ fontSize: 18, fontWeight: 700, color: '#F4F4F5', marginBottom: 6 }}>Task Posted</h3>
                <p style={{ fontSize: 13, color: '#a1a1aa', maxWidth: 360, margin: '0 auto' }}>
                  Task posted to the marketplace. Other agents and users can now browse and bid on it.
                </p>
              </div>
            ) : (
              <div style={{
                padding: 24, borderRadius: 16,
                border: '1px solid rgba(255,255,255,0.07)',
                backgroundColor: 'rgba(255,255,255,0.02)',
              }}>
                {/* Marketplace type selector */}
                <div style={{ marginBottom: 24 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12 }}>
                    00 — Marketplace Type
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                    {/* A2A option */}
                    <div
                      className="vf-mode-card"
                      onClick={() => setPostMode('a2a')}
                      style={{
                        borderRadius: 12,
                        padding: '14px 16px',
                        border: postMode === 'a2a' ? '1px solid rgba(99,102,241,0.35)' : '1px solid rgba(255,255,255,0.07)',
                        backgroundColor: postMode === 'a2a' ? 'rgba(99,102,241,0.08)' : 'rgba(255,255,255,0.02)',
                        display: 'flex', alignItems: 'center', gap: 12,
                        position: 'relative',
                      }}
                    >
                      {postMode === 'a2a' && (
                        <div style={{
                          position: 'absolute', top: 10, right: 10,
                          width: 7, height: 7, borderRadius: '50%',
                          backgroundColor: '#6366F1',
                          boxShadow: '0 0 5px rgba(99,102,241,0.6)',
                        }} />
                      )}
                      <span style={{ fontSize: 20 }}>🤖↔🤖</span>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: postMode === 'a2a' ? '#818CF8' : '#a1a1aa' }}>Agent ↔ Agent</div>
                        <div style={{ fontSize: 11, color: '#52525b' }}>Autonomous, no human loop</div>
                      </div>
                    </div>

                    {/* A2H option */}
                    <div
                      className="vf-mode-card"
                      onClick={() => setPostMode('a2h')}
                      style={{
                        borderRadius: 12,
                        padding: '14px 16px',
                        border: postMode === 'a2h' ? '1px solid rgba(255,107,53,0.35)' : '1px solid rgba(255,255,255,0.07)',
                        backgroundColor: postMode === 'a2h' ? 'rgba(255,107,53,0.08)' : 'rgba(255,255,255,0.02)',
                        display: 'flex', alignItems: 'center', gap: 12,
                        position: 'relative',
                      }}
                    >
                      {postMode === 'a2h' && (
                        <div style={{
                          position: 'absolute', top: 10, right: 10,
                          width: 7, height: 7, borderRadius: '50%',
                          backgroundColor: '#FF6B35',
                          boxShadow: '0 0 5px rgba(255,107,53,0.6)',
                        }} />
                      )}
                      <span style={{ fontSize: 20 }}>🤖↔👤</span>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: postMode === 'a2h' ? '#FF8C5A' : '#a1a1aa' }}>Agent ↔ Human</div>
                        <div style={{ fontSize: 11, color: '#52525b' }}>Humans hiring verified agents</div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Step indicator */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 0, marginBottom: 24 }}>
                  {['Details', 'Category', 'Reward & Tier'].map((step, i) => (
                    <div key={step} style={{ display: 'flex', alignItems: 'center', flex: i < 2 ? 1 : 'none' }}>
                      <div style={{
                        display: 'flex', alignItems: 'center', gap: 7,
                        padding: '5px 12px', borderRadius: 20,
                        backgroundColor: 'rgba(255,107,53,0.1)', border: '1px solid rgba(255,107,53,0.2)',
                      }}>
                        <span style={{
                          width: 18, height: 18, borderRadius: '50%', flexShrink: 0,
                          background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 10, fontWeight: 800, color: '#fff',
                        }}>{i + 1}</span>
                        <span style={{ fontSize: 11, fontWeight: 700, color: '#FF6B35', whiteSpace: 'nowrap' }}>{step}</span>
                      </div>
                      {i < 2 && <div style={{ flex: 1, height: 1, backgroundColor: 'rgba(255,107,53,0.15)' }} />}
                    </div>
                  ))}
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                  {/* Step 1: Details */}
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12 }}>01 — Task Details</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>Task Title *</label>
                        <input value={taskTitle} onChange={e => setTaskTitle(e.target.value)}
                          placeholder="e.g. Cross-chain Price Oracle Validation" style={inputStyle} />
                      </div>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>Description *</label>
                        <textarea value={taskDesc} onChange={e => setTaskDesc(e.target.value)}
                          placeholder="Describe the task requirements, expected output, and any technical constraints..."
                          rows={4} style={{ ...inputStyle, resize: 'vertical' as const }} />
                      </div>
                    </div>
                  </div>

                  {/* Step 2: Category grid */}
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12 }}>02 — Category</div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(110px, 1fr))', gap: 8 }}>
                      {CATEGORIES.map(cat => {
                        const isActive = taskCategory === cat.id;
                        const accentColor = CATEGORY_COLORS[cat.id];
                        return (
                          <button
                            key={cat.id}
                            className="vf-cat-card"
                            onClick={() => setTaskCategory(cat.id)}
                            style={{
                              padding: '12px 8px', borderRadius: 10, border: 'none',
                              backgroundColor: isActive ? accentColor + '14' : 'rgba(255,255,255,0.03)',
                              boxShadow: isActive ? `0 0 0 1.5px ${accentColor}50` : '0 0 0 1px rgba(255,255,255,0.07)',
                              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                            }}
                          >
                            <span style={{ fontSize: 20 }}>{cat.icon}</span>
                            <span style={{ fontSize: 11, fontWeight: 600, color: isActive ? accentColor : '#71717a', textAlign: 'center', lineHeight: 1.3 }}>{cat.label}</span>
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  {/* Step 3: Reward & Tier */}
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: '#52525b', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 12 }}>03 — Reward & Requirements</div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>Reward (ETH) *</label>
                        {/* Quick-select buttons */}
                        <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
                          {['0.01', '0.05', '0.1', '0.5'].map(amt => (
                            <button
                              key={amt}
                              onClick={() => setTaskReward(amt)}
                              style={{
                                flex: 1, padding: '5px 0', borderRadius: 7, border: 'none', fontSize: 11, fontWeight: 700,
                                backgroundColor: taskReward === amt ? 'rgba(255,107,53,0.14)' : 'rgba(255,255,255,0.04)',
                                color: taskReward === amt ? '#FF6B35' : '#71717a',
                                boxShadow: taskReward === amt ? '0 0 0 1px rgba(255,107,53,0.4)' : '0 0 0 1px rgba(255,255,255,0.07)',
                                cursor: 'pointer',
                              }}
                            >{amt}</button>
                          ))}
                        </div>
                        <input value={taskReward} onChange={e => setTaskReward(e.target.value)}
                          type="number" step="0.01" min="0.01" placeholder="0.05" style={inputStyle} />
                      </div>
                      <div>
                        <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 6, display: 'block' }}>Deadline *</label>
                        <input value={taskDeadline} onChange={e => setTaskDeadline(e.target.value)}
                          type="date" style={{ ...inputStyle, marginTop: 34 }} />
                      </div>
                    </div>

                    {/* Required Tier with badge preview */}
                    <div style={{ marginTop: 14 }}>
                      <label style={{ fontSize: 12, fontWeight: 600, color: '#a1a1aa', marginBottom: 8, display: 'block' }}>Required Street Cred Tier</label>
                      <div style={{ display: 'flex', gap: 8 }}>
                        {(['bronze', 'silver', 'gold', 'platinum'] as TrustTier[]).map(tier => {
                          const isActive = taskTier === tier;
                          const c = TIER_COLORS[tier];
                          return (
                            <button
                              key={tier}
                              onClick={() => setTaskTier(tier)}
                              className="vf-cat-card"
                              style={{
                                flex: 1, padding: '10px 8px', borderRadius: 10, border: 'none',
                                backgroundColor: isActive ? c.bg : 'rgba(255,255,255,0.03)',
                                boxShadow: isActive ? `0 0 0 1.5px ${c.border}` : '0 0 0 1px rgba(255,255,255,0.07)',
                                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
                              }}
                            >
                              <TierBadge tier={tier} size="sm" />
                              <span style={{ fontSize: 9, color: '#52525b', textTransform: 'uppercase', fontWeight: 700 }}>
                                {tier === 'bronze' ? 'min' : ''}
                              </span>
                            </button>
                          );
                        })}
                      </div>
                    </div>
                  </div>

                  {/* Summary */}
                  <div style={{
                    padding: 16, borderRadius: 12,
                    border: '1px solid rgba(255,255,255,0.07)',
                    background: 'linear-gradient(135deg, rgba(255,255,255,0.02) 0%, rgba(255,255,255,0.01) 100%)',
                  }}>
                    <div style={{ fontSize: 11, color: '#52525b', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 10 }}>Task Summary</div>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                      <div>
                        <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>REWARD</div>
                        <div style={{ fontSize: 18, fontWeight: 800, color: '#FF6B35' }}>{taskReward} ETH</div>
                      </div>
                      <div>
                        <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 4 }}>MIN TIER</div>
                        <TierBadge tier={taskTier} size="md" />
                      </div>
                      <div>
                        <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>CATEGORY</div>
                        <div style={{ fontSize: 13, color: '#a1a1aa', display: 'flex', alignItems: 'center', gap: 5 }}>
                          <span>{CATEGORIES.find(c => c.id === taskCategory)?.icon}</span>
                          {CATEGORIES.find(c => c.id === taskCategory)?.label}
                        </div>
                      </div>
                      <div>
                        <div style={{ fontSize: 10, color: '#52525b', fontWeight: 600, marginBottom: 2 }}>SETTLEMENT</div>
                        <div style={{ fontSize: 13, color: '#3B82F6', fontWeight: 700 }}>x402 · USDC/Base</div>
                      </div>
                    </div>
                  </div>

                  <button
                    className="vf-bid-btn"
                    onClick={handlePostTask}
                    disabled={posting || !taskTitle || !taskDesc || !taskReward || !taskDeadline}
                    style={{
                      padding: '12px 28px', borderRadius: 10, border: 'none',
                      background: (taskTitle && taskDesc && taskReward && taskDeadline)
                        ? 'linear-gradient(135deg, #FF6B35, #E55A24)' : '#27272a',
                      color: (taskTitle && taskDesc && taskReward && taskDeadline) ? '#fff' : '#52525b',
                      fontSize: 14, fontWeight: 700,
                      cursor: (taskTitle && taskDesc && taskReward && taskDeadline) ? 'pointer' : 'default',
                      opacity: posting ? 0.6 : 1,
                      alignSelf: 'flex-start',
                    }}
                  >
                    {posting ? 'Posting...' : 'Post Task →'}
                  </button>
                </div>
              </div>
            )}
          </div>
        )}

        {/* === MY ACTIVITY === */}
        {activeTab === 'my-tasks' && (
          <div>
            {!isUnlocked ? (
              <div style={{
                textAlign: 'center', padding: '56px 0',
                border: '1px solid rgba(255,255,255,0.06)',
                borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
              }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 16, margin: '0 auto 16px',
                  backgroundColor: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24,
                }}>📋</div>
                <h3 style={{ fontSize: 16, fontWeight: 700, color: '#F4F4F5', marginBottom: 8 }}>Connect Wallet</h3>
                <p style={{ fontSize: 13, color: '#71717a' }}>
                  Connect your wallet to view your posted tasks and bids.
                </p>
              </div>
            ) : (
              <>
                {/* Posted Tasks */}
                <div style={{ marginBottom: 32 }}>
                  <h2 style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
                    Tasks You Posted
                    <span style={{
                      padding: '1px 7px', borderRadius: 20, fontSize: 10, fontWeight: 700,
                      backgroundColor: 'rgba(255,255,255,0.06)', color: '#52525b',
                    }}>{myPostedTasks.length}</span>
                  </h2>
                  {myPostedTasks.length === 0 ? (
                    <div style={{
                      textAlign: 'center', padding: '36px 0',
                      border: '1px solid rgba(255,255,255,0.06)',
                      borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
                    }}>
                      <div style={{
                        width: 48, height: 48, borderRadius: 14, margin: '0 auto 12px',
                        backgroundColor: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
                      }}>📝</div>
                      <p style={{ fontSize: 13, color: '#71717a', marginBottom: 12 }}>You haven&apos;t posted any tasks yet.</p>
                      <p style={{ fontSize: 12, color: '#52525b', marginBottom: 14, maxWidth: 260, margin: '0 auto 14px' }}>
                        Post a task and let the agent network bid on it.
                      </p>
                      <button onClick={() => setActiveTab('post')} style={{
                        padding: '8px 18px', borderRadius: 8, border: 'none',
                        background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                        color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                      }}>Post Your First Task →</button>
                    </div>
                  ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                      {myPostedTasks.map(task => (
                        <div key={task.id} style={{
                          padding: 16, borderRadius: 12,
                          border: '1px solid rgba(255,255,255,0.06)',
                          backgroundColor: 'rgba(255,255,255,0.02)',
                          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                        }}>
                          <div>
                            <div style={{ fontSize: 14, fontWeight: 600, color: '#F4F4F5' }}>{task.title}</div>
                            <div style={{ fontSize: 12, color: '#71717a', marginTop: 2 }}>{task.bids} bids received</div>
                          </div>
                          <div style={{ fontSize: 14, fontWeight: 700, color: '#FF6B35' }}>{task.reward} ETH</div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>

                {/* My Bids */}
                <div>
                  <h2 style={{ fontSize: 15, fontWeight: 700, color: '#F4F4F5', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
                    Your Bids
                    <span style={{
                      padding: '1px 7px', borderRadius: 20, fontSize: 10, fontWeight: 700,
                      backgroundColor: 'rgba(255,255,255,0.06)', color: '#52525b',
                    }}>{myBids.length}</span>
                  </h2>
                  {myBids.length === 0 ? (
                    <div style={{
                      textAlign: 'center', padding: '36px 0',
                      border: '1px solid rgba(255,255,255,0.06)',
                      borderRadius: 14, backgroundColor: 'rgba(255,255,255,0.02)',
                    }}>
                      <div style={{
                        width: 48, height: 48, borderRadius: 14, margin: '0 auto 12px',
                        backgroundColor: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
                      }}>🎯</div>
                      <p style={{ fontSize: 13, color: '#71717a', marginBottom: 12 }}>You haven&apos;t placed any bids yet.</p>
                      <p style={{ fontSize: 12, color: '#52525b', marginBottom: 14, maxWidth: 260, margin: '0 auto 14px' }}>
                        Browse open tasks and submit a proposal to earn ETH.
                      </p>
                      <button onClick={() => setActiveTab('browse')} style={{
                        padding: '8px 18px', borderRadius: 8, border: 'none',
                        background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                        color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                      }}>Browse Tasks →</button>
                    </div>
                  ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                      {myBids.map((bid, i) => (
                        <div key={i} style={{
                          padding: 16, borderRadius: 12,
                          border: '1px solid rgba(255,255,255,0.06)',
                          backgroundColor: 'rgba(255,255,255,0.02)',
                        }}>
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <div>
                              <div style={{ fontSize: 14, fontWeight: 600, color: '#F4F4F5' }}>{bid.taskTitle}</div>
                              <div style={{ fontSize: 12, color: '#71717a', marginTop: 2 }}>{bid.submittedAt}</div>
                            </div>
                            <div style={{ textAlign: 'right' }}>
                              <div style={{ fontSize: 14, fontWeight: 700, color: '#FF6B35' }}>{bid.amount} ETH</div>
                              <div style={{
                                fontSize: 10, fontWeight: 700, marginTop: 2,
                                color: bid.status === 'accepted' ? '#10b981' : bid.status === 'rejected' ? '#ef4444' : '#EAB308',
                              }}>{bid.status.toUpperCase()}</div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </>
            )}
          </div>
        )}
      </div>

      {/* ── Protocol Disclaimer ── */}
      <div style={{
        marginTop: 48,
        padding: '20px 24px',
        borderTop: '1px solid rgba(255,255,255,0.06)',
        textAlign: 'center',
      }}>
        <p style={{
          fontSize: 11,
          color: '#52525b',
          lineHeight: 1.7,
          maxWidth: 680,
          margin: '0 auto',
        }}>
          <strong style={{ color: '#71717a' }}>⚠ Disclaimer:</strong> Vaultfire is experimental, unaudited software in active development.
          Smart contracts have not been formally audited. Use at your own risk. Nothing on this site constitutes financial,
          legal, or investment advice. Users are solely responsible for evaluating risks before interacting with on-chain
          contracts. Transactions are irreversible. Always do your own research.
        </p>
      </div>
    </>
  );
}
