/* screen-influencer-detail-v2.jsx — Influencer detail with v2 chip vocab.
   Replaces ScreenBrandInfluencerDetail. Uses AppSidebar + AppTopbar.
   Same data source as Discover (RD_CREATORS) so signals stay consistent. */
/* global React, RD_CREATORS, AppSidebar, AppTopbar, useRouter, useT,
   ProvenanceBadge, RiskBadge, RebookChip, CPEBadge, MatchChip, PlatformIcon, fmtK,
   Avatar, Sparkline, LineChart, Donut, BarChart, Icon, Pill */

const { useState: useID2State } = React;

// Default to Linh Châu (id=1) — extend if you want to pass an id via tweak/url later
function ScreenBrandInfluencerDetail({ creatorId = 1 }) {
  const { go } = useRouter();
  const [tab, setTab] = useID2State('overview');
  const c = RD_CREATORS.find((x) => x.id === creatorId) || RD_CREATORS[0];

  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-discovery" />
      <main className="main">
        <AppTopbar />

        {/* Crumbs */}
        <div className="row items-center gap-6 muted mb-3" style={{ fontSize: 12 }}>
          <a onClick={() => go('brand-discovery')} style={{ cursor: 'pointer' }}>Discover</a>
          <span>·</span>
          <span className="bold" style={{ color: 'var(--ink)' }}>{c.name}</span>
        </div>

        {/* Hero */}
        <CreatorHero c={c} />

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 4, marginTop: 22, borderBottom: '1px solid var(--line)' }}>
          {[
            { id: 'overview',   label: 'Overview' },
            { id: 'audience',   label: 'Audience' },
            { id: 'content',    label: 'Recent content' },
            { id: 'rate',       label: 'Rate card' },
            { id: 'history',    label: 'Collab history' },
            { id: 'risk',       label: 'Risk & data' },
          ].map((tb) => (
            <button key={tb.id}
              onClick={() => setTab(tb.id)}
              style={{
                background: 'transparent', border: 0,
                padding: '11px 16px',
                fontSize: 12.5, fontWeight: 700, fontFamily: 'inherit',
                color: tab === tb.id ? 'var(--ink)' : 'var(--ink-soft)',
                borderBottom: '2px solid ' + (tab === tb.id ? 'var(--ink)' : 'transparent'),
                marginBottom: -1, cursor: 'pointer',
                transition: 'color .15s'
              }}>{tb.label}</button>
          ))}
        </div>

        {tab === 'overview' && <OverviewTab c={c} />}
        {tab === 'audience' && <AudienceTab c={c} />}
        {tab === 'content'  && <ContentTab c={c} />}
        {tab === 'rate'     && <RateCardTab c={c} />}
        {tab === 'history'  && <HistoryTab c={c} />}
        {tab === 'risk'     && <RiskTab c={c} />}
      </main>
    </div>
  );
}

