// role-ops.jsx — Operations: employee roster + job pipeline + clients.

function RoleOps() {
  const [tab, setTab] = useState('employees');
  return (
    <>
      <PageHeader
        eyebrow="OPERATIONS"
        title="Run the business"
        subtitle="Employees, jobs, and clients. First-step approver for timecards."
        right={
          <>
            <Button variant="secondary" size="md" icon={<IconKanban size={14} />}>Schedule view</Button>
            <Button variant="primary" size="md" icon={<IconPlus size={14} />}>New job</Button>
          </>
        }
      />
      <div style={{ padding: '14px 32px 0', borderBottom: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', gap: 4 }}>
        {[
          { id: 'employees', label: 'Employees' },
          { id: 'jobs',      label: 'Jobs & projects' },
          { id: 'clients',   label: 'Clients & rates' },
        ].map(t => {
          const on = tab === t.id;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '10px 14px',
              background: 'transparent', border: 'none',
              borderBottom: on ? '2px solid var(--accent)' : '2px solid transparent',
              marginBottom: -1,
              color: on ? 'var(--text)' : 'var(--muted)',
              fontWeight: on ? 600 : 500, fontSize: 13.5,
            }}>{t.label}</button>
          );
        })}
      </div>
      <PageBody>
        {tab === 'employees' && <EmployeesTab />}
        {tab === 'jobs'      && <JobsTab />}
        {tab === 'clients'   && <ClientsTab />}
      </PageBody>
    </>
  );
}

// ── Employees tab ────────────────────────────────────────────
function EmployeesTab() {
  const { employees, setEmployeeDrawer } = useAdmin();
  const [filter, setFilter] = useState('all');
  const filtered = employees.filter(e => {
    if (filter === 'all') return true;
    if (filter === 'on-duty')  return e.status === 'on-duty';
    if (filter === 'off-duty') return e.status === 'off-duty';
    if (filter === 'expired')  return new Date(e.certExpires) < new Date('2026-08-22');
    if (filter === 'non-rrb')  return !e.rrbContributor;
    return true;
  });
  const cols = [
    { key: 'name', label: 'Employee', width: '24%', render: (r) => (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 16,
          background: r.status === 'on-duty' ? 'var(--accent-soft)' : 'var(--panel-3)',
          color: r.status === 'on-duty' ? 'var(--accent-deep)' : 'var(--text-2)',
          display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700,
        }}>{r.avatar}</div>
        <div>
          <div style={{ fontWeight: 600 }}>{r.name}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }} className="mono">{r.badge} · {r.role}</div>
        </div>
      </div>
    ) },
    { key: 'resident', label: 'Resident', mono: true },
    { key: 'baseRate', label: 'Rate', align: 'right', mono: true, render: (r) => A_fmtCurrency(r.baseRate) + '/hr' },
    { key: 'payrollFreq', label: 'Pay', render: (r) => <Pill tone="neutral">{r.payrollFreq}</Pill> },
    { key: 'rrb', label: 'RRB', render: (r) => r.rrbContributor ? <Pill tone="info">Tier I/II</Pill> : <Pill tone="neutral">FICA only</Pill> },
    { key: 'certExpires', label: 'Cert expires', mono: true, render: (r) => {
      const exp = new Date(r.certExpires);
      const days = Math.round((exp - new Date()) / 86400000);
      const tone = days < 60 ? 'bad' : days < 120 ? 'warn' : 'good';
      return <Pill tone={tone}>{r.certExpires} · {days}d</Pill>;
    } },
    { key: 'status', label: 'Status', render: (r) => r.status === 'on-duty'
      ? <Pill tone="good"><StatusDot tone="good" size={6} pulse /> On duty</Pill>
      : <Pill tone="neutral">Off duty</Pill> },
  ];
  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        <FilterChip active={filter==='all'}      onClick={() => setFilter('all')}      count={employees.length}>All</FilterChip>
        <FilterChip active={filter==='on-duty'}  onClick={() => setFilter('on-duty')}  count={employees.filter(e=>e.status==='on-duty').length}>On duty</FilterChip>
        <FilterChip active={filter==='off-duty'} onClick={() => setFilter('off-duty')} count={employees.filter(e=>e.status==='off-duty').length}>Off duty</FilterChip>
        <FilterChip active={filter==='expired'}  onClick={() => setFilter('expired')}>Cert expiring</FilterChip>
        <FilterChip active={filter==='non-rrb'}  onClick={() => setFilter('non-rrb')}>Not in RRB</FilterChip>
        <div style={{ flex: 1 }} />
        <Button variant="secondary" size="sm" icon={<IconDownload size={12} />}>Roster CSV</Button>
      </div>
      <DataTable columns={cols} rows={filtered} onRowClick={(r) => setEmployeeDrawer(r)} />
    </>
  );
}

