/* screen-creator-extra-actions.jsx — Interactive prototypes for Earnings + Media Kit
   ─────────────────────────────────────────────────────────────────────────────────
   Exposes:
     <CreatorExtraActionsHost />  – mounts overlays controlled by the hook
     useCreatorActions()          – returns API
       .openPayoutDetail(payout)
       .openWithdraw()
       .openStatements()
       .openPublicMediaKit()
       .openShareKit()
       .openAddPost()
       .toast(message, kind?)
*/
/* global React, Modal, Drawer, Toast, Avatar, Pill, Icon, Donut, BarChart, Sparkline, Counter */

// ── 1. Payout detail modal ─────────────────────────────────────────
function PayoutDetailModal({ open, onClose, payout, onToast }) {
  if (!payout) return null;
  const [d, source, campaign, gross, fee, net, status] = payout;
  return (
    <Modal open={open} onClose={onClose} width={560}
      title={`Payout · ${campaign}`}
      subtitle={`${d}, 2026 · ${source}`}
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Close</button>
          <button onClick={() => { onToast('Invoice INV-2026-' + Math.floor(Math.random() * 9999) + '.pdf downloaded'); onClose(); }} className="btn btn-primary btn-sm">{Icon.external} Download invoice</button>
        </div>
      }>
      <div style={{ padding: 16, background: 'linear-gradient(135deg, #79FEE7 0%, #009CFF 100%)', borderRadius: 12, color: 'var(--ink)', marginBottom: 16 }}>
        <div className="cap-label">Net to your account</div>
        <div className="font-display tabular" style={{ fontSize: 44, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1, marginTop: 4 }}>
          $<Counter to={net} duration={1200} />
        </div>
        <div className="row items-center gap-8 mt-2">
          <Pill variant={status === 'paid' ? 'mint' : 'yellow'}>{status}</Pill>
          {status === 'paid' && <span style={{ fontSize: 11, fontWeight: 600 }}>Arrived {d}, 2026</span>}
          {status === 'pending' && <span style={{ fontSize: 11, fontWeight: 600 }}>Expected within 7 business days</span>}
        </div>
      </div>

      <div className="cap-label mb-2">Breakdown</div>
      <table className="tbl" style={{ marginBottom: 16 }}>
        <tbody>
          <tr>
            <td className="muted">Gross</td>
            <td className="text-right tabular bold">${gross}</td>
          </tr>
          <tr>
            <td className="muted">Platform fee (5%)</td>
            <td className="text-right tabular" style={{ color: 'var(--ink-soft)' }}>-${fee}</td>
          </tr>
          <tr style={{ borderTop: '1px solid var(--line)' }}>
            <td className="bold">Net</td>
            <td className="text-right font-display bold tabular" style={{ fontSize: 18 }}>${net}</td>
          </tr>
        </tbody>
      </table>

      <div className="cap-label mb-2">Destination</div>
      <div className="row items-center gap-12" style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 10, marginBottom: 12 }}>
        <div style={{ fontSize: 22 }}>🏦</div>
        <div className="flex-1">
          <div className="bold" style={{ fontSize: 13 }}>Vietcombank ··· 8421</div>
          <div className="muted" style={{ fontSize: 11 }}>Primary · VND auto-converted at $1 = ₫25,420</div>
        </div>
      </div>

      <div className="cap-label mb-2">Timeline</div>
      <div style={{ position: 'relative', paddingLeft: 4 }}>
        {[
          ['Invoice issued', d + ', 2026 · 10:14 AM', 'done'],
          ['Reviewed & approved', d + ', 2026 · 02:32 PM', 'done'],
          [status === 'paid' ? 'Sent to your bank' : 'Awaiting processing', d + ', 2026 · 05:08 PM', status === 'paid' ? 'done' : 'active'],
          [status === 'paid' ? 'Arrived in account' : 'Will arrive', d + ', 2026', status === 'paid' ? 'done' : 'pending'],
        ].map(([l, w, st], i) => (
          <div key={i} className="row items-center gap-12" style={{ padding: '6px 0' }}>
            <span style={{
              width: 18, height: 18, borderRadius: 999, flexShrink: 0,
              background: st === 'done' ? 'var(--mint-deep)' : st === 'active' ? 'var(--yellow)' : 'var(--line)',
              display: 'grid', placeItems: 'center', color: 'white', fontSize: 10, fontWeight: 800
            }}>{st === 'done' ? '✓' : ''}</span>
            <span className="bold" style={{ fontSize: 12.5, color: st === 'pending' ? 'var(--ink-soft)' : 'var(--ink)' }}>{l}</span>
            <span className="muted tabular" style={{ fontSize: 11, marginLeft: 'auto' }}>{w}</span>
          </div>
        ))}
      </div>
    </Modal>
  );
}