// ─── Hero ────────────────────────────────────────────────────────
function CreatorHero({ c }) {
  return (
    <div style={{
      background: 'white',
      border: '1px solid var(--line)',
      borderRadius: 18,
      padding: 22,
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Decor */}
      <div style={{
        position: 'absolute', top: -80, right: -80,
        width: 280, height: 280, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(0,156,255,0.10), transparent 60%)',
        filter: 'blur(8px)', pointerEvents: 'none'
      }} />

      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 22, position: 'relative' }}>
        {/* Avatar + verified */}
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <Avatar name={c.name} size={92} />
          {c.verified && <div style={{ position: 'absolute', bottom: -2, right: -2, background: 'white', borderRadius: '50%', padding: 2 }}>{Icon.verified}</div>}
        </div>

        {/* Center info */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <h1 style={{ fontFamily: 'Space Grotesk', fontSize: 30, fontWeight: 700, letterSpacing: '-0.025em', margin: 0 }}>
              {c.name}
            </h1>
            {c.star && (
              <span style={{ background: 'var(--yellow)', color: 'var(--ink)', fontSize: 10, fontWeight: 800, padding: '3px 8px', borderRadius: 5, letterSpacing: '0.06em' }}>
                BEST ROI
              </span>
            )}
          </div>
          <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
            <PlatformIcon name={c.platform} />
            {c.handle} · {c.cat} · {c.geo} · {c.level}
          </div>

          {/* Signal row — the new chip vocab */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginTop: 12 }}>
            <RiskBadge bot={c.bot} growth={c.growth} />
            {c.rebookCount > 0 && <RebookChip count={c.rebookCount} last={c.rebookLast} />}
            {c.growth > 15 && (
              <span style={{ fontSize: 10.5, fontWeight: 700, color: '#0a8a72', background: 'rgba(31,214,180,0.16)', padding: '3px 9px', borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                {Icon.trend} +{c.growth}% MoM
              </span>
            )}
            {c.audienceFit >= 70 && (
              <span style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--cyan-dark)', background: 'rgba(0,156,255,0.10)', padding: '3px 9px', borderRadius: 999 }}>
                ICP {c.audienceFit}% fit · matches active brief
              </span>
            )}
          </div>

          {/* Platform dots */}
          <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
            <div style={{ width: 28, height: 28, background: '#002B50', color: 'white', borderRadius: 7, display: 'grid', placeItems: 'center' }}>{Icon.tiktok}</div>
            <div style={{ width: 28, height: 28, background: '#FF6FA3', color: 'white', borderRadius: 7, display: 'grid', placeItems: 'center' }}>{Icon.instagram}</div>
            <div style={{ width: 28, height: 28, background: '#FF4444', color: 'white', borderRadius: 7, display: 'grid', placeItems: 'center' }}>{Icon.youtube}</div>
          </div>
        </div>

        {/* Right: actions + match + CPE */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-end', minWidth: 240 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm">{Icon.external} View public</button>
            <button className="btn btn-primary btn-sm">{Icon.plus} Add to campaign</button>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 14px', background: 'var(--bg-soft)', borderRadius: 14, marginTop: 4 }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>Match</div>
              <div style={{ marginTop: 4 }}><MatchChip score={c.match} /></div>
            </div>
            <div style={{ width: 1, height: 36, background: 'var(--line)' }} />
            <CPEBadge value={c.cpe} />
          </div>

          {/* Per-post price */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5, color: 'var(--ink-soft)' }}>
            <span>Price · post</span>
            <b style={{ fontFamily: 'Space Grotesk', fontSize: 14, color: 'var(--ink)', fontWeight: 700 }}>
              ${c.priceMin}–{c.priceMax}K
            </b>
          </div>
        </div>
      </div>

      {/* AI reason banner */}
      <div style={{ marginTop: 14, background: 'rgba(28,28,201,0.05)', border: '1px solid rgba(28,28,201,0.15)', borderRadius: 12, padding: '10px 12px', display: 'flex', gap: 10, alignItems: 'flex-start', position: 'relative' }}>
        <div style={{ width: 24, height: 24, borderRadius: 7, background: 'linear-gradient(135deg, var(--ink), var(--indigo))', color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
          {Icon.spark}
        </div>
        <div>
          <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--indigo)', marginBottom: 2 }}>Why AI ranked this creator</div>
          <div style={{ fontSize: 12, color: 'var(--ink)', lineHeight: 1.5 }}>{c.reason}</div>
        </div>
      </div>
    </div>
  );
}

