/* screen-discovery.jsx — Influencer discovery + AI Shortlist (data-poetic) */
/* global React, Sidebar, Topbar, Counter, Sparkline, Avatar, Pill, MatchCircle, Icon, useInView */

function ScreenDiscovery() {
  const [aiState, setAiState] = React.useState('idle'); // idle | thinking | done
  const [shortlist, setShortlist] = React.useState([]);

  React.useEffect(() => {
    // Auto-trigger AI to show the feature
    const t1 = setTimeout(() => setAiState('thinking'), 600);
    const t2 = setTimeout(() => {
      setAiState('done');
      setShortlist(MOCK_SHORTLIST);
    }, 3200);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  const regenerate = () => {
    setAiState('thinking');
    setShortlist([]);
    setTimeout(() => {
      setAiState('done');
      setShortlist(MOCK_SHORTLIST);
    }, 2400);
  };

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

        <div className="row items-end justify-between mb-6">
          <div>
            <span className="pill pill-cyan">Discovery</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>Find your next creator.</h1>
            <div className="page-subtitle"><span className="bold tabular"><Counter to={31247} duration={1600} /></span> creators across TikTok, Instagram, YouTube · Shopee &amp; TikTok Shop</div>
          </div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm">{Icon.sliders} Advanced</button>
            <button className="btn btn-primary btn-sm">{Icon.plus} Save segment</button>
          </div>
        </div>

        {/* AI bar — the hero */}
        <div style={{ marginTop: 24 }}>
          <AIBriefBar
            state={aiState}
            onGenerate={regenerate}
            count={shortlist.length}
          />
        </div>

        {/* Filter chips */}
        <FilterBar />

        {/* Main grid: shortlist + insights side */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 18, marginTop: 18 }}>
          {/* Cards grid */}
          <div>
            <div className="row items-center justify-between mb-3">
              <div className="cap-label">
                {aiState === 'done'
                  ? <>AI ranked · showing <span className="bold" style={{ color: 'var(--ink)' }}>{shortlist.length}</span> of 312 matches</>
                  : 'Loading matches…'}
              </div>
              <div className="row items-center gap-8">
                <span className="cap-label">Sort by</span>
                <button className="row items-center gap-4 btn-sm" style={{ background: 'var(--bg-soft)', borderRadius: 8, padding: '6px 10px', border: 0, color: 'var(--ink)', fontSize: 12, fontWeight: 700 }}>
                  Match score {Icon.arrowDown}
                </button>
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
              {aiState !== 'done' && Array.from({ length: 6 }).map((_, i) => <CreatorSkeleton key={i} />)}
              {aiState === 'done' && shortlist.map((c, i) => <CreatorCard key={c.id} {...c} index={i} />)}
            </div>
          </div>

          {/* Insights panel */}
          <InsightsPanel />
        </div>
      </main>
    </div>
  );
}

