'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';

import { decodeBusinessJwt, getActiveBusinessSession, getBusinessAccessToken } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import { AdminHero } from '@/components/admin/AdminHero';
import { initials, timeAgo, formatMediumDate } from '@/components/admin-approvals/format';
import {
  deactivateEmployee,
  listDepartments,
  listGroups,
  listEmployees,
  listInvited,
  reactivateEmployee,
  resendInvite,
  revokeInvite,
  type EmployeeRow,
  type InvitedRow,
  type GroupOption,
} from '@/services/workforce/workforce.client';

import InviteModal from './InviteModal';
import BulkInviteModal from './BulkInviteModal';
import EditEmployeeModal from './EditEmployeeModal';
import ConfirmModal from './ConfirmModal';
import { EMPLOYEE_HOME } from '@/constants/business-routes';

type Tab = 'employees' | 'invited';
type StatKey = 'active' | 'invited' | 'deactivated' | 'incomplete' | '';
/** 'incomplete' only applies on the Employees tab; 'pending'/'expired' only on Invited. */
type StatusFilter = '' | 'active' | 'deactivated' | 'incomplete' | 'pending' | 'expired';

type MenuTarget = { kind: 'employee'; row: EmployeeRow } | { kind: 'invited'; row: InvitedRow };

/**
 * One pulsing placeholder bar, sized to roughly the real column's content
 * width. The table has no `table-layout: fixed`/explicit column widths (it
 * doesn't need them once real rows are in — see the design's own
 * flight-approval.css), so with an empty `<tbody>` the browser can only size
 * columns from the header text, then jumps to the real widths the instant
 * data arrives — a large, measured layout shift (confirmed via the
 * PerformanceObserver layout-shift API), not just a vague feeling. Real
 * per-column skeleton cells, not a single colSpan bar, give the column-width
 * algorithm realistic content from the very first paint so that jump never
 * happens.
 */
function SkeletonBar({ width }: { width: string }) {
  return <div className="h-4 animate-pulse rounded bg-[var(--fra-hover)]" style={{ width }} />;
}

/** PRD §8.4, D3: invite employees (single + CSV), see who hasn't set up their
 *  account, and deactivate/reactivate. Admin-only — employees are redirected
 *  to Search, same gate as the approval queue. Markup and behaviour ported
 *  from the design (workforce.php / workforce.js): stat cards double as
 *  filters, one table at a time behind Employees/Invited tabs, a kebab menu
 *  per row. Unlike the design's own localStorage demo, every action here is a
 *  real call to the backend. */
