/* screen-discovery-v2.jsx — Unified Discover with list/card view toggle.
   Replaces old ScreenDiscovery. Uses AppSidebar + AppTopbar (consistent app chrome).
   Per Ben: list & card are two views of the same feature, not separate options. */
/* global React, RD_CREATORS, RD_FILTERS,
   ProvenanceBadge, RiskBadge, RebookChip, CPEBadge, MatchChip, PlatformIcon, fmtK,
   Avatar, Sparkline, Icon, AppSidebar, AppTopbar, useT, useRouter */
const { useState: useDV2State } = React;

function ScreenDiscovery() {
  const { go } = useRouter();
  const [view, setView] = useDV2State('table'); // 'table' | 'cards'
  const [selected, setSelected] = useDV2State(new Set([1, 6]));
  const [filters, setFilters] = useDV2State(RD_FILTERS);
  const [showReason, setShowReason] = useDV2State(true);

  const toggleSel = (id) => {
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };
  const toggleFilter = (id) => {
    setFilters((f) => f.map((c) => c.id === id ? { ...c, active: !c.active } : c));
  };

  // Default sort = CPE (best ROI first)
  const ordered = [...RD_CREATORS].sort((a, b) => a.cpe - b.cpe);

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

        {/* Page head */}
        <div className="row items-end justify-between mb-4">
          <div>
            <span className="pill pill-cyan">Discover · 31,247 creators</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>Discover creators.</h1>
            <div className="page-subtitle">
              Provenance-checked · ranked by <b style={{ color: 'var(--ink)' }}>cost per engagement</b>, not vanity reach
            </div>
          </div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm">{Icon.sliders} Advanced filters</button>
            <button className="btn btn-primary btn-sm">{Icon.plus} Save segment</button>
          </div>
        </div>

        {/* Natural-language search hero */}
        <NaturalSearchHero />

        {/* Filter chips + view toggle */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, margin: '16px 0', flexWrap: 'wrap' }}>
          <div className="rd-filters" style={{ margin: 0 }}>
            <span className="cap-label" style={{ marginRight: 4 }}>Filters</span>
            {filters.map((c) => (
              <button key={c.id}
                className={'chip' + (c.active ? ' active' : '') + (c.guard ? ' guard' : '')}
                onClick={() => toggleFilter(c.id)}
              >
                {c.guard && (
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                  </svg>
                )}
                {c.label}
                <span className="cnt">{c.count}</span>
              </button>
            ))}
            <button className="more">+3 more</button>
          </div>

          <ViewToggle view={view} onChange={setView} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 296px', gap: 16 }}>
          {/* Left: results */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <div className="cap-label">
                Ranked by <b style={{ color: 'var(--ink)', fontSize: 11 }}>$ / engagement</b> · 312 matches · showing {view === 'table' ? 8 : 6}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <button onClick={() => setShowReason(!showReason)} style={{ background: 'transparent', border: '1px solid var(--line)', color: showReason ? 'var(--ink)' : 'var(--ink-soft)', padding: '5px 10px', borderRadius: 7, fontSize: 11.5, fontWeight: 700, cursor: 'pointer' }}>
                  {Icon.spark} AI reasoning {showReason ? 'on' : 'off'}
                </button>
                <button style={{ background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink-soft)', padding: '5px 10px', borderRadius: 7, fontSize: 11.5, fontWeight: 700 }}>
                  Export CSV
                </button>
              </div>
            </div>

            {view === 'table' && <DiscoveryTable creators={ordered} selected={selected} onToggle={toggleSel} />}
            {view === 'cards' && <DiscoveryCards creators={ordered.slice(0, 6)} selected={selected} onToggle={toggleSel} showReason={showReason} />}

            {showReason && (
              <div style={{ marginTop: 14, background: 'rgba(28,28,201,0.04)', border: '1px dashed rgba(28,28,201,0.2)', borderRadius: 12, padding: '12px 14px', 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={{ flex: 1 }}>
                  <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--indigo)', marginBottom: 3 }}>AI rationale · shortlist</div>
                  <div style={{ fontSize: 12, color: 'var(--ink)', lineHeight: 1.5 }}>
                    Your basket leans <b>nano + micro skincare in HCM</b> with avg CPE of <b>$0.30</b> — strong ROI signal.
                    Diệu Linh &amp; Khánh Vy together cover 73% of your 18–24F target with only 6% audience overlap.
                    Consider adding <b>Linh Châu</b> — she rebooked twice and has the lowest bot ratio in shortlist.
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Right: compare basket */}
          <CompareBasket selected={selected} onRemove={(id) => toggleSel(id)} />
        </div>
      </main>
    </div>
  );
}

// ─── View toggle (list/card) — Ben's note ──────────────────────────
function ViewToggle({ view, onChange }) {
  const Btn = ({ id, label, icon }) => (
    <button
      onClick={() => onChange(id)}
      style={{
        background: view === id ? 'var(--ink)' : 'transparent',
        color: view === id ? 'white' : 'var(--ink-soft)',
        border: 0,
        padding: '6px 12px',
        borderRadius: 8,
        fontSize: 12, fontWeight: 700,
        fontFamily: 'inherit',
        cursor: 'pointer',
        display: 'inline-flex',
        alignItems: 'center',
        gap: 6,
        transition: 'background .15s'
      }}>
      {icon}
      {label}
    </button>
  );
  return (
    <div style={{ display: 'inline-flex', background: 'white', border: '1px solid var(--line)', borderRadius: 10, padding: 3, gap: 2 }}>
      <Btn id="table" label="List" icon={
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><circle cx="3" cy="6" r="1" fill="currentColor"/><circle cx="3" cy="12" r="1" fill="currentColor"/><circle cx="3" cy="18" r="1" fill="currentColor"/></svg>
      } />
      <Btn id="cards" label="Cards" icon={
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
      } />
    </div>
  );
}

// ─── Natural-language search hero ──────────────────────────────────
function NaturalSearchHero() {
  return (
    <div className="rd-nl focus" style={{ marginTop: 18 }}>
      <div className="row1">
        <div className="spark-ai">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="m12 3 1.9 5.8a2 2 0 0 0 1.3 1.3L21 12l-5.8 1.9a2 2 0 0 0-1.3 1.3L12 21l-1.9-5.8a2 2 0 0 0-1.3-1.3L3 12l5.8-1.9a2 2 0 0 0 1.3-1.3Z"/>
          </svg>
        </div>
        <div className="nl-input">
          <span className="typed">Find</span>
          <span className="nl-token cat">micro skincare creators</span>
          <span className="typed">in</span>
          <span className="nl-token geo">HCM</span>
          <span className="typed">under</span>
          <span className="nl-token budget">$5K · per post</span>
          <span className="typed">with</span>
          <span className="nl-token">ER ≥ 4%</span>
          <span className="typed">·</span>
          <span className="nl-token guard">bot &lt; 10%</span>
          <span className="caret"></span>
        </div>
        <button className="submit">
          Run brief {Icon.arrow}
        </button>
      </div>
      <div className="row2">
        <span className="lbl">Try:</span>
        <span className="suggest">"Mid-tier wellness creators ready to ship to HN in May"</span>
        <span className="suggest">"Re-book my top 3 from Q1 skincare push"</span>
        <span className="suggest">"Nano on TikTok Shop with derm authority"</span>
      </div>
      <div className="meta">
        <span className="dot"></span>
        <span><b>AI parsed</b> 5 tokens · <b>312</b> matches · <b>8</b> shortlisted by ROI per dollar</span>
        <span style={{ marginLeft: 'auto' }}>Filters update live below ↓</span>
      </div>
    </div>
  );
}

// ─── Table view ────────────────────────────────────────────────────
function DiscoveryTable({ creators, selected, onToggle }) {
  const { go } = useRouter();
  return (
    <div className="rd-tbl-wrap">
      <table className="rd-tbl">
        <thead>
          <tr>
            <th style={{ width: 36 }}></th>
            <th>Creator</th>
            <th className="center" style={{ width: 50 }}>Match</th>
            <th className="num">Followers</th>
            <th className="num">ER</th>
            <th className="num">$ / engage</th>
            <th className="num">Price · post</th>
            <th>Risk</th>
            <th>Signals</th>
            <th style={{ width: 80 }}></th>
          </tr>
        </thead>
        <tbody>
          {creators.map((c) => {
            const isSel = selected.has(c.id);
            return (
              <tr key={c.id} className={isSel ? 'selected' : ''}>
                <td>
                  <div className={'check' + (isSel ? ' on' : '')} onClick={() => onToggle(c.id)}>
                    {isSel && Icon.check}
                  </div>
                </td>
                <td>
                  <div className="cell-name" onClick={(e) => { e.stopPropagation(); go('brand-influencer-detail'); }} style={{ cursor: 'pointer' }}>
                    <Avatar name={c.name} size={32} />
                    <div className="who">
                      <div className="n">
                        {c.name}
                        {c.verified && Icon.verified}
                        {c.star && (
                          <span style={{ background: 'var(--yellow)', color: 'var(--ink)', fontSize: 9, fontWeight: 800, padding: '1px 5px', borderRadius: 4, marginLeft: 4 }}>BEST ROI</span>
                        )}
                      </div>
                      <div className="h"><PlatformIcon name={c.platform} />{c.handle} · {c.cat} · {c.geo}</div>
                    </div>
                  </div>
                </td>
                <td className="center"><MatchChip score={c.match} /></td>
                <td className="num">
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3 }}>
                    <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 13 }}>{fmtK(c.followers)}</div>
                    <ProvenanceBadge src={c.provSrc} age={c.provAge} />
                  </div>
                </td>
                <td className="num">
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3 }}>
                    <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 13 }}>{c.er}<span style={{ color: 'var(--ink-soft)', fontSize: 10 }}>%</span></div>
                    <div style={{ display: 'inline-block', width: 56, height: 14, opacity: 0.7 }}>
                      <Sparkline data={c.sparkData} color="var(--cyan-dark)" fillId={`tbl-${c.id}`} height={14} animate={false} />
                    </div>
                  </div>
                </td>
                <td className="num">
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                    <div style={{ fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 14, color: c.cpe < 0.30 ? '#0a8a72' : c.cpe < 0.80 ? 'var(--ink)' : '#856200', letterSpacing: '-0.015em' }}>
                      ${c.cpe.toFixed(2)}
                    </div>
                    <div style={{ fontSize: 9.5, color: 'var(--ink-soft)', fontWeight: 600 }}>est · 30d</div>
                  </div>
                </td>
                <td className="num">
                  <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 12 }}>${c.priceMin}–{c.priceMax}K</div>
                  <div style={{ fontSize: 10, color: 'var(--ink-soft)', fontWeight: 600 }}>{c.level}</div>
                </td>
                <td><RiskBadge bot={c.bot} growth={c.growth} /></td>
                <td>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-start' }}>
                    {c.rebookCount > 0 && <RebookChip count={c.rebookCount} last={c.rebookLast} />}
                    {c.growth > 15 && (
                      <span style={{ fontSize: 10, fontWeight: 700, color: '#0a8a72', background: 'rgba(31,214,180,0.16)', padding: '2px 7px', borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                        {Icon.trend} +{c.growth}% MoM
                      </span>
                    )}
                    {c.audienceFit >= 70 && (
                      <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--cyan-dark)', background: 'rgba(0,156,255,0.10)', padding: '2px 7px', borderRadius: 999 }}>
                        ICP {c.audienceFit}% fit
                      </span>
                    )}
                  </div>
                </td>
                <td>
                  <button onClick={() => onToggle(c.id)} style={{ background: isSel ? 'var(--ink)' : 'white', color: isSel ? 'white' : 'var(--ink)', border: '1px solid ' + (isSel ? 'var(--ink)' : 'var(--line)'), borderRadius: 7, padding: '6px 10px', fontSize: 11.5, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
                    {isSel ? Icon.check : Icon.plus}
                    {isSel ? 'In basket' : 'Add'}
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ─── Cards view ────────────────────────────────────────────────────
function DiscoveryCards({ creators, selected, onToggle, showReason }) {
  const { go } = useRouter();
  return (
    <div className="rd-grid-cards" style={{ gridTemplateColumns: 'repeat(3, 1fr)' }}>
      {creators.map((c) => {
        const isSel = selected.has(c.id);
        const riskCls = c.bot >= 15 ? 'risk-bad' : c.bot >= 10 ? 'risk-warn' : '';
        return (
          <div key={c.id} className={'rd-card ' + riskCls + (isSel ? ' in-basket' : '')}>
            <div className="ribbon"></div>
            <div className="rd-card-body">
              <div className="top">
                <div style={{ position: 'relative' }}>
                  <Avatar name={c.name} size={44} />
                  {c.verified && <div style={{ position: 'absolute', bottom: -2, right: -2, background: 'white', borderRadius: '50%' }}>{Icon.verified}</div>}
                </div>
                <div className="meta">
                  <div className="name">
                    {c.name}
                    {c.star && <span style={{ background: 'var(--yellow)', color: 'var(--ink)', fontSize: 8.5, fontWeight: 800, padding: '1px 5px', borderRadius: 4, marginLeft: 2, letterSpacing: '0.04em' }}>BEST ROI</span>}
                  </div>
                  <div className="handle"><PlatformIcon name={c.platform} />{c.handle} · {c.cat}</div>
                  <div style={{ marginTop: 5 }}><MatchChip score={c.match} /></div>
                </div>
              </div>

              <div className="metrics">
                <div className="metric">
                  <div className="lbl">Followers</div>
                  <div className="v">{fmtK(c.followers)}</div>
                  <div style={{ marginTop: 4 }}><ProvenanceBadge src={c.provSrc} age={c.provAge} /></div>
                </div>
                <div className="metric">
                  <div className="lbl">ER · 30d</div>
                  <div className="v">{c.er}<small>%</small></div>
                  <div style={{ marginTop: 4, height: 12 }}>
                    <Sparkline data={c.sparkData} color="var(--cyan-dark)" fillId={`crd-${c.id}`} height={12} animate={false} />
                  </div>
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'stretch', gap: 8, marginTop: 8 }}>
                <CPEBadge value={c.cpe} />
                <div style={{ flex: 1, background: 'var(--bg-soft)', borderRadius: 10, padding: '5px 9px' }}>
                  <div style={{ fontSize: 9, fontWeight: 700, color: 'var(--ink-soft)', letterSpacing: '0.10em', textTransform: 'uppercase' }}>Price · per post</div>
                  <div style={{ fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 14, letterSpacing: '-0.015em' }}>${c.priceMin}–{c.priceMax}K</div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-soft)', fontWeight: 600 }}>{c.level} · {c.geo}</div>
                </div>
              </div>

              {showReason && (
                <div className="ai-reason">
                  <div className="tag">
                    <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="m12 3 1.9 5.8 5.8 1.9-5.8 1.9L12 18l-1.9-5.8L4.3 10.7l5.8-1.9z"/></svg>
                    AI
                  </div>
                  {c.reason}
                </div>
              )}

              <div className="signals">
                <RiskBadge bot={c.bot} growth={c.growth} />
                {c.rebookCount > 0 && <RebookChip count={c.rebookCount} last={c.rebookLast} />}
                {c.growth > 15 && (
                  <span style={{ fontSize: 10, fontWeight: 700, color: '#0a8a72', background: 'rgba(31,214,180,0.16)', padding: '2px 7px', borderRadius: 999, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                    {Icon.trend} +{c.growth}%
                  </span>
                )}
                {c.audienceFit >= 70 && (
                  <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--cyan-dark)', background: 'rgba(0,156,255,0.10)', padding: '2px 7px', borderRadius: 999 }}>
                    ICP {c.audienceFit}% fit
                  </span>
                )}
              </div>

              <div className="actions">
                <button className="btn-ghost-sm" onClick={() => go('brand-influencer-detail')}>{Icon.external} Profile</button>
                <button className="btn-primary-sm" onClick={() => onToggle(c.id)} style={{ background: isSel ? 'var(--indigo)' : 'var(--ink)' }}>
                  {isSel ? Icon.check : Icon.plus}
                  {isSel ? 'In basket' : 'Add to basket'}
                </button>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Compare basket (right rail) ──────────────────────────────────
function CompareBasket({ selected, onRemove }) {
  const items = RD_CREATORS.filter((c) => selected.has(c.id));
  const totalReach = items.reduce((s, c) => s + c.followers, 0);
  const blendCpe = items.length ? items.reduce((s, c) => s + c.cpe, 0) / items.length : 0;
  const blendBudgetLo = items.reduce((s, c) => s + c.priceMin, 0);
  const blendBudgetHi = items.reduce((s, c) => s + c.priceMax, 0);
  const avgOverlap = items.length ? Math.round(items.reduce((s, c) => s + c.audienceFit, 0) / items.length) : 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="brief-mini">
        <div className="lbl">Active brief · auto-attached</div>
        <div className="t">Vitamin C Skin Glow · Q2 Launch</div>
        <div className="stats">
          <div><b>$12K</b><span>budget</span></div>
          <div><b>HCM</b><span>geo</span></div>
          <div><b>18–24F</b><span>ICP</span></div>
        </div>
      </div>

      <div className="basket">
        <div className="basket-head">
          <div className="t">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/>
            </svg>
            Compare basket
            <span className="pill">{items.length}</span>
          </div>
          {items.length > 0 && <button style={{ background: 'transparent', border: 0, color: 'var(--ink-soft)', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>Clear</button>}
        </div>

        {items.length === 0 ? (
          <div className="basket-empty">Click <b>+ Add</b> on any creator to compare side-by-side.</div>
        ) : (
          <>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {items.map((c) => (
                <div key={c.id} className="basket-item">
                  <Avatar name={c.name} size={28} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="nm">{c.name}</div>
                    <div className="meta">${c.cpe.toFixed(2)} CPE · {fmtK(c.followers)} · {c.er}%</div>
                  </div>
                  <div className="x" onClick={() => onRemove(c.id)}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
                  </div>
                </div>
              ))}
            </div>

            <div className="basket-summary">
              <div><b>{fmtK(totalReach)}</b>blended reach</div>
              <div><b>${blendCpe.toFixed(2)}</b>avg CPE</div>
              <div><b>${blendBudgetLo.toFixed(1)}–{blendBudgetHi.toFixed(0)}K</b>est. spend</div>
              <div><b>{avgOverlap}%</b>ICP overlap</div>
            </div>

            <button className="basket-cta">Add {items.length} to campaign {Icon.arrow}</button>
            <button style={{ background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink)', borderRadius: 10, padding: '8px 12px', fontWeight: 600, fontSize: 12 }}>
              Side-by-side compare
            </button>
          </>
        )}

        <div className="rd-divider"></div>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 8 }}>
          Data sources
        </div>
        <div className="legend-row">
          <span className="legend-pill"><span style={{ width: 8, height: 8, borderRadius: 3, background: 'var(--mint-deep)' }}></span><b>API</b> · live</span>
          <span className="legend-pill"><span style={{ width: 8, height: 8, borderRadius: 3, background: 'var(--cyan)' }}></span><b>Crawl</b> · 7-day</span>
          <span className="legend-pill"><span style={{ width: 8, height: 8, borderRadius: 3, background: 'var(--lavender-deep)' }}></span><b>Import</b> · CSV</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenDiscovery });
