// SCREEN: Creator Management
// Manage creator relationships, UTM links, campaign briefs, attributed performance.

// ─── Mock data ────────────────────────────────────────────────────────────────
const CREATOR_MOCK_CREATORS = [
  { id: 'cr_001', name: 'Priya M.',   handle: '@priyam_growth',  platform: 'Instagram', niche: 'SaaS/Marketing', audience_size: 124000, status: 'active',   last_post: '2d ago',  email: 'priya@example.com' },
  { id: 'cr_002', name: 'Davi R.',    handle: '@davirodrigues',  platform: 'LinkedIn',  niche: 'B2B Tech',        audience_size:  89000, status: 'active',   last_post: '1d ago',  email: 'davi@example.com' },
  { id: 'cr_003', name: 'Yuki T.',    handle: '@yukitech',       platform: 'TikTok',    niche: 'Tech/AI',         audience_size: 312000, status: 'active',   last_post: '6h ago',  email: 'yuki@example.com' },
  { id: 'cr_004', name: 'Nia W.',     handle: '@niawalker',      platform: 'YouTube',   niche: 'Marketing',       audience_size:  44000, status: 'active',   last_post: '3d ago',  email: 'nia@example.com' },
  { id: 'cr_005', name: 'Sam L.',     handle: '@samleads',       platform: 'Twitter',   niche: 'RevOps',          audience_size:  28000, status: 'pending',  last_post: '5d ago',  email: 'sam@example.com' },
  { id: 'cr_006', name: 'Kai D.',     handle: '@kaid',           platform: 'Instagram', niche: 'eCommerce',       audience_size:  67000, status: 'active',   last_post: '1d ago',  email: 'kai@example.com' },
  { id: 'cr_007', name: 'Mira S.',    handle: '@miras',          platform: 'LinkedIn',  niche: 'CMO Network',     audience_size:  91000, status: 'inactive', last_post: '3w ago',  email: 'mira@example.com' },
  { id: 'cr_008', name: 'Jake P.',    handle: '@jakeproducts',   platform: 'TikTok',    niche: 'Product',         audience_size: 188000, status: 'pending',  last_post: '2d ago',  email: 'jake@example.com' },
];

const CREATOR_MOCK_BRIEF = {
  title: 'Campaign Brief: AstraReach × Priya M.',
  platform: 'Instagram',
  niche: 'SaaS/Marketing',
  format: 'Carousel post + Story sequence (6 slides)',
  key_messages: [
    'AstraReach unifies all your marketing data into one journey graph',
    'See exactly which touchpoints lead to conversions — no more last-click lies',
    'AI-powered insights surface bottlenecks and budget opportunities automatically',
  ],
  cta: 'Try AstraReach free for 14 days → link in bio',
  hashtags: ['#MarketingOps', '#AttributionModel', '#SaaSMarketing', '#GrowthMarketing', '#MarketingAnalytics'],
  tone: 'Educational + conversational. Position as insider knowledge, not ad.',
  deliverables: '1× carousel post, 3× Story slides, 1× IG Reel (30–60s optional)',
  deadline: '2026-05-20',
};

// ─── Sub-components ───────────────────────────────────────────────────────────

// Platform color/icon helper
const CrPlatformBadge = ({ platform }) => {
  const map = {
    Instagram: { color: '#C13584', label: 'IG' },
    TikTok:    { color: '#FF0050', label: 'TT' },
    YouTube:   { color: '#FF0000', label: 'YT' },
    LinkedIn:  { color: '#0A66C2', label: 'LI' },
    Twitter:   { color: '#22D3EE', label: 'X'  },
  };
  const p = map[platform] || { color: 'var(--text-4)', label: '?' };
  return (
    <span style={{display: 'inline-flex', alignItems: 'center', gap: 5}}>
      <span style={{width: 18, height: 18, borderRadius: 4, background: p.color, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 9, fontWeight: 700, color: '#fff', flexShrink: 0}}>{p.label}</span>
      <span style={{fontSize: 12, color: 'var(--text-2)'}}>{platform}</span>
    </span>
  );
};

// Status badge
const CrStatusBadge = ({ status }) => {
  const map = { active: 'green', pending: 'amber', inactive: 'plain' };
  return <span className={`badge ${map[status] || 'plain'}`}>{status}</span>;
};

