// role-dispatch.jsx — Dispatch: where-is-my-RWIC + this-week schedule board.

function RoleDispatch() {
  const { employees, jobs } = useAdmin();
  const onDuty = employees.filter(e => e.status === 'on-duty');
  return (
    <>
      <PageHeader
        eyebrow="DISPATCH"
        title="Where is everyone?"
        subtitle="Live RWIC positions and this week's assignment board."
        right={
          <>
            <Pill tone="good"><StatusDot tone="good" size={6} pulse /> {onDuty.length} on duty</Pill>
            <Button variant="primary" size="md" icon={<IconPlus size={14} />}>Assign RWIC</Button>
          </>
        }
      />
      <PageBody>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 22, marginBottom: 22 }}>
          <AdminSection title="Live map" style={{ marginBottom: 0 }}>
            <LiveOperationsMap />
          </AdminSection>
          <AdminSection title="Status board" style={{ marginBottom: 0 }}>
            <StatusBoard />
          </AdminSection>
        </div>
        <AdminSection title="This week · assignment schedule">
          <ScheduleBoard />
        </AdminSection>
      </PageBody>
    </>
  );
}

// ── Status board ─────────────────────────────────────────────
function StatusBoard() {
  const { employees, jobs } = useAdmin();
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
      {employees.map((e, i) => {
        const job = jobs.find(j => j.rwicIds.includes(e.id));
        const on = e.status === 'on-duty';
        return (
          <div key={e.id} style={{
            padding: '11px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{ position: 'relative' }}>
              <div style={{
                width: 34, height: 34, borderRadius: 17,
                background: on ? 'var(--accent-soft)' : 'var(--panel-3)',
                color: on ? 'var(--accent-deep)' : 'var(--muted)',
                display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700,
              }}>{e.avatar}</div>
              <span style={{
                position: 'absolute', bottom: -1, right: -1,
                width: 11, height: 11, borderRadius: 6,
                background: on ? 'var(--good)' : 'var(--muted-2)',
                border: '2px solid var(--panel)',
              }} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{e.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {on && job ? `${job.id} · ${job.subdivision}` : `Available · ${e.homeBase}`}
              </div>
              {job && (() => {
                const m = managerForJob(job.id);
                return m ? <div style={{ fontSize: 10.5, color: 'var(--indigo)', marginTop: 1 }}>⤷ approves to {m.name}</div> : null;
              })()}
            </div>
            {on
              ? <Pill tone="good">{job?.state || e.resident}</Pill>
              : <Pill tone="neutral">Off</Pill>}
          </div>
        );
      })}
    </div>
  );
}

// ── Schedule board (week grid) ──────────────────────────────
function ScheduleBoard() {
  const { employees, jobs } = useAdmin();
  const days = ['Mon 25', 'Tue 26', 'Wed 27', 'Thu 28', 'Fri 29', 'Sat 30', 'Sun 31'];
  // Deterministic assignment bars
  const assignmentFor = (e) => {
    const job = jobs.find(j => j.rwicIds.includes(e.id));
    if (!job) return null;
    const seed = e.id.charCodeAt(2) % 3;
    return { job, start: seed === 0 ? 0 : seed === 1 ? 0 : 1, span: seed === 2 ? 4 : 5 };
  };
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ display: 'grid', gridTemplateColumns: '180px repeat(7, 1fr)', background: 'var(--panel-2)', borderBottom: '1px solid var(--line)' }}>
        <div style={{ padding: '10px 14px', fontSize: 11, fontWeight: 600, color: 'var(--muted)', letterSpacing: 0.5, textTransform: 'uppercase' }}>RWIC</div>
        {days.map(d => (
          <div key={d} style={{ padding: '10px 8px', fontSize: 11, fontWeight: 600, color: 'var(--muted)', textAlign: 'center', borderLeft: '1px solid var(--line)' }}>{d}</div>
        ))}
      </div>
      {employees.map((e, i) => {
        const a = assignmentFor(e);
        return (
          <div key={e.id} style={{
            display: 'grid', gridTemplateColumns: '180px repeat(7, 1fr)',
            borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            position: 'relative', minHeight: 44, alignItems: 'center',
          }}>
            <div style={{ padding: '8px 14px', display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{ width: 24, height: 24, borderRadius: 12, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700 }}>{e.avatar}</div>
              <span style={{ fontSize: 12.5, fontWeight: 600 }}>{e.name.split(' ')[0]} {e.name.split(' ').pop().charAt(0)}.</span>
            </div>
            {/* day cells */}
            {Array.from({ length: 7 }).map((_, d) => (
              <div key={d} style={{ borderLeft: '1px solid var(--line)', minHeight: 44 }} />
            ))}
            {/* assignment bar overlay */}
            {a && (
              <div style={{
                position: 'absolute',
                left: `calc(180px + ${a.start} * ((100% - 180px) / 7) + 4px)`,
                width: `calc(${a.span} * ((100% - 180px) / 7) - 8px)`,
                top: 8, bottom: 8,
                background: 'var(--accent-soft)', border: '1px solid var(--accent)',
                borderRadius: 6, padding: '0 10px',
                display: 'flex', alignItems: 'center', gap: 6,
                overflow: 'hidden',
              }}>
                <span className="mono" style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--accent-deep)' }}>{a.job.id}</span>
                <span style={{ fontSize: 11, color: 'var(--accent-deep)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.job.subdivision}</span>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { RoleDispatch });
