// person-modal.jsx — drilldown modal for one annotator. Used by Roster's
// "View" button (and any future click-through). Pulls getIndividualForAdmin
// for the rich payload (KPI by project, daily breakdown, dailyTarget, qc).

const { useState: pmUseState, useEffect: pmUseEffect } = React;

function PersonModal({ email, onClose }) {
  const [data, setData] = pmUseState(null);
  const [err, setErr] = pmUseState(null);
  const [logTarget, setLogTarget] = pmUseState(null);
  const [toast, setToast] = pmUseState(null);

  pmUseEffect(() => {
    window.YDApp.call('getIndividualForAdmin', { email })
      .then(setData)
      .catch((e) => setErr(e.message || String(e)));
  }, [email]);

  // Pull the matching member from the team data so we can show severity +
  // dailyShifts overlay (that data isn't in getIndividualForAdmin).
  const member = (window.YD.MEMBERS || []).find((m) => m.email === email);
  // Filter the team-level action log to just this person's history.
  const personActions = (window.YD.ACTION_LOG || []).filter(
    (a) => a.subject && member && a.subject === member.name,
  );

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-card modal-card-xwide" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hd">
          <div className="flex ac g8" style={{ minWidth: 0, flex: 1 }}>
            <Avatar name={(data && data.name) || (member && member.name) || email} size={36}/>
            <div style={{ minWidth: 0 }}>
              <h3 style={{ margin: 0, fontSize: 16 }}>
                {(data && data.name) || (member && member.name) || email}
                {member && member.severity && member.severity !== 'ok' && member.severity !== 'leave' && (
                  <span className="chip chip-mini" style={{
                    marginLeft: 8,
                    background: window.YDLoader.SEV_META[member.severity].bg,
                    color: window.YDLoader.SEV_META[member.severity].color,
                    borderColor: window.YDLoader.SEV_META[member.severity].border,
                  }}>
                    <SevDot sev={member.severity} size={5}/>
                    {window.YDLoader.SEV_META[member.severity].label}
                  </span>
                )}
              </h3>
              <div className="meta" style={{ marginTop: 2 }}>
                {email} · {(member && member.role) || (data && data.role) || ''} · {(member && member.team) || (data && data.team) || ''}
              </div>
            </div>
          </div>
          <button className="modal-x" onClick={onClose}>×</button>
        </div>

        <div className="modal-bd">
          {err && <div className="modal-err">{err}</div>}
          {!data && !err && <div className="meta">Loading…</div>}
          {data && <PersonBody data={data} member={member} actions={personActions}/>}
        </div>

        <div className="modal-actions">
          <button
            className="btn"
            onClick={() => member && setLogTarget([member])}
            disabled={!member}>
            + Log action
          </button>
          <button className="btn btn-dark" onClick={onClose}>Close</button>
        </div>
      </div>

      {logTarget && (
        <ActionModal
          targets={logTarget}
          onClose={() => setLogTarget(null)}
          onSaved={(count) => {
            setLogTarget(null);
            setToast(`Logged action for ${count} ${count === 1 ? 'person' : 'people'}`);
            setTimeout(() => setToast(null), 2400);
          }}/>
      )}
      {toast && <div className="toast">{toast}</div>}
    </div>
  );
}