// Avatar placeholder (initials)
const CrAvatar = ({ name, size = 32 }) => {
  const initials = name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  const colors = ['#8B5CF6','#22D3EE','#10B981','#F59E0B','#F43F5E','#6366F1','#EC4899','#14B8A6'];
  const idx = name.charCodeAt(0) % colors.length;
  return (
    <div style={{width: size, height: size, borderRadius: '50%', background: colors[idx], display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: size * 0.35, fontWeight: 600, color: '#fff', flexShrink: 0}}>
      {initials}
    </div>
  );
};

// Format audience size
const fmtAudience = n => n >= 1000000 ? (n / 1000000).toFixed(1) + 'M' : (n / 1000).toFixed(0) + 'K';

// ─── UTM Panel ────────────────────────────────────────────────────────────────
const CrUtmPanel = ({ creator, onClose }) => {
  const [attribution, setAttribution] = React.useState('30d');
  const [copied, setCopied] = React.useState(false);

  const today = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  const platform = (creator.platform || '').toLowerCase().replace('/', '_');
  const handle = (creator.handle || '').replace('@', '');
  const utmUrl = `https://astrareach.com/?utm_source=${platform}&utm_medium=creator&utm_campaign=${handle}&utm_content=${today}&attribution_window=${attribution}`;

  const handleCopy = () => {
    navigator.clipboard.writeText(utmUrl).catch(() => {});
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div style={{position: 'fixed', top: 0, right: 0, bottom: 0, width: 420, background: 'var(--bg-1)', borderLeft: '1px solid var(--border)', zIndex: 100, display: 'flex', flexDirection: 'column', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)'}}>
      {/* Header */}
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--border)'}}>
        <div>
          <div style={{fontSize: 14, fontWeight: 600}}>UTM Link Generator</div>
          <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 2}}>{creator.name} · {creator.platform}</div>
        </div>
        <button className="btn ghost" style={{padding: 6}} onClick={onClose}><Icon name="x" size={14} /></button>
      </div>

      <div style={{flex: 1, overflow: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 20}}>
        {/* UTM URL */}
        <div>
          <div style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>Generated URL</div>
          <div style={{background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8, padding: '10px 12px', fontFamily: 'var(--mono)', fontSize: 11, color: '#c4b5fd', wordBreak: 'break-all', lineHeight: 1.6}}>
            {utmUrl}
          </div>
          <button className="btn" style={{marginTop: 10, width: '100%', justifyContent: 'center', background: copied ? 'rgba(16,185,129,0.15)' : '', borderColor: copied ? 'var(--emerald)' : '', color: copied ? 'var(--emerald)' : ''}} onClick={handleCopy}>
            <Icon name={copied ? 'check' : 'copy'} size={12} />
            {copied ? '✓ Copied!' : 'Copy Link'}
          </button>
        </div>

        {/* Attribution window */}
        <div>
          <div style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>Attribution Window</div>
          <div className="seg">
            {['7d', '14d', '30d'].map(w => (
              <button key={w} className={attribution === w ? 'active' : ''} onClick={() => setAttribution(w)}>{w}</button>
            ))}
          </div>
          <div style={{fontSize: 11, color: 'var(--text-4)', marginTop: 8}}>
            Conversions attributed up to {attribution} after the first click on this link.
          </div>
        </div>

        {/* UTM parameter breakdown */}
        <div>
          <div style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10}}>Parameters</div>
          <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
            {[
              ['utm_source', platform],
              ['utm_medium', 'creator'],
              ['utm_campaign', handle],
              ['utm_content', today],
              ['attribution_window', attribution],
            ].map(([k, v]) => (
              <div key={k} style={{display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '6px 10px', background: 'var(--bg-3)', borderRadius: 6}}>
                <span className="mono" style={{color: 'var(--text-3)', fontSize: 11}}>{k}</span>
                <span className="mono" style={{color: 'var(--cyan)', fontSize: 11}}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Performance note */}
        <div style={{padding: 14, background: 'rgba(139,92,246,0.07)', border: '1px solid rgba(139,92,246,0.2)', borderRadius: 8, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.6}}>
          <Icon name="sparkle" size={11} style={{color: '#c4b5fd', marginRight: 6}} />
          AstraReach will automatically attribute conversions to <strong style={{color: 'var(--text-1)'}}>{creator.name}</strong> via the journey graph when this link is used.
        </div>
      </div>
    </div>
  );
};