// ── 2. Withdraw flow (multi-step modal) ────────────────────────────
function WithdrawModal({ open, onClose, onToast }) {
  const [step, setStep] = React.useState(1); // 1: amount, 2: method, 3: confirm, 4: success
  const [amount, setAmount] = React.useState(1080);
  const [method, setMethod] = React.useState('vcb');
  const available = 1080;

  React.useEffect(() => { if (open) setStep(1); }, [open]);

  const methods = [
    { id: 'vcb', l: 'Vietcombank ··· 8421', sub: 'Primary · VND · 1-2 business days', icon: '🏦', fee: 0 },
    { id: 'paypal', l: 'PayPal · linh@gmail.com', sub: 'Backup · USD · instant', icon: '💳', fee: 4 },
    { id: 'wise', l: 'Wise USD account', sub: 'USD wire · 1-3 business days', icon: '💵', fee: 2 },
  ];
  const selectedMethod = methods.find(m => m.id === method);
  const fee = selectedMethod?.fee || 0;
  const net = amount - fee;

  const close = () => { onClose(); setTimeout(() => setStep(1), 200); };

  return (
    <Modal open={open} onClose={close} width={520}
      title={step === 4 ? 'Withdrawal sent' : 'Withdraw earnings'}
      subtitle={step === 4 ? null : `Available · $${available.toLocaleString()} · Step ${step} of 3`}
      footer={
        step === 4 ? (
          <button onClick={close} className="btn btn-primary btn-sm">Done</button>
        ) : (
          <div className="row gap-8">
            {step > 1 && <button onClick={() => setStep(s => s - 1)} className="btn btn-ghost btn-sm">Back</button>}
            <button onClick={close} className="btn btn-ghost btn-sm">Cancel</button>
            {step < 3 ? (
              <button onClick={() => setStep(s => s + 1)} className="btn btn-primary btn-sm"
                disabled={step === 1 && (amount <= 0 || amount > available)}
                style={{ opacity: (step === 1 && (amount <= 0 || amount > available)) ? 0.4 : 1 }}>
                Continue {Icon.arrow}
              </button>
            ) : (
              <button onClick={() => { setStep(4); onToast(`$${net} on its way to ${selectedMethod.l}`, 'success'); }} className="btn btn-primary btn-sm">Confirm withdrawal</button>
            )}
          </div>
        )
      }>
      {/* Stepper */}
      {step < 4 && (
        <div className="row items-center gap-6 mb-6">
          {[
            ['Amount', 1], ['Method', 2], ['Confirm', 3]
          ].map(([l, n], i, arr) => (
            <React.Fragment key={n}>
              <div className="row items-center gap-6">
                <span style={{
                  width: 22, height: 22, borderRadius: 999, display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11,
                  background: n <= step ? 'var(--ink)' : 'var(--bg-soft)',
                  color: n <= step ? 'white' : 'var(--ink-soft)'
                }}>{n < step ? '✓' : n}</span>
                <span style={{ fontSize: 12, fontWeight: 700, color: n === step ? 'var(--ink)' : 'var(--ink-soft)' }}>{l}</span>
              </div>
              {i < arr.length - 1 && <div style={{ flex: 1, height: 2, background: n < step ? 'var(--ink)' : 'var(--line)' }} />}
            </React.Fragment>
          ))}
        </div>
      )}

      {step === 1 && (
        <div>
          <label className="cap-label mb-2">Amount to withdraw</label>
          <div className="row items-center gap-12" style={{ padding: '14px 16px', background: 'var(--bg-soft)', borderRadius: 12 }}>
            <span className="font-display bold" style={{ fontSize: 32, color: 'var(--ink-soft)' }}>$</span>
            <input
              type="number" value={amount} onChange={e => setAmount(Math.max(0, parseInt(e.target.value) || 0))}
              style={{ flex: 1, border: 0, background: 'transparent', fontSize: 32, fontWeight: 700, fontFamily: 'Space Grotesk', letterSpacing: '-0.02em', outline: 'none' }} />
            <button onClick={() => setAmount(available)} className="btn btn-ghost btn-sm">Max</button>
          </div>
          <div className="row gap-6 mt-3" style={{ flexWrap: 'wrap' }}>
            {[100, 250, 500, 1000].map(v => (
              <button key={v} onClick={() => setAmount(v)} style={{
                padding: '6px 12px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
                background: amount === v ? 'var(--ink)' : 'var(--bg-soft)',
                color: amount === v ? 'white' : 'var(--ink-soft)', fontWeight: 700, fontSize: 12
              }}>${v}</button>
            ))}
          </div>
          {amount > available && <div className="mt-3" style={{ color: 'var(--pink-hot)', fontSize: 12 }}>⚠️ Amount exceeds available balance</div>}
          <div className="muted mt-4" style={{ fontSize: 11.5 }}>You'll be paid in your account currency. Minimum withdrawal: $20.</div>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {methods.map(m => (
            <label key={m.id} className="row items-center gap-12" style={{
              padding: 14, borderRadius: 12, cursor: 'pointer',
              background: method === m.id ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
              border: '2px solid ' + (method === m.id ? 'var(--cyan)' : 'transparent')
            }}>
              <input type="radio" checked={method === m.id} onChange={() => setMethod(m.id)} />
              <div style={{ fontSize: 22 }}>{m.icon}</div>
              <div className="flex-1">
                <div className="bold">{m.l}</div>
                <div className="muted" style={{ fontSize: 11 }}>{m.sub}</div>
              </div>
              <div className="text-right">
                <div className="cap-label" style={{ fontSize: 9 }}>Fee</div>
                <div className="bold tabular" style={{ fontSize: 13 }}>{m.fee ? '$' + m.fee : 'Free'}</div>
              </div>
            </label>
          ))}
        </div>
      )}

      {step === 3 && (
        <div>
          <div className="card-elevated" style={{ padding: 20, background: 'linear-gradient(135deg, #79FEE7, #009CFF)', color: 'var(--ink)', marginBottom: 16 }}>
            <div className="cap-label">You'll receive</div>
            <div className="font-display tabular" style={{ fontSize: 56, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1, marginTop: 4 }}>
              ${net.toLocaleString()}
            </div>
            <div style={{ fontSize: 12, fontWeight: 600, marginTop: 6 }}>To {selectedMethod.l} · arrives in {selectedMethod.sub.includes('instant') ? 'minutes' : '1-2 business days'}</div>
          </div>
          <table className="tbl">
            <tbody>
              <tr><td className="muted">Withdraw</td><td className="text-right tabular">${amount}</td></tr>
              <tr><td className="muted">Network fee</td><td className="text-right tabular">-${fee}</td></tr>
              <tr><td className="muted">Exchange rate</td><td className="text-right tabular">$1 = ₫25,420</td></tr>
              <tr style={{ borderTop: '1px solid var(--line)' }}>
                <td className="bold">Net to bank</td>
                <td className="text-right font-display bold tabular" style={{ fontSize: 16 }}>${net} ≈ ₫{(net * 25420).toLocaleString()}</td>
              </tr>
            </tbody>
          </table>
        </div>
      )}

      {step === 4 && (
        <div className="text-center" style={{ padding: '20px 12px' }}>
          <div style={{ fontSize: 64, marginBottom: 8, animation: 'cardIn .5s cubic-bezier(.4,0,.2,1)' }}>✅</div>
          <div className="title-md mb-2">Withdrawal of ${net} sent</div>
          <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>Reference WD-2026-{Math.floor(Math.random() * 100000)}. Expected to arrive at {selectedMethod.l.split(' · ')[0]} within {selectedMethod.sub.includes('instant') ? 'a few minutes' : '1-2 business days'}.</div>
        </div>
      )}
    </Modal>
  );
}

