/* screen-campaign-v2.jsx — Campaign list (status-driven) + Campaign detail (timeline + applications).
   Replaces ScreenBrandCampaigns and ScreenCampaign (detail). Uses AppSidebar + AppTopbar. */
/* global React, CF_CAMPAIGNS, CF_APPLICATIONS, CF_MILESTONES,
   CFStatusPill, CFStatusDropdown, CFAvatar, Icon, AppSidebar, AppTopbar, useRouter, useT, PlatformIcon */

const { useState: useCV2State } = React;

// ─── Campaign list (replaces ScreenBrandCampaigns) ─────────────────
function ScreenBrandCampaigns() {
  const { go } = useRouter();
  const [filter, setFilter] = useCV2State('all');
  const [selected, setSelected] = useCV2State(new Set());

  const filterCounts = {
    all: CF_CAMPAIGNS.length,
    draft: CF_CAMPAIGNS.filter(c => c.status === 'draft').length,
    recruiting: CF_CAMPAIGNS.filter(c => c.status === 'recruiting').length,
    in_progress: CF_CAMPAIGNS.filter(c => c.status === 'in_progress').length,
    completed: CF_CAMPAIGNS.filter(c => c.status === 'completed').length,
  };
  const filtered = filter === 'all' ? CF_CAMPAIGNS : CF_CAMPAIGNS.filter(c => c.status === filter);
  const toggleSel = (id) => {
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };

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

        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <span className="pill pill-cyan">{CF_CAMPAIGNS.length} campaigns</span>
            <h1 className="page-title" style={{ marginTop: 8 }}>Campaigns</h1>
            <div className="page-subtitle">
              <b style={{ color: 'var(--ink)' }}>{filterCounts.recruiting + filterCounts.in_progress}</b> active right now ·
              status changes are instant · brief content lives <b>inside</b> the campaign
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm">{Icon.filter} Filter</button>
            <button className="btn btn-primary btn-sm" onClick={() => go('brand-campaign-new')}>{Icon.plus} New campaign</button>
          </div>
        </div>

        {/* Status filter pills */}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
          {[
            { id: 'all', label: 'All' },
            { id: 'draft', label: 'Draft' },
            { id: 'recruiting', label: 'Recruiting' },
            { id: 'in_progress', label: 'In progress' },
            { id: 'completed', label: 'Completed' },
          ].map(f => (
            <button key={f.id} onClick={() => setFilter(f.id)}
              style={{
                padding: '6px 12px',
                borderRadius: 999,
                border: '1.5px solid ' + (filter === f.id ? 'var(--ink)' : 'var(--line)'),
                background: filter === f.id ? 'var(--ink)' : 'white',
                color: filter === f.id ? 'white' : 'var(--ink)',
                fontSize: 12, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 6
              }}>
              {f.label}
              <span style={{
                fontSize: 10, fontWeight: 700,
                background: filter === f.id ? 'rgba(255,255,255,0.18)' : 'var(--bg-soft)',
                color: filter === f.id ? 'white' : 'var(--ink-soft)',
                padding: '0 6px', borderRadius: 999
              }}>{filterCounts[f.id]}</span>
            </button>
          ))}
        </div>

        {/* Bulk action bar */}
        {selected.size > 0 && (
          <div className="cf-bulkbar">
            <span className="count">{selected.size}</span>
            <span style={{ fontWeight: 700, fontSize: 12.5 }}>selected</span>
            <div className="grow"></div>
            <button>{Icon.spark} Move to recruiting</button>
            <button>Archive</button>
            <button className="danger">Cancel…</button>
            <button onClick={() => setSelected(new Set())} style={{ background: 'rgba(255,255,255,0.06)' }}>Clear</button>
          </div>
        )}

        {/* Cards grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {filtered.map((c) => (
            <CampaignCard
              key={c.id}
              c={c}
              checked={selected.has(c.id)}
              onCheck={() => toggleSel(c.id)}
              onOpen={() => go('brand-campaign-detail')}
            />
          ))}
        </div>
      </main>
    </div>
  );
}

function CampaignCard({ c, checked, onCheck, onOpen }) {
  return (
    <div className={'cf-card' + (checked ? ' checked' : '')} onClick={onOpen} style={{ cursor: 'pointer' }}>
      <div className="check" onClick={(e) => { e.stopPropagation(); onCheck(); }}>{checked && Icon.check}</div>

      <div className="head" style={{ paddingRight: 28 }}>
        <div className="icon" style={{ background: c.color }}>{c.code}</div>
        <div className="meta">
          <div className="nm">
            {c.name}
            <CFStatusPill status={c.status} />
          </div>
          <div className="sub">
            {c.brand} · {c.id} ·
            <span style={{ display: 'inline-flex', gap: 4, marginLeft: 4 }}>
              {c.platforms.map((p) => (
                <span key={p} style={{ color: 'var(--ink-soft)' }}>
                  {p === 'tiktok' ? Icon.tiktok : p === 'instagram' ? Icon.instagram : Icon.youtube}
                </span>
              ))}
            </span>
          </div>
        </div>
      </div>

      <div className="kpis">
        <div className="kpi">
          <div className="k">Budget</div>
          <div className="v">${(c.budget / 1000).toFixed(0)}K</div>
        </div>
        <div className="kpi">
          <div className="k">Applied</div>
          <div className="v">{c.applied}</div>
        </div>
        <div className="kpi">
          <div className="k">Approved</div>
          <div className="v">{c.approved}<span style={{ fontSize: 10, color: 'var(--ink-soft)', fontWeight: 600 }}> / 6</span></div>
        </div>
      </div>

      <div className="progress-track">
        <div className="fill" style={{ width: c.progress + '%' }}></div>
      </div>

      <div className="footer">
        <div>{c.start} → {c.end}</div>
        <div className="due">
          {c.status === 'in_progress' && c.due.includes('late') ? (
            <span style={{ color: '#B12B2B', fontWeight: 700 }}>● {c.due}</span>
          ) : c.status === 'completed' ? (
            <span style={{ color: 'var(--indigo)', fontWeight: 700 }}>✓ {c.due}</span>
          ) : (
            <span><b>{c.due}</b></span>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Campaign detail (replaces ScreenCampaign) ─────────────────────
// ─── Campaign detail (replaces ScreenCampaign) ───────────────────
function CampaignDetailBody() {
  const { go } = useRouter();
  const actions = useBrandActions();
  const [apps, setApps] = React.useState(CF_APPLICATIONS);
  const total = CF_MILESTONES.length;
  const lastDone = CF_MILESTONES.reduce((acc, m, i) => (m.state === 'done' || m.state === 'late' || m.state === 'active') ? i : acc, -1);
  const progress = total > 1 ? (lastDone / (total - 1)) * 100 : 0;

  const updateApp = (id, status) => setApps(a => a.map(x => x.id === id ? { ...x, status } : x));
  const review = (a) => actions.openReviewApplication(a, updateApp);

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

        {/* Crumbs */}
        <div className="row items-center gap-6 muted mb-3" style={{ fontSize: 12 }}>
          <a onClick={() => go('brand-campaigns')} style={{ cursor: 'pointer' }}>Campaigns</a>
          <span>·</span>
          <span className="bold" style={{ color: 'var(--ink)' }}>Acne Spot Cream · Launch</span>
        </div>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--pink-hot)', color: 'white', display: 'grid', placeItems: 'center', fontFamily: 'Space Grotesk', fontWeight: 800, fontSize: 18, letterSpacing: '-0.02em' }}>
              AC
            </div>
            <div>
              <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginBottom: 2 }}>Aurora Beauty · C-2417</div>
              <h1 className="page-title" style={{ marginTop: 0, display: 'flex', alignItems: 'center', gap: 10 }}>
                Acne Spot Cream · Launch
                <CFStatusDropdown status="in_progress" />
              </h1>
              <div style={{ fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 4 }}>
                Recruiting closed May 12 · in progress · ends Jun 1 · <b style={{ color: 'var(--ink)' }}>5 / 6</b> creators booked
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost btn-sm">Edit brief</button>
            <button className="btn btn-ghost btn-sm">{Icon.external} Share public link</button>
            <button className="btn btn-primary btn-sm" onClick={() => go('brand-report-detail')}>{Icon.chart} View report</button>
          </div>
        </div>

        {/* KPI strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10, marginBottom: 14 }}>
          {[
            { l: 'Reach',         v: '1.2M', d: '+18% MoM', up: true },
            { l: 'Engagements',   v: '94.8K', d: '$0.31 CPE', up: true },
            { l: 'Spend',         v: '$8.4K', d: 'of $11K', up: false },
            { l: 'Applications',  v: '19',   d: '5 approved · 1 pending', up: false },
            { l: 'Deliverables',  v: '11/18', d: '2 late', late: true },
          ].map((k, i) => (
            <div key={i} style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 12, padding: 12 }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--ink-soft)', letterSpacing: '0.10em', textTransform: 'uppercase' }}>{k.l}</div>
              <div style={{ fontFamily: 'Space Grotesk', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', marginTop: 2 }}>{k.v}</div>
              <div style={{ fontSize: 10.5, color: k.late ? '#B12B2B' : k.up ? '#0a8a72' : 'var(--ink-soft)', fontWeight: 700, marginTop: 4 }}>
                {k.late && '● '}{k.d}
              </div>
            </div>
          ))}
        </div>

        {/* Milestone timeline */}
        <div className="cf-timeline" style={{ marginBottom: 14 }}>
          <h3>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
            Milestone timeline
            <span style={{ marginLeft: 'auto', fontSize: 10.5, fontWeight: 700, color: '#B12B2B', background: 'rgba(255,68,68,0.10)', padding: '3px 9px', borderRadius: 999 }}>
              ● 2 deliverables late · review
            </span>
          </h3>
          <div className="track">
            <div className="rail"><div className="fill" style={{ width: progress + '%' }}></div></div>
            <div className="milestones">
              {CF_MILESTONES.map((m) => (
                <div key={m.id} className={'ms ' + m.state}>
                  {m.state === 'late' && <span className="badge-late">LATE</span>}
                  <div className="node"></div>
                  <div className="lbl">{m.label}</div>
                  <div className="dt">{m.date}{m.late && ' · ' + m.late}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Pending deliverable to review (new section) */}
        <div style={{
          background: 'linear-gradient(90deg, rgba(0,156,255,0.06), rgba(121,254,231,0.04))',
          border: '1px solid rgba(0,156,255,0.25)',
          borderRadius: 14, padding: 14, marginBottom: 14
        }}>
          <div className="row items-center gap-14">
            <div style={{
              width: 60, height: 84, borderRadius: 10, flexShrink: 0,
              background: 'linear-gradient(135deg, #79FEE7, #009CFF)',
              display: 'grid', placeItems: 'center', color: 'white', fontSize: 22
            }}>▶</div>
            <div className="flex-1">
              <div className="row items-center gap-8 mb-1">
                <span style={{ background: 'var(--yellow-deep)', color: 'white', fontSize: 10, fontWeight: 800, padding: '2px 8px', borderRadius: 999, letterSpacing: '0.04em' }}>NEEDS REVIEW</span>
                <span className="bold" style={{ fontSize: 13 }}>Linh Châu submitted D2 · 30s TikTok cut</span>
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>Submitted 12 min ago · Trang typically reviews within 4h · $720 ready to release</div>
            </div>
            <button className="btn btn-primary btn-sm" onClick={() => actions.openReviewDeliverable({
              title: 'Vitamin C · D2 first video', creator: 'Linh Châu', when: '12 min ago',
              length: '0:30', size: '184 MB', pay: 720
            })}>Review &amp; decide →</button>
          </div>
        </div>

        {/* Applications + side */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 14 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
                Applications · {CF_APPLICATIONS.length}
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <button style={{ background: 'var(--bg-soft)', border: 0, color: 'var(--ink)', borderRadius: 7, padding: '4px 10px', fontSize: 11, fontWeight: 700 }}>All</button>
                <button style={{ background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink-soft)', borderRadius: 7, padding: '4px 10px', fontSize: 11, fontWeight: 700 }}>Pending only</button>
                <button style={{ background: 'transparent', border: '1px solid var(--line)', color: 'var(--ink-soft)', borderRadius: 7, padding: '4px 10px', fontSize: 11, fontWeight: 700 }}>Approved</button>
              </div>
            </div>
            <div className="cf-apps">
              {apps.map((a) => (
                <div className={'cf-app-row ' + (a.status === 'pending' ? 'pending' : '')} key={a.id}
                  onClick={() => review(a)}
                  style={{ cursor: 'pointer' }}>
                  <div className="who">
                    <CFAvatar name={a.name} />
                    <div style={{ minWidth: 0 }}>
                      <div className="nm">
                        {a.name}
                        {a.rebookCount > 0 && (
                          <span style={{ background: 'rgba(28,28,201,0.10)', color: 'var(--indigo)', fontSize: 9, fontWeight: 800, padding: '1px 5px', borderRadius: 4, marginLeft: 5, letterSpacing: '0.04em' }}>
                            {a.rebookCount}× REBOOK
                          </span>
                        )}
                      </div>
                      <div className="hl">
                        {a.platform === 'tiktok' ? Icon.tiktok : a.platform === 'instagram' ? Icon.instagram : Icon.youtube} {a.handle} · {a.followers} · ER {a.er}%
                      </div>
                    </div>
                  </div>
                  <div style={{ textAlign: 'center' }}>
                    <div style={{ fontFamily: 'Space Grotesk', fontSize: 16, fontWeight: 800, letterSpacing: '-0.015em', color: a.match >= 80 ? '#0a8a72' : a.match >= 65 ? 'var(--ink)' : '#B12B2B' }}>
                      {a.match}<span style={{ fontSize: 9, fontWeight: 700, opacity: 0.7 }}>%</span>
                    </div>
                    <div style={{ fontSize: 9, color: 'var(--ink-soft)', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>match</div>
                  </div>
                  <div className="msg">{a.note}</div>
                  <div className="rate">
                    ${a.rate.toLocaleString()}
                    <div className="sub">{a.status === 'accepted' ? 'agreed' : 'proposed'}</div>
                  </div>
                  <div className="actions" onClick={(e) => e.stopPropagation()}>
                    {a.status === 'pending' && (
                      <>
                        <button className="btn-mini reject" onClick={() => review(a)}>Reject</button>
                        <button className="btn-mini approve" onClick={() => review(a)}>{Icon.check} Approve</button>
                      </>
                    )}
                    {a.status === 'accepted' && (
                      <button className="btn-mini view" onClick={() => review(a)} style={{ background: 'rgba(31,214,180,0.18)', color: '#0a8a72' }}>
                        {Icon.check} Booked
                      </button>
                    )}
                    {a.status === 'rejected' && <button className="btn-mini view" onClick={() => review(a)}>View notes</button>}
                    {a.status === 'shortlisted' && <button className="btn-mini view" onClick={() => review(a)} style={{ background: 'rgba(0,156,255,0.12)', color: 'var(--cyan-dark)' }}>Shortlisted</button>}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Right rail */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 14, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 8 }}>Brief snapshot</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12 }}>
                <Row k="Type" v="paid + affiliate · 12% commission" />
                <Row k="Platforms" v="TikTok, Instagram" />
                <Row k="Categories" v="Skincare · Beauty · Derm" />
                <Row k="Audience" v="HCM · 18–24 · F skew" />
                <Row k="Guards" v="Bot < 10% · provenance ≤ 14d" />
              </div>
            </div>

            <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 14, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 10 }}>Deliverables</div>
              <Deliv plat="TikTok" type="short video · 30–60s" done={5} total={6} />
              <Deliv plat="Instagram" type="reel · 30s + stories" done={3} total={6} late={1} />
              <Deliv plat="TikTok" type="unboxing live · 20m" done={3} total={6} late={1} />
            </div>

            <div style={{ background: 'rgba(255,68,68,0.06)', border: '1px solid rgba(255,68,68,0.25)', borderRadius: 14, padding: 14, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: '#B12B2B', color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                {Icon.bell}
              </div>
              <div>
                <div style={{ fontSize: 11.5, fontWeight: 700 }}>2 deliverables overdue</div>
                <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 2, lineHeight: 1.4 }}>
                  Hà Giang &amp; Diệu Linh missed the May 18 drafts. Nudge or extend?
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                  <button onClick={() => actions.openNudgeCreators()} style={{ background: 'var(--ink)', color: 'white', border: 0, borderRadius: 7, padding: '5px 10px', fontSize: 10.5, fontWeight: 700, cursor: 'pointer' }}>Nudge creators</button>
                  <button onClick={() => actions.openExtendDeadline()} style={{ background: 'white', color: 'var(--ink)', border: '1px solid var(--line)', borderRadius: 7, padding: '5px 10px', fontSize: 10.5, fontWeight: 700, cursor: 'pointer' }}>Extend deadline</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      <span style={{ width: 80, flexShrink: 0, color: 'var(--ink-soft)', fontWeight: 600 }}>{k}</span>
      <span style={{ color: 'var(--ink)', fontWeight: 600 }}>{v}</span>
    </div>
  );
}

function Deliv({ plat, type, done, total, late }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        <span style={{ fontSize: 11, fontWeight: 700 }}>{plat}</span>
        <span style={{ fontSize: 11, color: 'var(--ink-soft)' }}>· {type}</span>
        <span style={{ marginLeft: 'auto', fontFamily: 'Space Grotesk', fontWeight: 700, fontSize: 12, color: 'var(--ink)' }}>
          {done}/{total}
          {late > 0 && <span style={{ color: '#B12B2B', marginLeft: 4 }}>· {late} late</span>}
        </span>
      </div>
      <div style={{ height: 4, background: 'var(--bg-soft)', borderRadius: 999, overflow: 'hidden' }}>
        <div style={{ height: '100%', width: ((done / total) * 100) + '%', background: late > 0 ? 'linear-gradient(90deg, var(--coral), var(--yellow-deep))' : 'linear-gradient(90deg, var(--mint-deep), var(--cyan))', borderRadius: 999 }}></div>
      </div>
    </div>
  );
}

// Override exports (load this AFTER screen-campaign.jsx and screen-brand-list-pages.jsx)
function ScreenCampaign() {
  return <BrandActionsHost><CampaignDetailBody /></BrandActionsHost>;
}

Object.assign(window, { ScreenBrandCampaigns, ScreenCampaign });