// ─── Brief Panel ──────────────────────────────────────────────────────────────
const CrBriefPanel = ({ creator, onClose }) => {
  const [generating, setGenerating] = React.useState(false);
  const [brief, setBrief] = React.useState(null);

  const mockBriefFor = (c) => ({
    ...CREATOR_MOCK_BRIEF,
    title: `Campaign Brief: AstraReach × ${c.name}`,
    platform: c.platform,
    niche: c.niche,
  });

  const handleGenerate = () => {
    setGenerating(true);
    arFetch(`/v1/creators/${creator.id}/brief`, { method: 'POST', body: JSON.stringify({ creator_id: creator.id }) })
      .then(d => { if (d) setBrief(d); else setBrief(mockBriefFor(creator)); })
      .catch(() => setBrief(mockBriefFor(creator)))
      .finally(() => setGenerating(false));
  };

  const displayBrief = brief || (generating ? null : null);

  return (
    <div style={{position: 'fixed', top: 0, right: 0, bottom: 0, width: 480, background: 'var(--bg-1)', borderLeft: '1px solid var(--border)', zIndex: 100, display: 'flex', flexDirection: 'column', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)'}}>
      {/* Header */}
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--border)'}}>
        <div>
          <div style={{fontSize: 14, fontWeight: 600}}>Campaign Brief Generator</div>
          <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 2}}>{creator.name} · {creator.niche}</div>
        </div>
        <button className="btn ghost" style={{padding: 6}} onClick={onClose}><Icon name="x" size={14} /></button>
      </div>

      <div style={{flex: 1, overflow: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 18}}>
        {/* Creator summary */}
        <div style={{display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--bg-3)', borderRadius: 8, border: '1px solid var(--border)'}}>
          <CrAvatar name={creator.name} size={38} />
          <div>
            <div style={{fontSize: 13, fontWeight: 600}}>{creator.name}</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>{creator.handle} · {fmtAudience(creator.audience_size)} followers</div>
          </div>
          <div style={{marginLeft: 'auto'}}>
            <CrPlatformBadge platform={creator.platform} />
          </div>
        </div>

        {/* Generate button */}
        <button className="btn primary" style={{width: '100%', justifyContent: 'center'}} disabled={generating} onClick={handleGenerate}>
          <Icon name="sparkle" size={13} />
          {generating ? 'Generating brief…' : displayBrief ? 'Regenerate with AI' : 'Generate with AI'}
        </button>

        {/* Brief output */}
        {displayBrief && (
          <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
            <div style={{fontSize: 14, fontWeight: 600, color: 'var(--text-1)'}}>{displayBrief.title}</div>

            {[
              { label: 'Platform', value: displayBrief.platform },
              { label: 'Content Format', value: displayBrief.format },
              { label: 'Tone', value: displayBrief.tone },
              { label: 'Deliverables', value: displayBrief.deliverables },
              { label: 'Deadline', value: displayBrief.deadline },
            ].map(({ label, value }) => (
              <div key={label}>
                <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4}}>{label}</div>
                <div style={{fontSize: 13, color: 'var(--text-2)'}}>{value}</div>
              </div>
            ))}

            <div>
              <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>Key Messages</div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
                {displayBrief.key_messages.map((msg, i) => (
                  <div key={i} style={{display: 'flex', gap: 10, padding: '8px 12px', background: 'var(--bg-3)', borderRadius: 6, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.55, borderLeft: '2px solid var(--accent)'}}>
                    <span style={{color: 'var(--accent)', fontWeight: 700, flexShrink: 0}}>{i + 1}.</span>
                    {msg}
                  </div>
                ))}
              </div>
            </div>

            <div>
              <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>CTA</div>
              <div style={{padding: '8px 12px', background: 'rgba(34,211,238,0.08)', border: '1px solid rgba(34,211,238,0.2)', borderRadius: 6, fontSize: 12, color: 'var(--cyan)', fontFamily: 'var(--mono)'}}>
                {displayBrief.cta}
              </div>
            </div>

            <div>
              <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>Hashtags</div>
              <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
                {displayBrief.hashtags.map(h => (
                  <span key={h} className="badge violet" style={{fontSize: 11, padding: '3px 8px', textTransform: 'none', letterSpacing: 0}}>{h}</span>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Pre-generate placeholder */}
        {!displayBrief && !generating && (
          <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10, color: 'var(--text-4)', textAlign: 'center', padding: 32}}>
            <Icon name="sparkle" size={28} />
            <div style={{fontSize: 13}}>Click "Generate with AI" to create a personalized campaign brief for {creator.name}.</div>
          </div>
        )}

        {/* Generating spinner */}
        {generating && (
          <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12}}>
            <span className="dot pulse violet" style={{width: 10, height: 10}} />
            <div style={{fontSize: 13, color: 'var(--text-3)'}}>Crafting brief with AI…</div>
          </div>
        )}
      </div>
    </div>
  );
};

