// WeWire team dashboard — views: Overview, Pipeline, Profile, Compare.

// ── KPI card ─────────────────────────────────────────────────
function Kpi({ label, value, sub, accent }) {
  return (
    <Card pad={20} style={{ flex: 1 }}>
      <div style={{ fontSize: 13, color: T.muted, fontWeight: 600 }}>{label}</div>
      <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 38, letterSpacing: '-0.02em', lineHeight: 1,
        margin: '10px 0 6px', color: accent || T.ink }}>{value}</div>
      <div style={{ fontSize: 12.5, color: T.subtle }}>{sub}</div>
    </Card>
  );
}

function Overview({ data, setView, openProfile }) {
  const { STAGES, PROGRAM } = window.WWData;
  const total = data.length;
  const offers = data.filter(a => a.status === 'offer').length;
  const shortlisted = data.filter(a => a.status === 'shortlist' || a.status === 'offer').length;
  const inAssess = data.filter(a => ['in_review', 'advancing'].includes(a.status)).length;
  const reached = STAGES.map((s, i) => data.filter(a => a.stage >= i).length);
  const maxR = reached[0] || 1;
  const ranked = [...data].filter(a => a.status !== 'rejected').sort((a, b) => overall(b.scores) - overall(a.scores));
  const interviewBookings = data
    .filter((a) => a.stagePayload?.interview?.slot)
    .map((a) => ({
      id: a.id,
      name: a.name,
      slot: a.stagePayload.interview.slot,
    }));

  // track distribution
  const trackCounts = {};
  data.forEach(a => { trackCounts[a.track] = (trackCounts[a.track] || 0) + 1; });

  return (
    <div style={{ padding: '30px 36px 48px' }}>
      <Eyebrow>Cohort 2026 · live</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 34, letterSpacing: '-0.02em', margin: '8px 0 4px' }}>Overview</h1>
      <p style={{ color: T.muted, fontSize: 15 }}>Selecting {PROGRAM.seats} graduates from {total} applicants across {Object.keys(trackCounts).length} tracks.</p>

      <div style={{ display: 'flex', gap: 16, marginTop: 24 }}>
        <Kpi label="Total applicants" value={total} sub="this cycle" />
        <Kpi label="In assessment" value={inAssess} sub="actively progressing" accent={T.blue} />
        <Kpi label="Shortlisted" value={shortlisted} sub={`for ${PROGRAM.seats} seats`} accent={T.orange} />
        <Kpi label="Seats remaining" value={PROGRAM.seats - offers} sub={`${offers} offer${offers === 1 ? '' : 's'} extended`} accent={T.green} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 16, marginTop: 16 }}>
        {/* funnel */}
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <div>
              <Eyebrow>Recruitment funnel</Eyebrow>
              <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 19, marginTop: 4 }}>Where applicants are</div>
            </div>
            <Btn variant="ghost" size="sm" icon="list" onClick={() => setView('pipeline')}>Open pipeline</Btn>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
            {STAGES.map((s, i) => {
              const c = reached[i];
              return (
                <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <div style={{ width: 150, flex: 'none', display: 'flex', alignItems: 'center', gap: 9 }}>
                    <span style={{ fontFamily: DISP, fontWeight: 600, fontSize: 11, color: T.subtle }}>{s.n}</span>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: T.ink }}>{s.name}</span>
                  </div>
                  <div style={{ flex: 1, height: 26, background: T.sand, borderRadius: 8, overflow: 'hidden', position: 'relative' }}>
                    <div style={{ width: `${(c / maxR) * 100}%`, height: '100%', borderRadius: 8,
                      background: `linear-gradient(90deg, ${T.orange}, ${T.amber})`, transition: 'width 500ms' }} />
                  </div>
                  <span style={{ width: 30, textAlign: 'right', fontWeight: 700, fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>{c}</span>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: `1px dashed ${T.lineStrong}`, display: 'flex',
            alignItems: 'center', gap: 8, fontSize: 13, color: T.muted }}>
            <Icon name="flag" size={15} color={T.orange} />
            The final interview pool narrows to the <b style={{ color: T.ink, margin: '0 4px' }}>{PROGRAM.seats}</b> graduates we'll welcome to Accra.
          </div>
        </Card>

        {/* leaderboard */}
        <Card>
          <Eyebrow>Top of the pool</Eyebrow>
          <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 19, margin: '4px 0 16px' }}>Highest overall</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {ranked.slice(0, 6).map((a, i) => (
              <div key={a.id} onClick={() => openProfile(a.id)} style={{ display: 'flex', alignItems: 'center', gap: 12,
                padding: '9px 8px', borderRadius: 11, cursor: 'pointer' }}
                onMouseEnter={(e) => e.currentTarget.style.background = T.panel}
                onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                <span style={{ width: 20, fontFamily: DISP, fontWeight: 600, fontSize: 14, color: i < 3 ? T.orange : T.subtle }}>{i + 1}</span>
                <Avatar name={a.name} size={34} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</div>
                  <div style={{ fontSize: 11.5, color: T.subtle }}>{a.track}</div>
                </div>
                <span style={{ fontFamily: DISP, fontWeight: 600, fontSize: 17 }}>{overall(a.scores)}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <div>
            <Eyebrow>Final interviews</Eyebrow>
            <div style={{ fontFamily: DISP, fontWeight: 600, fontSize: 19, marginTop: 4 }}>Booked slots ({interviewBookings.length})</div>
          </div>
          <Btn variant="ghost" size="sm" icon="clock" onClick={() => setView('interviews')}>Manage slots</Btn>
        </div>
        {interviewBookings.length === 0 ? (
          <div style={{ fontSize: 14, color: T.muted, lineHeight: 1.5 }}>No interviews booked yet. Shortlist candidates so they can schedule in Accra.</div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 12 }}>
            {interviewBookings.map((b) => (
              <div key={b.id} onClick={() => openProfile(b.id)} style={{ padding: '14px 16px', borderRadius: 12, background: T.panel, cursor: 'pointer' }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{b.name}</div>
                <div style={{ fontSize: 13, color: T.muted, marginTop: 4 }}>
                  {b.slot.day || b.slot.date} · {b.slot.time}
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

// ── Pipeline table ───────────────────────────────────────────
function StageDots({ stage }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'flex', gap: 3 }}>
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} style={{ width: 7, height: 7, borderRadius: '50%',
            background: i < stage ? T.orange : i === stage ? T.amber : T.sand }} />
        ))}
      </div>
      <span style={{ fontSize: 12.5, color: T.muted, fontWeight: 600 }}>{Math.min(stage + 1, 8)}/8</span>
    </div>
  );
}

