/* screen-brand-dashboard-details.jsx — Sub-screens for Dashboard interactions */
/* global React, Modal, Drawer, Popover, Toast, Counter, Sparkline, Avatar, Pill, MatchCircle, Icon, useT, formatMoney */

/* ─────────────────────────────────────────────────────────────────
   1. Date range filter — popover with presets + custom range
   ───────────────────────────────────────────────────────────────── */
function DateRangePopover({ open, onClose, anchorRef, value, onChange }) {
  const presets = [
    { id: '7d', label: 'Last 7 days', sub: '6 → 12 May' },
    { id: '14d', label: 'Last 14 days', sub: '29 Apr → 12 May' },
    { id: '30d', label: 'Last 30 days', sub: '13 Apr → 12 May' },
    { id: '90d', label: 'Last 90 days', sub: 'Q2 to date' },
    { id: 'month', label: 'This month', sub: 'May 2026' },
    { id: 'q', label: 'This quarter', sub: 'Q2 2026' },
  ];
  return (
    <Popover open={open} onClose={onClose} anchorRef={anchorRef} width={320}>
      <div style={{ padding: '12px 14px 8px', borderBottom: '1px solid var(--line)' }}>
        <div className="cap-label" style={{ fontSize: 10 }}>Date range</div>
      </div>
      <div style={{ padding: 6 }}>
        {presets.map(p => {
          const active = value === p.id;
          return (
            <button key={p.id} onClick={() => { onChange(p.id); onClose(); }}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                width: '100%', padding: '10px 10px', border: 0,
                background: active ? 'var(--bg-soft, #F5F7FA)' : 'transparent',
                borderRadius: 10, textAlign: 'left',
                cursor: 'pointer', fontFamily: 'inherit', color: 'var(--ink)'
              }}>
              <span style={{
                width: 26, height: 26, borderRadius: 8,
                background: active ? 'var(--ink)' : 'transparent',
                border: active ? 0 : '1.5px solid var(--line)',
                color: active ? 'white' : 'var(--ink-soft)',
                display: 'grid', placeItems: 'center'
              }}>
                {active && (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5" /></svg>
                )}
              </span>
              <div style={{ flex: 1 }}>
                <div className="bold" style={{ fontSize: 13 }}>{p.label}</div>
                <div className="muted" style={{ fontSize: 11 }}>{p.sub}</div>
              </div>
            </button>
          );
        })}
      </div>
      <div style={{ padding: 6, borderTop: '1px solid var(--line)' }}>
        <button onClick={() => { onChange('custom'); onClose(); }}
          style={{
            display: 'flex', alignItems: 'center', gap: 10,
            width: '100%', padding: '10px 10px', border: 0,
            background: 'transparent', borderRadius: 10, textAlign: 'left',
            cursor: 'pointer', fontFamily: 'inherit', color: 'var(--cyan-dark)',
            fontWeight: 700, fontSize: 13
          }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></svg>
          Pick custom range…
        </button>
      </div>
    </Popover>
  );
}

const DATE_RANGE_LABELS = {
  '7d': 'Last 7 days', '14d': 'Last 14 days', '30d': 'Last 30 days',
  '90d': 'Last 90 days', month: 'This month', q: 'This quarter', custom: 'Custom range'
};

/* ─────────────────────────────────────────────────────────────────
   2. Export modal — choose format, range, fields, delivery
   ───────────────────────────────────────────────────────────────── */
