'use client';

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

import { toast } from '@/lib/toast';
import { buildActivityTimeline, type TimelineItem, type TimelineTone } from '@/services/employee-requests/activity-timeline';
import {
  approveRequest,
  getCancelOptions,
  getCancellationQuote,
  rejectRequest,
  repriceRequest,
  requestMoreInfo,
  type AdminRequestRow,
  type CancellationQuote,
} from '@/services/admin-approvals/admin-approvals.client';
import type { PriceCheckView } from '@/services/employee-requests/employee-requests.types';

import { badgeKey, displayName, formatDateTime, initials, formatMediumDate, formatMoney, statusBadgeLabel } from './format';
import { REJECT_REASONS, cityName, policyName } from './sample';

export type ReviewDecision = 'approve' | 'reject' | 'info';
type Tab = 'approved' | 'rejected' | 'changes';

const TIMELINE_CLASS: Record<TimelineTone, string> = {
  submitted: 'submitted',
  info: 'changes',
  reply: 'changes',
  approved: 'approved',
  rejected: 'rejected',
  price: 'changes',
  waiting: 'waiting',
};

const TIMELINE_ICON: Record<TimelineItem['icon'], string> = {
  Send: 'bi-send',
  MessageSquare: 'bi-chat-left-dots',
  CornerDownLeft: 'bi-reply',
  Check: 'bi-check-lg',
  X: 'bi-x-lg',
  Ticket: 'bi-ticket',
  Hourglass: 'bi-hourglass-split',
  Tag: 'bi-tag',
};

interface ReviewOverlayProps {
  row: AdminRequestRow;
  token: string;
  initialTab?: Tab;
  onClose: () => void;
  /** Called when the live fare changed, so the queue shows the new figure. */
  onRepriced?: () => void;
  /** Called once the decision is done. Reject and request-info are already stored; approve is not sent anywhere yet. */
  onDecision: (decision: ReviewDecision) => void;
  /** Forces the decision panel off regardless of `row.status`. For a caller
   *  like a read-only view, which can open a still-PENDING row purely to
   *  look at it — without this, a PENDING row would render live
   *  Approve/Reject/Request-info buttons that call the real API (reject a
   *  request, message the employee, navigate to checkout) even though the
   *  caller only wired `onDecision` as a no-op; the no-op never stops the
   *  action underneath it from firing. */
  readOnly?: boolean;
}

/** The design's review overlay (flight-approval.html "fraDetail" modal). */
/** Placeholder bar where a price will appear, so the panel does not show the
 *  submitted figure as if it were current while the live fare is fetched. */
function PriceSkeleton() {
  return <span aria-hidden className="inline-block h-3.5 w-20 animate-pulse rounded bg-[var(--fra-hover)] motion-reduce:animate-none" />;
}