// ── Jobs tab ─────────────────────────────────────────────────
function JobsTab() {
  const { jobs, clients, employees } = useAdmin();
  const cols = [
    { key: 'projectNumber', label: 'Project #', mono: true, width: '14%' },
    { key: 'name', label: 'Job', render: (r) => (
      <div>
        <div style={{ fontWeight: 600 }}>{r.name}</div>
        <div style={{ fontSize: 11, color: 'var(--muted)' }}>{r.subdivision} · MP {r.mp}</div>
      </div>
    ) },
    { key: 'railroad', label: 'Railroad', render: (r) => <Pill tone="dark">{r.railroad}</Pill> },
    { key: 'state', label: 'State', mono: true },
    { key: 'staffing', label: 'Staffed', render: (r) => (
      <div style={{ display: 'flex', gap: -4, alignItems: 'center' }}>
        {r.rwicIds.length === 0
          ? <Pill tone="warn">Unstaffed</Pill>
          : r.rwicIds.map((id, i) => {
            const e = employees.find(x => x.id === id);
            return e ? (
              <div key={id} title={e.name} style={{
                width: 24, height: 24, borderRadius: 12,
                background: 'var(--accent-soft)', color: 'var(--accent-deep)',
                display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700,
                border: '2px solid var(--panel)',
                marginLeft: i === 0 ? 0 : -6,
              }}>{e.avatar}</div>
            ) : null;
          })}
      </div>
    ) },
    { key: 'billRate', label: 'Bill rate', mono: true, align: 'right', render: (r) => A_fmtCurrency(r.billRate) + '/hr' },
    { key: 'range', label: 'Schedule', render: (r) => (
      <span className="mono" style={{ fontSize: 12 }}>{A_fmtDateShort(r.start)} – {A_fmtDateShort(r.end)}</span>
    ) },
    { key: 'status', label: 'Status', render: (r) => {
      const tone = { active: 'good', wrapping: 'warn', starting: 'info' }[r.status] || 'neutral';
      return <Pill tone={tone}>{r.status}</Pill>;
    } },
  ];
  return <DataTable columns={cols} rows={jobs} />;
}

// ── Clients tab ──────────────────────────────────────────────
function ClientsTab() {
  const { clients, jobs, timecards } = useAdmin();
  const enriched = clients.map(c => {
    const myJobs = jobs.filter(j => j.clientId === c.id);
    const hours = timecards.filter(t => myJobs.find(j => j.id === t.jobId)).reduce((s, t) => s + t.total, 0);
    return { ...c, jobsCount: myJobs.length, hours, billed: hours * c.billRate };
  });
  const cols = [
    { key: 'name', label: 'Client', render: (r) => (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          background: 'var(--text)', color: '#fff',
          display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700,
          fontFamily: 'var(--font-mono)',
        }}>{r.railroad}</div>
        <div>
          <div style={{ fontWeight: 600 }}>{r.name}</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>{r.terms} payment</div>
        </div>
      </div>
    ) },
    { key: 'billRate', label: 'Bill rate', mono: true, align: 'right', render: (r) => A_fmtCurrency(r.billRate) + '/hr' },
    { key: 'jobsCount', label: 'Active jobs', mono: true, align: 'right' },
    { key: 'hours', label: 'Period hours', mono: true, align: 'right', render: (r) => A_fmtNum(r.hours, 1) },
    { key: 'billed', label: 'Period billed', mono: true, align: 'right', render: (r) => A_fmtCurrency(r.billed) },
  ];
  return <DataTable columns={cols} rows={enriched} />;
}

Object.assign(window, { RoleOps });