// ─── Overview tab ───────────────────────────────────────────────
function OverviewTab({ c }) {
  return (
    <>
      {/* KPI row with provenance under each metric */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 18 }}>
        <KpiTile l="Followers"     v={fmtK(c.followers)}        prov={{ src: c.provSrc, age: c.provAge }} color="var(--cyan)" />
        <KpiTile l="ER · 30d"      v={c.er + '%'}               prov={{ src: c.provSrc, age: c.provAge }} color="var(--mint-deep)" />
        <KpiTile l="$ / engage"    v={'$' + c.cpe.toFixed(2)}   sub="est · 30d" color="var(--indigo)" highlight={c.cpe < 0.30} />
        <KpiTile l="Audience fit"  v={c.audienceFit + '%'}      sub="vs active brief ICP" color="var(--pink-hot)" />
      </div>

      {/* Two columns: growth + audience snapshot */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14, marginTop: 18 }}>
        <div className="card-elevated">
          <div className="row items-center justify-between mb-2">
            <div className="title-md">Follower growth · 6 months</div>
            <ProvenanceBadge src={c.provSrc} age={c.provAge} />
          </div>
          <div className="muted mb-3" style={{ fontSize: 12 }}>
            +{c.growth}% MoM · {c.growth > 15 ? 'accelerating in last 8 weeks' : 'stable'}
          </div>
          <LineChart
            series={[{ name: 'Followers (K)', color: '#009CFF', data: [310, 340, 365, 395, 422, 450, c.followers / 1000].map(Math.round) }]}
            xLabels={['Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May']}
            height={220}
          />
        </div>

        <div className="card-elevated">
          <div className="title-md mb-3">Audience snapshot</div>
          <div className="row items-center gap-12">
            <Donut
              data={[
                { label: 'F', value: 78, color: '#FF6FA3' },
                { label: 'M', value: 20, color: '#009CFF' },
                { label: 'Other', value: 2, color: '#FEE960' },
              ]}
              size={130} thickness={16}
              centerLabel="Female"
              centerValue="78%"
            />
            <div className="flex-1">
              <div className="cap-label mb-2">Age</div>
              <BarChart
                data={[
                  { label: '13–17', value: 12, color: 'var(--lavender)' },
                  { label: '18–24', value: 48, color: 'var(--pink-hot)' },
                  { label: '25–34', value: 28, color: 'var(--cyan)' },
                  { label: '35+',   value: 12, color: 'var(--mint-deep)' },
                ]}
                height={70}
                labelFmt={(v) => v + '%'}
              />
            </div>
          </div>
          <div style={{ marginTop: 10, padding: 10, background: 'rgba(0,156,255,0.06)', borderRadius: 10, fontSize: 11.5, color: 'var(--ink)', display: 'flex', gap: 8 }}>
            <span style={{ color: 'var(--cyan-dark)', fontWeight: 700 }}>●</span>
            <span><b style={{ fontWeight: 700 }}>{c.audienceFit}%</b> overlap with your active brief (HCM · 18–24F · skincare).</span>
          </div>
        </div>
      </div>

      {/* Recent content thumbnails */}
      <div className="card-elevated mt-6">
        <div className="row items-center justify-between mb-3">
          <div>
            <div className="title-md">Recent content</div>
            <div className="muted" style={{ fontSize: 12 }}>Last 6 posts · sorted by reach</div>
          </div>
          <ProvenanceBadge src="api" age="5h" />
        </div>
        <ContentGrid />
      </div>
    </>
  );
}