// ─── Add Creator Panel ────────────────────────────────────────────────────────
const CrAddPanel = ({ onClose, onCreated }) => {
  const [form, setForm] = React.useState({ name: '', handle: '', platform: 'Instagram', niche: '', audience_size: '', email: '', status: 'active' });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = () => {
    if (!form.name.trim() || !form.handle.trim()) { setError('Name and handle are required.'); return; }
    setSaving(true);
    setError(null);
    const payload = { ...form, audience_size: parseInt(form.audience_size) || 0 };
    arFetch('/v1/creators/', { method: 'POST', body: JSON.stringify(payload) })
      .then(d => {
        const created = d || { ...payload, id: 'cr_' + Date.now(), created_at: new Date().toISOString() };
        created.id = created.creator_id || created.id || 'cr_' + Date.now();
        onCreated && onCreated(created);
        onClose();
      })
      .catch(() => {
        setError('Failed to save creator. Please try again.');
      })
      .finally(() => setSaving(false));
  };

  const inputStyle = { width: '100%', padding: '8px 12px', background: 'var(--bg-3)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text-1)', fontSize: 13, outline: 'none', fontFamily: 'inherit' };
  const labelStyle = { fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6, display: 'block' };

  return (
    <div style={{position: 'fixed', top: 0, right: 0, bottom: 0, width: 400, background: 'var(--bg-1)', borderLeft: '1px solid var(--border)', zIndex: 100, display: 'flex', flexDirection: 'column', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)'}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--border)'}}>
        <div style={{fontSize: 14, fontWeight: 600}}>Add Creator</div>
        <button className="btn ghost" style={{padding: 6}} onClick={onClose}><Icon name="x" size={14} /></button>
      </div>

      <div style={{flex: 1, overflow: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 16}}>
        {error && (
          <div style={{padding: '8px 12px', background: 'rgba(244,63,94,0.1)', border: '1px solid rgba(244,63,94,0.3)', borderRadius: 6, fontSize: 12, color: 'var(--rose)'}}>{error}</div>
        )}

        <div><label style={labelStyle}>Name *</label><input style={inputStyle} value={form.name} onChange={e => set('name', e.target.value)} placeholder="e.g. Priya M." /></div>
        <div><label style={labelStyle}>Handle *</label><input style={inputStyle} value={form.handle} onChange={e => set('handle', e.target.value)} placeholder="@handle" /></div>

        <div>
          <label style={labelStyle}>Platform</label>
          <select style={{...inputStyle}} value={form.platform} onChange={e => set('platform', e.target.value)}>
            {['Instagram','TikTok','YouTube','LinkedIn','Twitter'].map(p => <option key={p} value={p}>{p}</option>)}
          </select>
        </div>

        <div><label style={labelStyle}>Niche</label><input style={inputStyle} value={form.niche} onChange={e => set('niche', e.target.value)} placeholder="e.g. SaaS/Marketing" /></div>
        <div><label style={labelStyle}>Audience Size</label><input style={inputStyle} type="number" value={form.audience_size} onChange={e => set('audience_size', e.target.value)} placeholder="e.g. 124000" /></div>
        <div><label style={labelStyle}>Email</label><input style={inputStyle} type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="creator@example.com" /></div>

        <div>
          <label style={labelStyle}>Status</label>
          <select style={{...inputStyle}} value={form.status} onChange={e => set('status', e.target.value)}>
            <option value="active">Active</option>
            <option value="pending">Pending</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
      </div>

      <div style={{padding: '16px 20px', borderTop: '1px solid var(--border)', display: 'flex', gap: 10}}>
        <button className="btn ghost" style={{flex: 1, justifyContent: 'center'}} onClick={onClose}>Cancel</button>
        <button className="btn primary" style={{flex: 2, justifyContent: 'center'}} disabled={saving} onClick={handleSubmit}>
          <Icon name="plus" size={13} />
          {saving ? 'Adding…' : 'Add Creator'}
        </button>
      </div>
    </div>
  );
};