// ── 3. Download statements modal ───────────────────────────────────
function StatementsModal({ open, onClose, onToast }) {
  const [range, setRange] = React.useState('q2');
  const [format, setFormat] = React.useState('pdf');
  const [includeTax, setTax] = React.useState(true);

  return (
    <Modal open={open} onClose={onClose} width={480}
      title="Download earnings statement"
      subtitle="For taxes, accountants, or your own records"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={() => { onToast(`Statement exported · earnings-${range}-${format}.${format}`, 'success'); onClose(); }} className="btn btn-primary btn-sm">{Icon.external} Download</button>
        </div>
      }>
      <div className="cap-label mb-2">Date range</div>
      <div className="row gap-6 mb-4" style={{ flexWrap: 'wrap' }}>
        {[
          ['mtd', 'Month to date'],
          ['q2', 'Q2 2026'],
          ['ytd', 'Year to date'],
          ['2025', 'All of 2025'],
          ['all', 'All time'],
        ].map(([k, l]) => (
          <button key={k} onClick={() => setRange(k)} style={{
            padding: '7px 14px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: range === k ? 'var(--ink)' : 'var(--bg-soft)',
            color: range === k ? 'white' : 'var(--ink)', fontWeight: 700, fontSize: 12
          }}>{l}</button>
        ))}
      </div>

      <div className="cap-label mb-2">Format</div>
      <div className="row gap-8 mb-4">
        {[
          ['pdf', 'PDF', '📄', 'Best for taxes & humans'],
          ['csv', 'CSV', '📊', 'Best for spreadsheets'],
          ['json', 'JSON', '⚙️', 'For accounting software'],
        ].map(([k, l, ic, sub]) => (
          <button key={k} onClick={() => setFormat(k)} style={{
            flex: 1, padding: 14, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
            background: format === k ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
            outline: '2px solid ' + (format === k ? 'var(--cyan)' : 'transparent')
          }}>
            <div style={{ fontSize: 22 }}>{ic}</div>
            <div className="bold mt-1" style={{ fontSize: 13 }}>{l}</div>
            <div className="muted" style={{ fontSize: 10.5 }}>{sub}</div>
          </button>
        ))}
      </div>

      <label className="row items-center gap-8 mt-4" style={{ cursor: 'pointer' }}>
        <input type="checkbox" checked={includeTax} onChange={e => setTax(e.target.checked)} />
        <span style={{ fontSize: 13 }}>Include Vietnam withholding tax summary (VAT/PIT)</span>
      </label>
    </Modal>
  );
}

