// affiliate-dashboard.jsx — Logged-in affiliate dashboard

function AffiliateDashboard() {
  const [platform, setPlatform] = React.useState('kick');
  const [range, setRange] = React.useState('30d');
  const [copied, setCopied] = React.useState(false);

  const handleCopy = () => {
    navigator.clipboard?.writeText('viewbot.to/r/marcus');
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  return (
    <Stage>
      <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', minHeight: '100%' }}>
        <DashSidebar active="affiliate"/>
        <div style={{ padding: '24px 40px 80px', maxWidth: 1280 }}>
          <DashTopbar platform={platform} setPlatform={setPlatform}/>

          <div className="vb-row" style={{ marginTop: 28, marginBottom: 28, alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
            <div>
              <div className="vb-row" style={{ gap: 10, marginBottom: 8 }}>
                <h1 className="vb-h1">Affiliate dashboard</h1>
                <span style={{ padding: '4px 10px', borderRadius: 999, background: 'oklch(0.88 0.27 142 / 0.14)', border: '1px solid oklch(0.88 0.27 142 / 0.3)', color: 'oklch(0.88 0.27 142)', fontSize: 11, fontWeight: 600, letterSpacing: '0.04em' }}>PRO TIER</span>
              </div>
              <p className="vb-body" style={{ fontSize: 14, color: 'var(--vb-fg-2)' }}>You're <span style={{ color: 'oklch(0.62 0.23 295)', fontWeight: 600 }}>13 referrals away</span> from Elite tier (40% commission). Next payout: <span style={{ color: 'var(--vb-fg-1)', fontWeight: 600 }}>Mon, Apr 30</span>.</p>
            </div>
            <span className="vb-spacer"/>
            <Btn variant="glass" icon={<IconReceipt size={14}/>}>Tax docs</Btn>
            <Btn variant="primary" icon={<IconPlus size={14}/>} style={{ marginLeft: 10 }}>Request payout</Btn>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
            <Glass style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
              <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, background: 'radial-gradient(circle, oklch(0.88 0.27 142 / 0.2), transparent 65%)', pointerEvents: 'none' }}/>
              <div style={{ position: 'relative' }}>
                <div className="vb-row" style={{ marginBottom: 12 }}>
                  <span className="vb-caption">Available balance</span>
                  <span className="vb-spacer"/>
                  <span style={{ fontSize: 10, color: 'oklch(0.85 0.18 142)', display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 5, height: 5, borderRadius: 3, background: 'oklch(0.85 0.18 142)' }}/>READY</span>
                </div>
                <span className="vb-mono" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em', display: 'block', marginBottom: 4, color: 'oklch(0.88 0.27 142)' }}>$2,847.<span style={{ fontSize: 22, opacity: 0.7 }}>20</span></span>
                <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>$184.40 pending · clears in 7d</span>
              </div>
            </Glass>
            <Glass style={{ padding: 22 }}>
              <span className="vb-caption" style={{ display: 'block', marginBottom: 12 }}>Active referrals</span>
              <div className="vb-row" style={{ alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                <span className="vb-mono" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>87</span>
                <span style={{ fontSize: 12, color: 'oklch(0.85 0.18 142)' }}>+12 this week</span>
              </div>
              <Sparkline data={[42,46,48,52,55,58,62,65,68,72,75,78,82,85,87]} color="oklch(0.62 0.23 295)" width={240} height={36}/>
            </Glass>
            <Glass style={{ padding: 22 }}>
              <span className="vb-caption" style={{ display: 'block', marginBottom: 12 }}>Lifetime earned</span>
              <span className="vb-mono" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em', display: 'block', marginBottom: 4 }}>$18,420</span>
              <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>across 13 months</span>
            </Glass>
            <Glass style={{ padding: 22 }}>
              <span className="vb-caption" style={{ display: 'block', marginBottom: 12 }}>Conversion rate</span>
              <div className="vb-row" style={{ alignItems: 'baseline', gap: 8, marginBottom: 4 }}>
                <span className="vb-mono" style={{ fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em', color: 'oklch(0.7 0.23 295)' }}>14.2<span style={{ fontSize: 22, color: 'var(--vb-fg-2)' }}>%</span></span>
                <span style={{ fontSize: 12, color: 'oklch(0.85 0.18 142)' }}>+2.1pp</span>
              </div>
              <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>4,182 clicks → 593 signups</span>
            </Glass>
          </div>

          <Glass style={{ padding: 24, marginBottom: 24, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: -80, right: -40, width: 320, height: 220, background: 'radial-gradient(ellipse, oklch(0.62 0.23 295 / 0.18), transparent 65%)', pointerEvents: 'none' }}/>
            <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 24, alignItems: 'center' }}>
              <div>
                <span className="vb-caption" style={{ display: 'block', marginBottom: 8 }}>Your referral link</span>
                <div className="vb-row" style={{ gap: 0, padding: 4, background: 'rgba(0,0,0,0.3)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 14 }}>
                  <div className="vb-row" style={{ flex: 1, padding: '0 14px', gap: 8, minWidth: 0 }}>
                    <IconLink size={14} style={{ color: 'var(--vb-fg-3)', flexShrink: 0 }}/>
                    <span className="vb-mono" style={{ fontSize: 13, color: 'var(--vb-fg-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>viewbot.to/r/marcus</span>
                  </div>
                  <Btn variant="glass" size="sm" icon={copied ? <IconCheck size={13}/> : <IconCopy size={13}/>} onClick={handleCopy}>
                    {copied ? 'Copied' : 'Copy'}
                  </Btn>
                  <Btn variant="primary" size="sm" iconRight={<IconArrow size={12}/>} style={{ marginLeft: 4 }}>Generate UTM</Btn>
                </div>
                <div className="vb-row" style={{ gap: 16, marginTop: 14, fontSize: 11, color: 'var(--vb-fg-3)', flexWrap: 'wrap' }}>
                  <span>4,182 clicks all-time</span>
                  <span style={{ width: 3, height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.2)' }}/>
                  <span>90-day attribution + fingerprint</span>
                  <span style={{ width: 3, height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.2)' }}/>
                  <span>Lifetime customer tracking</span>
                </div>
              </div>
              <div className="vb-row" style={{ gap: 12, justifyContent: 'flex-end' }}>
                <QrPreview/>
                <div className="vb-col" style={{ gap: 6 }}>
                  <Btn variant="glass" size="sm" icon={<IconCopy size={12}/>}>Stream panel</Btn>
                  <Btn variant="glass" size="sm" icon={<IconCopy size={12}/>}>Discord embed</Btn>
                  <Btn variant="glass" size="sm" icon={<IconCopy size={12}/>}>X graphic</Btn>
                </div>
              </div>
            </div>
          </Glass>

          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, marginBottom: 24 }}>
            <Glass style={{ padding: 28 }}>
              <div className="vb-row" style={{ marginBottom: 20 }}>
                <div>
                  <h3 className="vb-h3">Earnings</h3>
                  <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>Recurring + one-time, last {range}</span>
                </div>
                <span className="vb-spacer"/>
                <Tabs items={[{value:'7d',label:'7D'},{value:'30d',label:'30D'},{value:'90d',label:'90D'},{value:'all',label:'ALL'}]} value={range} onChange={setRange}/>
              </div>
              <EarningsChart/>
            </Glass>
            <TierProgressCard/>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16 }}>
            <ReferralsTable/>
            <PayoutsHistory/>
          </div>
        </div>
      </div>
    </Stage>
  );
}

function QrPreview() {
  const cells = React.useMemo(() => Array.from({ length: 169 }, () => Math.random() > 0.55), []);
  return (
    <div style={{ width: 76, height: 76, padding: 6, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 12 }}>
      <div style={{ width: '100%', height: '100%', display: 'grid', gridTemplateColumns: 'repeat(13, 1fr)', gap: 1 }}>
        {cells.map((on, i) => (
          <span key={i} style={{ background: on ? 'var(--vb-fg-0)' : 'transparent', borderRadius: 1 }}/>
        ))}
      </div>
    </div>
  );
}

function TierProgressCard() {
  const current = 87;
  const eliteTarget = 100;
  const pct = (current / eliteTarget) * 100;
  return (
    <Glass style={{ padding: 28, position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: -60, right: -60, width: 240, height: 240, background: 'radial-gradient(circle, oklch(0.62 0.23 295 / 0.22), transparent 65%)', pointerEvents: 'none' }}/>
      <div style={{ position: 'relative' }}>
        <div className="vb-row" style={{ marginBottom: 6 }}>
          <span className="vb-caption">Tier progress</span>
          <span className="vb-spacer"/>
          <span style={{ fontSize: 10, color: 'var(--vb-fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Auto-promotes May 1</span>
        </div>
        <h3 className="vb-h3" style={{ marginBottom: 4 }}>Almost <span style={{ fontStyle: 'italic' }}>Elite</span>.</h3>
        <p style={{ fontSize: 12, color: 'var(--vb-fg-2)', marginBottom: 22 }}>13 more active referrals to unlock 40% commission, same-day payouts, and your dedicated manager.</p>

        <div className="vb-row" style={{ alignItems: 'baseline', marginBottom: 8 }}>
          <span className="vb-mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{current}</span>
          <span className="vb-mono" style={{ fontSize: 13, color: 'var(--vb-fg-3)', marginLeft: 4 }}>/ {eliteTarget}</span>
          <span className="vb-spacer"/>
          <span className="vb-mono" style={{ fontSize: 13, color: 'oklch(0.7 0.23 295)', fontWeight: 600 }}>{Math.round(pct)}%</span>
        </div>
        <div style={{ height: 6, background: 'rgba(255,255,255,0.06)', borderRadius: 3, overflow: 'hidden', marginBottom: 24 }}>
          <div style={{ height: '100%', width: `${pct}%`, background: 'linear-gradient(90deg, oklch(0.88 0.27 142), oklch(0.7 0.23 295))', borderRadius: 3, boxShadow: '0 0 14px oklch(0.7 0.23 295 / 0.6)' }}/>
        </div>

        <div className="vb-col" style={{ gap: 10 }}>
          <TierStep name="Starter" pct="15%" status="done"/>
          <TierStep name="Pro" pct="25%" status="current"/>
          <TierStep name="Elite" pct="40%" status="locked"/>
        </div>
      </div>
    </Glass>
  );
}

function TierStep({ name, pct, status }) {
  const colors = {
    done: { bg: 'oklch(0.88 0.27 142 / 0.14)', border: 'oklch(0.88 0.27 142 / 0.3)', text: 'oklch(0.88 0.27 142)', dot: 'oklch(0.88 0.27 142)' },
    current: { bg: 'rgba(255,255,255,0.05)', border: 'rgba(255,255,255,0.12)', text: 'var(--vb-fg-0)', dot: 'oklch(0.7 0.23 295)' },
    locked: { bg: 'transparent', border: 'rgba(255,255,255,0.05)', text: 'var(--vb-fg-3)', dot: 'rgba(255,255,255,0.15)' },
  }[status];
  return (
    <div className="vb-row" style={{ gap: 12, padding: '10px 12px', borderRadius: 10, background: colors.bg, border: `1px solid ${colors.border}` }}>
      <span style={{ width: 10, height: 10, borderRadius: 5, background: colors.dot, boxShadow: status === 'current' ? `0 0 10px ${colors.dot}` : 'none', flexShrink: 0 }}/>
      <span style={{ fontSize: 13, fontWeight: 600, color: colors.text }}>{name}</span>
      <span className="vb-spacer"/>
      <span className="vb-mono" style={{ fontSize: 12, color: colors.text, fontWeight: 600 }}>{pct}</span>
      {status === 'done' && <IconCheck size={12} style={{ color: colors.text }}/>}
      {status === 'locked' && <IconLock size={11} style={{ color: colors.text }}/>}
    </div>
  );
}

function EarningsChart() {
  const days = 30;
  const data = React.useMemo(() => Array.from({ length: days }, (_, i) => ({
    rec: 40 + Math.sin(i * 0.4) * 18 + i * 1.6 + Math.random() * 8,
    one: 8 + Math.random() * 16 + (i > 18 ? 12 : 0),
  })), []);
  const max = Math.max(...data.map((d) => d.rec + d.one));
  const w = 700, h = 200;
  const bw = w / days * 0.7;
  return (
    <div>
      <svg width="100%" height={h + 24} viewBox={`0 0 ${w} ${h + 24}`} preserveAspectRatio="none" style={{ display: 'block' }}>
        {[0.25, 0.5, 0.75].map((p) => (
          <line key={p} x1="0" x2={w} y1={h * p} y2={h * p} stroke="rgba(255,255,255,0.04)"/>
        ))}
        {data.map((d, i) => {
          const x = (i / days) * w + (w / days - bw) / 2;
          const recH = (d.rec / max) * h * 0.9;
          const oneH = (d.one / max) * h * 0.9;
          return (
            <g key={i}>
              <rect x={x} y={h - recH} width={bw} height={recH} fill="oklch(0.88 0.27 142)" opacity="0.85" rx="2"/>
              <rect x={x} y={h - recH - oneH} width={bw} height={oneH} fill="oklch(0.7 0.23 295)" opacity="0.9" rx="2"/>
            </g>
          );
        })}
      </svg>
      <div className="vb-row" style={{ gap: 18, marginTop: 14, flexWrap: 'wrap' }}>
        <div className="vb-row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 2, background: 'oklch(0.88 0.27 142)' }}/><span style={{ fontSize: 11, color: 'var(--vb-fg-2)' }}>Recurring · $1,847</span></div>
        <div className="vb-row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, borderRadius: 2, background: 'oklch(0.7 0.23 295)' }}/><span style={{ fontSize: 11, color: 'var(--vb-fg-2)' }}>One-time bounties · $1,000</span></div>
        <span className="vb-spacer"/>
        <span className="vb-mono" style={{ fontSize: 12, color: 'var(--vb-fg-3)' }}>Avg $94.90 / day</span>
      </div>
    </div>
  );
}

const REFS = [
  { user: 'twitchqueen22', joined: 'Apr 24', status: 'active', spend: 184, comm: 46.00, plat: 'twitch', hue: 295 },
  { user: 'kick_destroyer', joined: 'Apr 22', status: 'active', spend: 248, comm: 62.00, plat: 'kick', hue: 142 },
  { user: 'streamer_sara', joined: 'Apr 19', status: 'active', spend: 96, comm: 24.00, plat: 'twitch', hue: 295 },
  { user: 'bigmoves_live', joined: 'Apr 16', status: 'active', spend: 412, comm: 103.00, plat: 'kick', hue: 142 },
  { user: 'pixelpal', joined: 'Apr 11', status: 'pending', spend: 0, comm: 0, plat: 'twitch', hue: 295 },
  { user: 'lategame', joined: 'Apr 08', status: 'active', spend: 156, comm: 39.00, plat: 'kick', hue: 142 },
];

function ReferralsTable() {
  return (
    <Glass style={{ padding: 0, overflow: 'hidden' }}>
      <div className="vb-row" style={{ padding: '20px 24px', borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
        <div>
          <h3 className="vb-h3">Recent referrals</h3>
          <span style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>87 active · 12 this week</span>
        </div>
        <span className="vb-spacer"/>
        <Btn variant="glass" size="sm" iconRight={<IconArrow size={12}/>}>View all</Btn>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.04)' }}>
            {['User', 'Joined', 'Status', 'Spend', 'Your cut'].map((h) => (
              <th key={h} style={{ padding: '12px 24px', fontSize: 10, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--vb-fg-3)', textAlign: h === 'Spend' || h === 'Your cut' ? 'right' : 'left' }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {REFS.map((r) => (
            <tr key={r.user} style={{ borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
              <td style={{ padding: '14px 24px' }}>
                <div className="vb-row" style={{ gap: 10 }}>
                  <Avatar name={r.user} size={26} hue={r.hue}/>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{r.user}</span>
                  <PlatformPill platform={r.plat}/>
                </div>
              </td>
              <td style={{ padding: '14px 24px', fontSize: 12, color: 'var(--vb-fg-2)' }}>{r.joined}</td>
              <td style={{ padding: '14px 24px' }}>
                {r.status === 'active' ? (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px', borderRadius: 999, background: 'oklch(0.85 0.18 142 / 0.12)', color: 'oklch(0.85 0.18 142)', fontSize: 11, fontWeight: 500 }}>
                    <span style={{ width: 5, height: 5, borderRadius: 3, background: 'oklch(0.85 0.18 142)' }}/>Active
                  </span>
                ) : (
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 9px', borderRadius: 999, background: 'rgba(255,255,255,0.05)', color: 'var(--vb-fg-3)', fontSize: 11, fontWeight: 500 }}>
                    <IconClock size={10}/>Pending
                  </span>
                )}
              </td>
              <td style={{ padding: '14px 24px', textAlign: 'right' }} className="vb-mono">
                <span style={{ fontSize: 13, color: 'var(--vb-fg-1)' }}>{r.spend ? `$${r.spend.toFixed(2)}` : '—'}</span>
              </td>
              <td style={{ padding: '14px 24px', textAlign: 'right' }} className="vb-mono">
                <span style={{ fontSize: 13, fontWeight: 600, color: r.comm ? 'oklch(0.88 0.27 142)' : 'var(--vb-fg-3)' }}>{r.comm ? `+$${r.comm.toFixed(2)}` : '—'}</span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </Glass>
  );
}

const PAYOUTS = [
  { date: 'Apr 22, 2026', method: 'USDT', amount: 412.80, status: 'paid', tx: '0x4f2a…891c' },
  { date: 'Apr 15, 2026', method: 'USDT', amount: 286.40, status: 'paid', tx: '0x8b1d…4c20' },
  { date: 'Apr 08, 2026', method: 'BTC',  amount: 318.20, status: 'paid', tx: 'bc1q…7f9a' },
  { date: 'Apr 01, 2026', method: 'USDT', amount: 254.10, status: 'paid', tx: '0x1f9e…3a72' },
  { date: 'Mar 25, 2026', method: 'BTC',  amount: 198.40, status: 'paid', tx: 'bc1q…2e88' },
];

function PayoutsHistory() {
  return (
    <Glass style={{ padding: 24 }}>
      <div className="vb-row" style={{ marginBottom: 18 }}>
        <h3 className="vb-h3">Payouts</h3>
        <span className="vb-spacer"/>
        <Btn variant="ghost" size="sm" iconRight={<IconArrow size={12}/>}>All</Btn>
      </div>

      <div style={{ padding: 14, borderRadius: 14, background: 'oklch(0.88 0.27 142 / 0.06)', border: '1px solid oklch(0.88 0.27 142 / 0.18)', marginBottom: 14 }}>
        <div className="vb-row" style={{ marginBottom: 6 }}>
          <span style={{ fontSize: 10, color: 'oklch(0.88 0.27 142)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>Next payout</span>
          <span className="vb-spacer"/>
          <span style={{ fontSize: 11, color: 'var(--vb-fg-2)' }}>Mon, Apr 30</span>
        </div>
        <div className="vb-row" style={{ alignItems: 'baseline' }}>
          <span className="vb-mono" style={{ fontSize: 22, fontWeight: 700, color: 'oklch(0.88 0.27 142)' }}>$2,847.20</span>
          <span className="vb-spacer"/>
          <span className="vb-mono" style={{ fontSize: 11, color: 'var(--vb-fg-3)' }}>via USDT</span>
        </div>
      </div>

      <div className="vb-col" style={{ gap: 4 }}>
        {PAYOUTS.map((p, i) => (
          <div key={i} className="vb-row" style={{ padding: '10px 0', gap: 12, borderBottom: i < PAYOUTS.length - 1 ? '1px solid rgba(255,255,255,0.04)' : 'none' }}>
            <span style={{ width: 26, height: 26, borderRadius: 7, background: p.method === 'USDT' ? 'oklch(0.88 0.27 142 / 0.16)' : 'oklch(0.78 0.16 60 / 0.16)', color: p.method === 'USDT' ? 'oklch(0.88 0.27 142)' : 'oklch(0.85 0.18 60)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, fontFamily: 'var(--vb-font-mono)' }}>{p.method === 'USDT' ? '₮' : '₿'}</span>
            <div className="vb-col" style={{ flex: 1, minWidth: 0, gap: 1 }}>
              <span style={{ fontSize: 12, fontWeight: 500 }}>{p.date}</span>
              <span className="vb-mono" style={{ fontSize: 10, color: 'var(--vb-fg-3)' }}>{p.tx}</span>
            </div>
            <span className="vb-mono" style={{ fontSize: 13, fontWeight: 600 }}>${p.amount.toFixed(2)}</span>
          </div>
        ))}
      </div>
    </Glass>
  );
}

Object.assign(window, { AffiliateDashboard });