// ─── Main Screen ──────────────────────────────────────────────────────────────
const CreatorScreen = () => {
  const [creators, setCreators] = React.useState(CREATOR_MOCK_CREATORS);
  const [panel, setPanel] = React.useState(null);    // null | { type: 'utm'|'brief'|'add', creator? }
  const [search, setSearch] = React.useState('');
  const [filterStatus, setFilterStatus] = React.useState('all');

  const confirmDiscard = () => {
    if (panel && panel.type === 'add') return window.confirm('Discard unsaved creator?');
    return true;
  };

  // Attempt to load creators from API — fall back to MOCK silently
  React.useEffect(() => {
    arFetch('/v1/creators/')
      .then(d => { if (Array.isArray(d) && d.length) setCreators(d); })
      .catch(() => {});
  }, []);

  // Dismiss panel on Escape
  React.useEffect(() => {
    const h = e => { if (e.key === 'Escape') { if (confirmDiscard()) setPanel(null); } };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [panel]);

  const handleCreated = (creator) => {
    setCreators(prev => [{ ...creator, id: creator.creator_id || creator.id, last_post: 'just now' }, ...prev]);
  };

  // Filtered list
  const visible = creators.filter(c => {
    const matchSearch = !search || c.name.toLowerCase().includes(search.toLowerCase()) || c.handle.toLowerCase().includes(search.toLowerCase()) || c.niche.toLowerCase().includes(search.toLowerCase());
    const matchStatus = filterStatus === 'all' || c.status === filterStatus;
    return matchSearch && matchStatus;
  });

  // KPI summary
  const activeCount = creators.filter(c => c.status === 'active').length;
  const totalAudience = creators.reduce((s, c) => s + (c.audience_size || 0), 0);
  const avgAudience = creators.length ? Math.round(totalAudience / creators.length) : 0;

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 20}}>

      {/* ── Header ── */}
      <div style={{display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16}}>
        <div>
          <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6}}>Creator Suite / Creators</div>
          <div style={{fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em'}}>Creator Management</div>
          <div style={{fontSize: 13, color: 'var(--text-3)', marginTop: 2}}>Manage creator relationships, track UTM performance, and generate campaign briefs</div>
        </div>
        <button className="btn primary" onClick={() => setPanel({ type: 'add' })}>
          <Icon name="plus" size={12} /> Add Creator
        </button>
      </div>

      {/* ── KPI row ── */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14}}>
        {[
          { label: 'Total Creators',    value: creators.length,         color: 'var(--accent)' },
          { label: 'Active Campaigns',  value: 3,                        color: 'var(--emerald)' },
          { label: 'Attributed Revenue', value: '$124K',                 color: 'var(--cyan)' },
          { label: 'Avg Audience',       value: fmtAudience(avgAudience), color: 'var(--amber)' },
        ].map(({ label, value, color }) => (
          <div key={label} className="metric">
            <div className="metric-label">{label}</div>
            <div className="metric-value" style={{color}}>{value}</div>
          </div>
        ))}
      </div>

      {/* ── Filter bar ── */}
      <div style={{display: 'flex', gap: 10, alignItems: 'center'}}>
        <div style={{flex: 1, display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 8, maxWidth: 340}}>
          <Icon name="search" size={12} style={{color: 'var(--text-3)'}} />
          <input placeholder="Search name, handle, niche…" value={search} onChange={e => setSearch(e.target.value)} style={{flex: 1, background: 'transparent', border: 'none', color: 'var(--text-1)', fontSize: 12, outline: 'none'}} />
        </div>
        <div style={{display: 'flex', gap: 6}}>
          {['all', 'active', 'pending', 'inactive'].map(s => (
            <button key={s} className={`filter-chip ${filterStatus === s ? 'active' : ''}`} onClick={() => setFilterStatus(s)} style={{textTransform: 'capitalize'}}>{s}</button>
          ))}
        </div>
        <div style={{marginLeft: 'auto', fontSize: 12, color: 'var(--text-3)'}}>{visible.length} creator{visible.length !== 1 ? 's' : ''}</div>
      </div>

      {/* ── Creator Roster Table ── */}
      <div className="card" style={{padding: 0}}>
        <div style={{overflow: 'auto'}}>
          <table className="data-table">
            <thead>
              <tr>
                <th>Creator</th>
                <th>Platform</th>
                <th>Handle</th>
                <th>Niche</th>
                <th style={{textAlign: 'right'}}>Audience</th>
                <th>Status</th>
                <th>Last Post</th>
                <th style={{textAlign: 'right'}}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {visible.length === 0 && (
                <tr><td colSpan={8} style={{textAlign: 'center', color: 'var(--text-4)', padding: 32}}>No creators match your filters.</td></tr>
              )}
              {visible.map(c => (
                <tr key={c.id}>
                  {/* Avatar + Name */}
                  <td>
                    <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                      <CrAvatar name={c.name} size={30} />
                      <span style={{fontWeight: 500, color: 'var(--text-1)', fontSize: 13}}>{c.name}</span>
                    </div>
                  </td>
                  <td><CrPlatformBadge platform={c.platform} /></td>
                  <td><span className="mono" style={{fontSize: 12, color: '#c4b5fd'}}>{c.handle}</span></td>
                  <td style={{fontSize: 12, color: 'var(--text-2)'}}>{c.niche}</td>
                  <td className="mono" style={{textAlign: 'right', fontSize: 12}}>{fmtAudience(c.audience_size)}</td>
                  <td><CrStatusBadge status={c.status} /></td>
                  <td style={{fontSize: 12, color: 'var(--text-3)'}}>{c.last_post || '—'}</td>
                  <td>
                    <div style={{display: 'flex', gap: 6, justifyContent: 'flex-end'}}>
                      <button className="btn ghost" style={{fontSize: 11, padding: '4px 8px', color: 'var(--cyan)'}} onClick={() => setPanel({ type: 'utm', creator: c })}>
                        <Icon name="link" size={11} /> UTM
                      </button>
                      <button className="btn ghost" style={{fontSize: 11, padding: '4px 8px', color: '#c4b5fd'}} onClick={() => setPanel({ type: 'brief', creator: c })}>
                        <Icon name="sparkle" size={11} /> Brief
                      </button>
                      <button className="btn ghost" style={{fontSize: 11, padding: '4px 8px'}} onClick={() => setPanel({ type: 'view', creator: c })}>
                        <Icon name="eye" size={11} /> View
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* ── AI callout ── */}
      <AICallout>
        <b>3 creators are driving 78% of attributed conversions</b> — Yuki T., Priya M., and Davi R. Consider increasing brief frequency and UTM tracking granularity for their campaigns. Mira S. has been inactive for 3 weeks; a re-engagement brief may help.
      </AICallout>

      {/* ── Slide-in panels (render outside table so they overlay) ── */}
      {panel && panel.type === 'utm' && panel.creator && (
        <CrUtmPanel creator={panel.creator} onClose={() => setPanel(null)} />
      )}
      {panel && panel.type === 'brief' && panel.creator && (
        <CrBriefPanel creator={panel.creator} onClose={() => setPanel(null)} />
      )}
      {panel && panel.type === 'add' && (
        <CrAddPanel onClose={() => setPanel(null)} onCreated={handleCreated} />
      )}
      {panel && panel.type === 'view' && panel.creator && (
        <div style={{position: 'fixed', top: 0, right: 0, bottom: 0, width: 360, background: 'var(--bg-1)', borderLeft: '1px solid var(--border)', zIndex: 100, display: 'flex', flexDirection: 'column', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)'}}>
          <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 20px', borderBottom: '1px solid var(--border)'}}>
            <div style={{fontSize: 14, fontWeight: 600}}>Creator Detail</div>
            <button className="btn ghost" style={{padding: 6}} onClick={() => setPanel(null)}><Icon name="x" size={14} /></button>
          </div>
          <div style={{padding: 20, display: 'flex', flexDirection: 'column', gap: 16}}>
            <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
              <CrAvatar name={panel.creator.name} size={44} />
              <div>
                <div style={{fontSize: 15, fontWeight: 600}}>{panel.creator.name}</div>
                <div style={{fontSize: 12, color: 'var(--text-3)'}}>{panel.creator.handle}</div>
              </div>
            </div>
            {[
              { label: 'Platform',   value: panel.creator.platform },
              { label: 'Followers',  value: fmtAudience(panel.creator.audience_size) },
              { label: 'Niche',      value: panel.creator.niche },
              { label: 'Status',     value: panel.creator.status },
            ].map(({ label, value }) => (
              <div key={label} style={{display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '8px 0', borderBottom: '1px solid var(--border)'}}>
                <span style={{color: 'var(--text-3)'}}>{label}</span>
                <span style={{color: 'var(--text-1)', fontWeight: 500}}>{value}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Backdrop when panel is open */}
      {panel && (
        <div onClick={() => { if (confirmDiscard()) setPanel(null); }} style={{position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 99}} />
      )}
    </div>
  );
};

window.CreatorScreen = CreatorScreen;