function Pipeline({ data, openProfile, selected, toggleSelect, setView, onBulkDelete }) {
  const { STAGES } = window.WWData;
  const [q, setQ] = React.useState('');
  const [statusF, setStatusF] = React.useState('all');
  const [sort, setSort] = React.useState('overall');
  const [dir, setDir] = React.useState(-1);

  let rows = data.filter(a =>
    (statusF === 'all' || a.status === statusF) &&
    (q === '' || a.name.toLowerCase().includes(q.toLowerCase()) || a.track.toLowerCase().includes(q.toLowerCase()) || a.id.toLowerCase().includes(q.toLowerCase())));
  const key = { overall: a => overall(a.scores) || 0, stage: a => a.stage, name: a => a.name, applied: a => a.applied };
  rows = rows.sort((a, b) => { const va = key[sort](a), vb = key[sort](b); return (va > vb ? 1 : va < vb ? -1 : 0) * dir; });

  const Th = ({ id, children, w, align = 'left' }) => (
    <th onClick={id ? () => { if (sort === id) setDir(-dir); else { setSort(id); setDir(-1); } } : undefined}
      style={{ textAlign: align, padding: '0 14px 12px', fontSize: 12, fontWeight: 700, color: T.muted, letterSpacing: '0.04em',
        textTransform: 'uppercase', cursor: id ? 'pointer' : 'default', width: w, whiteSpace: 'nowrap', userSelect: 'none' }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>{children}
        {sort === id && <Icon name={dir === -1 ? 'down' : 'up'} size={13} color={T.orange} />}</span>
    </th>
  );

  const statuses = ['all', 'in_review', 'advancing', 'shortlist', 'offer', 'rejected'];

  return (
    <div style={{ padding: '30px 36px 48px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 22 }}>
        <div>
          <Eyebrow>Applicants</Eyebrow>
          <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 34, letterSpacing: '-0.02em', margin: '8px 0 0' }}>Pipeline</h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {selected.length > 0 && (
            <Btn variant="ghost" icon="x" onClick={onBulkDelete}
              style={{ color: T.red, borderColor: `${T.red}33` }}>Remove ({selected.length})</Btn>
          )}
          <Btn variant={selected.length >= 2 ? 'dark' : 'ghost'} icon="compare" disabled={selected.length < 2}
            onClick={() => setView('compare')}>Compare {selected.length > 0 ? `(${selected.length})` : ''}</Btn>
        </div>
      </div>

      {/* toolbar */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: T.white, border: `1px solid ${T.lineStrong}`,
          borderRadius: 10, padding: '0 14px', height: 42, flex: 1, minWidth: 220, maxWidth: 340 }}>
          <Icon name="search" size={17} color={T.muted} />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name, track, ID…"
            style={{ border: 'none', outline: 'none', fontFamily: FONT, fontSize: 14, flex: 1, background: 'transparent', color: T.ink }} />
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {statuses.map(s => {
            const on = statusF === s;
            return <button key={s} onClick={() => setStatusF(s)} style={{ height: 42, padding: '0 14px', borderRadius: 10,
              border: 'none', cursor: 'pointer', fontFamily: FONT, fontSize: 13, fontWeight: 600,
              background: on ? T.ink : T.white, color: on ? T.cream : T.muted,
              boxShadow: on ? 'none' : `inset 0 0 0 1px ${T.line}` }}>
              {s === 'all' ? 'All' : (STATUS[s].label)}</button>;
          })}
        </div>
      </div>

      <Card pad={20} style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', minWidth: 740, borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={{ width: 40, padding: '0 0 12px' }}></th>
            <Th id="name">Candidate</Th>
            <Th>Track</Th>
            <Th id="stage">Stage</Th>
            <Th id="overall" w={140}>Overall</Th>
            <Th>Status</Th>
            <th style={{ width: 30 }}></th>
          </tr></thead>
          <tbody>
            {rows.map(a => {
              const sel = selected.includes(a.id);
              return (
                <tr key={a.id} onClick={() => openProfile(a.id)} style={{ cursor: 'pointer', borderTop: `1px solid ${T.line}` }}
                  onMouseEnter={(e) => e.currentTarget.style.background = T.panel}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '12px 0' }} onClick={(e) => { e.stopPropagation(); toggleSelect(a.id); }}>
                    <div style={{ width: 20, height: 20, margin: '0 auto', borderRadius: 6, border: `1.5px solid ${sel ? T.orange : T.lineStrong}`,
                      background: sel ? T.orange : T.white, display: 'grid', placeItems: 'center' }}>
                      {sel && <Icon name="check" size={14} color="#fff" />}</div>
                  </td>
                  <td style={{ padding: '11px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <Avatar name={a.name} size={36} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 14.5, fontWeight: 600, whiteSpace: 'nowrap' }}>{a.name}</div>
                        <div style={{ fontSize: 12, color: T.subtle, whiteSpace: 'nowrap' }}>{a.uni} · {a.id}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '11px 14px', fontSize: 13.5, color: T.muted, fontWeight: 500 }}>{a.track}</td>
                  <td style={{ padding: '11px 14px' }}><StageDots stage={a.stage} /></td>
                  <td style={{ padding: '11px 14px' }}><ScoreBar value={overall(a.scores)} w="full" /></td>
                  <td style={{ padding: '11px 14px' }}><Badge status={a.status} size="sm" /></td>
                  <td style={{ padding: '11px 8px' }}><Icon name="chevron" size={16} color={T.subtle} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {rows.length === 0 && <div style={{ textAlign: 'center', padding: '36px', color: T.subtle, fontSize: 14 }}>No applicants match.</div>}
      </Card>
    </div>
  );
}

Object.assign(window, { Overview, Pipeline, Kpi, StageDots });
