// 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 === 'SportsTool') : []), [people]);
  const cultureStats = useMemo(() => compute(Array.isArray(people) ? people.filter(p => p.source === 'CultureTool') : []), [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, total: 0, locked: 0, missing: 0, review: 0, verified: 0, nonExisting: 0, togo: 0 };
    for (const p of list) {
      const c = computeCounts(p, PLATFORMS);
      if (c.complete) s.complete++;
      else if (c.qc + c.verified + c['non-existing'] > 0) s.inProgress++;
      else s.untouched++;
      for (const pl of PLATFORMS) {
        const h = p.handles[pl.id];
        const row = s.byPlatform[pl.id];
        s.totalSlots++; row.total++;
        if (h.status === 'qc' || h.status === 'non-existing') { s.locked++; row.locked++; }
        else { s.togo++; row.togo++; }
        if (h.status === 'qc') s.qc++;
        if (h.status === 'verified') { s.verified++; row.verified++; }
        if (h.status === 'unverified') { s.needsReview++; row.review++; }
        if (h.status === 'missing') { s.missing++; row.missing++; }
        if (h.status === 'non-existing') { s.nonExisting++; row.nonExisting++; }
        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 className="seg" style={{marginRight: 8}}>
          <button className={tab==='workflow'?'on':''} onClick={() => setTab('workflow')}>Workflow</button>
          <button className={tab==='quality'?'on':''} onClick={() => setTab('quality')}>Quality</button>
        </div>
        <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==='SportsTool'?'active':''}`} onClick={() => setScope('SportsTool')}>SportsTool <span className="count">{sportsStats.people}</span></button>
        <button className={`chip ${scope==='CultureTool'?'active':''}`} onClick={() => setScope('CultureTool')}>CultureTool <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">
        {tab === 'workflow' ? <Workflow stats={stats} sports={sportsStats} culture={cultureStats} pct={pct} scope={scope}/> : <Quality stats={stats} sports={sportsStats} culture={cultureStats} pct={pct}/>}
      </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">Still to go</span>
          <span className="m-val" style={{fontSize: 44}}>{stats.togo.toLocaleString()}</span>
          <span className="m-sub">handles remaining · {togoPct}% of {stats.totalSlots.toLocaleString()} total slots</span>
          <div className="progress-bar" style={{marginTop: 8}}>
            <span style={{flex: stats.locked, background: 'var(--ok)'}}/>
            <span style={{flex: stats.togo, background: 'var(--border-2)'}}/>
          </div>
        </div>
        <div className="metric">
          <span className="m-label">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">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 className="metric">
          <span className="m-label">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">People complete</span>
          <span className="m-val">{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>
        <div className="metric">
          <span className="m-label">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">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>

      <div className="report-section">
        <h2>To-go by platform</h2>
        <div className="sub">Where the remaining work sits — {scope === 'all' ? 'across all records' : scope}.</div>
        <div className="sbs">
          <div className="panel wide">
            <table className="platform-table">
              <thead>
                <tr>
                  <th>Platform</th>
                  <th>To go</th>
                  <th>Needs review</th>
                  <th>Awaiting QC</th>
                  <th>Missing</th>
                  <th style={{width: 120}}>Done</th>
                </tr>
              </thead>
              <tbody>
                {PLATFORMS.map(pl => {
                  const r = stats.byPlatform[pl.id];
                  const p = pct(r.locked, r.total);
                  return (
                    <tr key={pl.id}>
                      <td><div className="pcell"><Tile platform={pl.id} status="verified"/>{r.name}</div></td>
                      <td><b style={{color: r.togo > 0 ? 'var(--ink)' : 'var(--muted-2)'}}>{r.togo}</b> / {r.total}</td>
                      <td style={{color: r.review > 0 ? 'var(--warn)' : 'var(--muted-2)'}}>{r.review}</td>
                      <td style={{color: r.verified > 0 ? 'var(--info)' : 'var(--muted-2)'}}>{r.verified}</td>
                      <td style={{color: r.missing > 0 ? 'var(--err)' : 'var(--muted-2)'}}>{r.missing}</td>
                      <td>
                        <div className="pcell" style={{justifyContent: 'flex-end'}}>
                          <span style={{fontVariantNumeric: 'tabular-nums', fontWeight: 500}}>{p}%</span>
                          <span className="pbar"><span style={{width: `${p}%`}}/></span>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </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="SportsTool" stats={sports} pct={pct}/>
          <WorkflowSource name="CultureTool" stats={culture} pct={pct}/>
        </div>
      </div>
    </>
  );
}

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

function Quality({ stats, sports, culture, pct }) {
  return (
    <>
      <div className="report-grid">
        <div className="metric accent">
          <span className="m-label">Quality score</span>
          <span className="m-val">{pct(stats.locked, stats.totalSlots)}%</span>
          <span className="m-sub">{stats.locked.toLocaleString()} of {stats.totalSlots.toLocaleString()} handles locked in</span>
        </div>
        <div className="metric">
          <span className="m-label">QC passed</span>
          <span className="m-val" style={{color: 'var(--ok)'}}>{stats.qc}</span>
          <span className="m-sub">four-eye confirmed</span>
        </div>
        <div className="metric">
          <span className="m-label">Source mismatches</span>
          <span className="m-val" style={{color: 'var(--warn)'}}>{stats.mismatches}</span>
          <span className="m-sub">SportsTool ≠ Panel</span>
        </div>
        <div className="metric">
          <span className="m-label">Confirmed absent</span>
          <span className="m-val">{stats.nonExisting}</span>
          <span className="m-sub">verified: no account</span>
        </div>
      </div>

      <div className="report-section">
        <h2>Report back to source systems</h2>
        <div className="sub">Quality delivered to the teams who own the upstream data.</div>
        <div className="sbs">
          <QualitySource name="SportsTool" stats={sports} pct={pct}/>
          <QualitySource name="CultureTool" stats={culture} pct={pct}/>
        </div>
      </div>

      <div className="report-section" style={{paddingBottom: 40}}>
        <h2>Issues found</h2>
        <div className="sub">Corrections and additions our team has contributed.</div>
        <div className="sbs">
          <div className="panel">
            <div className="m-label">Records cleaned</div>
            <div className="m-val" style={{fontSize: 24}}>{stats.mismatches + stats.needsReview}</div>
            <div className="m-sub" style={{marginTop: 4}}>Source disagreements resolved and outdated handles corrected.</div>
          </div>
          <div className="panel">
            <div className="m-label">Handles added</div>
            <div className="m-val" style={{fontSize: 24}}>{Math.max(0, stats.qc + stats.verified - stats.mismatches)}</div>
            <div className="m-sub" style={{marginTop: 4}}>New handles researched and added where source data had nothing.</div>
          </div>
        </div>
      </div>
    </>
  );
}

function QualitySource({ name, stats, pct }) {
  const q = pct(stats.locked, stats.totalSlots);
  return (
    <div className="panel">
      <div className="panel-head">
        <div className="mark">{name === 'SportsTool' ? 'ST' : 'CT'}</div>
        <div>
          <div className="src-name">{name}</div>
          <div className="src-count">{stats.people} records · {stats.totalSlots} handle slots</div>
        </div>
        <div style={{marginLeft: 'auto', textAlign: 'right'}}>
          <div style={{fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em', color: q >= 80 ? 'var(--ok)' : q >= 50 ? 'var(--warn)' : 'var(--err)'}}>{q}%</div>
          <div style={{fontSize: 11, color: 'var(--muted)'}}>quality</div>
        </div>
      </div>
      <div className="stack">
        <span style={{flex: stats.qc, background: '#16A34A'}}/>
        <span style={{flex: stats.verified, background: '#84CC16'}}/>
        <span style={{flex: stats.nonExisting, background: '#78716C'}}/>
        <span style={{flex: stats.needsReview, background: '#D97706'}}/>
        <span style={{flex: stats.missing, background: '#DC2626'}}/>
      </div>
      <div className="stack-legend">
        <span className="ll"><span className="sw" style={{background:'#16A34A'}}/> QC passed <b>{stats.qc}</b></span>
        <span className="ll"><span className="sw" style={{background:'#84CC16'}}/> Verified <b>{stats.verified}</b></span>
        <span className="ll"><span className="sw" style={{background:'#78716C'}}/> No account <b>{stats.nonExisting}</b></span>
        <span className="ll"><span className="sw" style={{background:'#D97706'}}/> Needs review <b>{stats.needsReview}</b></span>
        <span className="ll"><span className="sw" style={{background:'#DC2626'}}/> Missing <b>{stats.missing}</b></span>
        <span className="ll"><span className="sw" style={{background:'var(--border-2)'}}/> Mismatches <b>{stats.mismatches}</b></span>
      </div>
    </div>
  );
}

window.ReportView = ReportView;
