'use client';

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

import { decodeBusinessJwt, getActiveBusinessSession, getBusinessAccessToken } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import { AdminHero } from '@/components/admin/AdminHero';
import {
  getCompanySummary,
  listCompanyRequests,
  type AdminQueueMeta,
  type AdminQueueQuery,
  type AdminRequestRow,
  type AdminSummary,
  type RequestStatus,
} from '@/services/admin-approvals/admin-approvals.client';

import ReviewOverlay, { type ReviewDecision } from './ReviewOverlay';
import DateCalendar, { type DateRange } from './DateCalendar';
import { EMPLOYEE_HOME } from '@/constants/business-routes';
import { badgeKey, displayName, formatMoney, formatShortDate, formatWholeMoney, initials, statusBadgeLabel, timeAgo } from './format';

/**
 * Design tab keys (fra-tab data-status) mapped to the API's status values.
 *
 * Approved is APPROVED *and* BOOKED: a booked request has been approved (or
 * booked directly by an admin), it has simply moved on a step, so it must not
 * drop out of this tab. Upcoming is the same set narrowed to trips that have not
 * finished yet — approved + travel date not gone — which the server filters
 * (`upcoming`) so paging and counts stay right.
 */
const APPROVED_STATUSES = 'APPROVED,BOOKED';
const TABS: Array<{ key: string; label: string; status: string; upcoming?: boolean }> = [
  { key: 'all', label: 'All', status: 'all' },
  { key: 'pending', label: 'Pending', status: 'PENDING' },
  { key: 'approved', label: 'Approved', status: APPROVED_STATUSES },
  { key: 'upcoming', label: 'Upcoming', status: APPROVED_STATUSES, upcoming: true },
  { key: 'changes', label: 'Info requested', status: 'INFO_REQUESTED' },
  { key: 'rejected', label: 'Rejected', status: 'REJECTED' },
  // LEIS-1044: travel date passed before anyone decided it.
  { key: 'expired', label: 'Expired', status: 'EXPIRED' },
];

