// Dashboards: Workflow (how much left to go) + Quality (what we achieved)
function ReportView({ people, onOpen }) {
  const [scope, setScope] = useState('all');
  const [tab, setTab] = useState('workflow');

  const filtered = useMemo(() => {
    if (!Array.isArray(people)) return [];
    return scope === 'all' ? people : people.filter(p => p.source === scope);
  }, [people, scope]);
  const stats = useMemo(() => compute(filtered), [filtered]);
  const sportsStats = useMemo(() => compute(Array.isArray(people) ? people.filter(p => p.source === 'SportsNet') : []), [people]);
  const cultureStats = useMemo(() => compute(Array.isArray(people) ? people.filter(p => p.source === 'CultureNet') : []), [people]);

  function compute(list) {
    const s = {
      people: list.length, complete: 0, inProgress: 0, untouched: 0,
      totalSlots: 0, locked: 0, missing: 0, needsReview: 0, verified: 0, qc: 0, nonExisting: 0,
      mismatches: 0, togo: 0,
      byPlatform: {},
    };
    for (const pl of PLATFORMS) s.byPlatform[pl.id] = { name: pl.name, people: 0, complete: 0, inProgress: 0, untouched: 0 };
    for (const p of list) {
      const c = computeCounts(p, PLATFORMS);
      if (c.complete) s.complete++;
      else if (c.qc + c.verified > 0) s.inProgress++;
      else s.untouched++;
      for (const pl of PLATFORMS) {
        const handles = p.handles[pl.id];
        if (handles && (Array.isArray(handles) ? handles.length > 0 : handles !== null)) {
          const row = s.byPlatform[pl.id];
          row.people++;
          const pc = computeCounts(p, [pl]);
          if (pc.complete) row.complete++;
          else if (pc.qc + pc.verified > 0) row.inProgress++;
          else row.untouched++;
        }
        const handlesArray = Array.isArray(handles) ? handles : [handles];
        const row = s.byPlatform[pl.id];
        for (const h of handlesArray) {
          if (!h) continue;
          s.totalSlots++; row.total = (row.total || 0) + 1;
          if (h.status === 'qc') { s.locked++; row.locked = (row.locked || 0) + 1; }
          else { s.togo++; row.togo = (row.togo || 0) + 1; }
          if (h.status === 'qc') s.qc++;
          if (h.status === 'verified') { s.verified++; row.verified = (row.verified || 0) + 1; }
          if (h.status === 'unverified') { s.needsReview++; row.review = (row.review || 0) + 1; }
          if (h.status === 'missing') { s.missing++; row.missing = (row.missing || 0) + 1; }
          if (h.status === 'non-existing') { s.nonExisting++; row.nonExisting = (row.nonExisting || 0) + 1; }
          if (h.sports && h.panel && h.sports !== h.panel) s.mismatches++;
        }
      }
    }
    return s;
  }

  const pct = (n, d) => d ? Math.round(n/d * 100) : 0;

  return (
    <>
      <div className="report-scope">
        <div style={{fontSize: 12, color: 'var(--muted)', marginRight: 4}}>Scope:</div>
        <button className={`chip ${scope==='all'?'active':''}`} onClick={() => setScope('all')}>All <span className="count">{people.length}</span></button>
        <button className={`chip ${scope==='SportsNet'?'active':''}`} onClick={() => setScope('SportsNet')}>SportsNet <span className="count">{sportsStats.people}</span></button>
        <button className={`chip ${scope==='CultureNet'?'active':''}`} onClick={() => setScope('CultureNet')}>CultureNet <span className="count">{cultureStats.people}</span></button>
        <div className="spacer"/>
        <button className="btn sm"><Icon name="export" size={12}/> Export</button>
      </div>

      <div className="scroll">
        <Workflow stats={stats} sports={sportsStats} culture={cultureStats} pct={pct} scope={scope}/>
      </div>
    </>
  );
}