function PersonBody({ data, member, actions }) {
  const kpi = data.kpi || {};
  const weekly = data.weekly || { days: [] };
  const expected = data.expectedPace || 0;
  const dailyTarget = data.dailyTarget || null;

  return (
    <>
      {/* KPI tiles */}
      <div className="kpi-row" style={{ gridTemplateColumns: 'repeat(4, 1fr)', marginBottom: 18 }}>
        <div className="kpi-tile">
          <div className="lbl">Week resources</div>
          <div className="val">{fmtK(kpi.totalResources || 0)}</div>
          <div className="sub">WTD</div>
        </div>
        <div className="kpi-tile">
          <div className="lbl">Pace /hr</div>
          <div className="val" style={expected > 0 ? { color: kpi.avgPace >= expected ? '#15803d' : '#b45309' } : undefined}>
            {kpi.avgPace || 0}
          </div>
          <div className="sub">{expected > 0 ? `vs ${expected} expected` : ''}</div>
        </div>
        <div className="kpi-tile">
          <div className="lbl">Hours</div>
          <div className="val">{(kpi.totalHours || 0).toFixed(1)}h</div>
          <div className="sub">vs {weekly.totalCommitted || 0}h committed</div>
        </div>
        <div className="kpi-tile">
          <div className="lbl">Today target</div>
          <div className="val">{dailyTarget ? fmtK(dailyTarget.todayTarget) : '—'}</div>
          <div className="sub">
            {dailyTarget
              ? `${fmtK(dailyTarget.todayActual)} done${dailyTarget.cumDeficit > 0 ? ` · ${fmtK(dailyTarget.cumDeficit)} cum deficit` : ' · on pace'}`
              : ''}
          </div>
        </div>
      </div>

      {/* 7-day heatmap (compact reuse of the Performance row treatment) */}
      <div style={{ marginBottom: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>This week</div>
        <table className="perf-hm">
          <thead>
            <tr>
              {window.YD.DAYS.map((d, i) => (
                <th key={d} className={'d' + (i === window.YD.TODAY_IDX ? ' today' : '')}>{d}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            <tr>
              {(member?.dailyShifts || weekly.days || []).map((s, i) => {
                const k = (member?.dailyKpi || kpi.dailyBreakdown || [])[i] || { resources: 0, hours: 0 };
                const st = personCellStyle(s, k, i === window.YD.TODAY_IDX);
                return (
                  <td key={i} className={'cell-td' + (i === window.YD.TODAY_IDX ? ' today' : '')}>
                    <div className="cell" style={{ background: st.bg, color: st.color }}>{st.label}</div>
                  </td>
                );
              })}
            </tr>
          </tbody>
        </table>
      </div>

      {/* By project */}
      {kpi.entries && kpi.entries.length > 0 && (
        <div style={{ marginBottom: 18 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>By project</div>
          <table className="pl-table">
            <thead>
              <tr>
                <th>Project</th>
                <th className="num">Resources</th>
                <th className="num">Hours</th>
                <th className="num">Pace</th>
                <th className="num">vs Target</th>
              </tr>
            </thead>
            <tbody>
              {kpi.entries.map((e) => (
                <tr key={e.project}>
                  <td>{e.project}</td>
                  <td className="num mono">{fmtK(e.resources)}</td>
                  <td className="num mono">{e.hours}h</td>
                  <td className="num mono" style={{ color: e.paceStatus === 'critical' ? '#b91c1c' : e.paceStatus === 'on_track' ? '#15803d' : '' }}>
                    {e.pace}{e.paceTarget > 0 ? ` / ${e.paceTarget}` : ''}
                  </td>
                  <td className="num mono">{e.resPct != null ? e.resPct + '%' : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Recent actions for this person — Active rows get a small badge so
          you can see at a glance what's still open vs. resolved/dismissed.
          Dismissed contact logs stay visible here intentionally; that's the
          historical record. */}
      <div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Recent actions</div>
        {actions.length === 0 ? (
          <div className="meta">No actions logged yet.</div>
        ) : (
          <div className="al-list" style={{ border: '1px solid var(--line)', borderRadius: 8 }}>
            {actions.slice(0, 8).map((a, i) => {
              const status = a.status || 'open';
              const tone = status === 'open'
                ? { color: '#b45309', bg: '#fffbeb', label: 'Active' }
                : status === 'escalated'
                  ? { color: '#b91c1c', bg: '#fef2f2', label: 'Escalated' }
                  : status === 'resolved'
                    ? { color: '#15803d', bg: '#f0fdf4', label: 'Resolved' }
                    : { color: '#6b7280', bg: '#f3f4f6', label: 'Dismissed' };
              return (
                <div key={a.id || i} className="al-entry">
                  <div className="al-entry-when">{a.when ? a.when.slice(0, 16).replace('T', ' ') : '—'}</div>
                  <div className="al-entry-main">
                    <div className="al-entry-hd">
                      <span className="al-entry-action">{a.action}</span>
                      <span
                        className="chip chip-mini"
                        style={{ marginLeft: 8, color: tone.color, background: tone.bg, borderColor: 'transparent' }}>
                        {tone.label}
                      </span>
                    </div>
                    {a.isMonitored && a.targetDescription && (
                      <div className="al-entry-note"><b>Target:</b> {a.targetDescription}</div>
                    )}
                    {a.note && a.note !== a.action && <div className="al-entry-note">{a.note}</div>}
                  </div>
                  <div className="al-entry-by">
                    <Avatar name={a.who} size={20}/>
                    <span>{a.who}</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </>
  );
}

function personCellStyle(s, kpi, isToday) {
  const res = (kpi && kpi.resources) || 0;
  if (!s) return { bg: '#fafafa', color: '#d1d5db', label: '—' };
  if (s.isLeave || s.status === 'On Leave') {
    return res > 0
      ? { bg: '#f5f3ff', color: '#7c3aed', label: fmtK(res) }
      : { bg: '#eff6ff', color: '#1d4ed8', label: 'leave' };
  }
  if (s.isDayOff) {
    return res > 0
      ? { bg: '#f5f3ff', color: '#7c3aed', label: fmtK(res) }
      : { bg: '#fafafa', color: '#d1d5db', label: 'off' };
  }
  if (s.isPending || s.status === 'Pending') return { bg: '#fafafa', color: '#d1d5db', label: '—' };
  if (s.isMissed) {
    if (res > 0) return { bg: '#fffbeb', color: '#b45309', label: fmtK(res) };
    return { bg: '#fef2f2', color: '#b91c1c', label: '✗' };
  }
  if (res > 0) {
    if (s.isExceeded) return { bg: '#bbf7d0', color: '#14532d', label: fmtK(res) };
    if (s.isIncomplete) return { bg: '#fffbeb', color: '#b45309', label: fmtK(res) };
    if (s.isInProgress) return { bg: '#dbeafe', color: '#1d4ed8', label: fmtK(res) };
    return { bg: '#f0fdf4', color: '#15803d', label: fmtK(res) };
  }
  if (isToday) return { bg: '#fafafa', color: '#9ca3af', label: 'today' };
  return { bg: '#fef2f2', color: '#b91c1c', label: '✗' };
}

Object.assign(window, { PersonModal });