/**
 * One pulsing placeholder bar, sized to roughly the real column's content
 * width. The table has no explicit/fixed column widths (doesn't need them
 * once real rows are in), so an empty `<tbody>` — or, as it was here, a
 * single `colSpan`-wide skeleton bar — leaves the browser nothing per-column
 * to size by, then it 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 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 }} />;
}

const DEFAULT_QUERY: AdminQueueQuery = {
  status: 'all',
  upcoming: false,
  type: 'all',
  outOfPolicy: false,
  search: '',
  sortBy: 'submitted',
  sortOrder: 'desc',
  page: 1,
  limit: 20,
};

export default function ApprovalQueue() {
  const router = useRouter();
  const [authorised, setAuthorised] = useState(false);
  const [token, setToken] = useState<string | null>(null);
  const [query, setQuery] = useState<AdminQueueQuery>(DEFAULT_QUERY);
  const [searchDraft, setSearchDraft] = useState('');
  const [dateRange, setDateRange] = useState<DateRange>(null);
  const [hasLoaded, setHasLoaded] = useState(false);
  const [dept, setDept] = useState('');
  const [summary, setSummary] = useState<AdminSummary | null>(null);
  const [rows, setRows] = useState<AdminRequestRow[]>([]);
  const [meta, setMeta] = useState<AdminQueueMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [openRow, setOpenRow] = useState<AdminRequestRow | null>(null);

  /**
   * `?request=FR-1234` opens that request's review overlay (LEIS-1019).
   *
   * Two things link here: the admin home's Review buttons, and the
   * notification email — whose `buildReviewUrl` pointed at `/approvals`, a
   * route that has never existed, until this landed.
   *
   * DERIVED from the URL rather than pushed into state by an effect. A
   * `setOpenRow` in a `useEffect` keyed on the rows is the exact
   * `react-hooks/set-state-in-effect` shape corp's lint forbids, and it would
   * also re-open the overlay on every poll tick. Closing clears the parameter,
   * which is what lets the derivation settle.
   */
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const requestedReference = searchParams.get('request');
  const deepLinkedRow = requestedReference
    ? (rows.find((row) => row.reference === requestedReference) ?? null)
    : null;
  const activeRow = openRow ?? deepLinkedRow;

  const closeOverlay = () => {
    setOpenRow(null);
    if (!requestedReference) return;
    const next = new URLSearchParams(searchParams.toString());
    next.delete('request');
    const qs = next.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
  };
  const [selected, setSelected] = useState<Record<string, boolean>>({});
  // Bumped to refetch the queue after a decision, and every poll tick, so a
  // request an employee resubmits shows up here without a reload.
  const [refreshKey, setRefreshKey] = useState(0);

  // Only the company admin sees this panel. Employees go to the Search page;
  // anyone without a session goes to sign-in.
  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]);

  // Debounce search so typing doesn't fire a request per keystroke.
  useEffect(() => {
    const id = setTimeout(() => setQuery((q) => ({ ...q, search: searchDraft.trim(), page: 1 })), 300);
    return () => clearTimeout(id);
  }, [searchDraft]);

  // Fetches the queue and the dashboard for the current query. `cancelled`
  // drops a stale response when the query changes mid-flight.
  useEffect(() => {
    if (!authorised || !token) return;
    let cancelled = false;
    async function run(activeToken: string) {
      setLoading(true);
      setError(null);
      const [list, sum] = await Promise.all([listCompanyRequests(activeToken, query), getCompanySummary(activeToken)]);
      if (cancelled) return;
      if (!list.success) {
        setError(list.message ?? 'Could not load the approval queue. Please try again.');
      } else {
        setRows(list.data ?? []);
        setMeta(list.meta ?? null);
      }
      if (sum.success && sum.data) setSummary(sum.data);
      setLoading(false);
      setHasLoaded(true);
    }
    run(token);
    return () => {
      cancelled = true;
    };
  }, [authorised, token, query, refreshKey]);

  // Approvers act on the queue while employees reply, so poll for changes. The
  // table keeps its rows across a poll (see the hasLoaded check in the tbody).
  useEffect(() => {
    if (!authorised) return;
    const id = setInterval(() => setRefreshKey((k) => k + 1), 15_000);
    return () => clearInterval(id);
  }, [authorised]);

  const departments = useMemo(() => {
    const set = new Set<string>();
    rows.forEach((r) => r.employee.department && set.add(r.employee.department));
    return Array.from(set).sort();
  }, [rows]);

  // Department is applied on the rows already fetched (no department filter
  // on the API yet). Everything else goes to the server.
  const visibleRows = useMemo(() => (dept ? rows.filter((r) => r.employee.department === dept) : rows), [rows, dept]);

  const applyDateRange = (range: DateRange) => {
    setDateRange(range);
    setQuery((q) => ({ ...q, travelFrom: range?.from, travelTo: range?.to, page: 1 }));
  };

  // Departures per day across the loaded rows, for the calendar's dots.
  const dateCounts = useMemo(() => {
    const out: Record<string, number> = {};
    rows.forEach((r) => {
      // A request can have no travel date — the column is nullable and the API
      // says so. Skipped rather than bucketed under a placeholder: a dot on the
      // calendar means "departures on this day", and an undated request has no
      // day to claim.
      if (!r.travelStartDate) return;
      const key = r.travelStartDate.slice(0, 10);
      out[key] = (out[key] ?? 0) + 1;
    });
    return out;
  }, [rows]);

  const toggleSort = (sortBy: AdminQueueQuery['sortBy']) => {
    setQuery((q) => ({
      ...q,
      sortBy,
      sortOrder: q.sortBy === sortBy && q.sortOrder === 'desc' ? 'asc' : 'desc',
      page: 1,
    }));
  };

  // UI-only: decisions update the queue in place. They are not sent to the
  // backend until the decision endpoints exist.
  const applyDecision = (ids: string[], decision: ReviewDecision) => {
    const nextStatus: RequestStatus = decision === 'approve' ? 'APPROVED' : decision === 'reject' ? 'REJECTED' : 'INFO_REQUESTED';
    setRows((rs) => rs.map((r) => (ids.includes(r.id) ? { ...r, status: nextStatus, decidedAt: new Date().toISOString() } : r)));
    setSelected({});
  };

  const quickApprove = (row: AdminRequestRow) => {
    applyDecision([row.id], 'approve');
    toast.success(`${row.reference} approved (preview).`);
  };

  const bulkApprove = () => {
    const ids = Object.keys(selected).filter((id) => selected[id]);
    applyDecision(ids, 'approve');
    toast.success(`${ids.length} request${ids.length === 1 ? '' : 's'} approved (preview).`);
  };

  // Excludes CANCELLATION/CHANGE rows — see `quickApprovable`'s own note in
  // the row loop for why those can never go through the local-only quick
  // approve, only Review.
  const pendingVisible = visibleRows.filter((r) => r.status === 'PENDING' && r.kind === 'NEW');
  const selectedCount = Object.values(selected).filter(Boolean).length;
  const allSelected = pendingVisible.length > 0 && pendingVisible.every((r) => selected[r.id]);
  const someSelected = !allSelected && pendingVisible.some((r) => selected[r.id]);

  const toggleAll = () => {
    if (allSelected) setSelected({});
    else setSelected(Object.fromEntries(pendingVisible.map((r) => [r.id, true])));
  };

  const filtersActive = Boolean(dept || query.search || dateRange || query.outOfPolicy || query.status !== 'all' || query.type !== 'all');
  const clearFilters = () => {
    setSearchDraft('');
    setDept('');
    setDateRange(null);
    setQuery(DEFAULT_QUERY);
  };

  // Design's stat cards double as filters.
  const statPending = () => setQuery((q) => ({ ...q, status: 'PENDING', upcoming: false, outOfPolicy: false, page: 1 }));
  const statApproved = () => setQuery((q) => ({ ...q, status: APPROVED_STATUSES, upcoming: false, outOfPolicy: false, page: 1 }));
  const statFlagged = () => setQuery((q) => ({ ...q, status: 'PENDING', upcoming: false, outOfPolicy: !(q.outOfPolicy && q.status === 'PENDING'), page: 1 }));

  const counts = meta?.counts;
  const countFor = (tab: (typeof TABS)[number]) => {
    if (tab.upcoming) return counts?.upcoming ?? 0;
    if (tab.status === 'all') return counts?.all ?? 0;
    // A tab can span several statuses ("APPROVED,BOOKED"): add them up.
    return tab.status.split(',').reduce((sum, s) => sum + (counts?.byStatus[s as RequestStatus] ?? 0), 0);
  };
  const activeTab =
    query.outOfPolicy && query.status === 'PENDING'
      ? null
      : TABS.find((t) => t.status === query.status && Boolean(t.upcoming) === Boolean(query.upcoming))?.key;
  const lastMonthLabel = summary ? new Date(`${summary.period.lastMonth}-15T12:00:00Z`).toLocaleDateString('en-US', { month: 'short', timeZone: 'UTC' }) : '';

  if (!authorised) return null;

  return (
    <section className="fra-ui fra-section py-[24px] md:py-[48px]">
      <div className="fra-page mx-auto w-full max-w-[1320px] px-3">
        {/* Page hero */}
        <AdminHero
          title="Flight/Hotel Approval Queue"
          subtitle="Employees request specific flights and hotel stays. Managers and corporate travel admins review and approve them here."
          active="approvals"
        />

        {/* Stats */}
        <div className="fra-stats mb-6">
          <button type="button" className={`fra-stat fra-stat-pending${query.status === 'PENDING' && !query.outOfPolicy ? ' active' : ''}`} onClick={statPending}>
            <span className="fra-stat-icon">
              <i className="bi bi-hourglass-split" />
            </span>
            <span className="fra-stat-text">
              <small>Awaiting approval</small>
              <strong>{summary?.awaitingApproval.count ?? 0}</strong>
              <em>{summary ? (summary.awaitingApproval.urgent ? `${summary.awaitingApproval.urgent} marked urgent` : 'Nothing urgent') : ' '}</em>
            </span>
          </button>
          <button type="button" className={`fra-stat fra-stat-approved${query.status === APPROVED_STATUSES && !query.upcoming ? ' active' : ''}`} onClick={statApproved}>
            <span className="fra-stat-icon">
              <i className="bi bi-check2-circle" />
            </span>
            <span className="fra-stat-text">
              <small>Approved</small>
              <strong>{summary?.approved.count ?? 0}</strong>
              <em>{summary ? `${summary.approved.thisMonth} this month` : ' '}</em>
            </span>
          </button>
          <button type="button" className={`fra-stat fra-stat-flag${query.outOfPolicy ? ' active' : ''}`} onClick={statFlagged}>
            <span className="fra-stat-icon">
              <i className="bi bi-shield-exclamation" />
            </span>
            <span className="fra-stat-text">
              <small>Out of policy</small>
              <strong>{summary?.outOfPolicy.count ?? 0}</strong>
              <em>{summary ? (summary.outOfPolicy.count ? 'Review before approving' : 'All pending in policy') : ' '}</em>
            </span>
          </button>
          <div className="fra-stat fra-stat-spend">
            <div className="fra-spend-main">
              <span className="fra-stat-icon">
                <i className="bi bi-wallet2" />
              </span>
              <span className="fra-stat-text">
                <small>
                  Total spend <span className="fra-muted">(approved)</span>
                </small>
                <strong>{formatWholeMoney(summary?.spend.total)}</strong>
                <em>{formatWholeMoney(summary?.spend.thisMonth)} so far this month</em>
              </span>
            </div>
            <div className="fra-spend-split">
              <div>
                <small>Last month{lastMonthLabel ? ` (${lastMonthLabel})` : ''}</small>
                <strong>{formatWholeMoney(summary?.spend.lastMonth)}</strong>
              </div>
              <div>
                <small>Pending</small>
                <strong>{formatWholeMoney(summary?.spend.pending)}</strong>
              </div>
            </div>
          </div>
        </div>

        {/* Queue card */}
        <div className="fra-card">
          <div className="fra-toolbar">
            <div className="fra-tabs-row">
              <div className="fra-tabs" role="tablist">
                {TABS.map((tab) => (
                  <button
                    key={tab.key}
                    type="button"
                    role="tab"
                    aria-selected={activeTab === tab.key}
                    data-status={tab.key}
                    className={`fra-tab${activeTab === tab.key ? ' active' : ''}`}
                    onClick={() => setQuery((q) => ({ ...q, status: tab.status, upcoming: Boolean(tab.upcoming), outOfPolicy: false, page: 1 }))}
                  >
                    {tab.label} <span data-count={tab.key}>{countFor(tab)}</span>
                  </button>
                ))}
              </div>
              <button
                type="button"
                className="fra-chip"
                aria-pressed={query.outOfPolicy}
                onClick={() => setQuery((q) => ({ ...q, outOfPolicy: !q.outOfPolicy, page: 1 }))}
              >
                <i className="bi bi-shield-exclamation" />
                <span>Out of policy</span>
                <span className="fra-chip-count">{counts?.outOfPolicy ?? 0}</span>
              </button>
            </div>

            <div className="fra-filters">
              <div className="fra-search">
                <i className="bi bi-search" />
                <input
                  type="search"
                  className="fra-input"
                  placeholder="Search employee, route, flight or ID"
                  autoComplete="off"
                  aria-label="Search requests"
                  value={searchDraft}
                  onChange={(e) => setSearchDraft(e.target.value)}
                />
              </div>

              <Dropdown
                icon="bi-building"
                value={dept}
                placeholder="All departments"
                options={[{ value: '', label: 'All departments' }, ...departments.map((d) => ({ value: d, label: d }))]}
                onChange={setDept}
              />
              <DateCalendar value={dateRange} counts={dateCounts} onChange={applyDateRange} />

              {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>

          {/* Bulk action bar */}
          {selectedCount > 0 && (
            <div className="fra-bulk">
              <span>
                <i className="bi bi-check2-square" /> <strong>{selectedCount}</strong> selected
              </span>
              <div className="d-flex gap-2">
                <button type="button" className="fra-btn fra-btn-sm fra-btn-ghost" onClick={() => setSelected({})}>
                  Clear
                </button>
                <button type="button" className="fra-btn fra-btn-sm fra-btn-approve" onClick={bulkApprove}>
                  <i className="bi bi-check-lg" />
                  <span>Approve selected</span>
                </button>
              </div>
            </div>
          )}

          {error && <div className="mx-4 my-3 rounded-[10px] bg-[var(--fra-rejected-bg)] px-4 py-3 text-sm text-[var(--fra-rejected)]">{error}</div>}

          <div className="fra-table-wrap">
            <table className="fra-table">
              <thead>
                <tr>
                  <th className="fra-col-check">
                    <IndeterminateCheckbox
                      checked={allSelected}
                      indeterminate={someSelected}
                      disabled={pendingVisible.length === 0}
                      onChange={toggleAll}
                      label="Select all pending"
                    />
                  </th>
                  <th>Request</th>
                  <th>Employee</th>
                  <th>Bookings</th>
                  <th>
                    <SortButton label="Travel dates" sortKey="travelDate" query={query} onSort={toggleSort} />
                  </th>
                  <th className="text-end">
                    <SortButton label="Fare" sortKey="fare" query={query} onSort={toggleSort} />
                  </th>
                  <th>Policy</th>
                  <th>Status</th>
                  <th>
                    <SortButton label="Submitted" sortKey="submitted" query={query} onSort={toggleSort} />
                  </th>
                  <th className="text-end">Actions</th>
                </tr>
              </thead>
              <tbody>
                {loading && !hasLoaded &&
                  Array.from({ length: 4 }).map((_, i) => (
                    <tr key={`skeleton-${i}`}>
                      <td className="fra-col-check" />
                      <td>
                        <SkeletonBar width="60%" />
                      </td>
                      <td>
                        <SkeletonBar width="80%" />
                      </td>
                      <td>
                        <SkeletonBar width="85%" />
                      </td>
                      <td>
                        <SkeletonBar width="55%" />
                      </td>
                      <td className="text-end">
                        <SkeletonBar width="45%" />
                      </td>
                      <td>
                        <SkeletonBar width="50%" />
                      </td>
                      <td>
                        <SkeletonBar width="55%" />
                      </td>
                      <td>
                        <SkeletonBar width="45%" />
                      </td>
                      <td className="text-end">
                        <SkeletonBar width="60%" />
                      </td>
                    </tr>
                  ))}

                {hasLoaded &&
                  visibleRows.map((row) => {
                    const pending = row.status === 'PENDING';
                    const flags = row.policy.flagCount;
                    const isSelected = Boolean(selected[row.id]);
                    const roundTrip = row.flight?.tripType === 'ROUND_TRIP';
                    const dates = `${formatShortDate(row.travelStartDate)}${roundTrip && row.travelEndDate ? ` – ${formatShortDate(row.travelEndDate)}` : ''}`;
                    // Quick-approve (the row button and bulk-select) is a
                    // local-only preview — see quickApprove/applyDecision's
                    // own comment — which is harmless for an ordinary NEW
                    // request (the real approve endpoint also writes nothing
                    // until Checkout succeeds, so nothing is out of sync).
                    // It is NOT harmless for a CANCELLATION/CHANGE row: its
                    // real approve cancels and refunds money immediately, no
                    // Checkout involved, so flipping it to "Approved" locally
                    // without ever calling that endpoint would show the admin
                    // a done deal that never happened. Those rows go through
                    // Review only.
                    const quickApprovable = pending && row.kind === 'NEW';
                    return (
                      <tr key={row.id} className={`${isSelected ? 'is-selected ' : ''}${pending && flags ? 'is-flagged' : ''}`.trim()}>
                        <td className="fra-col-check">
                          {quickApprovable && (
                            <input
                              className="fra-check fra-row-check"
                              type="checkbox"
                              aria-label={`Select ${row.reference}`}
                              checked={isSelected}
                              onChange={() => setSelected((s) => ({ ...s, [row.id]: !s[row.id] }))}
                            />
                          )}
                        </td>
                        <td>
                          <span className="fra-id">{row.reference}</span>
                          {row.priority === 'URGENT' && pending && (
                            <span className="fra-urgent">
                              <i className="bi bi-lightning-charge-fill" />
                              Urgent
                            </span>
                          )}
                        </td>
                        <td className="fra-cell-employee">
                          <div className="fra-person">
                            <span className="fra-avatar">{initials(row.employee.name)}</span>
                            <div>
                              <strong title={displayName(row.employee.name) ?? row.employee.workEmail}>
                                {displayName(row.employee.name) ?? row.employee.workEmail}
                              </strong>
                              <span className="fra-sub" title={row.employee.department ?? undefined}>
                                {row.employee.department ?? '—'}
                              </span>
                              {/* LEIS-1042 — the traveller is who this row is otherwise
                                  all about; the one thing missing without this line is
                                  who actually raised the request on their behalf. */}
                              {row.isColleagueRequest && (
                                <span className="fra-sub" title={row.requester.workEmail}>
                                  Booked by {displayName(row.requester.name) ?? row.requester.workEmail}
                                </span>
                              )}
                            </div>
                          </div>
                        </td>
                        <td>
                          <div>
                            {row.flight ? (
                              <>
                                <span className="fra-route">
                                  {row.flight.origin} <i className={`bi ${roundTrip ? 'bi-arrow-left-right' : 'bi-arrow-right'}`} /> {row.flight.destination}
                                </span>
                                <span className="fra-sub">
                                  {row.flight.airline ?? '—'} · {row.flight.cabin.replace('_', ' ').toLowerCase()}
                                </span>
                              </>
                            ) : (
                              <span className="fra-route fra-route-hotel" title={row.hotel?.property}>
                                {row.hotel?.property ?? '—'}
                              </span>
                            )}
                          </div>
                        </td>
                        <td>
                          <span className="fra-dates">{dates}</span>
                        </td>
                        <td className="text-end">
                          <span className="fra-fare">{formatMoney(row.cost.estTotal ?? row.cost.fare, row.cost.currency)}</span>
                        </td>
                        <td>
                          {flags ? (
                            <span className="fra-policy-flag">
                              <i className="bi bi-exclamation-triangle-fill" />
                              {flags} flag{flags > 1 ? 's' : ''}
                            </span>
                          ) : (
                            <span className="fra-policy-ok">
                              <i className="bi bi-check-circle-fill" />
                              In policy
                            </span>
                          )}
                        </td>
                        <td>
                          {/*
                           * A change or cancellation is a row like any other
                           * here — same status, same shape — so without a
                           * second signal the admin cannot tell "book this
                           * trip" from "cancel the trip you already booked".
                           * The rows only started existing with LEIS-1013;
                           * until then `kind` was always NEW and there was
                           * nothing to show. `parentReference` names the trip
                           * it is raised against.
                           *
                           * While it's PENDING, and once a CANCELLATION's own
                           * APPROVED, `statusBadgeLabel` folds the kind into
                           * the status text itself ("Cancellation requested",
                           * "Cancelled") instead of pairing a generic status
                           * word with a separate tag — a bare "Pending" or
                           * "Approved" next to a "Cancellation" tag read as if
                           * the TRIP itself were unbooked or just got the
                           * green light, when it's the cancellation REQUEST
                           * that's pending/decided. The second badge below
                           * only shows when the status word alone genuinely
                           * doesn't say which kind this is (Rejected, Info
                           * requested, or a CHANGE's own Approved).
                           */}
                          <div className="d-flex flex-column align-items-start gap-1">
                            {/* One line, like every other status badge: the labels are short
                                ("Cancel requested", "Change requested") so no wrapping is needed. */}
                            {/* LEIS-1055: while support has the booking, its badge replaces "Booked" (the status itself stays Booked). */}
                            {row.supportStatus !== 'WITH_SUPPORT' && (
                              <span className={`fra-badge fra-badge-${badgeKey(row.status, row.kind)}`}>
                                {statusBadgeLabel(row.status, row.kind)}
                              </span>
                            )}
                            {row.supportStatus === 'WITH_SUPPORT' && (
                              <span className="fra-badge fra-badge-changes" title="leisure.com support is working on this booking">
                                With support{row.supportReference ? ` \u00b7 ${row.supportReference}` : ''}
                              </span>
                            )}
                            {/*
                             * Only when the status badge's own text doesn't
                             * already say which kind this is — PENDING
                             * ("Cancellation requested"/"Change requested")
                             * and a CANCELLATION's own APPROVED ("Cancelled",
                             * same word and color as the trip it cancelled)
                             * both come from `statusBadgeLabel` already
                             * naming it, so a second badge here would just
                             * repeat that, not add anything — one badge only.
                             */}
                            {row.kind !== 'NEW' &&
                              row.status !== 'PENDING' &&
                              !(row.status === 'APPROVED' && row.kind === 'CANCELLATION') && (
                                <span
                                  className="fra-badge fra-badge-changes"
                                  title={row.parentReference ? `Against ${row.parentReference}` : undefined}
                                >
                                  {row.kind === 'CANCELLATION' ? 'Cancellation' : 'Change'}
                                </span>
                              )}
                          </div>
                        </td>
                        <td>
                          <span className="fra-submitted" title={row.submittedAt}>
                            {timeAgo(row.submittedAt)}
                          </span>
                        </td>
                        <td className="text-end fra-cell-actions">
                          <div className="fra-actions">
                            {quickApprovable && !flags ? (
                              <button type="button" className="fra-row-btn fra-row-approve" onClick={() => quickApprove(row)} aria-label={`Approve ${row.reference}`}>
                                <i className="bi bi-check-lg" />
                                <span>Approve</span>
                              </button>
                            ) : (
                              <span className="fra-row-spacer" aria-hidden="true" />
                            )}
                            <button type="button" className="fra-row-btn" onClick={() => setOpenRow(row)} aria-label={`Open ${row.reference}`}>
                              <span>{pending ? 'Review' : 'View'}</span>
                              <i className="bi bi-arrow-right-short" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
              </tbody>
            </table>

            {!loading && !error && visibleRows.length === 0 && (
              <div className="fra-empty">
                <span className="fra-empty-icon">
                  <i className="bi bi-airplane" />
                </span>
                <strong>{query.upcoming ? 'No upcoming trips' : 'No flight requests found'}</strong>
                <p>
                  {query.upcoming
                    ? 'Approved trips with a travel date that hasn’t passed show up here.'
                    : 'Try a different tab, date range or department.'}
                </p>
              </div>
            )}
          </div>

          {meta && meta.total > meta.limit && (
            <div className="d-flex align-items-center justify-content-between px-3 py-3" style={{ borderTop: '1px solid var(--fra-border)' }}>
              <span className="fra-muted">
                Page {meta.page} of {Math.ceil(meta.total / meta.limit)}
              </span>
              <div className="d-flex gap-2">
                <button type="button" className="fra-btn fra-btn-sm fra-btn-ghost" disabled={meta.page <= 1} onClick={() => setQuery((q) => ({ ...q, page: q.page - 1 }))}>
                  Previous
                </button>
                <button
                  type="button"
                  className="fra-btn fra-btn-sm fra-btn-ghost"
                  disabled={meta.page * meta.limit >= meta.total}
                  onClick={() => setQuery((q) => ({ ...q, page: q.page + 1 }))}
                >
                  Next
                </button>
              </div>
            </div>
          )}
        </div>
      </div>

      {activeRow && (
        <ReviewOverlay
          row={activeRow}
          onClose={closeOverlay}
          token={token ?? ''}
          onRepriced={() => setRefreshKey((k) => k + 1)}
          onDecision={(decision) => {
            // Reject and request-info are sent to the server by the overlay, so
            // the queue reloads to show the stored status. A NEW/CHANGE
            // approve has no endpoint yet (it triggers booking) and stays a
            // local preview — but a CANCELLATION approve (LEIS-1034) already
            // cancelled and refunded the real trip server-side, so that one
            // needs the real reload too, not a fabricated preview.
            if (decision === 'approve' && activeRow.kind !== 'CANCELLATION') applyDecision([activeRow.id], decision);
            else setRefreshKey((k) => k + 1);
            closeOverlay();
          }}
        />
      )}
    </section>
  );
}

/** The design's custom dropdown (fra-dd): a toggle and a menu of options. */
function Dropdown({
  icon,
  value,
  placeholder,
  options,
  onChange,
}: {
  icon: string;
  value: string;
  placeholder: string;
  options: Array<{ value: string; label: string }>;
  onChange: (value: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const current = options.find((o) => o.value === value);
  const hasValue = value !== '' && value !== 'all';

  useEffect(() => {
    const onDoc = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('click', onDoc);
    return () => document.removeEventListener('click', onDoc);
  }, []);

  return (
    <div ref={ref} className={`fra-dd${open ? ' open' : ''}${hasValue ? ' has-value' : ''}`}>
      <button type="button" className="fra-dd-toggle" aria-haspopup="listbox" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
        <i className={`bi ${icon}`} />
        <span className="fra-dd-label">{current?.label ?? placeholder}</span>
        <i className="bi bi-chevron-down fra-dd-caret" />
      </button>
      <ul className="fra-dd-menu" role="listbox">
        {options.map((o) => (
          <li key={o.value || 'none'} role="option" aria-selected={o.value === value}>
            <button
              type="button"
              className={`fra-dd-option${o.value === value ? ' is-selected' : ''}`}
              onClick={() => {
                onChange(o.value);
                setOpen(false);
              }}
            >
              <span>{o.label}</span>
              <i className="bi bi-check2 fra-dd-check" />
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

function SortButton({
  label,
  sortKey,
  query,
  onSort,
}: {
  label: string;
  sortKey: AdminQueueQuery['sortBy'];
  query: AdminQueueQuery;
  onSort: (key: AdminQueueQuery['sortBy']) => void;
}) {
  const active = query.sortBy === sortKey;
  const icon = active ? (query.sortOrder === 'desc' ? 'bi-arrow-down' : 'bi-arrow-up') : 'bi-arrow-down-up';
  return (
    <button type="button" className={`fra-sort${active ? ' active' : ''}`} data-sort={sortKey} onClick={() => onSort(sortKey)}>
      {label} <i className={`bi ${icon}`} />
    </button>
  );
}

function IndeterminateCheckbox({
  checked,
  indeterminate,
  disabled,
  onChange,
  label,
}: {
  checked: boolean;
  indeterminate: boolean;
  disabled: boolean;
  onChange: () => void;
  label: string;
}) {
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (ref.current) ref.current.indeterminate = indeterminate;
  }, [indeterminate]);
  return <input ref={ref} type="checkbox" className="fra-check" checked={checked} disabled={disabled} onChange={onChange} aria-label={label} />;
}