function ExportModal({ open, onClose, onDone }) {
  const [format, setFormat] = React.useState('pdf');
  const [range, setRange] = React.useState('30d');
  const [fields, setFields] = React.useState({ kpis: true, campaigns: true, creators: true, raw: false });
  const [recipient, setRecipient] = React.useState('me');
  const [emails, setEmails] = React.useState('linh@coolmate.me');
  const [busy, setBusy] = React.useState(false);

  const submit = () => {
    setBusy(true);
    setTimeout(() => { setBusy(false); onDone?.({ format, range }); onClose(); }, 900);
  };

  return (
    <Modal
      open={open}
      onClose={busy ? () => {} : onClose}
      width={620}
      title="Export dashboard"
      subtitle="Snapshot your numbers and ship them anywhere."
      footer={
        <div className="row items-center justify-between">
          <div className="muted" style={{ fontSize: 11 }}>Generated reports are kept for 30 days.</div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm" onClick={onClose} disabled={busy}>Cancel</button>
            <button className="btn btn-primary btn-sm" onClick={submit} disabled={busy}>
              {busy
                ? <><span className="dots" /> Preparing…</>
                : <>{format === 'link' ? 'Create link' : 'Generate'} {Icon.arrow}</>}
            </button>
          </div>
          <style>{`.dots::after { content: '...'; animation: dotsBlink 1.2s steps(4, end) infinite; } @keyframes dotsBlink { 0% { content: ''; } 25% { content: '.'; } 50% { content: '..'; } 75% { content: '...'; } }`}</style>
        </div>
      }>
      {/* Format picker */}
      <div className="cap-label" style={{ fontSize: 10 }}>Format</div>
      <div className="row gap-8 mt-2" style={{ flexWrap: 'wrap' }}>
        {[
          { id: 'pdf', label: 'PDF report', sub: 'Branded, paginated', icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></svg> },
          { id: 'csv', label: 'CSV data', sub: 'For BI tools', icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" /><path d="M3 9h18M9 3v18" /></svg> },
          { id: 'png', label: 'PNG image', sub: 'For decks', icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="9" cy="9" r="2" /><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21" /></svg> },
          { id: 'link', label: 'Share link', sub: 'Read-only, 30d', icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.5.5L21 10a5 5 0 0 0-7-7l-2 2" /><path d="M14 11a5 5 0 0 0-7.5-.5L3 14a5 5 0 0 0 7 7l2-2" /></svg> },
        ].map(f => {
          const active = format === f.id;
          return (
            <button key={f.id} onClick={() => setFormat(f.id)}
              style={{
                flex: '1 1 calc(50% - 4px)',
                padding: 12,
                border: '2px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
                background: active ? 'var(--ink)' : 'white',
                color: active ? 'white' : 'var(--ink)',
                borderRadius: 12, fontFamily: 'inherit', textAlign: 'left',
                cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10
              }}>
              <span style={{
                width: 36, height: 36, borderRadius: 10,
                background: active ? 'rgba(255,255,255,0.12)' : 'var(--bg-soft, #F5F7FA)',
                color: active ? '#79FEE7' : 'var(--cyan-dark)',
                display: 'grid', placeItems: 'center', flexShrink: 0
              }}>{f.icon}</span>
              <div>
                <div className="bold" style={{ fontSize: 13 }}>{f.label}</div>
                <div style={{ fontSize: 11, opacity: 0.7 }}>{f.sub}</div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Date range */}
      <div className="cap-label mt-6" style={{ fontSize: 10 }}>Date range</div>
      <div className="row gap-6 mt-2" style={{ flexWrap: 'wrap' }}>
        {[['7d','7d'],['14d','14d'],['30d','30d'],['90d','90d'],['q','This quarter'],['ytd','YTD']].map(([id, label]) => (
          <button key={id} onClick={() => setRange(id)}
            style={{
              padding: '7px 12px', borderRadius: 999,
              border: '1.5px solid ' + (range === id ? 'var(--ink)' : 'var(--line)'),
              background: range === id ? 'var(--ink)' : 'white',
              color: range === id ? 'white' : 'var(--ink)',
              fontSize: 12, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer'
            }}>{label}</button>
        ))}
      </div>

      {/* Fields */}
      <div className="cap-label mt-6" style={{ fontSize: 10 }}>Include</div>
      <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        {[
          ['kpis', 'KPI summary'],
          ['campaigns', 'Campaign breakdown'],
          ['creators', 'Top creators list'],
          ['raw', 'Raw data tables']
        ].map(([k, label]) => (
          <label key={k} className="row items-center gap-8" style={{
            padding: '10px 12px', border: '1px solid var(--line)',
            borderRadius: 10, cursor: 'pointer',
            background: fields[k] ? 'var(--bg-soft, #F5F7FA)' : 'white'
          }}>
            <input type="checkbox" checked={fields[k]} onChange={() => setFields({ ...fields, [k]: !fields[k] })}
              style={{ width: 16, height: 16, accentColor: 'var(--cyan)' }} />
            <span style={{ fontSize: 13, fontWeight: 600 }}>{label}</span>
          </label>
        ))}
      </div>

      {/* Delivery */}
      {format !== 'png' && format !== 'link' && (
        <>
          <div className="cap-label mt-6" style={{ fontSize: 10 }}>Delivery</div>
          <div className="row gap-6 mt-2">
            {[['me','Download'],['email','Email']].map(([id, label]) => (
              <button key={id} onClick={() => setRecipient(id)}
                style={{
                  flex: 1, padding: '10px 12px', borderRadius: 10,
                  border: '1.5px solid ' + (recipient === id ? 'var(--ink)' : 'var(--line)'),
                  background: recipient === id ? 'var(--ink)' : 'white',
                  color: recipient === id ? 'white' : 'var(--ink)',
                  fontSize: 13, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer'
                }}>{label}</button>
            ))}
          </div>
          {recipient === 'email' && (
            <input className="input mt-3" value={emails} onChange={e => setEmails(e.target.value)} placeholder="comma-separated emails" />
          )}
        </>
      )}
    </Modal>
  );
}

/* ─────────────────────────────────────────────────────────────────
   3. Re-book drawer — full creator context, performance, decision
   ───────────────────────────────────────────────────────────────── */
function RebookDrawer({ open, onClose, onBook }) {
  return (
    <Drawer open={open} onClose={onClose} width={520}>
      {/* Header */}
      <div style={{
        padding: '22px 24px 18px',
        background: 'linear-gradient(135deg, #002B50, #1C1CC9)',
        color: 'white',
        position: 'relative', overflow: 'hidden'
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40,
          width: 200, height: 200, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(121,254,231,0.4), transparent 60%)',
          filter: 'blur(30px)'
        }} />
        <div className="row items-center justify-between" style={{ position: 'relative', zIndex: 1 }}>
          <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> AI re-book suggestion</Pill>
          <button onClick={onClose} aria-label="Close" style={{
            background: 'rgba(255,255,255,0.12)', border: 0,
            width: 32, height: 32, borderRadius: 10,
            display: 'grid', placeItems: 'center',
            cursor: 'pointer', color: 'white'
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>
        <div className="row items-center gap-12 mt-4" style={{ position: 'relative', zIndex: 1 }}>
          <Avatar name="Linh Châu" size={60} />
          <div style={{ flex: 1 }}>
            <div className="font-display bold" style={{ fontSize: 22, letterSpacing: '-0.02em' }}>Linh Châu</div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)' }}>
              Skincare · 482K followers · TikTok primary
            </div>
          </div>
          <MatchCircle score={94} size={56} />
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: 24 }}>
        {/* AI rationale */}
        <div style={{
          background: 'var(--bg-soft, #F5F7FA)',
          border: '1px solid var(--line)',
          borderRadius: 14, padding: 16
        }}>
          <div className="row items-center gap-6 mb-2">
            <div className="orb orb-sm" style={{ width: 22, height: 22 }} />
            <div className="bold" style={{ fontSize: 12, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Why we suggested her</div>
          </div>
          <p style={{ fontSize: 13.5, lineHeight: 1.55, margin: 0 }}>
            For your last Vitamin C campaign she <span className="bold" style={{ color: 'var(--mint-deep)' }}>over-performed by 38%</span> at a CPM of <span className="bold tabular">$6.12</span> (band: $9–12). Her audience overlap with the new SPF brief is <span className="bold">81%</span>, and her last 4 posts about clean-beauty serums averaged <span className="bold">6.2% ER</span>.
          </p>
        </div>

        {/* Perf vs band */}
        <div className="cap-label mt-6">Performance vs your benchmark</div>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { label: 'CPM', actual: 6.12, min: 9, max: 12, unit: '$', better: 'low' },
            { label: 'ER', actual: 6.2, min: 3, max: 5, unit: '%', better: 'high' },
            { label: 'Save rate', actual: 11.4, min: 4, max: 8, unit: '%', better: 'high' },
            { label: 'Audience overlap', actual: 81, min: 40, max: 60, unit: '%', better: 'high' },
          ].map((m, i) => (
            <PerfRow key={i} {...m} />
          ))}
        </div>

        {/* Past campaigns */}
        <div className="cap-label mt-6">Past collaborations</div>
        <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { c: 'Vitamin C launch · Q4 2025', r: '1.2M', er: '6.2%', d: 'Closed Dec 2025', good: true },
            { c: 'Cleansing balm · Q2 2025', r: '840K', er: '5.8%', d: 'Closed Aug 2025', good: true },
            { c: 'Hair mist beta', r: '212K', er: '3.1%', d: 'Closed Feb 2025', good: false },
          ].map((p, i) => (
            <div key={i} className="row items-center gap-10" style={{
              padding: '10px 12px',
              border: '1px solid var(--line)',
              borderRadius: 10,
              background: 'white'
            }}>
              <span style={{ width: 6, alignSelf: 'stretch', borderRadius: 999, background: p.good ? 'var(--mint-deep)' : 'var(--yellow)' }} />
              <div style={{ flex: 1 }}>
                <div className="bold" style={{ fontSize: 13 }}>{p.c}</div>
                <div className="muted" style={{ fontSize: 11 }}>{p.d}</div>
              </div>
              <div className="text-right">
                <div className="tabular bold" style={{ fontSize: 13 }}>{p.r}</div>
                <div className="muted" style={{ fontSize: 11 }}>{p.er} ER</div>
              </div>
            </div>
          ))}
        </div>

        {/* Risk notes */}
        <div style={{
          marginTop: 22, padding: 14,
          background: 'rgba(254,233,96,0.18)',
          border: '1px solid rgba(254,233,96,0.5)',
          borderRadius: 12,
          display: 'flex', gap: 10
        }}>
          <span style={{
            width: 28, height: 28, borderRadius: 8,
            background: 'var(--yellow)', display: 'grid', placeItems: 'center',
            color: 'var(--ink)', flexShrink: 0
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L1 21h22L12 2zm0 6 7 12H5l7-12zm-1 5v3h2v-3h-2zm0 4v2h2v-2h-2z" /></svg>
          </span>
          <div>
            <div className="bold" style={{ fontSize: 12.5, marginBottom: 2 }}>2 things to know</div>
            <ul style={{ paddingLeft: 16, margin: 0, fontSize: 12, color: 'var(--ink-soft)', lineHeight: 1.55 }}>
              <li>Her usual lead time is 12 days — book before May 22.</li>
              <li>Currently negotiating with 1 competing brand (skincare).</li>
            </ul>
          </div>
        </div>
      </div>

      {/* Sticky footer */}
      <div style={{
        position: 'sticky', bottom: 0, background: 'white',
        padding: '14px 24px',
        borderTop: '1px solid var(--line)',
        boxShadow: '0 -8px 24px rgba(0,16,32,0.04)'
      }}>
        <div className="row gap-8">
          <button className="btn btn-ghost btn-sm" onClick={onClose} style={{ flex: 1 }}>Dismiss</button>
          <button className="btn btn-ghost btn-sm" style={{ flex: 1 }}>View profile</button>
          <button className="btn btn-primary btn-sm" style={{ flex: 2 }} onClick={() => { onBook?.(); onClose(); }}>
            {Icon.spark} Re-book for SPF brief
          </button>
        </div>
      </div>
    </Drawer>
  );
}

function PerfRow({ label, actual, min, max, unit, better }) {
  // Compute relative position on a 0..max*1.4 scale
  const scaleMax = Math.max(max * 1.4, actual * 1.1);
  const minPct = (min / scaleMax) * 100;
  const maxPct = (max / scaleMax) * 100;
  const actPct = (actual / scaleMax) * 100;
  const beats = better === 'low' ? actual < min : actual > max;
  const isPrefix = unit === '$';
  const fmt = (v) => isPrefix ? `${unit}${v}` : `${v}${unit}`;
  return (
    <div>
      <div className="row items-center justify-between" style={{ marginBottom: 4 }}>
        <div style={{ fontSize: 12, fontWeight: 600 }}>{label}</div>
        <div className="row items-center gap-8">
          <span className="muted tabular" style={{ fontSize: 11 }}>band {fmt(min)}–{fmt(max)}</span>
          <span className="font-display bold tabular" style={{ fontSize: 14, color: beats ? '#0a8a72' : 'var(--ink)' }}>
            {fmt(actual)}
          </span>
        </div>
      </div>
      <div style={{ position: 'relative', height: 8, background: 'var(--bg-soft, #F5F7FA)', borderRadius: 999, overflow: 'visible' }}>
        {/* benchmark band */}
        <div style={{
          position: 'absolute', top: 0, height: '100%',
          left: minPct + '%', width: (maxPct - minPct) + '%',
          background: 'rgba(0,156,255,0.18)', borderRadius: 999
        }} />
        {/* actual marker */}
        <div style={{
          position: 'absolute', top: -3, left: `calc(${actPct}% - 7px)`,
          width: 14, height: 14, borderRadius: 999,
          background: beats ? '#1FD6B4' : 'var(--ink)',
          border: '2.5px solid white',
          boxShadow: '0 2px 6px rgba(0,16,32,0.18)'
        }} />
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   4. Top creators "View all" — drawer w/ full ranked list + quick actions
   ───────────────────────────────────────────────────────────────── */
function TopCreatorsDrawer({ open, onClose, onOpenCreator }) {
  const list = [
    { n: 'Linh Châu',  cat: 'Skincare',    r: 4.8, er: 6.2, m: 94, posts: 6, trend: 'up'   },
    { n: 'Mai Vy',     cat: 'Lifestyle',   r: 3.2, er: 5.8, m: 88, posts: 4, trend: 'up'   },
    { n: 'Hà Giang',   cat: 'Beauty',      r: 2.4, er: 7.1, m: 81, posts: 5, trend: 'up'   },
    { n: 'Phương Anh', cat: 'Fashion',     r: 1.9, er: 4.4, m: 78, posts: 3, trend: 'flat' },
    { n: 'Thảo Nhi',   cat: 'Wellness',    r: 1.6, er: 5.2, m: 75, posts: 4, trend: 'up'   },
    { n: 'Quỳnh Như',  cat: 'Mom & Baby',  r: 1.4, er: 4.8, m: 72, posts: 2, trend: 'flat' },
    { n: 'Bảo Trâm',   cat: 'Skincare',    r: 1.2, er: 6.0, m: 70, posts: 3, trend: 'up'   },
    { n: 'Minh Tú',    cat: 'Beauty',      r: 0.9, er: 3.8, m: 64, posts: 2, trend: 'down' },
  ];
  const [sort, setSort] = React.useState('match');
  const [filter, setFilter] = React.useState('all');
  const cats = ['all', ...new Set(list.map(l => l.cat))];
  const filtered = filter === 'all' ? list : list.filter(l => l.cat === filter);
  const sorted = [...filtered].sort((a, b) => sort === 'match' ? b.m - a.m : sort === 'reach' ? b.r - a.r : b.er - a.er);

  return (
    <Drawer open={open} onClose={onClose} width={560}>
      <div style={{ padding: '22px 24px 16px', borderBottom: '1px solid var(--line)' }}>
        <div className="row items-center justify-between mb-2">
          <div>
            <div className="font-display bold" style={{ fontSize: 22, letterSpacing: '-0.02em' }}>Top creators this week</div>
            <div className="muted" style={{ fontSize: 12 }}>{filtered.length} active · AI match × reach</div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{
            background: 'var(--bg-soft, #F5F7FA)', border: 0,
            width: 32, height: 32, borderRadius: 10,
            display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--ink-soft)'
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>

        {/* Sort + filter row */}
        <div className="row gap-8 items-center" style={{ marginTop: 12, flexWrap: 'wrap' }}>
          <span className="cap-label" style={{ fontSize: 10 }}>Sort</span>
          {[['match','Match'],['reach','Reach'],['er','ER']].map(([k, l]) => (
            <button key={k} onClick={() => setSort(k)}
              style={{
                padding: '5px 11px', borderRadius: 999,
                border: '1.5px solid ' + (sort === k ? 'var(--ink)' : 'var(--line)'),
                background: sort === k ? 'var(--ink)' : 'white',
                color: sort === k ? 'white' : 'var(--ink)',
                fontSize: 11.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit'
              }}>{l}</button>
          ))}
          <div style={{ width: 1, height: 18, background: 'var(--line)', margin: '0 4px' }} />
          <select value={filter} onChange={e => setFilter(e.target.value)}
            style={{
              padding: '5px 24px 5px 10px', borderRadius: 999,
              border: '1.5px solid var(--line)', background: 'white',
              fontSize: 11.5, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
              appearance: 'none',
              backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='%23425466' d='M0 0h10L5 6z'/></svg>")`,
              backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center'
            }}>
            {cats.map(c => <option key={c} value={c}>{c === 'all' ? 'All categories' : c}</option>)}
          </select>
        </div>
      </div>

      {/* List */}
      <div style={{ padding: '6px 8px 24px' }}>
        {sorted.map((c, i) => (
          <CreatorRow key={c.n} c={c} rank={i + 1} onOpen={() => onOpenCreator?.(c.n)} />
        ))}
      </div>
    </Drawer>
  );
}

function CreatorRow({ c, rank, onOpen }) {
  const [hover, setHover] = React.useState(false);
  const trendIcon = c.trend === 'up'
    ? <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#0a8a72" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6-6 6 6M12 3v18" /></svg>
    : c.trend === 'down'
    ? <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#B12B2B" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m6 15 6 6 6-6M12 21V3" /></svg>
    : <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--ink-soft)" strokeWidth="2.5" strokeLinecap="round"><path d="M5 12h14" /></svg>;

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        padding: '12px 14px',
        borderRadius: 12,
        background: hover ? 'var(--bg-soft, #F5F7FA)' : 'transparent',
        transition: 'background .15s',
        display: 'flex', alignItems: 'center', gap: 12
      }}>
      <div className="font-display bold tabular" style={{ fontSize: 18, width: 24, color: rank <= 3 ? 'var(--ink)' : 'var(--ink-soft)' }}>{rank}</div>
      <Avatar name={c.n} size={40} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="row items-center gap-6">
          <div className="bold" style={{ fontSize: 13 }}>{c.n}</div>
          {trendIcon}
        </div>
        <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>
          {c.cat} · {c.r}M reach · {c.er}% ER · {c.posts} posts
        </div>
      </div>
      <MatchCircle score={c.m} size={40} />
      {hover ? (
        <div className="row gap-4">
          <button className="btn btn-ghost btn-sm" style={{ padding: '6px 10px', fontSize: 11 }} onClick={onOpen}>Profile</button>
          <button className="btn btn-primary btn-sm" style={{ padding: '6px 10px', fontSize: 11 }}>{Icon.plus} Brief</button>
        </div>
      ) : (
        <button onClick={onOpen} style={{
          background: 'transparent', border: 0, padding: 6,
          color: 'var(--ink-soft)', cursor: 'pointer',
          display: 'grid', placeItems: 'center'
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m9 18 6-6-6-6" /></svg>
        </button>
      )}
    </div>
  );
}

/* ─────────────────────────────────────────────────────────────────
   5. Activity event drawer — drill-down into a single event
   ───────────────────────────────────────────────────────────────── */
function ActivityDrawer({ event, open, onClose }) {
  if (!event) return null;
  return (
    <Drawer open={open} onClose={onClose} width={460}>
      <div style={{ padding: '22px 24px 18px', borderBottom: '1px solid var(--line)' }}>
        <div className="row items-center justify-between mb-3">
          <Pill variant={event.ai ? 'cyan' : 'mint'}>
            {event.ai ? 'AI event' : 'Human event'}
          </Pill>
          <button onClick={onClose} aria-label="Close" style={{
            background: 'var(--bg-soft, #F5F7FA)', border: 0,
            width: 32, height: 32, borderRadius: 10,
            display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--ink-soft)'
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
          </button>
        </div>
        <div className="font-display bold" style={{ fontSize: 19, letterSpacing: '-0.02em', lineHeight: 1.3 }}>
          {event.who} {event.what} {event.detail}
        </div>
        <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>{event.t} · logged immutably</div>
      </div>

      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Provenance */}
        <div style={{ padding: 14, background: 'var(--bg-soft, #F5F7FA)', borderRadius: 12 }}>
          <div className="cap-label">Source</div>
          <div className="row items-center gap-8 mt-2">
            <span style={{ width: 8, height: 8, borderRadius: 999, background: event.ai ? 'var(--cyan)' : 'var(--mint-deep)' }} />
            <span className="bold" style={{ fontSize: 13 }}>{event.ai ? 'Prime AI' : event.who}</span>
            <span className="muted" style={{ fontSize: 11 }}>· event ID #EVT-{Math.floor(Math.random() * 9000 + 1000)}</span>
          </div>
        </div>

        {/* Context */}
        <div>
          <div className="cap-label mb-2">Context</div>
          <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0, color: 'var(--ink-soft)' }}>
            {event.ai
              ? 'Triggered automatically by the AI workflow. Inputs and outputs are stored alongside this event for replay and audit.'
              : 'User-initiated action. Captured at the source with device, IP and workspace role context (visible to admins only).'}
          </p>
        </div>

        {/* Linked items */}
        <div>
          <div className="cap-label mb-2">Linked</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <a className="row items-center gap-10" style={{
              padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 10, cursor: 'pointer'
            }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--mint)', display: 'grid', placeItems: 'center', color: 'var(--ink)' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><path d="M14 2v6h6" /></svg>
              </span>
              <span className="bold" style={{ fontSize: 13, flex: 1 }}>Brief #B-2419</span>
              <span style={{ color: 'var(--ink-soft)' }}>{Icon.arrow}</span>
            </a>
            <a className="row items-center gap-10" style={{
              padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 10, cursor: 'pointer'
            }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--cyan)', display: 'grid', placeItems: 'center', color: 'white' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" /><circle cx="9" cy="7" r="4" /></svg>
              </span>
              <span className="bold" style={{ fontSize: 13, flex: 1 }}>Campaign C-1182</span>
              <span style={{ color: 'var(--ink-soft)' }}>{Icon.arrow}</span>
            </a>
          </div>
        </div>

        {/* Audit actions */}
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <button className="btn btn-ghost btn-sm" style={{ flex: 1 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="m7 10 5 5 5-5" /><path d="M12 15V3" /></svg>
            Download log
          </button>
          {event.ai && (
            <button className="btn btn-ghost btn-sm" style={{ flex: 1 }}>
              {Icon.spark} Replay AI step
            </button>
          )}
        </div>
      </div>
    </Drawer>
  );
}

Object.assign(window, {
  DateRangePopover, DATE_RANGE_LABELS,
  ExportModal, RebookDrawer, TopCreatorsDrawer, ActivityDrawer,
});