export default function ReviewOverlay({ row, token, initialTab = 'approved', onClose, onRepriced, onDecision, readOnly = false }: ReviewOverlayProps) {
  const router = useRouter();
  // Advisory rows (passport validity today) are shown but excluded from
  // flagCount, so the panel's headline and its red rows can legitimately
  // differ — see the API's own note on PolicyCheck.
  const policyChecks = row.policy.checks ?? [];
  const timeline = buildActivityTimeline({
    viewer: 'admin',
    status: row.status,
    submittedAt: row.submittedAt,
    activity: row.activity ?? [],
    askedBy: [...(row.activity ?? [])].reverse().find((e) => e.action === 'INFO_REQUESTED')?.actorName ?? null,
  });
  const pending = row.status === 'PENDING' && !readOnly;
  const flags = row.policy.flagCount;
  // LEIS-1034: a CANCELLATION-kind row has no fare to re-price and nothing to
  // book — the decision cancels and refunds the PARENT trip immediately, so
  // the whole Approve tab branches on this rather than ever navigating to
  // Checkout.
  const isCancellation = row.kind === 'CANCELLATION';
  // LEIS-1053: a change or cancellation the booker asked for. With the new flow on, approving it sends it to
  // leisure.com support: no Checkout, no refund quote, no re-price. Whether the flow is on is the backend's
  // call (`flowEnabled`), asked once for linked rows; until it answers, or if it fails, the old behaviour holds.
  const isLinked = row.kind === 'CHANGE' || row.kind === 'CANCELLATION';
  const [supportFlow, setSupportFlow] = useState<'unknown' | 'on' | 'off'>(isLinked ? 'unknown' : 'off');
  const supportRoute = isLinked && supportFlow === 'on';
  useEffect(() => {
    if (!isLinked) return;
    let cancelled = false;
    getCancelOptions(token, row.id).then((res) => {
      if (!cancelled) setSupportFlow(res.success && res.data?.flowEnabled ? 'on' : 'off');
    });
    return () => {
      cancelled = true;
    };
  }, [isLinked, row.id, token]);
  const [tab, setTab] = useState<Tab>(initialTab);
  const [note, setNote] = useState('');
  const [reason, setReason] = useState(REJECT_REASONS[0]);
  const [fieldError, setFieldError] = useState<string | null>(null);
  const [sending, setSending] = useState(false);
  // The live fare, fetched as the review opens. Until it arrives the figure on
  // the row is the one quoted at submission, so the panel says it is checking.
  const [live, setLive] = useState<{ status: 'checking' | 'ready' | 'error'; priceCheck?: PriceCheckView; message?: string }>({
    status: 'checking',
  });
  // The refund/fee preview for a cancellation row — fetched once, shown above
  // the Approve button so the admin sees the number before committing to it.
  const [cancelQuote, setCancelQuote] = useState<{ status: 'checking' | 'ready' | 'error'; data?: CancellationQuote; message?: string }>({
    status: 'checking',
  });
  // Set once the server answers REFUND_AMOUNT_REQUIRED (a flight past its
  // free-cancellation window) — or, more usually, once the quote itself comes
  // back ineligible. Kept separate from the quote's own `eligible` so a retry
  // after a late-arriving quote still shows the field.
  const [manualAmountRequired, setManualAmountRequired] = useState(false);
  const [manualAmount, setManualAmount] = useState('');
  const showManualAmount = manualAmountRequired || cancelQuote.data?.eligible === false;

  // Dev StrictMode mounts effects twice. The ref makes the re-price fire once per
  // opened request; without it the airline is queried twice for one click.
  const repricedFor = useRef<string | null>(null);
  useEffect(() => {
    if (isLinked && supportFlow !== 'off') return;
    if (repricedFor.current === row.id) return;
    repricedFor.current = row.id;
    // A cancellation row has no live fare to check — the number that matters
    // here is the refund quote, fetched separately below. `live` itself is
    // left alone (it only ever matters for render via `liveStatus`), so
    // there's nothing to set here.
    if (isCancellation) return;
    // A change in the support flow has no fare to re-price; wait to learn which flow this is.
    if (isLinked && supportFlow !== 'off') return;
    async function reprice() {
      const res = await repriceRequest(token, row.id);
      if (!res.success || !res.data) {
        setLive({ status: 'error', message: res.message ?? 'Could not check the live fare.' });
        return;
      }
      setLive({ status: 'ready', priceCheck: res.data.priceCheck });
      if (res.data.priceCheck.changed) onRepriced?.();
    }
    reprice();
  }, [row.id, token, onRepriced, isCancellation, isLinked, supportFlow]);

  const quotedFor = useRef<string | null>(null);
  useEffect(() => {
    if (!isCancellation || supportFlow !== 'off') return;
    if (quotedFor.current === row.id) return;
    quotedFor.current = row.id;
    async function fetchQuote() {
      const res = await getCancellationQuote(token, row.id);
      if (!res.success || !res.data) {
        setCancelQuote({ status: 'error', message: res.message ?? 'Could not load the refund preview.' });
        return;
      }
      setCancelQuote({ status: 'ready', data: res.data });
    }
    fetchQuote();
  }, [isCancellation, supportFlow, row.id, token]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const submit = async () => {
    setFieldError(null);
    const name = row.employee.name ?? 'the employee';

    // LEIS-1053: approving a change or cancellation sends it to leisure.com support. No Checkout, no refund
    // here: support works with the airline or hotel and charges any fee to (and refunds) the original card.
    if (tab === 'approved' && supportRoute) {
      setSending(true);
      const res = await approveRequest(token, row.id, note.trim());
      setSending(false);
      if (!res.success) {
        setFieldError(res.message ?? 'This request could not be approved. Please try again.');
        return;
      }
      toast.success(`${row.reference} approved and sent to leisure.com support.`);
      onDecision('approve');
      return;
    }

    // LEIS-1034: a cancellation is cancelled and refunded right here — never
    // routed to Checkout, since there is no fare to pay for it.
    if (tab === 'approved' && isCancellation) {
      if (showManualAmount && !manualAmount.trim()) {
        setFieldError('Enter the refund amount to confirm before approving.');
        return;
      }
      setSending(true);
      const res = await approveRequest(token, row.id, note.trim(), showManualAmount ? manualAmount.trim() : undefined);
      setSending(false);
      if (!res.success) {
        if (res.code === 'REFUND_AMOUNT_REQUIRED') {
          const quote = (res.data as unknown as { quote?: CancellationQuote } | undefined)?.quote;
          if (quote) setCancelQuote({ status: 'ready', data: quote });
          setManualAmountRequired(true);
          setFieldError(res.message ?? 'Confirm the refund amount to continue.');
          return;
        }
        setFieldError(res.message ?? 'This cancellation could not be approved. Please try again.');
        return;
      }
      toast.success(`${row.reference} cancelled and refunded.`);
      onDecision('approve');
      return;
    }

    // LEIS-971: Approve no longer books straight away — it just confirms the
    // request is still approvable and hands off to Checkout, which is where
    // the request actually becomes `approved` (only once Pay succeeds).
    if (tab === 'approved') {
      setSending(true);
      const res = await approveRequest(token, row.id, note.trim());
      setSending(false);
      if (!res.success) {
        setFieldError(res.message ?? 'This request could not be opened for approval. Please try again.');
        return;
      }
      onDecision('approve');
      const comment = note.trim();
      router.push(`/admin/checkout/${row.id}${comment ? `?comment=${encodeURIComponent(comment)}` : ''}`);
      return;
    }

    if (tab === 'rejected') {
      setSending(true);
      const res = await rejectRequest(token, row.id, reason, note.trim());
      setSending(false);
      if (!res.success) {
        setFieldError(res.message ?? 'The request could not be rejected. Please try again.');
        return;
      }
      toast.success(`${row.reference} rejected. ${name} will see the reason.`);
      onDecision('reject');
      return;
    }

    if (!note.trim()) {
      setFieldError('Enter a message for the employee.');
      return;
    }
    setSending(true);
    const res = await requestMoreInfo(token, row.id, note.trim());
    setSending(false);
    if (!res.success) {
      setFieldError(res.message ?? 'The message could not be sent. Please try again.');
      return;
    }
    toast.success(`Question sent to ${name}.`);
    onDecision('info');
  };

  const days = row.travelEndDate && row.travelStartDate
    ? Math.max(1, Math.round((Date.parse(row.travelEndDate) - Date.parse(row.travelStartDate)) / 86400000) + 1)
    : 1;
  const roundTrip = row.flight?.tripType === 'ROUND_TRIP';
  const isHotelRequest = row.type === 'HOTEL';
  // A cancellation row never re-prices (see the effect above) — its `live`
  // stays 'checking' forever, which would spin the Estimated cost panel
  // indefinitely. Render it as settled instead; `live.priceCheck` is always
  // absent for it either way, so the fare simply falls back to `row.cost`.
  const liveStatus = isCancellation || supportRoute ? 'ready' : live.status;
  const liveFare = liveStatus === 'ready' && live.priceCheck?.status !== 'UNCONFIRMED' ? live.priceCheck?.fare : undefined;
  const fare = Number(liveFare ?? row.cost.fare ?? 0);
  const additional = Number(row.cost.additionalCost ?? 0);
  const liveTotal = (fare + additional).toFixed(2);
  const priceCheck = liveStatus === 'ready' ? live.priceCheck : undefined;
  const checkedAt = priceCheck?.checkedAt ? formatDateTime(priceCheck.checkedAt) : null;

  return (
    <>
      <div className="modal-backdrop fade show" onClick={onClose} />
      <div className="modal fade show fra-ui fra-modal fra-detail-modal" role="dialog" aria-modal="true" aria-labelledby="fraDetailTitle" style={{ display: 'block' }}>
        <div className="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
          <div className="modal-content">
            <div className="fra-detail-head">
              <div className="fra-detail-heading">
                <h5 className="fra-modal-title" id="fraDetailTitle">Request #{row.reference}</h5>
                <span>
                  {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>
                  )}
                  {row.priority === 'URGENT' && pending && (
                    <span className="fra-urgent ms-0">
                      <i className="bi bi-lightning-charge-fill" />
                      Urgent
                    </span>
                  )}
                </span>
              </div>
              <button type="button" className="fra-close" onClick={onClose} aria-label="Close">
                <i className="bi bi-x-lg" />
              </button>
            </div>

            <div className="modal-body">
              <div className="fra-dgrid">
                {/* Employee */}
                <div className="fra-panel fra-span-5">
                  <p className="fra-panel-title">
                    <i className="bi bi-person" />
                    Employee
                  </p>
                  <div className="fra-emp">
                    <span className="fra-avatar fra-avatar-lg">{initials(row.employee.name)}</span>
                    <div className="min-w-0">
                      <strong>{displayName(row.employee.name) ?? row.employee.workEmail}</strong>
                      <div className="fra-emp-line">
                        <i className="bi bi-building" />
                        {row.employee.department ?? '—'}
                      </div>
                      <div className="fra-emp-line">
                        <i className="bi bi-envelope" />
                        <a href={`mailto:${row.employee.workEmail}`}>{row.employee.workEmail}</a>
                      </div>
                      {/* Their own real, admin-assigned code — this used to
                          synthesize "EMP-{internal db id}" instead, which was
                          never a real employee ID, just this row's primary
                          key with a prefix on it. Omitted, not faked, when
                          their profile never set one. */}
                      {row.employee.employeeId && (
                        <div className="fra-emp-line">
                          <i className="bi bi-person-badge" />
                          Emp ID: {row.employee.employeeId}
                        </div>
                      )}
                      {/* LEIS-1042 — this panel is the TRAVELLER (see toAdminRow's
                          own comment on why it is still named `employee`); a
                          colleague request needs the requester named too, since
                          every action on this overlay is the requester's to take,
                          not theirs. */}
                      {row.isColleagueRequest && (
                        <div className="fra-emp-line">
                          <i className="bi bi-person-check" />
                          Booked by {displayName(row.requester.name) ?? row.requester.workEmail}
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* Trip — this panel was flight-only: a hotel request always
                    hit the `?? '—'` fallbacks (flight-only fields) and even
                    the plane icon and "Trip type: One way" line, neither of
                    which means anything for a stay. Branches on `row.type`
                    now, same discriminator `ApprovalQueue.tsx`'s own row
                    rendering already uses. */}
                <div className="fra-panel fra-span-7">
                  <p className="fra-panel-title">
                    <i className={`bi ${isHotelRequest ? 'bi-building' : 'bi-airplane'}`} />
                    Trip details
                  </p>
                  <div className="fra-trip-route">
                    <span className="fra-trip-icon">
                      <i className={`bi ${isHotelRequest ? 'bi-building-fill' : 'bi-airplane-fill'}`} />
                    </span>
                    <div>
                      <strong>
                        {isHotelRequest
                          ? row.hotel?.property
                          : `${cityName(row.flight!.origin)} → ${cityName(row.flight!.destination)}`}
                      </strong>
                      <small>
                        {formatMediumDate(row.travelStartDate)}
                        {isHotelRequest && row.travelEndDate ? ` – ${formatMediumDate(row.travelEndDate)}` : ''}
                        {!isHotelRequest && roundTrip && row.travelEndDate
                          ? ` – ${formatMediumDate(row.travelEndDate)}`
                          : ''}
                        {isHotelRequest ? (
                          <em>
                            {' '}({row.hotel?.nights ?? days} night{(row.hotel?.nights ?? days) === 1 ? '' : 's'})
                          </em>
                        ) : roundTrip ? (
                          <em>
                            {' '}({days} day{days === 1 ? '' : 's'})
                          </em>
                        ) : (
                          <em> (one way)</em>
                        )}
                      </small>
                    </div>
                  </div>
                  {isHotelRequest ? (
                    <ul className="fra-kv">
                      <li>
                        <i className="bi bi-geo-alt" />
                        <span className="fra-kv-label">Location</span>
                        <span className="fra-kv-value">{row.hotel?.location ?? '—'}</span>
                      </li>
                      <li>
                        <i className="bi bi-moon-stars" />
                        <span className="fra-kv-label">Nights</span>
                        <span className="fra-kv-value">{row.hotel?.nights ?? '—'}</span>
                      </li>
                      <li>
                        <i className="bi bi-door-open" />
                        <span className="fra-kv-label">Room type</span>
                        <span className="fra-kv-value">{row.hotel?.roomType ?? '—'}</span>
                      </li>
                      <li>
                        <i className="bi bi-star" />
                        <span className="fra-kv-label">Star rating</span>
                        <span className="fra-kv-value">
                          {row.hotel?.starRating ? `${row.hotel.starRating}-star` : '—'}
                        </span>
                      </li>
                    </ul>
                  ) : (
                    <ul className="fra-kv">
                      <li>
                        <i className="bi bi-arrow-left-right" />
                        <span className="fra-kv-label">Trip type</span>
                        <span className="fra-kv-value">{roundTrip ? 'Round trip' : 'One way'}</span>
                      </li>
                      <li>
                        <i className="bi bi-person-workspace" />
                        <span className="fra-kv-label">Cabin</span>
                        <span className="fra-kv-value">{row.flight?.cabin.replace('_', ' ').toLowerCase() ?? '—'}</span>
                      </li>
                      <li>
                        <i className="bi bi-airplane-engines" />
                        <span className="fra-kv-label">Preferred airline</span>
                        <span className="fra-kv-value">{row.flight?.airline ?? '—'}</span>
                      </li>
                      <li>
                        <i className="bi bi-ticket-perforated" />
                        <span className="fra-kv-label">Flight number(s)</span>
                        <span className="fra-kv-value">{row.flight?.flightNumbers ?? '—'}</span>
                      </li>
                    </ul>
                  )}
                </div>

                {/* Business information */}
                <div className="fra-panel fra-span-8">
                  <p className="fra-panel-title">
                    <i className="bi bi-briefcase" />
                    Business information
                  </p>
                  <ul className="fra-kv no-icon">
                    <li>
                      <span className="fra-kv-label">Client</span>
                      <span className="fra-kv-value">{row.business.client ?? '—'}</span>
                    </li>
                    <li>
                      <span className="fra-kv-label">Opportunity</span>
                      <span className="fra-kv-value">{row.business.opportunity ?? '—'}</span>
                    </li>
                    <li>
                      <span className="fra-kv-label">Meeting type</span>
                      <span className="fra-kv-value">{row.business.meetingType ?? '—'}</span>
                    </li>
                    <li>
                      <span className="fra-kv-label">Business justification</span>
                      <span className="fra-kv-value">{row.business.justification ?? '—'}</span>
                    </li>
                  </ul>
                </div>

                {/* Estimated cost */}
                <div className="fra-panel fra-span-4">
                  <p className="fra-panel-title">
                    <i className="bi bi-receipt" />
                    Estimated cost
                  </p>
                  <ul className="fra-cost">
                    <li>
                      <span>Flight</span>
                      {liveStatus === 'checking' ? <PriceSkeleton /> : <strong>{formatMoney(String(fare), row.cost.currency)}</strong>}
                    </li>
                    <li>
                      <span>Additional</span>
                      <strong>{formatMoney(String(additional), row.cost.currency)}</strong>
                    </li>
                    <li className="total">
                      <span>Total (est.)</span>
                      {liveStatus === 'checking' ? (
                        <PriceSkeleton />
                      ) : (
                        <strong>{formatMoney(liveFare ? liveTotal : (row.cost.estTotal ?? row.cost.fare), row.cost.currency)}</strong>
                      )}
                    </li>
                  </ul>
                  <div className="fra-cost-note">Currency: {row.cost.currency}</div>
                  {liveStatus === 'checking' && (
                    <div className="fra-cost-note inline-flex items-center gap-1.5" role="status">
                      <i className="bi bi-arrow-repeat animate-spin motion-reduce:animate-none" aria-hidden />
                      Checking the live fare with Amadeus…
                    </div>
                  )}
                  {liveStatus === 'error' && (
                    <div className="fra-cost-note" style={{ color: 'var(--fra-rejected)' }}>
                      {live.message} The figure shown is from submission.
                    </div>
                  )}
                  {priceCheck?.status === 'UNCONFIRMED' && (
                    <div className="fra-cost-note" style={{ color: 'var(--fra-rejected)' }}>
                      Could not confirm the live fare. The figure shown is from submission{checkedAt ? ` (last checked ${checkedAt})` : ''}.
                    </div>
                  )}
                  {priceCheck?.changed && priceCheck.previousFare && (
                    <div className="fra-cost-note" style={{ color: 'var(--fra-pending)' }}>
                      Fare moved from {row.cost.currency} {priceCheck.previousFare} to {row.cost.currency} {priceCheck.fare}
                      {checkedAt ? ` · checked ${checkedAt}` : ''}.
                    </div>
                  )}
                </div>

                {/* Travelers — a hotel request never collects a passport at
                    all (HotelGuestPayload is name + mobile number only, no
                    DOB/gender/nationality/passport step); showing the
                    passport-field grid for one rendered six "—" rows that
                    read exactly like missing data, when the fields were
                    never meant to exist for that request. Confirmed by
                    reading the raw stored `travellers` JSON for a hotel vs a
                    flight request directly. */}
                {isLinked && (
                  <div className="fra-panel fra-span-12" id="fraLinkedAsk">
                    <p className="fra-panel-title">
                      <i className={`bi ${isCancellation ? 'bi-x-octagon' : 'bi-arrow-repeat'}`} />
                      {isCancellation ? 'Cancellation requested' : 'Change requested'}
                      {row.parentReference && <span className="fra-muted fw-normal"> · for booking {row.parentReference}</span>}
                    </p>
                    <ul className="fra-kv no-icon">
                      <li>
                        <span className="fra-kv-label">Reason</span>
                        <span className="fra-kv-value">{row.business.justification || '\u2014'}</span>
                      </li>
                      {!isCancellation && (
                        <li>
                          <span className="fra-kv-label">What to change</span>
                          <span className="fra-kv-value">{row.linkedDetails?.changeDetails || '\u2014'}</span>
                        </li>
                      )}
                      {row.linkedDetails?.notes && (
                        <li>
                          <span className="fra-kv-label">Notes</span>
                          <span className="fra-kv-value">{row.linkedDetails.notes}</span>
                        </li>
                      )}
                      {row.parentBooking && (
                        <>
                          <li>
                            <span className="fra-kv-label">Amount paid</span>
                            <span className="fra-kv-value">{formatMoney(row.parentBooking.amountPaid, row.cost.currency)}</span>
                          </li>
                          <li>
                            <span className="fra-kv-label">Card used</span>
                            <span className="fra-kv-value">
                              {row.parentBooking.card
                                ? `${row.parentBooking.card.brand.charAt(0).toUpperCase()}${row.parentBooking.card.brand.slice(1)} \u2022\u2022\u2022\u2022 ${row.parentBooking.card.last4}`
                                : '\u2014'}
                            </span>
                          </li>
                        </>
                      )}
                    </ul>
                    <p className="fra-muted mb-0 mt-2">
                      Fees may apply under the {isHotelRequest ? 'cancellation terms' : 'fare rules'}. Support confirms any fee with the requester before it is final.
                    </p>
                  </div>
                )}

                <div className="fra-panel fra-span-12">
                  <p className="fra-panel-title">
                    <i className="bi bi-passport" />
                    Travelers {row.type === 'FLIGHT' && <span className="fra-muted fw-normal">· as per passport</span>}
                  </p>
                  <div className="fra-travelers">
                    {row.travellers.length === 0 && <p className="fra-muted mb-0">No traveller details on file for this request.</p>}
                    {row.travellers.map((t, i) => {
                      const name = [t.firstName, t.middleName, t.lastName].filter(Boolean).join(' ') || `Traveler ${i + 1}`;
                      return (
                        <div className="fra-traveler" key={i}>
                          <div className="fra-traveler-head">
                            <span className="fra-avatar">{initials(name)}</span>
                            <div className="min-w-0">
                              <strong>{displayName(name)}</strong>
                              <small>
                                Traveler {i + 1} · {t.type.charAt(0) + t.type.slice(1).toLowerCase()}
                              </small>
                            </div>
                            {t.isEmployee && (
                              <span className="fra-verified">
                                <i className="bi bi-patch-check-fill" />
                                Verified by traveler
                              </span>
                            )}
                          </div>
                          {row.type === 'FLIGHT' && (
                            <ul className="fra-traveler-kv">
                              <li>
                                <span>Date of birth</span>
                                <strong>{formatMediumDate(t.dateOfBirth)}</strong>
                              </li>
                              <li>
                                <span>Gender</span>
                                <strong>{t.gender ?? '—'}</strong>
                              </li>
                              <li>
                                <span>Nationality</span>
                                <strong>{t.nationality ?? '—'}</strong>
                              </li>
                              <li>
                                <span>Passport no.</span>
                                <strong>{t.passportMasked ?? '—'}</strong>
                              </li>
                              <li>
                                <span>Expires</span>
                                <strong>{formatMediumDate(t.passportExpiry)}</strong>
                              </li>
                              <li>
                                <span>Issued by</span>
                                <strong>{t.passportIssuingCountry ?? '—'}</strong>
                              </li>
                            </ul>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* Policy */}
                <div className="fra-panel fra-span-6">
                  <p className="fra-panel-title">
                    <i className={`bi ${flags ? 'bi-shield-exclamation' : 'bi-shield-check'}`} />
                    Policy check
                    {flags ? (
                      <span className="fra-policy-flag ms-auto">
                        {flags} flag{flags > 1 ? 's' : ''}
                      </span>
                    ) : (
                      <span className="fra-policy-ok ms-auto">In policy</span>
                    )}
                  </p>
                  <p className="fra-policy-applied">
                    <i className="bi bi-journal-check" />
                    <span>
                      Policy: <strong>{policyName(row)}</strong>
                    </span>
                    <small>Matched by Department: {row.employee.department ?? 'All'}</small>
                  </p>
                  {/* The request's OWN frozen checks (LEIS-1001), not a
                      reconstruction. This used to render three invented flight
                      checks derived from `flagCount` — on a hotel request that
                      told the approver the fare was over limit and the cabin
                      needed justifying, about a stay with neither. A request
                      that carries no checks shows none; inventing them is what
                      made this wrong in the first place. */}
                  {policyChecks.length > 0 ? (
                    <ul className="fra-checks">
                      {policyChecks.map((c, i) => (
                        <li key={`${c.rule}-${c.label}-${i}`} className={c.ok ? 'ok' : 'flag'}>
                          <span className="fra-check-icon">
                            <i className={`bi ${c.ok ? 'bi-check-lg' : 'bi-exclamation-lg'}`} />
                          </span>
                          <div>
                            <strong>{c.label}</strong>
                            <small>{c.detail}</small>
                          </div>
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p className="fra-policy-applied">
                      <span>No policy checks were stored with this request.</span>
                    </p>
                  )}
                </div>

                {/* Activity */}
                <div className="fra-panel fra-span-6">
                  <p className="fra-panel-title">
                    <i className="bi bi-clock-history" />
                    Activity
                  </p>
                  <ul className="fra-timeline">
                    {timeline.map((item) => (
                      <li key={item.key} className={`t-${TIMELINE_CLASS[item.tone]}`}>
                        <span className="fra-t-icon">
                          <i className={`bi ${TIMELINE_ICON[item.icon]}`} />
                        </span>
                        <div className="grow min-w-0">
                          <strong>{item.title}</strong>
                          {item.sub && <small>{item.sub}</small>}
                          {item.quote && (
                            <blockquote className="mt-1.5 mb-0 rounded-[10px] bg-[var(--fra-surface-2)] px-3 py-2 text-sm">{item.quote}</blockquote>
                          )}
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>

                {/* Decision */}
                {pending && (
                  <div className="fra-panel fra-decision-panel fra-span-12" id="fraDecision">
                    <div className="fra-decision-head">
                      <p className="fra-panel-title">
                        <i className="bi bi-person-check" />
                        Your decision <span className="fra-muted fw-normal">· as Corporate Travel Admin</span>
                      </p>
                      <div className="fra-decision-tabs">
                        <button type="button" data-tab="approved" className={`fra-dtab${tab === 'approved' ? ' active' : ''}`} onClick={() => setTab('approved')}>
                          <i className="bi bi-check-lg" />
                          <span>Approve</span>
                        </button>
                        <button type="button" data-tab="rejected" className={`fra-dtab${tab === 'rejected' ? ' active' : ''}`} onClick={() => setTab('rejected')}>
                          <i className="bi bi-x-lg" />
                          <span>Reject</span>
                        </button>
                        <button type="button" data-tab="changes" className={`fra-dtab${tab === 'changes' ? ' active' : ''}`} onClick={() => setTab('changes')}>
                          <i className="bi bi-chat-left-dots" />
                          <span>Request more info</span>
                        </button>
                      </div>
                    </div>

                    {tab === 'approved' && (
                      <div className="fra-dpane" data-pane="approved">
                        <div className="fra-dpane-title">
                          <span className="fra-dicon">
                            <i className="bi bi-check2-circle" />
                          </span>
                          <div>
                            <strong>{supportRoute ? (isCancellation ? 'Approve cancellation' : 'Approve change') : isCancellation ? 'Approve cancellation' : 'Approve request'}</strong>
                            <small>
                              {supportRoute
                                ? 'Sends it to leisure.com support. There is no Checkout step.'
                                : isCancellation
                                  ? 'Cancels the trip and refunds it right away — there is no Checkout step.'
                                  : 'Continue to Checkout to pay and confirm the reservation.'}
                            </small>
                          </div>
                        </div>

                        {supportRoute ? (
                          <div className="fra-confirm">
                            <i className="bi bi-headset" />
                            <div>
                              <strong>Send to leisure.com support</strong>
                              <small>
                                Support works with the airline or hotel and emails the requester and traveller. Any fee is charged to the original card
                                {row.parentBooking?.card ? ` (${row.parentBooking.card.brand} \u2022\u2022\u2022\u2022 ${row.parentBooking.card.last4})` : ''}, and the rest is refunded to it.
                              </small>
                            </div>
                          </div>
                        ) : isCancellation ? (
                          <>
                            {cancelQuote.status === 'checking' && (
                              <div className="fra-confirm">
                                <i className="bi bi-arrow-repeat animate-spin motion-reduce:animate-none" />
                                <div>
                                  <strong>Checking the refund…</strong>
                                </div>
                              </div>
                            )}
                            {cancelQuote.status === 'error' && (
                              <div className="fra-confirm warn">
                                <i className="bi bi-exclamation-triangle" />
                                <div>
                                  <strong>Could not load the refund preview</strong>
                                  <small>{cancelQuote.message}</small>
                                </div>
                              </div>
                            )}
                            {cancelQuote.status === 'ready' && cancelQuote.data && (
                              <div className={cancelQuote.data.eligible ? 'fra-confirm' : 'fra-confirm warn'}>
                                <i className={`bi ${cancelQuote.data.eligible ? 'bi-cash-coin' : 'bi-shield-exclamation'}`} />
                                <div>
                                  {cancelQuote.data.eligible ? (
                                    <strong>
                                      Refund {formatMoney(cancelQuote.data.refundAmount ?? '0', cancelQuote.data.currency)}
                                      {Number.parseFloat(cancelQuote.data.fee || '0') > 0
                                        ? ` · fee ${formatMoney(cancelQuote.data.fee, cancelQuote.data.currency)} withheld`
                                        : ''}
                                    </strong>
                                  ) : (
                                    <strong>Past the free-cancellation window</strong>
                                  )}
                                  <small>{cancelQuote.data.note}</small>
                                </div>
                              </div>
                            )}
                            {showManualAmount && (
                              <>
                                <label className="fra-label" htmlFor="fraManualRefundAmount">
                                  Refund amount to confirm <em>*</em>
                                </label>
                                <input
                                  className="fra-input"
                                  id="fraManualRefundAmount"
                                  type="number"
                                  min="0"
                                  step="0.01"
                                  value={manualAmount}
                                  onChange={(e) => setManualAmount(e.target.value)}
                                  placeholder={cancelQuote.data?.amountCharged ?? '0.00'}
                                />
                              </>
                            )}
                          </>
                        ) : flags ? (
                          <div className="fra-confirm warn">
                            <i className="bi bi-shield-exclamation" />
                            <div>
                              <strong>
                                This request is out of policy ({flags} flag{flags > 1 ? 's' : ''})
                              </strong>
                              <small>You can still continue. A short note helps the employee and the booking team.</small>
                            </div>
                          </div>
                        ) : (
                          <div className="fra-confirm">
                            <i className="bi bi-check-circle" />
                            <div>
                              <strong>Continue to Checkout?</strong>
                              <small>The request isn&rsquo;t approved until payment goes through on the next step.</small>
                            </div>
                          </div>
                        )}
                        <label className="fra-label" htmlFor="fraDecisionNote">
                          Comment <span className="fra-muted">(optional)</span>
                        </label>
                        <textarea
                          className="fra-input"
                          id="fraDecisionNote"
                          rows={2}
                          value={note}
                          onChange={(e) => setNote(e.target.value)}
                          placeholder={
                            isCancellation
                              ? 'e.g. Approved — the trip is no longer needed.'
                              : flags
                                ? 'e.g. Approved as an exception because the speaking slot was confirmed late.'
                                : 'e.g. Approved. Please book today while the fare holds.'
                          }
                        />
                        {fieldError && <p className="fra-muted m-0 mt-2" style={{ color: 'var(--fra-rejected)' }}>{fieldError}</p>}
                        <div className="fra-dfoot">
                          <button type="button" className="fra-btn fra-btn-ghost" onClick={onClose} disabled={sending}>
                            Cancel
                          </button>
                          <button
                            type="button"
                            className="fra-btn fra-btn-approve"
                            onClick={submit}
                            disabled={sending || (!supportRoute && isCancellation && showManualAmount && !manualAmount.trim())}
                          >
                            <i className="bi bi-check-lg" />
                            <span>
                              {sending
                                ? supportRoute
                                  ? 'Sending…'
                                  : isCancellation
                                    ? 'Cancelling…'
                                    : 'Opening Checkout…'
                                : supportRoute
                                  ? 'Approve & send to support'
                                  : isCancellation
                                    ? 'Cancel & refund'
                                    : 'Continue to Checkout'}
                            </span>
                          </button>
                        </div>
                      </div>
                    )}

                    {tab === 'rejected' && (
                      <div className="fra-dpane" data-pane="rejected">
                        <div className="fra-dpane-title">
                          <span className="fra-dicon">
                            <i className="bi bi-x-circle" />
                          </span>
                          <div>
                            <strong>Reject request</strong>
                            <small>The employee will see the reason and your message.</small>
                          </div>
                        </div>
                        <label className="fra-label">
                          Reason for rejection <em>*</em>
                        </label>
                        <div className="fra-radios" id="fraReasons">
                          {REJECT_REASONS.map((r) => (
                            <label key={r} className="fra-radio">
                              <input type="radio" name="fraReason" value={r} checked={reason === r} onChange={() => setReason(r)} />
                              <span>{r}</span>
                            </label>
                          ))}
                        </div>
                        <label className="fra-label" htmlFor="fraDecisionNote">
                          Add a message <span className="fra-muted" id="fraNoteHint">(optional)</span>
                        </label>
                        <textarea
                          className="fra-input"
                          id="fraDecisionNote"
                          rows={2}
                          value={note}
                          onChange={(e) => setNote(e.target.value)}
                          placeholder="e.g. Please provide alternative dates."
                        />
                        {fieldError && <p className="fra-muted m-0 mt-2" style={{ color: 'var(--fra-rejected)' }}>{fieldError}</p>}
                        <div className="fra-dfoot">
                          <button type="button" className="fra-btn fra-btn-ghost" onClick={onClose}>
                            Cancel
                          </button>
                          <button type="button" className="fra-btn fra-btn-reject-solid" onClick={submit} disabled={sending}>
                            <i className="bi bi-x-lg" />
                            <span>Reject</span>
                          </button>
                        </div>
                      </div>
                    )}

                    {tab === 'changes' && (
                      <div className="fra-dpane" data-pane="changes">
                        <div className="fra-dpane-title">
                          <span className="fra-dicon">
                            <i className="bi bi-chat-left-dots" />
                          </span>
                          <div>
                            <strong>Request more information</strong>
                            <small>The request moves to &quot;Info requested&quot; until the employee replies.</small>
                          </div>
                        </div>
                        <label className="fra-label" htmlFor="fraDecisionNote">
                          Message to employee <em>*</em>
                        </label>
                        <textarea
                          className="fra-input"
                          id="fraDecisionNote"
                          rows={4}
                          value={note}
                          onChange={(e) => setNote(e.target.value)}
                          placeholder="e.g. Can you share the client's preferred dates or more details about the meeting?"
                        />
                        {fieldError && <p className="fra-muted m-0 mt-2" style={{ color: 'var(--fra-rejected)' }}>{fieldError}</p>}
                        <div className="fra-dfoot">
                          <button type="button" className="fra-btn fra-btn-ghost" onClick={onClose}>
                            Cancel
                          </button>
                          <button type="button" className="fra-btn fra-btn-info-solid" onClick={submit} disabled={sending}>
                            <i className="bi bi-send" />
                            <span>Send</span>
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

