/* screen-brand-briefs.jsx — Brief list (table) + Brief detail */
/* global React, AppSidebar, AppTopbar, PageHeader, useRouter, useT, Counter, Sparkline, Avatar, Pill, MatchCircle, Icon, useInView */

const MOCK_BRIEFS = [
  { id: 'B-2419', title: 'Vitamin C Skin Glow · Q2 Launch', status: 'live', platforms: ['tiktok', 'instagram'], budget: 15000, kols: 6, matches: 24, deadline: '14d', created: '2d ago', spark: [2, 5, 8, 12, 18, 22, 24] },
  { id: 'B-2418', title: 'Tet 2026 Fashion Drop', status: 'review', platforms: ['instagram'], budget: 8000, kols: 4, matches: 18, deadline: '21d', created: '5d ago', spark: [4, 6, 10, 12, 14, 16, 18] },
  { id: 'B-2417', title: 'Vegan Snack Hero Spot', status: 'draft', platforms: ['tiktok'], budget: 3000, kols: 0, matches: 0, deadline: '—', created: '1w ago', spark: [0, 0, 0, 0, 0, 0, 0] },
  { id: 'B-2416', title: 'Sleep wellness · pillow launch', status: 'live', platforms: ['youtube', 'instagram'], budget: 22000, kols: 8, matches: 32, deadline: '7d', created: '2w ago', spark: [8, 14, 20, 24, 28, 30, 32] },
  { id: 'B-2415', title: 'SPF Glow · summer tour', status: 'completed', platforms: ['tiktok', 'instagram'], budget: 12000, kols: 5, matches: 22, deadline: '—', created: '3w ago', spark: [10, 14, 18, 20, 21, 22, 22] },
  { id: 'B-2414', title: 'Smart kettle · gift idea', status: 'completed', platforms: ['tiktok'], budget: 4000, kols: 3, matches: 14, deadline: '—', created: '1mo ago', spark: [6, 10, 12, 13, 14, 14, 14] },
];