// ── 4. Public media-kit preview drawer ─────────────────────────────
function PublicMediaKitDrawer({ open, onClose }) {
  return (
    <Drawer open={open} onClose={onClose} width={560}>
      <div style={{ padding: 24, background: 'var(--bg-canvas)' }}>
        <div className="row items-center justify-between mb-4">
          <div>
            <div className="cap-label" style={{ color: 'var(--cyan-dark)' }}>Brand-facing preview</div>
            <div className="title-lg">Your public media kit</div>
          </div>
          <button onClick={onClose} className="btn-sm" style={{ background: 'transparent', border: 0, fontSize: 20, cursor: 'pointer', color: 'var(--ink-soft)' }}>×</button>
        </div>

        <div className="card-elevated" style={{ padding: 0, overflow: 'hidden', border: '1px solid var(--line)' }}>
          {/* hero */}
          <div style={{
            padding: 24, background: 'linear-gradient(135deg, #79FEE7 0%, #EAC2FB 50%, #FFC3D6 100%)', color: 'var(--ink)'
          }}>
            <div className="row items-center gap-16">
              <Avatar name="Linh Châu" size={80} />
              <div>
                <h2 className="font-display" style={{ fontSize: 28, fontWeight: 700, margin: 0, letterSpacing: '-0.02em' }}>Linh Châu</h2>
                <div style={{ fontSize: 12, fontWeight: 600 }}>@linhchau · Skincare · Beauty · HCM 🇻🇳</div>
                <div className="row gap-6 mt-2">
                  <Pill variant="dark">482K</Pill>
                  <Pill variant="dark">6.2% ER</Pill>
                  <Pill variant="dark">VERIFIED</Pill>
                </div>
              </div>
            </div>
          </div>

          {/* body */}
          <div style={{ padding: 20 }}>
            <div className="cap-label mb-2">Bio</div>
            <p style={{ fontSize: 13, lineHeight: 1.5, margin: 0 }}>Skincare-obsessed creator from HCM. Honest before/after content and ingredient science for Gen-Z. Currently into vitamin C, niacinamide and SPF nerdery.</p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 }}>
              <div style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 10 }}>
                <div className="cap-label" style={{ fontSize: 9 }}>Audience</div>
                <div className="bold mt-1" style={{ fontSize: 13 }}>78% F · 18-24 skew · HCM/HN</div>
              </div>
              <div style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 10 }}>
                <div className="cap-label" style={{ fontSize: 9 }}>Top categories</div>
                <div className="bold mt-1" style={{ fontSize: 13 }}>Skincare · SPF · Vitamin C</div>
              </div>
            </div>

            <div className="cap-label mt-4 mb-2">Rate card (visible to verified brands only)</div>
            <div className="row items-center justify-between" style={{ padding: 10, background: 'var(--bg-soft)', borderRadius: 10, opacity: 0.4 }}>
              <span style={{ fontSize: 13, fontWeight: 700 }}>🔒 Sign in as a brand to view rates</span>
              <Pill variant="ink">$1.4-1.8K/post</Pill>
            </div>

            <div className="cap-label mt-4 mb-2">Best work</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
              {[
                ['#79FEE7', '#009CFF', '1.2M'],
                ['#FFC3D6', '#FF6FA3', '820K'],
                ['#EAC2FB', '#1C1CC9', '480K'],
              ].map(([c1, c2, r], i) => (
                <div key={i} style={{
                  aspectRatio: '9/14', borderRadius: 8, overflow: 'hidden',
                  background: `linear-gradient(135deg, ${c1}, ${c2})`, position: 'relative'
                }}>
                  <div style={{ position: 'absolute', bottom: 4, left: 4, color: 'white', fontSize: 10, fontWeight: 800, textShadow: '0 1px 3px rgba(0,0,0,0.4)' }}>{r}</div>
                </div>
              ))}
            </div>

            <button className="btn btn-primary btn-sm mt-6" style={{ width: '100%' }}>Invite to campaign →</button>
          </div>
        </div>

        <div className="muted text-center mt-4" style={{ fontSize: 11 }}>This is exactly what brands see when they click your profile</div>
      </div>
    </Drawer>
  );
}