function Workflow({ stats, sports, culture, pct, scope }) {
  const togoPct = pct(stats.togo, stats.totalSlots);
  return (
    <>
      <div className="report-grid">
        <div className="metric accent" style={{gridColumn: 'span 2'}}>
          <span className="m-label">People: Complete</span>
          <span className="m-val" style={{fontSize: 44}}>{stats.complete} <span style={{fontSize: 14, color: 'var(--muted)', fontWeight: 400}}>/ {stats.people}</span></span>
          <span className="m-sub">{pct(stats.complete, stats.people)}% of records done</span>
          <div className="progress-bar" style={{marginTop: 8}}>
            <span style={{flex: stats.complete, background: 'var(--ok)'}}/>
            <span style={{flex: stats.people - stats.complete, background: 'var(--border-2)'}}/>
          </div>
        </div>
        <div className="metric">
          <span className="m-label">People: In progress</span>
          <span className="m-val">{stats.inProgress}</span>
          <span className="m-sub">started, not complete</span>
        </div>
        <div className="metric">
          <span className="m-label">People: Untouched</span>
          <span className="m-val" style={{color: stats.untouched ? 'var(--err)' : 'var(--muted)'}}>{stats.untouched}</span>
          <span className="m-sub">not started yet</span>
        </div>
        <div className="metric">
          <span className="m-label">Handles: Still to go</span>
          <span className="m-val">{stats.togo.toLocaleString()}</span>
          <span className="m-sub">remaining to process</span>
        </div>
        <div className="metric">
          <span className="m-label">Handles: Needs review</span>
          <span className="m-val" style={{color: 'var(--warn)'}}>{stats.needsReview}</span>
          <span className="m-sub">waiting for an analyst</span>
        </div>
        <div className="metric">
          <span className="m-label">Handles: Missing</span>
          <span className="m-val" style={{color: 'var(--err)'}}>{stats.missing}</span>
          <span className="m-sub">no handle in either source</span>
        </div>
        <div className="metric">
          <span className="m-label">Handles: Awaiting QC</span>
          <span className="m-val" style={{color: 'var(--info)'}}>{stats.verified}</span>
          <span className="m-sub">verified, 2nd eye needed</span>
        </div>
      </div>

      <div className="report-section" style={{paddingBottom: 40}}>
        <h2>Split by source system</h2>
        <div className="sub">How much work remains in each feed.</div>
        <div className="sbs">
          <WorkflowSource name="SportsNet" stats={sports} pct={pct}/>
          <WorkflowSource name="CultureNet" stats={culture} pct={pct}/>
        </div>
      </div>
    </>
  );
}

function WorkflowSource({ name, stats, pct }) {
  return (
    <div className="panel">
      <div className="panel-head">
        <div className="mark">{name === 'SportsNet' ? 'SN' : 'CN'}</div>
        <div>
          <div className="src-name">{name}</div>
          <div className="src-count">{stats.people} records</div>
        </div>
        <div style={{marginLeft: 'auto', textAlign: 'right'}}>
          <div style={{fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em'}}>{stats.complete}</div>
          <div style={{fontSize: 11, color: 'var(--muted)'}}>complete</div>
        </div>
      </div>
      <div className="stack">
        <span style={{flex: stats.complete, background: 'var(--ok)'}}/>
        <span style={{flex: stats.inProgress, background: 'var(--info)'}}/>
        <span style={{flex: stats.untouched, background: 'var(--err)'}}/>
      </div>
      <div className="stack-legend">
        <span className="ll"><span className="sw" style={{background:'var(--ok)'}}/> Complete <b>{stats.complete}</b></span>
        <span className="ll"><span className="sw" style={{background:'var(--info)'}}/> In progress <b>{stats.inProgress}</b></span>
        <span className="ll"><span className="sw" style={{background:'var(--err)'}}/> Untouched <b>{stats.untouched}</b></span>
      </div>
      <div className="hr"/>
      <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 8, marginTop: 10}}>
        <div><div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em'}}>Still to go</div><div style={{fontSize: 18, fontWeight: 600}}>{stats.togo}</div></div>
        <div><div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em'}}>Needs review</div><div style={{fontSize: 18, fontWeight: 600, color: stats.needsReview ? 'var(--warn)' : 'var(--muted)'}}>{stats.needsReview}</div></div>
        <div><div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em'}}>Missing</div><div style={{fontSize: 18, fontWeight: 600, color: stats.missing ? 'var(--err)' : 'var(--muted)'}}>{stats.missing}</div></div>
        <div><div style={{fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em'}}>Awaiting QC</div><div style={{fontSize: 18, fontWeight: 600, color: stats.verified ? 'var(--info)' : 'var(--muted)'}}>{stats.verified}</div></div>
      </div>
    </div>
  );
}



window.ReportView = ReportView;