function statusPill(s, t) {
  const map = {
    live:      { variant: 'mint',   icon: <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor', display: 'inline-block', animation: 'pulse 1.5s infinite' }} /> },
    review:    { variant: 'yellow' },
    draft:     { variant: 'lav' },
    completed: { variant: 'cyan' },
  };
  const cfg = map[s] || map.draft;
  return <Pill variant={cfg.variant} icon={cfg.icon}>{t(`status.${s}`)}</Pill>;
}

function platformDots(platforms) {
  const map = { tiktok: ['#002B50', Icon.tiktok], instagram: ['#FF6FA3', Icon.instagram], youtube: ['#FF4444', Icon.youtube] };
  return (
    <div className="row gap-4">
      {platforms.map(p => (
        <div key={p} style={{
          width: 24, height: 24, borderRadius: 6,
          background: map[p][0], color: 'white',
          display: 'grid', placeItems: 'center'
        }}>{map[p][1]}</div>
      ))}
    </div>
  );
}

function ScreenBrandBriefs() {
  const { t } = useT();
  const { go } = useRouter();
  const [filter, setFilter] = React.useState('all');
  const filtered = filter === 'all' ? MOCK_BRIEFS : MOCK_BRIEFS.filter(b => b.status === filter);

  const counts = {
    all: MOCK_BRIEFS.length,
    live: MOCK_BRIEFS.filter(b => b.status === 'live').length,
    review: MOCK_BRIEFS.filter(b => b.status === 'review').length,
    draft: MOCK_BRIEFS.filter(b => b.status === 'draft').length,
    completed: MOCK_BRIEFS.filter(b => b.status === 'completed').length,
  };

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

        <PageHeader
          eyebrow={<span className="pill pill-cyan">{counts.all} {t('brand.briefs.title').toLowerCase()}</span>}
          title={t('brand.briefs.title')}
          subtitle={t('brand.briefs.subtitle')}
          actions={
            <>
              <button className="btn btn-ghost btn-sm">{Icon.filter} {t('common.filter')}</button>
              <button className="btn btn-primary btn-sm" onClick={() => go('brand-brief-new')}>{Icon.plus} {t('brand.briefs.new')}</button>
            </>
          }
        />

        {/* Status filters */}
        <div className="row gap-8 mb-4" style={{ flexWrap: 'wrap' }}>
          {['all', 'live', 'review', 'draft', 'completed'].map(s => (
            <button key={s} onClick={() => setFilter(s)}
              style={{
                padding: '8px 14px',
                borderRadius: 999,
                border: '1.5px solid ' + (filter === s ? 'var(--ink)' : 'var(--line)'),
                background: filter === s ? 'var(--ink)' : 'white',
                color: filter === s ? 'white' : 'var(--ink)',
                fontSize: 12, fontWeight: 700, fontFamily: 'inherit',
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 6
              }}>
              {s === 'all' ? t('common.viewAll') : t(`status.${s}`)}
              <span style={{
                fontSize: 10, opacity: 0.7,
                background: filter === s ? 'rgba(255,255,255,0.2)' : 'var(--bg-soft)',
                padding: '0 6px', borderRadius: 999
              }}>{counts[s]}</span>
            </button>
          ))}
        </div>

        {/* Table */}
        <div className="card-elevated" style={{ padding: 0, overflow: 'hidden' }}>
          <table className="tbl">
            <thead>
              <tr>
                <th>Brief</th>
                <th>{t('common.live')} / Status</th>
                <th>Platforms</th>
                <th className="text-right">{t('brand.briefDetail.budget')}</th>
                <th className="text-center">KOLs / Matches</th>
                <th>Progress</th>
                <th className="text-right">Deadline</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((b, i) => (
                <tr key={b.id} style={{
                  cursor: 'pointer',
                  animation: `slideIn .4s ${i * 50}ms backwards cubic-bezier(.4,0,.2,1)` }} onClick={() => go('brand-brief-detail')}>
                  <td>
                    <div className="row items-center gap-12">
                      <div style={{
                        width: 36, height: 36, borderRadius: 10,
                        background: ['var(--cyan)', 'var(--pink-hot)', 'var(--mint-deep)', 'var(--indigo)', 'var(--yellow-deep)', 'var(--lavender-deep)'][i % 6],
                        color: 'white', display: 'grid', placeItems: 'center',
                        fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 13
                      }}>{b.id.slice(-2)}</div>
                      <div>
                        <div className="bold" style={{ fontSize: 13 }}>{b.title}</div>
                        <div className="muted" style={{ fontSize: 11 }}>{b.id} · {b.created}</div>
                      </div>
                    </div>
                  </td>
                  <td>{statusPill(b.status, t)}</td>
                  <td>{platformDots(b.platforms)}</td>
                  <td className="text-right">
                    <div className="font-display bold tabular" style={{ fontSize: 14 }}>${(b.budget / 1000).toFixed(0)}K</div>
                  </td>
                  <td className="text-center">
                    <div className="row items-center gap-6 justify-center">
                      <span className="bold tabular" style={{ fontSize: 14 }}>{b.kols}</span>
                      <span className="muted" style={{ fontSize: 11 }}>/</span>
                      <span className="tabular" style={{ fontSize: 13, color: 'var(--cyan-dark)' }}>{b.matches}</span>
                    </div>
                  </td>
                  <td>
                    <div style={{ width: 100 }}>
                      <Sparkline data={b.spark.length && b.spark[b.spark.length - 1] ? b.spark : [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} color={b.status === 'live' ? 'var(--mint-deep)' : 'var(--ink-soft)'} fillId={`brief-${b.id}`} height={28} delay={0.1 + i * 0.06} />
                    </div>
                  </td>
                  <td className="text-right">
                    <span className="tabular bold" style={{ fontSize: 12 }}>{b.deadline}</span>
                  </td>
                  <td className="text-right">
                    <button className="btn-sm" style={{ background: 'transparent', border: 0, padding: 8, cursor: 'pointer', color: 'var(--ink-soft)' }}>{Icon.arrow}</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <style>{`@keyframes slideIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }`}</style>
      </main>
    </div>
  );
}

// ── Brief detail ──────────────────────────────────────────────────
function ScreenBrandBriefDetail() {
  const { t } = useT();
  const { go } = useRouter();
  return (
    <div className="app-shell">
      <AppSidebar portal="brand" active="brand-briefs" />
      <main className="main">
        <AppTopbar />

        {/* Breadcrumb */}
        <div className="row items-center gap-6 muted mb-4" style={{ fontSize: 12 }}>
          <a onClick={() => go('brand-briefs')} style={{ cursor: 'pointer' }}>{t('brand.briefs.title')}</a>
          <span>·</span>
          <span className="bold" style={{ color: 'var(--ink)' }}>Vitamin C Skin Glow · Q2 Launch</span>
        </div>

        <div className="row items-end justify-between mb-6">
          <div>
            <div className="row items-center gap-12 mb-2">
              <h1 className="page-title" style={{ margin: 0 }}>Vitamin C Skin Glow</h1>
              {statusPill('live', t)}
            </div>
            <div className="page-subtitle">Brief #B-2419 · created 2 days ago · awaiting your approval</div>
          </div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm">{Icon.edit ?? <>✎</>} {t('common.edit')}</button>
            <button className="btn btn-ghost btn-sm">Duplicate</button>
            <button className="btn btn-primary btn-sm">{Icon.spark} Approve &amp; launch</button>
          </div>
        </div>

        {/* Brief summary card */}
        <div className="card-elevated" style={{ padding: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 24 }}>
            <div>
              <div className="cap-label">Goal</div>
              <div className="bold mt-2" style={{ fontSize: 14, lineHeight: 1.4 }}>
                Launch new vitamin C serum to Gen-Z women in HCM &amp; HN
              </div>
            </div>
            <div>
              <div className="cap-label">Product</div>
              <div className="bold mt-2" style={{ fontSize: 14 }}>SkinDream Serum 10%</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>SKU: SDS-VC-30 · 30ml</div>
            </div>
            <div>
              <div className="cap-label">{t('brand.briefDetail.budget')}</div>
              <div className="font-display bold tabular mt-2" style={{ fontSize: 22 }}>$5K – $15K</div>
              <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>Total cap: $15,000</div>
            </div>
            <div>
              <div className="cap-label">{t('brand.briefDetail.timeline')}</div>
              <div className="bold mt-2" style={{ fontSize: 14 }}>May 14 – Jun 11</div>
              <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>28 days · D14 / D28</div>
            </div>
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '20px 0' }} />

          {/* Requirements as chips */}
          <div className="cap-label mb-2">{t('brand.briefDetail.requirements')}</div>
          <div className="row gap-6" style={{ flexWrap: 'wrap' }}>
            <Pill variant="cyan" icon={Icon.tiktok}>TikTok primary</Pill>
            <Pill variant="pink" icon={Icon.instagram}>Instagram supporting</Pill>
            <Pill variant="lav">18–24 yrs</Pill>
            <Pill variant="lav">Female 70%+</Pill>
            <Pill variant="mint">HCM · HN</Pill>
            <Pill variant="yellow">Skincare / Beauty</Pill>
            <Pill variant="ink">Micro–Mid tier</Pill>
            <Pill variant="ink">ER ≥ 4%</Pill>
            <Pill variant="ink">Vegan claim mention</Pill>
          </div>
        </div>

        {/* AI Shortlist (re-use existing widget pattern) */}
        <div className="mt-6">
          <ShortlistInline />
        </div>

        {/* Activity timeline + provenance */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14, marginTop: 18 }}>
          <BriefActivity />
          <BriefProvenance />
        </div>
      </main>
    </div>
  );
}