// ── 5. Share media kit modal ───────────────────────────────────────
function ShareKitModal({ open, onClose, onToast }) {
  const url = 'prime.so/k/linhchau';
  const [copied, setCopied] = React.useState(false);
  React.useEffect(() => { if (!open) setCopied(false); }, [open]);

  const copy = () => {
    navigator.clipboard?.writeText('https://' + url).catch(() => {});
    setCopied(true);
    onToast('Link copied to clipboard', 'success');
  };

  return (
    <Modal open={open} onClose={onClose} width={460}
      title="Share your media kit"
      subtitle="Send this to brands who want to evaluate you off-platform">

      {/* URL bar */}
      <div className="row items-center gap-8" style={{ padding: '10px 14px', background: 'var(--bg-soft)', borderRadius: 999, marginBottom: 16 }}>
        <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>🔗</span>
        <span style={{ flex: 1, fontFamily: 'monospace', fontSize: 13, fontWeight: 600 }}>{url}</span>
        <button onClick={copy} className="btn btn-primary btn-sm" style={{ minWidth: 80 }}>
          {copied ? '✓ Copied' : 'Copy link'}
        </button>
      </div>

      {/* QR code (faux) */}
      <div className="row gap-16">
        <div style={{
          width: 140, height: 140, background: 'white', border: '1px solid var(--line)', borderRadius: 10,
          padding: 8, display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 1
        }}>
          {Array.from({ length: 144 }).map((_, i) => {
            // Pseudo-random but stable QR-like pattern
            const on = ((i * 13 + 7) % 17) < 8 || [0, 1, 2, 10, 11, 12, 22, 110, 120, 132, 142, 143].includes(i);
            return <div key={i} style={{ background: on ? 'var(--ink)' : 'transparent', aspectRatio: 1 }} />;
          })}
        </div>
        <div className="flex-1">
          <div className="cap-label mb-2">Or scan</div>
          <p style={{ fontSize: 12, lineHeight: 1.5, margin: '0 0 12px' }}>Hand a brand rep your phone at a launch event — they can scan and save your kit instantly.</p>
          <button className="btn btn-ghost btn-sm" onClick={() => onToast('QR saved as PNG', 'success')}>{Icon.external} Download QR</button>
        </div>
      </div>

      <div className="cap-label mt-6 mb-2">Or share via</div>
      <div className="row gap-8">
        {[
          ['Email',   '✉️', 'mailto:?subject=My media kit&body=https://' + url],
          ['WhatsApp', '💬', null],
          ['Telegram', '✈️', null],
          ['Link in bio', '🌐', null],
        ].map(([l, ic]) => (
          <button key={l} onClick={() => { onToast(`Sharing to ${l}...`); onClose(); }} style={{
            flex: 1, padding: 12, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: 'var(--bg-soft)', textAlign: 'center'
          }}>
            <div style={{ fontSize: 22 }}>{ic}</div>
            <div className="bold mt-1" style={{ fontSize: 11 }}>{l}</div>
          </button>
        ))}
      </div>
    </Modal>
  );
}

// ── 6. Add portfolio post modal ────────────────────────────────────
function AddPostModal({ open, onClose, onToast }) {
  const [platform, setPlatform] = React.useState('tiktok');
  const [url, setUrl] = React.useState('');
  const [imported, setImported] = React.useState(false);
  const [importing, setImporting] = React.useState(false);
  const [cat, setCat] = React.useState('Vitamin C');

  React.useEffect(() => { if (!open) { setUrl(''); setImported(false); setImporting(false); } }, [open]);

  const startImport = () => {
    if (!url.trim()) return;
    setImporting(true);
    setTimeout(() => { setImporting(false); setImported(true); }, 1100);
  };

  return (
    <Modal open={open} onClose={onClose} width={520}
      title="Add to your best work"
      subtitle="Paste a post link — we'll auto-pull cover, views, and ER"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={() => { onToast('Post pinned to your media kit', 'success'); onClose(); }}
            className="btn btn-primary btn-sm"
            disabled={!imported}
            style={{ opacity: imported ? 1 : 0.4, cursor: imported ? 'pointer' : 'not-allowed' }}>
            Pin to media kit {Icon.arrow}
          </button>
        </div>
      }>
      <div className="cap-label mb-2">Platform</div>
      <div className="row gap-6 mb-4">
        {[
          ['tiktok', 'TikTok', Icon.tiktok, '#002B50'],
          ['instagram', 'Instagram', Icon.instagram, '#FF6FA3'],
          ['youtube', 'YouTube', Icon.youtube, '#FF4444'],
        ].map(([k, l, ic, c]) => (
          <button key={k} onClick={() => setPlatform(k)} style={{
            flex: 1, padding: 12, borderRadius: 12, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: platform === k ? c : 'var(--bg-soft)',
            color: platform === k ? 'white' : 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontSize: 13, fontWeight: 700
          }}>{ic} {l}</button>
        ))}
      </div>

      <div className="cap-label mb-2">Post URL</div>
      <div className="row gap-8 mb-4">
        <input
          className="input"
          placeholder="https://www.tiktok.com/@linhchau/video/..."
          value={url}
          onChange={e => setUrl(e.target.value)}
          style={{ flex: 1 }} />
        <button onClick={startImport} disabled={!url.trim() || importing} className="btn btn-primary btn-sm"
          style={{ opacity: (url.trim() && !importing) ? 1 : 0.4 }}>
          {importing ? 'Importing…' : 'Import'}
        </button>
      </div>

      {imported && (
        <div className="card-elevated" style={{ padding: 14, background: 'rgba(31,214,180,0.08)', border: '1px solid rgba(31,214,180,0.3)', animation: 'cardIn .35s ease-out' }}>
          <div className="row items-center gap-14">
            <div style={{
              width: 70, height: 100, borderRadius: 8, flexShrink: 0,
              background: 'linear-gradient(135deg, #79FEE7, #009CFF)',
              display: 'grid', placeItems: 'center', color: 'white', fontSize: 22
            }}>▶</div>
            <div className="flex-1">
              <div className="bold" style={{ fontSize: 13 }}>"POV: when ur niacinamide hits ✨"</div>
              <div className="muted" style={{ fontSize: 11 }}>@linhchau · 14d ago · 30s</div>
              <div className="row gap-6 mt-2">
                <Pill variant="cyan">1.2M views</Pill>
                <Pill variant="mint">7.4% ER</Pill>
                <Pill variant="ink">38K likes</Pill>
              </div>
            </div>
          </div>

          <div className="cap-label mt-4 mb-2">Tag category</div>
          <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
            {['Vitamin C', 'SPF', 'Niacinamide', 'AHA', 'Routine', 'Acne'].map(c => (
              <button key={c} onClick={() => setCat(c)} style={{
                padding: '5px 12px', borderRadius: 999, border: 0, cursor: 'pointer', fontFamily: 'inherit',
                background: cat === c ? 'var(--ink)' : 'var(--bg-soft)',
                color: cat === c ? 'white' : 'var(--ink-soft)', fontWeight: 700, fontSize: 11
              }}>{c}</button>
            ))}
          </div>
        </div>
      )}
    </Modal>
  );
}

// ── Host + hook ────────────────────────────────────────────────────
const CreatorExtraCtx = React.createContext(null);

function CreatorExtraActionsHost({ children }) {
  const [payout, setPayout]     = React.useState(null);
  const [withdraw, setWithdraw] = React.useState(false);
  const [stmts, setStmts]       = React.useState(false);
  const [publicKit, setPublic]  = React.useState(false);
  const [share, setShare]       = React.useState(false);
  const [addPost, setAddPost]   = React.useState(false);
  const [toast, setToast]       = React.useState(null);

  const showToast = React.useCallback((message, kind = 'success', action) => {
    setToast({ message, kind, action });
  }, []);

  const api = React.useMemo(() => ({
    openPayoutDetail: (p) => setPayout(p),
    openWithdraw:     () => setWithdraw(true),
    openStatements:   () => setStmts(true),
    openPublicMediaKit: () => setPublic(true),
    openShareKit:     () => setShare(true),
    openAddPost:      () => setAddPost(true),
    toast: showToast,
  }), [showToast]);

  return (
    <CreatorExtraCtx.Provider value={api}>
      {children}
      <PayoutDetailModal     open={!!payout} onClose={() => setPayout(null)} payout={payout} onToast={showToast} />
      <WithdrawModal         open={withdraw} onClose={() => setWithdraw(false)} onToast={showToast} />
      <StatementsModal       open={stmts}    onClose={() => setStmts(false)}    onToast={showToast} />
      <PublicMediaKitDrawer  open={publicKit} onClose={() => setPublic(false)} />
      <ShareKitModal         open={share}    onClose={() => setShare(false)}    onToast={showToast} />
      <AddPostModal          open={addPost}  onClose={() => setAddPost(false)}  onToast={showToast} />
      <Toast open={!!toast} onClose={() => setToast(null)} kind={toast?.kind} message={toast?.message} action={toast?.action} />
    </CreatorExtraCtx.Provider>
  );
}

function useCreatorActions() {
  return React.useContext(CreatorExtraCtx) || {
    openPayoutDetail: () => {}, openWithdraw: () => {}, openStatements: () => {},
    openPublicMediaKit: () => {}, openShareKit: () => {}, openAddPost: () => {}, toast: () => {}
  };
}

Object.assign(window, { CreatorExtraActionsHost, useCreatorActions });
