// tab-roster.jsx — searchable / filterable full-team table.

const { useState: rUseState, useMemo: rUseMemo, useEffect: rUseEffect } = React;

function TabRoster({ initialSev, clearInitialSev }) {
  const [q, setQ] = rUseState('');
  const [sevFilter, setSevFilter] = rUseState(initialSev || null);
  const [roleFilter, setRoleFilter] = rUseState(null);
  const [limit, setLimit] = rUseState(50);
  const [viewEmail, setViewEmail] = rUseState(null);

  // When the user clicks a triage tile on Overview, LeadShell sets
  // `initialSev` and switches tab. Sync the prop into our local filter
  // state and ack to LeadShell so a second click on the same tile
  // re-fires the effect (LeadShell clears its rosterSev, sets it again).
  rUseEffect(() => {
    if (initialSev) {
      setSevFilter(initialSev);
      if (typeof clearInitialSev === 'function') clearInitialSev();
    }
  }, [initialSev, clearInitialSev]);

  const filtered = rUseMemo(() => {
    let list = window.YD.MEMBERS;
    if (q) {
      const qq = q.toLowerCase();
      list = list.filter(m => m.name.toLowerCase().includes(qq) || m.email.toLowerCase().includes(qq));
    }
    if (sevFilter) list = list.filter(m => m.severity === sevFilter);
    if (roleFilter) list = list.filter(m => m.role === roleFilter);
    return list;
  }, [q, sevFilter, roleFilter]);

  const visible = filtered.slice(0, limit);

  return (
    <div className="page">
      <PageHeader
        eyebrow="Roster"
        title="All annotators"
        subtitle={`${window.YD.MEMBERS.length} on team · ${filtered.length} shown`}
        actions={
          <div className="flex g8">
            <button className="btn">Export</button>
            <button className="btn btn-dark">+ Add annotator</button>
          </div>
        }/>

      <div className="roster-filters">
        <div className="roster-search">
          <svg width="14" height="14" viewBox="0 0 14 14" style={{ opacity: 0.5 }}>
            <circle cx="6" cy="6" r="4" stroke="currentColor" fill="none" strokeWidth="1.5"/>
            <path d="M9 9l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
          <input placeholder="Search name or email…" value={q} onChange={e => setQ(e.target.value)}/>
        </div>

        <div className="flex g8">
          <div className="segbar">
            <button className={!sevFilter ? 'active' : ''} onClick={() => setSevFilter(null)}>All status</button>
            {Object.keys(window.YDLoader.SEV_META).map(s => (
              <button key={s} className={sevFilter === s ? 'active' : ''} onClick={() => setSevFilter(s)}>
                <SevDot sev={s} size={6}/>
                <span style={{ marginLeft: 4 }}>{window.YDLoader.SEV_META[s].label}</span>
                <span style={{ marginLeft: 6, color: '#9ca3af' }}>{(window.YD.BY_SEVERITY[s] || []).length}</span>
              </button>
            ))}
          </div>
          <div className="segbar">
            <button className={!roleFilter ? 'active' : ''} onClick={() => setRoleFilter(null)}>All roles</button>
            <button className={roleFilter === 'admin' ? 'active' : ''} onClick={() => setRoleFilter('admin')}>Admin</button>
            <button className={roleFilter === 'teamLead' ? 'active' : ''} onClick={() => setRoleFilter('teamLead')}>Lead</button>
            <button className={roleFilter === 'annotator' ? 'active' : ''} onClick={() => setRoleFilter('annotator')}>Annotator</button>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-bd" style={{ padding: 0 }}>
          <table className="roster-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Role</th>
                <th>Status</th>
                <th className="num">Pace</th>
                <th className="num">Week resources</th>
                <th className="num">Missed</th>
                <th className="num">Incomplete</th>
                <th>Shift today</th>
                <th/>
              </tr>
            </thead>
            <tbody>
              {visible.map(m => (
                <tr key={m.email}>
                  <td>
                    <div className="flex ac g8">
                      <Avatar name={m.name} size={24}/>
                      <div>
                        <div style={{ fontWeight: 600, color: '#111' }}>{m.name}</div>
                        <div style={{ fontSize: 10, color: '#9ca3af' }}>{m.email}</div>
                      </div>
                    </div>
                  </td>
                  <td>{m.role}</td>
                  <td>
                    <span className="chip chip-mini" style={{
                      background: window.YDLoader.SEV_META[m.severity].bg,
                      color: window.YDLoader.SEV_META[m.severity].color,
                      borderColor: window.YDLoader.SEV_META[m.severity].border,
                    }}>
                      <SevDot sev={m.severity} size={5}/>
                      {window.YDLoader.SEV_META[m.severity].label}
                    </span>
                  </td>
                  <td className="num mono">{m.pace || '—'}</td>
                  <td className="num mono" style={{ fontWeight: 600 }}>{fmtK(m.resources)}</td>
                  <td className="num mono" style={{ color: m.missed > 0 ? '#b91c1c' : '#d1d5db' }}>{m.missed || 0}</td>
                  <td className="num mono" style={{ color: m.incomplete > 0 ? '#b45309' : '#d1d5db' }}>{m.incomplete || 0}</td>
                  <td className="mono" style={{ fontSize: 11 }}>{m.todayShiftStart || '—'}</td>
                  <td>
                    <button className="btn btn-sm btn-ghost" onClick={() => setViewEmail(m.email)}>View</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length > limit && (
            <div className="pt-more">
              <button className="btn" onClick={() => setLimit(limit + 50)}>
                Show 50 more · {filtered.length - limit} hidden
              </button>
            </div>
          )}
        </div>
      </div>

      {viewEmail && (
        <PersonModal email={viewEmail} onClose={() => setViewEmail(null)}/>
      )}
    </div>
  );
}

Object.assign(window, { TabRoster });