export default function WorkforcePage() {
  const router = useRouter();
  const [authorised, setAuthorised] = useState(false);
  const [token, setToken] = useState<string | null>(null);

  const [departments, setDepartments] = useState<string[]>([]);
  const [groups, setGroups] = useState<GroupOption[]>([]);
  const [invited, setInvited] = useState<InvitedRow[]>([]);
  const [employees, setEmployees] = useState<EmployeeRow[]>([]);
  const [loaded, setLoaded] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  const [tab, setTab] = useState<Tab>('employees');
  const [stat, setStat] = useState<StatKey>('');
  const [status, setStatus] = useState<StatusFilter>('');
  const [department, setDepartment] = useState('');
  const [groupFilter, setGroupFilter] = useState('');
  const [searchDraft, setSearchDraft] = useState('');
  const [search, setSearch] = useState('');

  const [showInvite, setShowInvite] = useState(false);
  const [showBulk, setShowBulk] = useState(false);
  const [editTarget, setEditTarget] = useState<EmployeeRow | null>(null);
  const [deactivateTarget, setDeactivateTarget] = useState<EmployeeRow | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);

  const [menu, setMenu] = useState<{ target: MenuTarget; top: number; left: number } | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  // Only the company admin sees this page; same gate as the approval queue.
  useEffect(() => {
    async function checkAccess() {
      const session = getActiveBusinessSession();
      if (!session) {
        router.replace('/employee-login');
        return;
      }
      const current = getBusinessAccessToken();
      const payload = decodeBusinessJwt(current ?? '');
      if (payload?.role !== 'ADMIN') {
        router.replace(EMPLOYEE_HOME);
        return;
      }
      setToken(current);
      setAuthorised(true);
    }
    checkAccess();
  }, [router]);

  useEffect(() => {
    const id = setTimeout(() => setSearch(searchDraft.trim().toLowerCase()), 300);
    return () => clearTimeout(id);
  }, [searchDraft]);

  useEffect(() => {
    if (!authorised || !token) return;
    async function run() {
      const [deptRes, groupRes, invitedRes, employeesRes] = await Promise.all([
        listDepartments(token!),
        listGroups(token!),
        listInvited(token!),
        listEmployees(token!, { limit: 200 }),
      ]);
      if (deptRes.success) setDepartments(deptRes.data ?? []);
      if (groupRes.success) setGroups(groupRes.data ?? []);
      if (invitedRes.success) setInvited(invitedRes.data ?? []);
      if (employeesRes.success) setEmployees(employeesRes.data ?? []);
      setLoaded(true);
    }
    run();
  }, [authorised, token, refreshKey]);

  // Close the kebab menu on an outside click, Escape, or the page moving under it.
  useEffect(() => {
    if (!menu) return;
    const onDocClick = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenu(null);
    };
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setMenu(null);
    document.addEventListener('click', onDocClick);
    document.addEventListener('keydown', onKey);
    window.addEventListener('scroll', () => setMenu(null), true);
    window.addEventListener('resize', () => setMenu(null));
    return () => {
      document.removeEventListener('click', onDocClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [menu]);

  const refreshAll = () => setRefreshKey((k) => k + 1);

  // Client-side, like every other filter on this page: the list is fetched
  // once (limit 200) and narrowed here. The API also accepts a `groupId`,
  // which is what a paginated caller would use — this page is not one yet.
  const matchesCommon = (name: string, email: string, dept: string | null, group: { id: string } | null) => {
    if (department && dept !== department) return false;
    if (groupFilter && group?.id !== groupFilter) return false;
    if (search && !`${name} ${email}`.toLowerCase().includes(search)) return false;
    return true;
  };

  const activeEmployees = useMemo(() => employees.filter((e) => e.status === 'ACTIVE'), [employees]);
  const pendingInvites = useMemo(() => invited.filter((i) => !i.expired), [invited]);

  const employeeRows = useMemo(() => {
    return employees
      .filter((e) => matchesCommon(e.name, e.email, e.department, e.group))
      .filter((e) => {
        if (status === 'incomplete') return e.status === 'ACTIVE' && !e.profileComplete;
        if (status === 'active') return e.status === 'ACTIVE';
        if (status === 'deactivated') return e.status === 'DEACTIVATED';
        return true;
      })
      .sort((a, b) => (a.status === b.status ? a.name.localeCompare(b.name) : a.status === 'ACTIVE' ? -1 : 1));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [employees, department, groupFilter, search, status]);

  const invitedRows = useMemo(() => {
    return invited
      .filter((i) => matchesCommon(i.name, i.email, i.department, i.group))
      .filter((i) => {
        if (status === 'pending') return !i.expired;
        if (status === 'expired') return i.expired;
        return true;
      })
      .sort((a, b) => new Date(b.invitedAt).getTime() - new Date(a.invitedAt).getTime());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [invited, department, groupFilter, search, status]);

  const filtersActive = Boolean(search || department || groupFilter || status);
  const clearFilters = () => {
    setSearchDraft('');
    setSearch('');
    setDepartment('');
    setGroupFilter('');
    setStatus('');
    setStat('');
  };

  const clickStat = (s: Exclude<StatKey, ''>) => {
    if (stat === s) {
      setStat('');
      setStatus('');
      return;
    }
    setStat(s);
    setStatus(s === 'invited' ? 'pending' : s);
    setTab(s === 'invited' ? 'invited' : 'employees');
  };

  const clickTab = (t: Tab) => {
    setTab(t);
    setStatus('');
    setStat('');
  };

  const openMenu = (target: MenuTarget, button: HTMLElement) => {
    if (menu && menu.target.row.id === target.row.id) {
      setMenu(null);
      return;
    }
    const r = button.getBoundingClientRect();
    setMenu({ target, top: r.bottom + 6, left: Math.max(8, r.right - 190) });
  };

  const onInvited = (email: string) => {
    setShowInvite(false);
    toast.success(`Invite sent to ${email}.`);
    setTab('invited');
    setStatus('');
    setStat('');
    refreshAll();
  };

  const onBulkDone = (sent: number, skipped: number) => {
    setShowBulk(false);
    toast.success(`${sent} invite${sent === 1 ? '' : 's'} sent.${skipped ? ` ${skipped} row${skipped === 1 ? '' : 's'} skipped.` : ''}`);
    setTab('invited');
    setStatus('');
    setStat('');
    refreshAll();
  };

  const onEdited = () => {
    setEditTarget(null);
    toast.success('Employee updated.');
    refreshAll();
  };

  const doDeactivate = async () => {
    if (!deactivateTarget || !token) return;
    setBusyId(deactivateTarget.id);
    const res = await deactivateEmployee(token, deactivateTarget.id);
    setBusyId(null);
    setDeactivateTarget(null);
    if (!res.success) {
      toast.error(res.message ?? 'Could not deactivate this employee.');
      return;
    }
    toast.success(`${deactivateTarget.name} was deactivated. They can no longer request travel.`);
    refreshAll();
  };

  const doReactivate = async (row: EmployeeRow) => {
    if (!token) return;
    setBusyId(row.id);
    const res = await reactivateEmployee(token, row.id);
    setBusyId(null);
    if (!res.success) {
      toast.error(res.message ?? 'Could not reactivate this employee.');
      return;
    }
    toast.success(`${row.name} is active again.`);
    refreshAll();
  };

  const doResend = async (row: InvitedRow) => {
    if (!token) return;
    setBusyId(row.id);
    const res = await resendInvite(token, row.id);
    setBusyId(null);
    if (!res.success) {
      toast.error(res.message ?? 'Could not resend that invite.');
      return;
    }
    toast.success(`Invite resent to ${row.email}.`);
    refreshAll();
  };

  const doRevoke = async (row: InvitedRow) => {
    if (!token) return;
    setBusyId(row.id);
    const res = await revokeInvite(token, row.id);
    setBusyId(null);
    if (!res.success) {
      toast.error(res.message ?? 'Could not revoke that invite.');
      return;
    }
    toast.success(`Invite for ${row.name} was revoked.`);
    refreshAll();
  };

  const runMenuAction = (action: string) => {
    if (!menu) return;
    const { target } = menu;
    setMenu(null);
    if (target.kind === 'employee') {
      if (action === 'edit') setEditTarget(target.row);
      else if (action === 'deactivate') setDeactivateTarget(target.row);
      else if (action === 'reactivate') void doReactivate(target.row);
      else if (action === 'requests') router.push(`/admin/flight-approvals?q=${encodeURIComponent(target.row.name)}`);
    } else {
      if (action === 'resend') void doResend(target.row);
      else if (action === 'revoke') void doRevoke(target.row);
    }
  };

  if (!authorised) return null;

  const rows = tab === 'employees' ? employeeRows : invitedRows;

  return (
    <section className="fra-ui fra-section wf-page py-4 py-md-5">
      <div className="fra-page mx-auto w-full max-w-[1320px] px-3">
        <AdminHero
          title="Workforce"
          subtitle="Add the people who can request business travel."
          active="workforce"
          actions={
            <>
              <button type="button" className="fra-btn fra-btn-lg fra-hero-link" onClick={() => setShowBulk(true)}>
                <i className="bi bi-file-earmark-spreadsheet" />
                <span>Bulk invite (XLS)</span>
              </button>
              <button type="button" className="fra-btn fra-btn-lg fra-btn-primary" onClick={() => setShowInvite(true)}>
                <i className="bi bi-envelope-plus" />
                <span>Invite via email</span>
              </button>
            </>
          }
        />

        {/* Stats (click to filter) */}
        <div className="wf-stats mb-4">
          <button type="button" className={`fra-stat wf-stat is-active${stat === 'active' ? ' selected' : ''}`} onClick={() => clickStat('active')}>
            <span className="fra-stat-icon">
              <i className="bi bi-person-check" />
            </span>
            <span className="fra-stat-text">
              <small>Active</small>
              <strong>{activeEmployees.length}</strong>
            </span>
          </button>
          <button type="button" className={`fra-stat wf-stat is-invited${stat === 'invited' ? ' selected' : ''}`} onClick={() => clickStat('invited')}>
            <span className="fra-stat-icon">
              <i className="bi bi-envelope-paper" />
            </span>
            <span className="fra-stat-text">
              <small>Invited</small>
              <strong>{pendingInvites.length}</strong>
            </span>
          </button>
          <button
            type="button"
            className={`fra-stat wf-stat is-deactivated${stat === 'deactivated' ? ' selected' : ''}`}
            onClick={() => clickStat('deactivated')}
          >
            <span className="fra-stat-icon">
              <i className="bi bi-person-slash" />
            </span>
            <span className="fra-stat-text">
              <small>Deactivated</small>
              <strong>{employees.length - activeEmployees.length}</strong>
            </span>
          </button>
          <button
            type="button"
            className={`fra-stat wf-stat is-incomplete${stat === 'incomplete' ? ' selected' : ''}`}
            onClick={() => clickStat('incomplete')}
          >
            <span className="fra-stat-icon">
              <i className="bi bi-person-exclamation" />
            </span>
            <span className="fra-stat-text">
              <small>Profile incomplete</small>
              <strong>{activeEmployees.filter((e) => !e.profileComplete).length}</strong>
            </span>
          </button>
        </div>

        {/* People card */}
        <div className="fra-card">
          <div className="fra-toolbar">
            <div className="fra-tabs-row">
              <div className="fra-tabs" role="tablist">
                <button type="button" className={`fra-tab${tab === 'employees' ? ' active' : ''}`} onClick={() => clickTab('employees')}>
                  Employees <span>{employees.length}</span>
                </button>
                <button type="button" className={`fra-tab${tab === 'invited' ? ' active' : ''}`} onClick={() => clickTab('invited')}>
                  Invited <span>{invited.length}</span>
                </button>
              </div>
            </div>
            <div className="fra-filters">
              <div className="fra-search">
                <i className="bi bi-search" />
                <input
                  type="search"
                  className="fra-input"
                  placeholder="Search by name or email"
                  value={searchDraft}
                  onChange={(e) => setSearchDraft(e.target.value)}
                  aria-label="Search by name or email"
                />
              </div>
              <div className="fra-select-wrap wf-filter">
                <select className="fra-input fra-select" value={groupFilter} onChange={(e) => setGroupFilter(e.target.value)} aria-label="Policy group">
                  <option value="">Group: All groups</option>
                  {groups.map((g) => (
                    <option value={g.id} key={g.id}>
                      Group: {g.name}
                    </option>
                  ))}
                </select>
                <i className="bi bi-chevron-down" />
              </div>
              <div className="fra-select-wrap">
                <select className="fra-input fra-select" value={department} onChange={(e) => setDepartment(e.target.value)} aria-label="Department">
                  <option value="">Department: All departments</option>
                  {departments.map((d) => (
                    <option key={d} value={d}>
                      {d}
                    </option>
                  ))}
                </select>
                <i className="bi bi-chevron-down" />
              </div>
              <div className="fra-select-wrap wf-filter">
                <select
                  className="fra-input fra-select"
                  value={status}
                  onChange={(e) => {
                    setStatus(e.target.value as StatusFilter);
                    setStat('');
                  }}
                  aria-label="Status"
                >
                  {tab === 'employees' ? (
                    <>
                      <option value="">Status: All</option>
                      <option value="active">Active</option>
                      <option value="deactivated">Deactivated</option>
                      <option value="incomplete">Profile incomplete</option>
                    </>
                  ) : (
                    <>
                      <option value="">Status: All</option>
                      <option value="pending">Pending</option>
                      <option value="expired">Expired</option>
                    </>
                  )}
                </select>
                <i className="bi bi-chevron-down" />
              </div>
              {filtersActive && (
                <button type="button" className="fra-link-btn fra-clear" onClick={clearFilters}>
                  <i className="bi bi-x-circle" />
                  <span>Clear filters</span>
                </button>
              )}
            </div>
          </div>

          <div className="fra-table-wrap">
            <table className="fra-table wf-table">
              {tab === 'employees' ? (
                <>
                  <thead>
                    <tr>
                      <th>Name</th>
                      <th>Work email</th>
                      <th>Department</th>
                      <th>Policy group</th>
                      <th>Status</th>
                      <th>Profile</th>
                      <th>Last sign-in</th>
                      <th>Open requests</th>
                      <th className="text-end">
                        <span className="fra-visually-hidden">Actions</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {!loaded &&
                      Array.from({ length: 6 }).map((_, i) => (
                        <tr key={`sk-emp-${i}`}>
                          <td>
                            <SkeletonBar width="65%" />
                          </td>
                          <td>
                            <SkeletonBar width="80%" />
                          </td>
                          <td>
                            <SkeletonBar width="55%" />
                          </td>
                          <td>
                            <SkeletonBar width="45%" />
                          </td>
                          <td>
                            <SkeletonBar width="35%" />
                          </td>
                          <td>
                            <SkeletonBar width="45%" />
                          </td>
                          <td>
                            <SkeletonBar width="25%" />
                          </td>
                          <td className="text-end">
                            <SkeletonBar width="20px" />
                          </td>
                        </tr>
                      ))}
                    {loaded &&
                      (rows as EmployeeRow[]).map((row) => {
                        const off = row.status !== 'ACTIVE';
                        return (
                          <tr key={row.id} className={off ? 'is-off' : ''}>
                            <td>
                              <div className="wf-person">
                                <span className="fra-avatar">{initials(row.name)}</span>
                                <div className="min-w-0">
                                  <strong>{row.name}</strong>
                                  {row.gender && <small>{row.gender}</small>}
                                </div>
                              </div>
                            </td>
                            <td className="wf-email">{row.email}</td>
                            <td>{row.department ? <span className="wf-dept">{row.department}</span> : '—'}</td>
                            <td>{row.group ? <span className="wf-dept">{row.group.name}</span> : '—'}</td>
                            <td>
                              <span className={`wf-badge is-${off ? 'deactivated' : 'active'}`}>{off ? 'Deactivated' : 'Active'}</span>
                            </td>
                            <td>
                              {row.profileComplete ? (
                                <span className="wf-profile is-yes">
                                  <i className="bi bi-check-circle-fill" />
                                  Yes
                                </span>
                              ) : (
                                <span className="wf-profile is-no">
                                  <i className="bi bi-exclamation-circle-fill" />
                                  No
                                </span>
                              )}
                            </td>
                            <td className="wf-muted">{timeAgo(row.lastSignInAt)}</td>
                            <td className="wf-open">{row.openRequests ? row.openRequests : <span className="wf-muted">—</span>}</td>
                            <td className="text-end">
                              <button
                                type="button"
                                className="wf-kebab"
                                aria-haspopup="menu"
                                aria-expanded={menu?.target.row.id === row.id}
                                aria-label="More actions"
                                onClick={(e) => openMenu({ kind: 'employee', row }, e.currentTarget)}
                              >
                                <i className="bi bi-three-dots-vertical" />
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                  </tbody>
                </>
              ) : (
                <>
                  <thead>
                    <tr>
                      <th>Name</th>
                      <th>Work email</th>
                      <th>Department</th>
                      <th>Policy group</th>
                      <th>Status</th>
                      <th>Invited</th>
                      <th>Expires</th>
                      <th className="text-end">
                        <span className="fra-visually-hidden">Actions</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {!loaded &&
                      Array.from({ length: 6 }).map((_, i) => (
                        <tr key={`sk-inv-${i}`}>
                          <td>
                            <SkeletonBar width="65%" />
                          </td>
                          <td>
                            <SkeletonBar width="80%" />
                          </td>
                          <td>
                            <SkeletonBar width="55%" />
                          </td>
                          <td>
                            <SkeletonBar width="45%" />
                          </td>
                          <td>
                            <SkeletonBar width="45%" />
                          </td>
                          <td>
                            <SkeletonBar width="45%" />
                          </td>
                          <td className="text-end">
                            <SkeletonBar width="20px" />
                          </td>
                        </tr>
                      ))}
                    {loaded &&
                      (rows as InvitedRow[]).map((row) => (
                        <tr key={row.id}>
                          <td>
                            <div className="wf-person">
                              <span className="fra-avatar">{initials(row.name)}</span>
                              <div className="min-w-0">
                                <strong>{row.name}</strong>
                                {row.gender && <small>{row.gender}</small>}
                              </div>
                            </div>
                          </td>
                          <td className="wf-email">{row.email}</td>
                          <td>{row.department ? <span className="wf-dept">{row.department}</span> : '—'}</td>
                          <td>{row.group ? <span className="wf-dept">{row.group.name}</span> : '—'}</td>
                          <td>
                            <span className={`wf-badge is-${row.expired ? 'expired' : 'pending'}`}>{row.expired ? 'Expired' : 'Pending'}</span>
                          </td>
                          <td className="wf-muted">{timeAgo(row.invitedAt)}</td>
                          <td className="wf-muted">{formatMediumDate(row.expiresAt)}</td>
                          <td className="text-end">
                            <button
                              type="button"
                              className="wf-kebab"
                              aria-haspopup="menu"
                              aria-expanded={menu?.target.row.id === row.id}
                              aria-label="More actions"
                              onClick={(e) => openMenu({ kind: 'invited', row }, e.currentTarget)}
                            >
                              <i className="bi bi-three-dots-vertical" />
                            </button>
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </>
              )}
            </table>
            {loaded && rows.length === 0 && (
              <div className="fra-empty">
                <span className="fra-empty-icon">
                  <i className="bi bi-people" />
                </span>
                <strong>No people found</strong>
                <p>Try another search or filter, or invite someone new.</p>
              </div>
            )}
          </div>
          <div className="fra-card-foot">
            <span>
              {rows.length} {tab === 'employees' ? (rows.length === 1 ? 'employee' : 'employees') : rows.length === 1 ? 'invite' : 'invites'}
            </span>
          </div>
        </div>
      </div>

      {menu && (
        <div ref={menuRef} className="fra-ui wf-menu" role="menu" style={{ display: 'block', top: menu.top, left: menu.left }}>
          {menu.target.kind === 'employee' ? (
            menu.target.row.status === 'ACTIVE' ? (
              <>
                <button type="button" role="menuitem" onClick={() => runMenuAction('edit')}>
                  <i className="bi bi-pencil" />
                  <span>Edit details</span>
                </button>
                <button type="button" role="menuitem" onClick={() => runMenuAction('requests')}>
                  <i className="bi bi-list-check" />
                  <span>View flight requests</span>
                </button>
                <hr />
                <button type="button" role="menuitem" className="is-danger" onClick={() => runMenuAction('deactivate')}>
                  <i className="bi bi-person-slash" />
                  <span>Deactivate</span>
                </button>
              </>
            ) : (
              <>
                <button type="button" role="menuitem" onClick={() => runMenuAction('edit')}>
                  <i className="bi bi-pencil" />
                  <span>Edit details</span>
                </button>
                <button type="button" role="menuitem" onClick={() => runMenuAction('reactivate')}>
                  <i className="bi bi-person-check" />
                  <span>Reactivate</span>
                </button>
              </>
            )
          ) : (
            <>
              <button type="button" role="menuitem" onClick={() => runMenuAction('resend')}>
                <i className="bi bi-arrow-repeat" />
                <span>Resend invite</span>
              </button>
              <hr />
              <button type="button" role="menuitem" className="is-danger" onClick={() => runMenuAction('revoke')}>
                <i className="bi bi-x-circle" />
                <span>Revoke invite</span>
              </button>
            </>
          )}
        </div>
      )}

      {showInvite && token && <InviteModal token={token} departments={departments} groups={groups} onClose={() => setShowInvite(false)} onInvited={onInvited} />}
      {showBulk && token && <BulkInviteModal token={token} onClose={() => setShowBulk(false)} onDone={onBulkDone} />}
      {editTarget && token && (
        <EditEmployeeModal token={token} employee={editTarget} departments={departments} groups={groups} onClose={() => setEditTarget(null)} onSaved={onEdited} />
      )}
      {deactivateTarget && (
        <ConfirmModal
          title="Deactivate employee"
          body={`${deactivateTarget.name} will be signed out immediately and won't be able to request travel until you reactivate them. Their history is kept.`}
          confirmLabel="Deactivate"
          confirmTone="danger"
          busy={busyId === deactivateTarget.id}
          onConfirm={doDeactivate}
          onCancel={() => setDeactivateTarget(null)}
        />
      )}
    </section>
  );
}