// ─── Audience tab ─────────────────────────────────────────────
function AudienceTab({ c }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 18 }}>
      <div className="card-elevated">
        <div className="title-md mb-2">Gender split</div>
        <Donut
          data={[
            { label: 'F', value: 78, color: '#FF6FA3' },
            { label: 'M', value: 20, color: '#009CFF' },
            { label: 'Other', value: 2, color: '#FEE960' },
          ]}
          size={200} thickness={26}
          centerLabel="Female"
          centerValue="78%"
        />
      </div>
      <div className="card-elevated">
        <div className="title-md mb-3">Geography</div>
        <BarChart
          data={[
            { label: 'HCM', value: 58, color: 'var(--cyan)' },
            { label: 'HN',  value: 22, color: 'var(--indigo)' },
            { label: 'DN',  value: 10, color: 'var(--mint-deep)' },
            { label: 'Other VN', value: 7, color: 'var(--lavender)' },
            { label: 'Overseas', value: 3, color: 'var(--coral)' },
          ]}
          height={180}
          labelFmt={(v) => v + '%'}
        />
      </div>
      <div className="card-elevated" style={{ gridColumn: '1 / -1' }}>
        <div className="row items-center justify-between mb-3">
          <div className="title-md">Brief fit · audience overlap</div>
          <Pill variant="mint">{c.audienceFit}% overlap</Pill>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, fontSize: 12.5 }}>
          <FitRow label="Geo · HCM"       creator="92%" brief="100%" match="strong" />
          <FitRow label="Age · 18–24"     creator="48%" brief="65%"  match="strong" />
          <FitRow label="Gender · F"      creator="78%" brief="60%"  match="strong" />
          <FitRow label="Interest · skincare" creator="62%" brief="100%" match="ok" />
          <FitRow label="Interest · vegan claim" creator="18%" brief="40%" match="weak" />
          <FitRow label="Spending power · mid+" creator="55%" brief="70%" match="ok" />
        </div>
      </div>
    </div>
  );
}

function FitRow({ label, creator, brief, match }) {
  const color = match === 'strong' ? 'var(--mint-deep)' : match === 'ok' ? 'var(--yellow-deep)' : 'var(--coral)';
  return (
    <div style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 10 }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--ink-soft)', letterSpacing: '0.10em', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
        <span style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 17 }}>{creator}</span>
        <span style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>vs brief {brief}</span>
      </div>
      <div style={{ height: 4, background: 'white', borderRadius: 999, marginTop: 6, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: creator, background: color, borderRadius: 999 }}></div>
      </div>
    </div>
  );
}

// ─── Content tab ──────────────────────────────────────────────
function ContentTab() {
  return (
    <div className="card-elevated" style={{ marginTop: 18 }}>
      <div className="row items-center justify-between mb-3">
        <div>
          <div className="title-md">Recent content · 12 posts</div>
          <div className="muted" style={{ fontSize: 12 }}>Sorted by reach · ER overlay</div>
        </div>
        <ProvenanceBadge src="api" age="5h" />
      </div>
      <ContentGrid count={12} />
    </div>
  );
}

function ContentGrid({ count = 6 }) {
  const posts = [
    { r: '1.2M', er: '7.4%', c1: '#79FEE7', c2: '#009CFF' },
    { r: '820K', er: '6.8%', c1: '#FFC3D6', c2: '#FF6FA3' },
    { r: '480K', er: '5.4%', c1: '#EAC2FB', c2: '#1C1CC9' },
    { r: '380K', er: '7.0%', c1: '#FEE960', c2: '#FF7A59' },
    { r: '320K', er: '6.4%', c1: '#79FEE7', c2: '#1FD6B4' },
    { r: '280K', er: '5.8%', c1: '#FFC3D6', c2: '#EAC2FB' },
    { r: '240K', er: '6.2%', c1: '#79FEE7', c2: '#1C1CC9' },
    { r: '210K', er: '5.9%', c1: '#FEE960', c2: '#FF6FA3' },
    { r: '195K', er: '5.4%', c1: '#FFC3D6', c2: '#1FD6B4' },
    { r: '170K', er: '6.0%', c1: '#EAC2FB', c2: '#009CFF' },
    { r: '155K', er: '5.7%', c1: '#79FEE7', c2: '#FF7A59' },
    { r: '140K', er: '5.4%', c1: '#FFC3D6', c2: '#1C1CC9' },
  ].slice(0, count);
  const cols = count <= 6 ? 6 : 6;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 8 }}>
      {posts.map((p, i) => (
        <div key={i} style={{
          position: 'relative', aspectRatio: '9/14', borderRadius: 10, overflow: 'hidden',
          background: `linear-gradient(135deg, ${p.c1}, ${p.c2})`,
        }}>
          <div style={{
            position: 'absolute', top: '50%', left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 30, height: 30, borderRadius: 999,
            background: 'rgba(255,255,255,0.30)', backdropFilter: 'blur(6px)',
            display: 'grid', placeItems: 'center', color: 'white', fontSize: 10
          }}>▶</div>
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            padding: '14px 7px 7px',
            background: 'linear-gradient(transparent, rgba(0,0,0,0.55))', color: 'white'
          }}>
            <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 12 }}>{p.r}</div>
            <div style={{ fontSize: 9, fontWeight: 700 }}>{p.er} ER</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Rate card tab ─────────────────────────────────────────────
function RateCardTab({ c }) {
  const rates = [
    ['TikTok 30s video',     1.8, 'var(--cyan)'],
    ['TikTok live 20m',      2.4, 'var(--indigo)'],
    ['IG reel · 15s',        1.4, 'var(--pink-hot)'],
    ['IG static · single',   0.6, 'var(--lavender-deep)'],
    ['IG stories · 3-pack',  0.9, 'var(--mint-deep)'],
    ['YouTube short',        1.2, 'var(--coral)'],
    ['Bundle · TT + IG reel',2.9, 'var(--yellow-deep)'],
    ['Long YT review',       3.6, 'var(--ink)'],
  ];
  return (
    <>
      <div className="card-elevated" style={{ marginTop: 18 }}>
        <div className="row items-center justify-between mb-3">
          <div>
            <div className="title-md">Rate card · self-reported</div>
            <div className="muted" style={{ fontSize: 12 }}>Creator publishes their rate so Brand sees price before invite. Negotiable case-by-case.</div>
          </div>
          <button className="btn btn-primary btn-sm">{Icon.spark} Request custom quote</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
          {rates.map(([l, p, col], i) => (
            <div key={i} style={{ padding: 14, background: 'var(--bg-soft)', borderRadius: 12 }}>
              <div style={{ width: 8, height: 8, borderRadius: 999, background: col, marginBottom: 6 }} />
              <div className="cap-label" style={{ fontSize: 9 }}>{l}</div>
              <div className="font-display bold tabular mt-1" style={{ fontSize: 22 }}>${p}K</div>
            </div>
          ))}
        </div>
      </div>

      <div className="card-elevated mt-6">
        <div className="row items-center justify-between mb-2">
          <div className="title-md">AI-suggested rate for your active brief</div>
          <Pill variant="mint">{Icon.spark} Save $0.8K vs avg</Pill>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginTop: 12 }}>
          <SuggestionRow label="Vitamin C Skin Glow · paid" suggest="$2.4K" reason="3-deliverable bundle (TT video + IG reel + IG stories)" />
          <SuggestionRow label="+ Affiliate (12% commission)" suggest="+$0.5K est." reason="Based on her conversion baseline in skincare" />
          <SuggestionRow label="Total package" suggest="≈ $2.9K" reason="Within your $2.5K per-creator budget — negotiate ↓" highlight />
        </div>
      </div>
    </>
  );
}

function SuggestionRow({ label, suggest, reason, highlight }) {
  return (
    <div style={{ padding: 14, background: highlight ? 'linear-gradient(135deg, rgba(31,214,180,0.10), rgba(0,156,255,0.10))' : 'var(--bg-soft)', borderRadius: 12, border: highlight ? '1px solid rgba(31,214,180,0.30)' : '1px solid transparent' }}>
      <div className="cap-label" style={{ fontSize: 9 }}>{label}</div>
      <div className="font-display bold mt-1" style={{ fontSize: 20, letterSpacing: '-0.02em' }}>{suggest}</div>
      <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 4, lineHeight: 1.4 }}>{reason}</div>
    </div>
  );
}