// ── AI bar ──
function AIBriefBar({ state, onGenerate, count }) {
  return (
    <div className="card-elevated" style={{
      padding: 18,
      background: 'linear-gradient(135deg, #002B50 0%, #1C1CC9 100%)',
      color: 'white',
      position: 'relative',
      overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', top: -50, right: -50,
        width: 200, height: 200, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(255,111,163,0.45), transparent 60%)',
        filter: 'blur(20px)'
      }} />
      <div className="row items-center gap-16" style={{ position: 'relative', zIndex: 1 }}>
        <div className="orb" />
        <div className="flex-1">
          <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> Active brief</Pill>
          <div className="font-display bold mt-2" style={{ fontSize: 18, letterSpacing: '-0.02em' }}>
            Vitamin C Skin Glow · Q2 Launch
          </div>
          <div className="row gap-6" style={{ marginTop: 8, flexWrap: 'wrap' }}>
            <Pill variant="dark">tiktok</Pill>
            <Pill variant="dark">18–24 yrs</Pill>
            <Pill variant="dark">HCM, HN</Pill>
            <Pill variant="dark">Skincare</Pill>
            <Pill variant="dark">$5K–$15K</Pill>
          </div>
        </div>
        <div className="text-right" style={{ minWidth: 220 }}>
          {state === 'thinking' && (
            <>
              <div className="ai-thinking" style={{ marginBottom: 6 }}>
                <span className="dot" /><span className="dot" /><span className="dot" />
              </div>
              <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)' }}>Scanning 31,247 creators…</div>
            </>
          )}
          {state === 'done' && (
            <>
              <div className="font-display bold" style={{ fontSize: 28, color: 'var(--mint)' }}>
                <Counter to={count} duration={800} /> matches
              </div>
              <div className="row gap-8" style={{ justifyContent: 'flex-end', marginTop: 6 }}>
                <button className="btn btn-yellow btn-sm" onClick={onGenerate}>{Icon.spark} Regenerate</button>
                <button className="btn btn-sm" style={{ background: 'rgba(255,255,255,0.12)', color: 'white', boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.25)' }}>Add all</button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Filter chips ──
function FilterBar() {
  const chips = [
    { label: 'TikTok', active: true, count: 184 },
    { label: 'Instagram', active: false, count: 96 },
    { label: 'YouTube', active: false, count: 32 },
    { label: 'Micro (50K–500K)', active: true, count: 142 },
    { label: 'HCM', active: true, count: 88 },
    { label: 'Beauty', active: true, count: 64 },
    { label: 'ER ≥ 4%', active: false, count: 102 },
    { label: 'Verified only', active: false, count: 48 },
  ];
  return (
    <div className="row items-center gap-8" style={{ marginTop: 18, flexWrap: 'wrap' }}>
      <span className="cap-label">Filters:</span>
      {chips.map((c, i) => (
        <button key={i} style={{
          padding: '6px 12px',
          borderRadius: 999,
          border: '1.5px solid ' + (c.active ? 'var(--ink)' : 'var(--line)'),
          background: c.active ? 'var(--ink)' : 'white',
          color: c.active ? 'white' : 'var(--ink)',
          fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 6,
          transition: 'all .15s'
        }}>
          {c.label}
          <span style={{
            fontSize: 10, opacity: 0.7, fontWeight: 600,
            background: c.active ? 'rgba(255,255,255,0.18)' : 'var(--bg-soft)',
            padding: '0 6px', borderRadius: 999
          }}>{c.count}</span>
        </button>
      ))}
      <button style={{
        background: 'transparent', border: 0, color: 'var(--cyan-dark)', fontWeight: 700, fontSize: 12, cursor: 'pointer'
      }}>Clear all</button>
    </div>
  );
}

// ── Creator card ──
function CreatorCard({ name, handle, cat, platform, followers, er, match, reason, level, sparkData, verified, index }) {
  const platformIcon = { tiktok: Icon.tiktok, instagram: Icon.instagram, youtube: Icon.youtube }[platform];
  return (
    <div className="card-elevated" style={{
      padding: 0, overflow: 'hidden', position: 'relative',
      animation: `cardIn .55s ${index * 80}ms backwards cubic-bezier(.4,0,.2,1)` }}>
      {/* gradient bar */}
      <div style={{
        height: 4,
        background: match >= 90 ? 'linear-gradient(90deg, #1FD6B4, #79FEE7)'
          : match >= 75 ? 'linear-gradient(90deg, #009CFF, #1C1CC9)'
          : 'linear-gradient(90deg, #FEE960, #FF7A59)'
      }} />

      <div style={{ padding: 18 }}>
        <div className="row items-start gap-12">
          <div style={{ position: 'relative' }}>
            <Avatar name={name} size={52} />
            {verified && (
              <div style={{ position: 'absolute', bottom: -2, right: -2 }}>{Icon.verified}</div>
            )}
          </div>
          <div className="flex-1" style={{ minWidth: 0 }}>
            <div className="row items-center gap-6">
              <div className="font-display bold" style={{ fontSize: 16, letterSpacing: '-0.015em' }}>{name}</div>
              <div style={{ color: 'var(--ink-soft)' }}>{platformIcon}</div>
            </div>
            <div className="muted" style={{ fontSize: 12 }}>{handle}</div>
            <div className="row gap-6 mt-2" style={{ flexWrap: 'wrap' }}>
              <Pill variant="lav">{cat}</Pill>
              <Pill variant="ink">{level}</Pill>
            </div>
          </div>
          <MatchCircle score={match} size={52} />
        </div>

        {/* AI reasoning */}
        <div style={{
          background: 'var(--bg-soft)',
          borderRadius: 12,
          padding: '10px 12px',
          marginTop: 12,
          fontSize: 12,
          lineHeight: 1.5,
          color: 'var(--ink)',
          position: 'relative'
        }}>
          <div className="cap-label" style={{ fontSize: 9, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--pink-hot)' }} />
            AI says
          </div>
          {reason}
        </div>

        {/* footer metrics */}
        <div className="row items-end justify-between mt-4">
          <div className="row gap-16">
            <div>
              <div className="cap-label" style={{ fontSize: 9 }}>Followers</div>
              <div className="font-display bold tabular" style={{ fontSize: 18 }}>{followers}</div>
            </div>
            <div>
              <div className="cap-label" style={{ fontSize: 9 }}>ER</div>
              <div className="font-display bold tabular" style={{ fontSize: 18 }}>{er}%</div>
            </div>
          </div>
          <div style={{ width: 96 }}>
            <Sparkline data={sparkData} color={match >= 90 ? 'var(--mint-deep)' : 'var(--cyan)'} fillId={`cc-${name}`} height={36} delay={0.3 + index * 0.05} />
          </div>
        </div>

        <div className="row gap-8 mt-3">
          <button className="btn btn-ghost btn-sm" style={{ flex: 1, padding: '8px 14px' }}>
            View profile
          </button>
          <button className="btn btn-primary btn-sm" style={{ flex: 1, padding: '8px 14px' }}>
            {Icon.plus} Add
          </button>
        </div>
      </div>
      <style>{`@keyframes cardIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </div>
  );
}

function CreatorSkeleton() {
  return (
    <div className="card" style={{ padding: 18 }}>
      <div className="row items-center gap-12">
        <div className="shimmer" style={{ width: 52, height: 52, borderRadius: 999 }} />
        <div style={{ flex: 1 }}>
          <div className="shimmer" style={{ height: 14, width: '60%', borderRadius: 6 }} />
          <div className="shimmer" style={{ height: 10, width: '40%', borderRadius: 6, marginTop: 8 }} />
        </div>
        <div className="shimmer" style={{ width: 52, height: 52, borderRadius: 999 }} />
      </div>
      <div className="shimmer" style={{ height: 56, borderRadius: 12, marginTop: 14 }} />
      <div className="row gap-8 mt-3">
        <div className="shimmer" style={{ flex: 1, height: 36, borderRadius: 999 }} />
        <div className="shimmer" style={{ flex: 1, height: 36, borderRadius: 999 }} />
      </div>
    </div>
  );
}

// ── Insights panel ──
function InsightsPanel() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14, position: 'sticky', top: 24, alignSelf: 'flex-start' }}>
      {/* Audience overlap */}
      <div className="card-elevated">
        <div className="cap-label">Audience overlap</div>
        <div className="title-md mt-2">Top 3 picks share <span style={{ color: 'var(--pink-hot)' }}>62%</span> of audience.</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>Consider diversifying to avoid waste.</div>

        {/* Overlap visualization — venn-ish */}
        <div style={{ position: 'relative', height: 160, marginTop: 14 }}>
          <svg viewBox="0 0 280 160" width="100%" height="100%">
            <defs>
              <radialGradient id="v1" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#009CFF" stopOpacity="0.55" />
                <stop offset="100%" stopColor="#009CFF" stopOpacity="0.2" />
              </radialGradient>
              <radialGradient id="v2" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#FF6FA3" stopOpacity="0.55" />
                <stop offset="100%" stopColor="#FF6FA3" stopOpacity="0.2" />
              </radialGradient>
              <radialGradient id="v3" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="#1FD6B4" stopOpacity="0.55" />
                <stop offset="100%" stopColor="#1FD6B4" stopOpacity="0.2" />
              </radialGradient>
            </defs>
            <circle cx="100" cy="78" r="58" fill="url(#v1)" style={{ animation: 'venn1 6s ease-in-out infinite' }} />
            <circle cx="170" cy="78" r="58" fill="url(#v2)" style={{ animation: 'venn2 6s ease-in-out infinite' }} />
            <circle cx="135" cy="118" r="48" fill="url(#v3)" style={{ animation: 'venn3 6s ease-in-out infinite' }} />
            <text x="80" y="40" fontSize="11" fontWeight="700" fill="#0066AA">Linh Châu</text>
            <text x="180" y="40" fontSize="11" fontWeight="700" fill="#B0457A">Mai Vy</text>
            <text x="120" y="155" fontSize="11" fontWeight="700" fill="#0a8a72">Hà Giang</text>
          </svg>
        </div>
        <style>{`
          @keyframes venn1 { 0%,100% { transform: translate(0,0); } 50% { transform: translate(-6px, 0); } }
          @keyframes venn2 { 0%,100% { transform: translate(0,0); } 50% { transform: translate(6px, 0); } }
          @keyframes venn3 { 0%,100% { transform: translate(0,0); } 50% { transform: translate(0, 6px); } }
        `}</style>
      </div>

      {/* Price band card */}
      <div className="card-elevated">
        <div className="cap-label">Price band · per post</div>
        <div className="title-md mt-2">
          <span className="tabular"><Counter to={2.2} prefix="$" decimals={1} />K</span> –
          <span className="tabular"><Counter to={6.8} prefix=" $" decimals={1} duration={1800} />K</span>
        </div>
        <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Based on level &amp; ER for selected filters</div>

        {/* Band visualization */}
        <div style={{ marginTop: 18, position: 'relative', height: 60 }}>
          <div style={{
            position: 'absolute', left: '20%', right: '20%', top: 24,
            height: 6, background: 'linear-gradient(90deg, var(--mint), var(--cyan), var(--indigo))',
            borderRadius: 999, transformOrigin: 'left',
            animation: 'grow-w 1.2s .4s cubic-bezier(.4,0,.2,1) both', transform: 'scaleX(0)'
          }} />
          {['Nano', 'Micro', 'Mid', 'Macro', 'Mega'].map((l, i) => (
            <div key={l} style={{
              position: 'absolute', left: (i * 20 + 10) + '%', top: 0,
              transform: 'translateX(-50%)', textAlign: 'center'
            }}>
              <div style={{
                width: 12, height: 12, borderRadius: 999,
                background: i >= 1 && i <= 2 ? 'var(--cyan)' : 'var(--line)',
                border: i >= 1 && i <= 2 ? '3px solid white' : '1px solid var(--line)',
                margin: '20px auto 0',
                boxShadow: i >= 1 && i <= 2 ? '0 0 0 3px rgba(0,156,255,0.2)' : 'none',
              }} />
              <div className="cap-label" style={{ fontSize: 9, marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>
        <style>{`@keyframes grow-w { to { transform: scaleX(1); } }`}</style>
      </div>

      {/* Risk flags */}
      <div className="card-elevated">
        <div className="row items-center justify-between mb-2">
          <div className="cap-label">Risk flags</div>
          <Pill variant="mint">2 flagged</Pill>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { color: 'var(--coral)', label: 'Phương Anh', detail: 'Audience bot ratio · 18% suspicious' },
            { color: 'var(--yellow-deep)', label: 'Hà Vy', detail: 'No fresh data for 47 days' },
          ].map((r, i) => (
            <div key={i} className="row items-center gap-8" style={{ padding: 10, background: 'var(--bg-soft)', borderRadius: 10 }}>
              <div style={{ width: 8, height: 8, borderRadius: 999, background: r.color, flexShrink: 0 }} />
              <div className="flex-1">
                <div className="bold" style={{ fontSize: 12 }}>{r.label}</div>
                <div className="muted" style={{ fontSize: 11 }}>{r.detail}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Mock data ──
const MOCK_SHORTLIST = [
  { id: 1, name: 'Linh Châu', handle: '@linhchau', cat: 'Skincare', platform: 'tiktok', followers: '482K', er: 6.2, match: 94, level: 'Micro', verified: true, sparkData: [3.2, 3.8, 4.2, 4.8, 5.4, 5.8, 6.2], reason: 'Strong audience overlap with HCM 18–24F (78%), past Vitamin C content over-performed her baseline by 38%.' },
  { id: 2, name: 'Mai Vy', handle: '@maivy', cat: 'Lifestyle', platform: 'instagram', followers: '1.2M', er: 5.8, match: 88, level: 'Macro', verified: true, sparkData: [4.0, 4.4, 4.8, 5.2, 5.4, 5.6, 5.8], reason: 'Authentic mom-coded skincare voice; 62% of her audience falls in your target ICP. Premium CPM but reliable.' },
  { id: 3, name: 'Hà Giang', handle: '@hagiang', cat: 'Beauty', platform: 'tiktok', followers: '320K', er: 7.1, match: 84, level: 'Micro', verified: false, sparkData: [5.5, 6.0, 6.4, 6.7, 6.9, 7.0, 7.1], reason: 'Highest ER in shortlist. Specialises in clean beauty — strong fit for vegan claim positioning.' },
  { id: 4, name: 'Phương Anh', handle: '@phuonganh.beauty', cat: 'Beauty Vlog', platform: 'youtube', followers: '210K', er: 4.4, match: 78, level: 'Micro', verified: true, sparkData: [3.8, 4.0, 4.2, 4.3, 4.4, 4.3, 4.4], reason: 'YouTube long-form complements TikTok. Strong tutorial format for "how to apply" content.' },
  { id: 5, name: 'Thảo Nhi', handle: '@thaonhi', cat: 'Wellness', platform: 'instagram', followers: '156K', er: 5.2, match: 75, level: 'Micro', verified: false, sparkData: [4.6, 4.8, 5.0, 5.1, 5.2, 5.2, 5.2], reason: 'Cross-category fit (wellness + skincare). Younger audience skew (16–22F).' },
  { id: 6, name: 'Diệu Linh', handle: '@dieulinh.skin', cat: 'Skincare', platform: 'tiktok', followers: '95K', er: 8.4, match: 72, level: 'Micro', verified: false, sparkData: [6.8, 7.2, 7.6, 8.0, 8.2, 8.3, 8.4], reason: 'Best price band ($1.8K). High ER but smaller reach — strong for nano-test.' },
];

Object.assign(window, { ScreenDiscovery });