function ShortlistInline() {
  const { t } = useT();
  const items = [
    { name: 'Linh Châu', cat: 'Skincare', match: 94, fol: '482K', er: 6.2, platform: 'tiktok', risk: 'low', reason: 'Audience overlap 78% HCM 18–24F. Past Vitamin C content over-performed by 38%.' },
    { name: 'Mai Vy', cat: 'Lifestyle', match: 88, fol: '1.2M', er: 5.8, platform: 'instagram', risk: 'low', reason: 'Mom-coded voice; 62% of audience in your target ICP.' },
    { name: 'Hà Giang', cat: 'Beauty', match: 84, fol: '320K', er: 7.1, platform: 'tiktok', risk: 'low', reason: 'Highest ER. Clean-beauty specialist — fits vegan claim.' },
    { name: 'Phương Anh', cat: 'Beauty Vlog', match: 78, fol: '210K', er: 4.4, platform: 'youtube', risk: 'medium', reason: 'YouTube long-form complements TikTok. Tutorial format.' },
    { name: 'Thảo Nhi', cat: 'Wellness', match: 75, fol: '156K', er: 5.2, platform: 'instagram', risk: 'low', reason: 'Cross-category wellness + skincare. Younger skew (16–22F).' },
  ];

  return (
    <div className="card-elevated" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ height: 4, background: 'linear-gradient(90deg, #009CFF, #1C1CC9, #FF6FA3, #FEE960)' }} />
      <div style={{ padding: 24 }}>
        <div className="row items-center justify-between mb-3">
          <div className="row items-center gap-12">
            <div className="orb orb-sm" />
            <div>
              <div className="title-md">{t('brand.briefDetail.shortlist')}</div>
              <div className="muted" style={{ fontSize: 12 }}>Generated 6.4s ago · 24 matches found · top 5 shown</div>
            </div>
          </div>
          <div className="row gap-8">
            <button className="btn btn-ghost btn-sm">{Icon.spark} Regenerate</button>
            <button className="btn btn-primary btn-sm">Add all 5</button>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {items.map((it, i) => (
            <div key={i} className="row items-center gap-12" style={{
              padding: '14px 4px',
              borderTop: i ? '1px solid var(--line)' : 'none'
            }}>
              <div className="bold tabular" style={{ fontSize: 14, color: 'var(--ink-soft)', width: 20 }}>{i + 1}</div>
              <Avatar name={it.name} size={40} />
              <div style={{ minWidth: 130 }}>
                <div className="row items-center gap-6">
                  <div className="bold" style={{ fontSize: 13 }}>{it.name}</div>
                  <span style={{ color: 'var(--ink-soft)' }}>{it.platform === 'tiktok' ? Icon.tiktok : it.platform === 'instagram' ? Icon.instagram : Icon.youtube}</span>
                </div>
                <div className="muted" style={{ fontSize: 11 }}>{it.cat} · {it.fol} · {it.er}% ER</div>
              </div>
              <div className="flex-1 muted" style={{ fontSize: 12, lineHeight: 1.45 }}>
                <span style={{ color: 'var(--pink-hot)', fontWeight: 700 }}>AI: </span>{it.reason}
              </div>
              <Pill variant={it.risk === 'low' ? 'mint' : 'yellow'}>{it.risk === 'low' ? 'Low risk' : 'Medium'}</Pill>
              <MatchCircle score={it.match} size={48} />
              <button className="btn btn-ghost btn-sm">{Icon.plus} {t('common.add')}</button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BriefActivity() {
  const events = [
    { who: 'AI', what: 'generated shortlist · 24 matches', t: '6m ago', ai: true },
    { who: 'You', what: 'edited budget cap to $15K', t: '12m ago' },
    { who: 'Trang Lê', what: 'left a comment on requirements', t: '38m ago' },
    { who: 'AI', what: 'parsed brief into structured filters', t: '1h ago', ai: true },
    { who: 'You', what: 'created brief', t: '2d ago' },
  ];
  return (
    <div className="card-elevated">
      <div className="title-md mb-2">Activity</div>
      <div className="muted mb-4" style={{ fontSize: 12 }}>Every change is logged with timestamp &amp; author</div>
      <div style={{ position: 'relative' }}>
        <div style={{ position: 'absolute', left: 19, top: 4, bottom: 4, width: 1.5, background: 'var(--line)' }} />
        {events.map((e, i) => (
          <div key={i} className="row items-start gap-12" style={{ position: 'relative', padding: '10px 0' }}>
            {e.ai
              ? <div className="orb orb-sm" style={{ width: 40, height: 40, flexShrink: 0 }} />
              : <Avatar name={e.who} size={40} />}
            <div className="flex-1" style={{ paddingTop: 6 }}>
              <div style={{ fontSize: 13 }}>
                <span className="bold">{e.who}</span>{' '}
                <span className="muted">{e.what}</span>
              </div>
              <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{e.t}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BriefProvenance() {
  return (
    <div className="card-elevated" style={{
      background: 'linear-gradient(135deg, #002B50, #1C1CC9)',
      color: 'white', position: 'relative', overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', top: -40, right: -40,
        width: 180, height: 180, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(121,254,231,0.45), transparent 60%)',
        filter: 'blur(20px)'
      }} />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <Pill variant="dark"><span style={{ color: 'var(--mint)' }}>●</span> Data provenance</Pill>
        <div className="title-md mt-2" style={{ color: 'white' }}>Where this brief came from</div>
        <div className="muted mt-2" style={{ fontSize: 12, color: 'rgba(255,255,255,0.7)' }}>
          You wrote the brief; AI parsed it; matches pull from these sources:
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14 }}>
          {[
            { l: 'TikTok official API', src: 'api', n: 24, c: '#79FEE7' },
            { l: 'Instagram Graph API', src: 'api', n: 18, c: '#FF6FA3' },
            { l: 'CSV manual import', src: 'csv', n: 6, c: '#FEE960' },
            { l: 'Public web crawler', src: 'web', n: 12, c: '#EAC2FB' },
          ].map((p, i) => (
            <div key={i} className="row items-center gap-12" style={{
              padding: 12, background: 'rgba(255,255,255,0.08)', borderRadius: 10
            }}>
              <div style={{ width: 8, height: 32, background: p.c, borderRadius: 3 }} />
              <div className="flex-1">
                <div className="bold" style={{ fontSize: 13 }}>{p.l}</div>
                <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)' }}>Refreshed 4h ago</div>
              </div>
              <div className="font-display bold tabular" style={{ fontSize: 18, color: p.c }}>{p.n}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenBrandBriefs, ScreenBrandBriefDetail });