// ─── Collab history tab (rebook context) ────────────────────────
function HistoryTab({ c }) {
  const past = c.rebookCount > 0
    ? [
      { id: 'C-2200', name: 'Vitamin C Series · Q4 2025', status: 'completed', reach: '410K', er: 7.8, paid: '$3.2K', cpe: '$0.42', score: 92 },
      { id: 'C-2280', name: 'Acne Patch Bundle · Q1 2026', status: 'completed', reach: '380K', er: 6.4, paid: '$2.8K', cpe: '$0.48', score: 88 },
    ]
    : [];
  return (
    <div style={{ marginTop: 18 }}>
      {past.length > 0 ? (
        <>
          <div className="card-elevated">
            <div className="row items-center justify-between mb-3">
              <div>
                <div className="title-md">Past collaborations · {past.length}</div>
                <div className="muted" style={{ fontSize: 12 }}>Average ER <b style={{ color: 'var(--ink)' }}>7.1%</b> · Average CPE <b style={{ color: 'var(--ink)' }}>$0.45</b> · 100% on time</div>
              </div>
              <button className="btn btn-primary btn-sm">{Icon.spark} Rebook for next campaign</button>
            </div>

            {past.map((p) => (
              <div key={p.id} style={{ display: 'grid', gridTemplateColumns: '1fr 90px 90px 90px 90px 110px', gap: 12, padding: '12px 0', borderTop: '1px solid var(--line)', fontSize: 12.5, alignItems: 'center' }}>
                <div>
                  <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14 }}>{p.name}</div>
                  <div className="muted" style={{ fontSize: 11 }}>{p.id} · paid + affiliate</div>
                </div>
                <div style={{ textAlign: 'right' }}><div style={{ fontFamily: 'Space Grotesk', fontWeight: 700 }}>{p.reach}</div><div className="muted" style={{ fontSize: 10 }}>reach</div></div>
                <div style={{ textAlign: 'right' }}><div style={{ fontFamily: 'Space Grotesk', fontWeight: 700 }}>{p.er}%</div><div className="muted" style={{ fontSize: 10 }}>ER</div></div>
                <div style={{ textAlign: 'right' }}><div style={{ fontFamily: 'Space Grotesk', fontWeight: 700 }}>{p.paid}</div><div className="muted" style={{ fontSize: 10 }}>paid</div></div>
                <div style={{ textAlign: 'right' }}><div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, color: '#0a8a72' }}>{p.cpe}</div><div className="muted" style={{ fontSize: 10 }}>CPE</div></div>
                <div style={{ textAlign: 'right' }}>
                  <MatchChip score={p.score} />
                </div>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 14, background: 'rgba(28,28,201,0.05)', border: '1px solid rgba(28,28,201,0.15)', borderRadius: 12, padding: 14, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{ width: 28, height: 28, borderRadius: 9, background: 'linear-gradient(135deg, var(--ink), var(--indigo))', color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
              {Icon.spark}
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--ink)', lineHeight: 1.5 }}>
              <b style={{ fontWeight: 800 }}>AI Recommendation:</b> Linh Châu rebooked <b>{c.rebookCount}×</b> and outperforms her baseline by 38% on Vitamin C content.
              Her contract turnaround averages <b>4.2 days</b>, fastest in your roster. Strong rebook signal for any skincare campaign in Q3.
            </div>
          </div>
        </>
      ) : (
        <div className="card-elevated" style={{ textAlign: 'center', padding: 40 }}>
          <div style={{ fontFamily: 'Space Grotesk', fontSize: 17, fontWeight: 700, letterSpacing: '-0.015em' }}>No prior collaborations</div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 6 }}>
            This is a fresh creator. Add to your active campaign for the first run — a rebook chip will appear here once she completes a deliverable.
          </div>
          <button className="btn btn-primary btn-sm" style={{ marginTop: 16 }}>{Icon.plus} Add to active campaign</button>
        </div>
      )}
    </div>
  );
}

// ─── Risk & data tab ──────────────────────────────────────────
function RiskTab({ c }) {
  const isRisky = c.bot >= 15;
  return (
    <div style={{ marginTop: 18 }}>
      <div className="card-elevated">
        <div className="row items-center justify-between mb-3">
          <div className="title-md">Audience quality</div>
          <RiskBadge bot={c.bot} growth={c.growth} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          <RiskTile l="Bot ratio" v={c.bot + '%'} threshold="< 10% safe" state={c.bot >= 15 ? 'bad' : c.bot >= 10 ? 'warn' : 'ok'} />
          <RiskTile l="Engagement authenticity" v="94%" threshold="real interactions" state="ok" />
          <RiskTile l="Growth pattern" v={c.growth > 30 ? 'spike' : c.growth > 0 ? 'organic' : 'flat'} threshold="organic preferred" state={c.growth > 30 ? 'warn' : 'ok'} />
        </div>
        {isRisky && (
          <div style={{ marginTop: 14, padding: 12, background: 'rgba(255,68,68,0.06)', border: '1px solid rgba(255,68,68,0.25)', borderRadius: 12, fontSize: 12.5, color: '#B12B2B', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
              <path d="M12 9v4M12 17h.01"/><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
            </svg>
            <span><b style={{ fontWeight: 800 }}>{c.bot}% audience flagged as suspicious.</b> Recommend skip or run a small test-buy first.</span>
          </div>
        )}
      </div>

      <div className="card-elevated mt-6">
        <div className="row items-center justify-between mb-3">
          <div className="title-md">Data provenance</div>
          <button className="btn btn-ghost btn-sm">Refresh now</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
          <ProvRow metric="Followers" src={c.provSrc} age={c.provAge} />
          <ProvRow metric="ER · 30d"  src={c.provSrc} age={c.provAge} />
          <ProvRow metric="Bot ratio" src="crawl" age="4d" />
          <ProvRow metric="Audience demographics" src="api" age="2d" />
          <ProvRow metric="Recent content" src="api" age="5h" />
          <ProvRow metric="Past collaborations" src="import" age="18d" />
        </div>
      </div>
    </div>
  );
}

function RiskTile({ l, v, threshold, state }) {
  const color = state === 'ok' ? '#0a8a72' : state === 'warn' ? '#856200' : '#B12B2B';
  const bg = state === 'ok' ? 'rgba(31,214,180,0.10)' : state === 'warn' ? 'rgba(242,196,17,0.16)' : 'rgba(255,68,68,0.10)';
  return (
    <div style={{ padding: 14, background: bg, borderRadius: 12 }}>
      <div className="cap-label" style={{ fontSize: 9 }}>{l}</div>
      <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 22, color, marginTop: 4 }}>{v}</div>
      <div style={{ fontSize: 10.5, color, fontWeight: 600, marginTop: 4 }}>{threshold}</div>
    </div>
  );
}

function ProvRow({ metric, src, age }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: 10, background: 'var(--bg-soft)', borderRadius: 10 }}>
      <span style={{ flex: 1, fontSize: 12, fontWeight: 600 }}>{metric}</span>
      <ProvenanceBadge src={src} age={age} />
    </div>
  );
}

// ─── KPI tile (used in overview) ────────────────────────────────
function KpiTile({ l, v, sub, prov, color, highlight }) {
  return (
    <div className="kpi" style={{ position: 'relative' }}>
      {highlight && <span style={{ position: 'absolute', top: 12, right: 12, background: 'var(--mint)', color: 'var(--ink)', fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 4, letterSpacing: '0.06em' }}>BEST</span>}
      <div className="kpi-decor" style={{ background: color }} />
      <div className="kpi-label">{l}</div>
      <div className="kpi-value">{v}</div>
      <div className="kpi-foot">
        {prov ? <ProvenanceBadge src={prov.src} age={prov.age} /> : (sub && <span style={{ fontSize: 11 }}>{sub}</span>)}
      </div>
    </div>
  );
}

Object.assign(window, { ScreenBrandInfluencerDetail });
