"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";

import { getCancellationQuote, getMyRequests } from "@/services/employee-requests/employee-requests.client";
import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { formatEnumLabel } from "@/services/employee-requests/format";
import { actionsFor } from "@/services/employee-requests/request-actions";
import AirlineLogo from "@/components/flights/AirlineLogo";
import CopyButton from "@/components/ui/CopyButton";
import { SUPPORT_LINKS } from "@/constants/product-links";

import { buildActivityTimeline } from "@/services/employee-requests/activity-timeline";
import { ActivityTimeline } from "./ActivityTimeline";
import { BookedTripActions } from "./BookedTripActions";
import { useBusinessSessionReady, useBusinessToken } from "./use-session";

/**
 * app/booking-details/page.tsx — the separate page My Trips' CTA now
 * navigates to, same as leisure-ui's own TripCard/FlightTripCard point
 * their "View & Manage Booking" button at `/booking-details?bookingId=...`.
 *
 * leisure-ui genuinely runs TWO DIFFERENT page designs behind this one URL,
 * branching on booking type (app/(protected)/booking-details/page.tsx picks
 * the component set via a cheap `isFlightBooking` probe) — they are not the
 * same layout with swapped icons, and this file now keeps that split
 * instead of flattening it into one shared shape:
 *
 *   FLIGHT — ported from FlightBookingDetailsHeader.tsx,
 *   FlightBookingDetailsInfo.tsx, FlightBookingDetailsSidebar.tsx: a back
 *   link, a trip-type pill + status badge, "Flight booking details", a
 *   "Booking reference" card, an "Itinerary" card, a "Pricing summary" card,
 *   a "Travelers" card, and a sidebar with Trip summary / Total amount paid
 *   / Need help. Card chrome is `bgColor-white border shadow-sm rounded-3`.
 *
 *   HOTEL — ported from BookingDetailsHeader.tsx,
 *   BookingDetailsStayInfo.tsx, BookingDetailsBookingSection.tsx,
 *   BookingDetailsSidebar.tsx: a "Your Booking is {STATUS}!" heading with a
 *   Booking ID / Email row (no back link, no status pill, no "booking
 *   reference" card — none of those exist on this page in leisure-ui), a
 *   plain property card, a "BOOKING DETAILS" card (nights + check-in/out,
 *   guests, room — exact icons and column grid from
 *   BookingDetailsBookingSection.tsx), and a sidebar that is *only* a
 *   "Price Summary" accordion — no Trip summary card, no Need help card;
 *   those don't exist on the real hotel page either. Card chrome is
 *   `bgColor-white shadow-sm rounded-3`, no border — also a real
 *   difference from the flight page, not an inconsistency to fix.
 *
 *   Left out on both, and why: HouseRulesInfo ("Important information for
 *   check-in"), BookingReviewSection ("Your review"), HomeStayDetails
 *   (amenities/photos) and BookingDetailsRefundStatus (the refund-timeline
 *   stepper) all read from data this product doesn't have at all — property
 *   images, address, phone, amenities, house rules, a review/rating
 *   feature, and a refund-tracking service — not from a field that's merely
 *   unpopulated on this one booking. Porting their markup would mean empty
 *   cards or a review form that submits nowhere, which is a worse mismatch
 *   than not having the section. Likewise `BusinessBooking.supplierReference`
 *   is hardcoded as `PENDING-SUPPLIER-${reference}` today, with a TODO
 *   noting real Amadeus order creation was never wired up (LEIS-973, still
 *   open) — confirmed by reading business-checkout.controller.ts and
 *   business-employee-checkout.controller.ts before building this — so
 *   there is no real PNR anywhere on this page, flight or hotel.
 */

// ─── Formatting helpers — ported from FlightBookingDetailsInfo.tsx,
// trimmed to the ones this page's thinner data can actually feed. ──────────

function formatFlightDate(iso: string | null | undefined): string {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${days[d.getUTCDay()]}, ${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
}

/** Ported from BookingDetailsStayInfo.tsx's formatStayDate — the big
 *  day-number + month/year + weekday block a hotel check-in/out uses,
 *  distinct from a flight's HH:MM (MyRequestRow carries no check-in/out
 *  time of day, so there's no time to show here either, same as the real
 *  component would get with no `timeOverride`). */
function formatStayParts(iso: string | null | undefined): { day: string; monthYear: string; weekday: string } | null {
  if (!iso) return null;
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return null;
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  return {
    day: String(d.getUTCDate()),
    monthYear: `${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`,
    weekday: weekdays[d.getUTCDay()],
  };
}

function formatShortDate(iso: string | null | undefined): string {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]}`;
}

function formatPlainDateTime(iso?: string | null): string {
  if (!iso) return "—";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return "—";
  try {
    const parts = new Intl.DateTimeFormat("en-US", {
      day: "2-digit",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
      timeZoneName: "short",
    }).formatToParts(d);
    const get = (type: string) => parts.find((p) => p.type === type)?.value ?? "";
    return `${get("day")} ${get("month")} ${get("year")}, ${get("hour")}:${get("minute")} ${get("dayPeriod").toLowerCase()} ${get("timeZoneName")}`;
  } catch {
    return d.toLocaleString();
  }
}

function titleCaseWords(value?: string | null): string {
  if (!value) return "";
  return value
    .split(/[_\s]+/)
    .filter(Boolean)
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
    .join(" ");
}

function formatMoney(value: string | number | null | undefined, currency = "USD"): string {
  const amount = typeof value === "string" ? Number.parseFloat(value) : value;
  if (amount == null || !Number.isFinite(amount)) return "—";
  return `${currency === "USD" ? "$" : currency + " "}${amount.toFixed(2)}`;
}

/** First 2 letters of a flight-number string, for AirlineLogo's `code`. */
function carrierCodeFrom(flightNumbers: string | null): string | null {
  const match = flightNumbers?.trim().match(/^([A-Z0-9]{2})\s?\d/i);
  return match ? match[1].toUpperCase() : null;
}

// ─── Small building blocks — ported verbatim from FlightBookingDetailsInfo.tsx ──

function Label({ children }: { children: React.ReactNode }) {
  return <div className="text-xs text-uppercase flight-detail-label">{children}</div>;
}

function Value({ children }: { children: React.ReactNode }) {
  return <span className="text-sm fw-600 color-text-black">{children}</span>;
}

function PersonAvatar() {
  return (
    <span
      className="d-inline-flex align-items-center justify-content-center rounded-circle color-text-first flex-shrink-0"
      style={{ width: 34, height: 34, background: "rgba(47,98,113,0.1)" }}
    >
      <svg width="17" height="17" viewBox="0 0 16 16" fill="currentColor">
        <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6m2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0m4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4m-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10s-3.516.68-4.168 1.332c-.678.678-.83 1.418-.832 1.664z" />
      </svg>
    </span>
  );
}

function PlaneIcon({ className }: { className?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
    </svg>
  );
}

function PlaneGlyph({ style }: { style?: React.CSSProperties }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="var(--color-first)" style={style} width={14} height={14}>
      <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
    </svg>
  );
}

/** Ported from FlightBookingDetailsInfo.tsx's RouteConnector — the dashed
 *  line + plane glyph between two endpoints. Shown without a duration here:
 *  MyRequestRow carries no segment-level flight time, only a calendar date. */
function RouteConnector({ note }: { note: string }) {
  return (
    <div className="flex-grow-1 text-center px-2">
      <small className="flight-detail-label d-block mb-1">{note}</small>
      <div className="d-flex align-items-center gap-1">
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#cbd5e1", flexShrink: 0 }} />
        <span className="position-relative flex-grow-1" style={{ borderTop: "1.5px dashed #cbd5e1" }}>
          <PlaneGlyph style={{ position: "absolute", top: -7, left: "50%", transform: "translateX(-50%) rotate(90deg)" }} />
        </span>
        <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#cbd5e1", flexShrink: 0 }} />
      </div>
    </div>
  );
}

/** Ported from FlightBookingDetailsHeader.tsx's StatusBadge. */
function StatusBadge({ cancelled }: { cancelled: boolean }) {
  const style = cancelled ? { background: "#fee2e2", color: "#b91c1c" } : { background: "#dcfce7", color: "#15803d" };
  return (
    <span className="text-xs fw-600 text-uppercase px-2 py-1 rounded-5" style={style}>
      {cancelled ? "Cancelled" : "Confirmed"}
    </span>
  );
}

export function BookingDetailsView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const reference = searchParams.get("reference");

  const token = useBusinessToken();
  const sessionReady = useBusinessSessionReady();
  useEffect(() => {
    if (sessionReady && token === null) {
      router.replace(`/employee-login?next=/booking-details${reference ? `?reference=${encodeURIComponent(reference)}` : ""}`);
    }
  }, [sessionReady, token, router, reference]);

  // Same query key as My Trips — if this page was reached by clicking a
  // card, the list is already warm in the cache and this resolves instantly
  // instead of refetching.
  const { data, isPending, isFetching } = useQuery({
    queryKey: ["employee-requests", "mine"],
    queryFn: async () => {
      const res = await getMyRequests({ tab: "all", limit: 100 });
      if (!res.success) throw new Error(res.message ?? "Could not load this booking.");
      return res.data!;
    },
    enabled: Boolean(token),
    refetchOnWindowFocus: false,
    staleTime: 30_000,
  });

  const row = useMemo(() => data?.data.find((r) => r.reference === reference) ?? null, [data, reference]);
  const loading = isPending || isFetching;

  if (!reference) return <NotFound reason="There's no booking reference in this link." />;
  if (loading) return <Skeleton />;
  if (!row) return <NotFound reason="This booking wasn't found on your trips." />;

  return <Loaded row={row} />;
}

function Loaded({ row }: { row: MyRequestRow }) {
  const isHotel = row.type === "HOTEL";
  const flight = row.trip.flight;
  const hotel = row.trip.hotel;
  const cancelled = row.status === "CANCELLED";
  const travelEnd = row.trip.travelEndDate ?? row.trip.travelStartDate;
  const completed = !cancelled && !!travelEnd && travelEnd.slice(0, 10) < new Date().toISOString().slice(0, 10);
  const statusWord = cancelled ? "CANCELLED" : completed ? "COMPLETED" : "CONFIRMED";
  const carrierCode = flight ? carrierCodeFrom(flight.flightNumbers) : null;
  const currency = row.cost.currency;
  const hasFees = Number.parseFloat(row.cost.additionalCost || "0") > 0;
  const hotelCheckIn = hotel ? formatStayParts(hotel.checkIn) : null;
  const hotelCheckOut = hotel ? formatStayParts(hotel.checkOut) : null;
  const adults = row.travellers.filter((t) => t.type === "ADULT").length || 1;
  const others = row.travellers.length - adults;
  const primaryGuestName =
    row.traveller.name ?? ([row.travellers[0]?.firstName, row.travellers[0]?.lastName].filter(Boolean).join(" ") || "—");
  const cardChrome = isHotel ? "bgColor-white shadow-sm rounded-3 p-3 p-md-4" : "bgColor-white border shadow-sm rounded-3 p-3 p-md-4";

  return (
    <>
      {/* Breadcrumb — leisure-ui renders <BreadcrumbsBar /> above the header
          on both the flight and hotel paths (app/(protected)/booking-details
          /page.tsx); that component pulls from a site-wide route trail this
          app doesn't have, so this mirrors MyTripsView's own PageShell
          breadcrumb instead — same classes, one level deeper. */}
      <div className="container webNewContent pt-3">
        <nav aria-label="Breadcrumb" className="leisure-breadcrumb mb-0">
          <ol className="breadcrumb leisure-breadcrumb__list mb-0">
            <li className="breadcrumb-item">
              <Link href="/" className="leisure-breadcrumb__link">
                <span className="leisure-breadcrumb__label">Home</span>
              </Link>
            </li>
            <li className="breadcrumb-item">
              <Link href="/my-trips" className="leisure-breadcrumb__link">
                <span className="leisure-breadcrumb__label">My Trips</span>
              </Link>
            </li>
            <li className="breadcrumb-item active" aria-current="page">
              <span className="leisure-breadcrumb__label">{row.reference}</span>
            </li>
          </ol>
        </nav>
      </div>

      {isHotel ? (
        // ── HOTEL header — ported from BookingDetailsHeader.tsx: no back
        // link, no status pill, no "Hotel booking details" heading — the
        // real hotel page says "Your Booking is {STATUS}!" and lists
        // Booking ID / Reference PNR / Email instead. No PNR exists here
        // (see this file's top doc comment), so that one row is left out.
        <section className="py-4 booking-form-listing-section">
          <div className="container webNewContent">
            <h1 className="mainHeading mb-2 d-flex align-items-center">Your Booking is {statusWord}!</h1>
            <div className="d-flex flex-wrap gap-sm-3 gap-1">
              <p className="mb-0">
                <small className="color-text-grey">Booking ID</small> <strong>{row.reference}</strong>
              </p>
              <p className="mb-0">
                <small className="color-text-grey">Email</small> <strong>{row.traveller.workEmail}</strong>
              </p>
            </div>
          </div>
        </section>
      ) : (
        // ── FLIGHT header — ported from FlightBookingDetailsHeader.tsx ──
        <section className="py-4 booking-form-listing-section">
          <div className="container webNewContent">
            <Link href="/my-trips" className="d-inline-flex align-items-center gap-2 text-decoration-none mb-3 color-text-first fw-500 text-sm">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M19 12H5M12 19l-7-7 7-7" />
              </svg>
              Back to My Trips
            </Link>

            <div className="d-flex align-items-center flex-wrap gap-2 mb-2">
              {flight && (
                <span className="text-xs fw-600 text-uppercase px-2 py-1 rounded-5 bgColor-second-light color-text-second">
                  {titleCaseWords(flight.tripType)}
                </span>
              )}
              {row.supportStatus !== "WITH_SUPPORT" && <StatusBadge cancelled={cancelled} />}
              {row.supportStatus === "WITH_SUPPORT" && (
                <span
                  className="text-xs fw-600 px-2 py-1 rounded-5"
                  style={{ background: "var(--fra-info-bg, #e8f0fe)", color: "var(--fra-info, #1a56c4)" }}
                  title="leisure.com support is working on this booking"
                >
                  With support{row.supportReference ? ` \u00b7 ${row.supportReference}` : ""}
                </span>
              )}
            </div>
            <h1 className="mainHeading mb-1">Flight booking details</h1>
            {flight && (
              <div className="d-flex align-items-center gap-2 color-text-gray text-sm fw-500">
                <span className="color-text-black fw-600">{flight.origin}</span>
                <PlaneIcon className="iconSize-15 stroke-first" />
                <span className="color-text-black fw-600">{flight.destination}</span>
              </div>
            )}
          </div>
        </section>
      )}

      {/* ── Main layout — ported from app/(protected)/booking-details/page.tsx ── */}
      <section className="py-md-5 py-3 booking-detail-listing-section travelContent">
        <div className="container webNewContent">
          <div className="row">
            <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-12 col-12 listing-details webNewContent d-flex flex-column gap-3">
              {isHotel ? (
                hotel ? (
                  <>
                    {/* Property — ported from BookingDetailsStayInfo.tsx's
                        title block. No property-type field or image exists
                        on MyRequestRow, so "Hotel" (we do know that much —
                        this is a hotel booking) stands in for the real
                        component's property.type badge, and the image
                        column is left out rather than shown with a
                        placeholder. */}
                    <div className={cardChrome}>
                      <small className="border rounded p-1 color-text-first text-capitalize">Hotel</small>
                      <h3 className="subHeading mb-0 text-capitalize fw-bold color-text-first mt-2">{hotel.property}</h3>
                      {hotel.location && <small className="text-secondary d-block">{hotel.location}</small>}
                    </div>

                    {/* BOOKING DETAILS — ported from
                        BookingDetailsBookingSection.tsx: same icons, same
                        row/col grid, same labels. Amenities, meal plan and
                        the room photo are left out — MyRequestRow carries
                        only a room TYPE string, not the amenities/mealPlan/
                        image fields the real room object has, and guessing
                        a meal plan would be asserting something this page
                        doesn't actually know. */}
                    <div className={cardChrome}>
                      <h3 className="subHeading fw-bold text-lg mb-0">BOOKING DETAILS</h3>
                      <p className="text-secondary text-md">Your room, meal plan and guest details</p>

                      <div className="row py-3 border-bottom">
                        <div className="col-xxl-1 col-xl-1 col-lg-1 col-md-1 col-1 mb-4 mb-lg-0">
                          <svg xmlns="http://www.w3.org/2000/svg" className="iconSize-20 fill-black" viewBox="0 0 16 16">
                            <path d="M7 8a3.5 3.5 0 0 1 3.5 3.555.5.5 0 0 0 .625.492A1.503 1.503 0 0 1 13 13.5a1.5 1.5 0 0 1-1.5 1.5H3a2 2 0 1 1 .1-3.998.5.5 0 0 0 .509-.375A3.5 3.5 0 0 1 7 8m4.473 3a4.5 4.5 0 0 0-8.72-.99A3 3 0 0 0 3 16h8.5a2.5 2.5 0 0 0 0-5z" />
                            <path d="M11.286 1.778a.5.5 0 0 0-.565-.755 4.595 4.595 0 0 0-3.18 5.003 5.5 5.5 0 0 1 1.055.209A3.6 3.6 0 0 1 9.83 2.617a4.593 4.593 0 0 0 4.31 5.744 3.58 3.58 0 0 1-2.241.634q.244.477.394 1a4.59 4.59 0 0 0 3.624-2.04.5.5 0 0 0-.565-.755 3.593 3.593 0 0 1-4.065-5.422z" />
                          </svg>
                        </div>
                        <div className="col-xxl-2 col-xl-2 col-lg-2 col-md-8 col-8 mb-4 mb-lg-0">
                          <strong className="text-sm">{hotel.nights} Night(s)</strong>
                        </div>
                        <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-5 col-12 mb-3 mb-md-0 order-4 order-md-3">
                          <div className="d-flex flex-column">
                            <small>CHECK IN</small>
                            <p className="mb-0">
                              {hotelCheckIn && (
                                <>
                                  <span className="text-sm">{hotelCheckIn.weekday}, </span>
                                  <strong className="text-sm">{hotelCheckIn.day} {hotelCheckIn.monthYear}</strong>
                                </>
                              )}
                            </p>
                          </div>
                        </div>
                        <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-5 col-12 order-5 order-md-4">
                          <div className="d-flex flex-column">
                            <small>CHECK OUT</small>
                            <p className="mb-0">
                              {hotelCheckOut && (
                                <>
                                  <span className="text-sm">{hotelCheckOut.weekday}, </span>
                                  <strong className="text-sm">{hotelCheckOut.day} {hotelCheckOut.monthYear}</strong>
                                </>
                              )}
                            </p>
                          </div>
                        </div>
                      </div>

                      <div className="row py-3 border-bottom">
                        <div className="col-xxl-1 col-xl-1 col-lg-1 col-md-1 mb-4 mb-lg-0 col-1">
                          <svg xmlns="http://www.w3.org/2000/svg" className="iconSize-20 fill-black" viewBox="0 0 16 16">
                            <path d="M15 14s1 0 1-1-1-4-5-4-5 3-5 4 1 1 1 1zm-7.978-1L7 12.996c.001-.264.167-1.03.76-1.72C8.312 10.629 9.282 10 11 10c1.717 0 2.687.63 3.24 1.276.593.69.758 1.457.76 1.72l-.008.002-.014.002zM11 7a2 2 0 1 0 0-4 2 2 0 0 0 0 4m3-2a3 3 0 1 1-6 0 3 3 0 0 1 6 0M6.936 9.28a6 6 0 0 0-1.23-.247A7 7 0 0 0 5 9c-4 0-5 3-5 4q0 1 1 1h4.216A2.24 2.24 0 0 1 5 13c0-1.01.377-2.042 1.09-2.904.243-.294.526-.569.846-.816M4.92 10A5.5 5.5 0 0 0 4 13H1c0-.26.164-1.03.76-1.724.545-.636 1.492-1.256 3.16-1.275ZM1.5 5.5a3 3 0 1 1 6 0 3 3 0 0 1-6 0m3-2a2 2 0 1 0 0 4 2 2 0 0 0 0-4" />
                          </svg>
                        </div>
                        <div className="col-xxl-2 col-xl-2 col-lg-2 col-md-8 mb-4 mb-lg-0 col-8">
                          <strong className="text-sm">{row.travellers.length || 1} Guest(s)</strong>
                        </div>
                        <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-5 col-12 mb-3 mb-md-0 order-4 order-md-3">
                          <div className="d-flex flex-column">
                            <small>TOTAL GUEST(S)</small>
                            <p className="mb-0">
                              <strong className="text-sm">
                                {adults} Adult{adults === 1 ? "" : "s"}
                                {others > 0 ? `, ${others} Other${others === 1 ? "" : "s"}` : ""}
                              </strong>
                            </p>
                          </div>
                        </div>
                        <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-5 col-12 order-5 order-md-4">
                          <div className="d-flex flex-column">
                            <small>PRIMARY GUEST</small>
                            <p className="mb-0">
                              <strong className="text-sm">{primaryGuestName}</strong>
                            </p>
                            <small>EMAIL ID</small>
                            <strong className="text-sm">{row.traveller.workEmail}</strong>
                          </div>
                        </div>
                      </div>

                      <div className="row pt-3">
                        <div className="col-xxl-1 col-xl-1 col-lg-1 col-md-1 mb-4 mb-lg-0 col-1">
                          <svg xmlns="http://www.w3.org/2000/svg" className="iconSize-20 fill-black" viewBox="0 0 16 16">
                            <path d="M2 1a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1zm11 0H3v14h3v-2.5a.5.5 0 0 1 .5-.5h3a.5.5 0 0 1 .5.5V15h3z" />
                          </svg>
                        </div>
                        <div className="col-xxl-2 col-xl-2 col-lg-2 col-md-8 mb-4 mb-lg-0 col-8">
                          <strong className="text-sm">1 ROOM</strong>
                        </div>
                        <div className="col-xxl-9 col-xl-9 col-lg-9 col-md-12 col-12 order-4 order-md-3">
                          <h4 className="fw-bold mb-0 text-md">{hotel.roomType ?? "Standard room"}</h4>
                        </div>
                      </div>
                    </div>
                  </>
                ) : (
                  <div className={cardChrome}>
                    <p className="flight-detail-label mb-0">Stay details aren&apos;t available yet.</p>
                  </div>
                )
              ) : (
                <>
                  {/* Booking reference — ported from FlightBookingDetailsInfo.tsx */}
                  <div className={cardChrome}>
                    <Label>Booking reference</Label>
                    <div className="d-flex align-items-center gap-2 mt-1">
                      <span className="text-xxl fw-bold color-text-black" style={{ wordBreak: "break-all" }}>
                        {row.reference}
                      </span>
                      <CopyButton value={row.reference} label="booking reference" />
                    </div>
                    <div className="row g-3 mt-1 pt-3 border-top">
                      <div className="col-6 col-md">
                        <Label>Booking type</Label>
                        <Value>Flight request</Value>
                      </div>
                      <div className="col-6 col-md">
                        <Label>Status</Label>
                        <Value>{formatEnumLabel(row.status)}</Value>
                      </div>
                      <div className="col-6 col-md">
                        <Label>Created</Label>
                        <Value>{formatPlainDateTime(row.submittedAt)}</Value>
                      </div>
                    </div>
                  </div>

                  {/* Everything that happened on this booking, including what leisure.com support wrote. */}
                  {row.activity.some((e) => e.action === "SUPPORT_UPDATE" || e.action === "SENT_TO_SUPPORT" || e.action === "SUPPORT_DONE") && (
                    <div className={cardChrome}>
                      <h3 className="subHeading mb-3 fw-bold">Activity</h3>
                      <ActivityTimeline
                        items={buildActivityTimeline({
                          viewer: "employee",
                          status: row.status,
                          submittedAt: row.submittedAt,
                          activity: row.activity,
                          askedBy: row.infoRequest?.askedBy ?? null,
                        })}
                      />
                    </div>
                  )}

                  {/* Itinerary — ported from FlightBookingDetailsInfo.tsx's
                      ItineraryLeg/SegmentRow, trimmed to the fields this
                      page's data actually has (no per-segment times/
                      terminals). */}
                  <div className={cardChrome}>
                    <div className="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
                      <h3 className="subHeading mb-0 fw-bold">Itinerary</h3>
                    </div>

                    {flight ? (
                      <>
                        {[
                          { label: "Outbound", date: flight.departDate, from: flight.origin, to: flight.destination },
                          ...(flight.returnDate
                            ? [{ label: "Return", date: flight.returnDate, from: flight.destination, to: flight.origin }]
                            : []),
                        ].map((leg, idx, legs) => {
                          const isReturn = leg.label === "Return";
                          const accent = isReturn ? "var(--color-second)" : "var(--color-first)";
                          return (
                            <div key={leg.label} className={idx === legs.length - 1 ? "" : "mb-3"} style={{ background: "#fafafa", borderRadius: 14, borderLeft: `4px solid ${accent}`, padding: "16px 18px" }}>
                              <div className="d-flex align-items-center flex-wrap gap-2 pb-2 mb-2" style={{ borderBottom: "1px solid #e5e7eb" }}>
                                <span
                                  className="text-xs fw-600 text-uppercase px-2 py-1 rounded-5"
                                  style={isReturn ? { background: "var(--color-second-light)", color: "var(--color-second)" } : { background: "rgba(47,98,113,0.1)", color: "var(--color-first)" }}
                                >
                                  {leg.label}
                                </span>
                                <span className="text-sm fw-600 color-text-black">{formatFlightDate(leg.date)}</span>
                              </div>
                              <div className="d-flex align-items-center gap-3">
                                <div className="text-start">
                                  <div className="fw-bold color-text-black" style={{ fontSize: "1.1rem" }}>{leg.from}</div>
                                </div>
                                <RouteConnector note="Direct" />
                                <div className="text-end">
                                  <div className="fw-bold color-text-black" style={{ fontSize: "1.1rem" }}>{leg.to}</div>
                                </div>
                              </div>
                              {idx === 0 && (
                                <div className="d-flex align-items-center gap-2 mt-3 pt-2" style={{ borderTop: "1px dashed #e5e7eb" }}>
                                  <AirlineLogo code={carrierCode} name={flight.airline ?? undefined} width={28} height={28} className="rounded-2 border flex-shrink-0" style={{ objectFit: "contain" }} />
                                  <div>
                                    <Value>{flight.airline || "Airline to be confirmed"}</Value>
                                    <Label>{[flight.flightNumbers, titleCaseWords(flight.cabin)].filter(Boolean).join(" · ")}</Label>
                                  </div>
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </>
                    ) : (
                      <p className="flight-detail-label mb-0">Flight details aren&apos;t available yet.</p>
                    )}
                  </div>
                </>
              )}

              {/* Cancellation (LEIS-1034) — three states, not one static
                  placeholder: a cancelled trip shows its real refund outcome
                  (unconditionally — inverted from the old `!cancelled` gate),
                  a still-live trip gets the refund preview + the actual
                  cancel action, and a completed trip shows neither — there is
                  nothing left to cancel. */}
              {cancelled ? (
                <CancellationOutcomeCard cardChrome={cardChrome} cancellation={row.cancellation} />
              ) : (
                !completed && <CancellationCard row={row} cardChrome={cardChrome} />
              )}

              {!isHotel && (
                <>
                  {/* Pricing summary — ported from FlightBookingDetailsInfo.tsx */}
                  <div className={cardChrome}>
                    <h3 className="subHeading mb-3 fw-bold">Pricing summary</h3>
                    <div className="d-flex justify-content-between py-2 text-sm">
                      <span className="flight-detail-label">Flight fare</span>
                      <span className="color-text-black">{formatMoney(row.cost.fare, currency)}</span>
                    </div>
                    {hasFees && (
                      <div className="d-flex justify-content-between py-2 text-sm">
                        <span className="flight-detail-label">Fees</span>
                        <span className="color-text-black">{formatMoney(row.cost.additionalCost, currency)}</span>
                      </div>
                    )}
                    <div className="d-flex justify-content-between align-items-center mt-2 p-3 rounded-3" style={{ background: "rgba(47,98,113,0.06)" }}>
                      <span className="fw-bold color-text-black">Total (Grand total)</span>
                      <span className="fw-bold text-lg color-text-first">{formatMoney(row.cost.estTotal ?? row.cost.fare, currency)}</span>
                    </div>
                  </div>

                  {/* Traveler pricing — ported from FlightBookingDetailsInfo.tsx's
                      TravelerCard, trimmed to what MyRequestRow carries: no
                      per-traveler fare split, no e-ticket number, and
                      passport editing stays locked (LEIS-973 hasn't wired
                      that up either). */}
                  {row.travellers.length > 0 && (
                    <div className={cardChrome}>
                      <h3 className="subHeading mb-3 fw-bold">Travelers</h3>
                      <div className="row g-3">
                        {row.travellers.map((t, i) => {
                          const name = [t.firstName, t.middleName, t.lastName].filter(Boolean).join(" ") || `Traveller ${i + 1}`;
                          return (
                            <div className="col-12 col-md-6" key={i}>
                              <div className="border rounded-3 p-3 h-100">
                                <div className="d-flex align-items-center gap-2 mb-2">
                                  <PersonAvatar />
                                  <div>
                                    <Value>{name}</Value>
                                    <Label>{titleCaseWords(t.type)}</Label>
                                  </div>
                                </div>
                                <div className="d-flex align-items-center justify-content-between gap-2 mt-2 pt-2" style={{ borderTop: "1px dashed #e5e7eb" }}>
                                  <div className="d-flex align-items-center gap-2">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" width={15} height={15} className="flight-detail-label flex-shrink-0">
                                      <rect x="3" y="4" width="18" height="16" rx="2" />
                                      <circle cx="9" cy="10" r="2" />
                                      <path d="M15 8h2M15 12h2M7 16h10" />
                                    </svg>
                                    {t.passportMasked ? (
                                      <span className="text-xs color-text-black">
                                        Passport <span className="fw-600">{t.passportMasked}</span>
                                      </span>
                                    ) : (
                                      <span className="text-xs flight-detail-label">No passport on file</span>
                                    )}
                                  </div>
                                  <span
                                    className="text-xs flight-detail-label flex-shrink-0"
                                    title="Passport details can only be edited before your ticket is issued. Contact support for help with this booking."
                                    style={{ cursor: "help" }}
                                  >
                                    Locked
                                  </span>
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* ── Sidebar ───────────────────────────────────────────────── */}
            <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-12 col-sm-12 col-12 mt-3 mt-md-0">
              <div className="d-flex flex-column gap-3">
                {isHotel ? (
                  // Ported from BookingDetailsSidebar.tsx's "Price Summary"
                  // accordion — this is the ENTIRE hotel sidebar in
                  // leisure-ui; there is no separate Trip summary or Need
                  // help card on the real hotel page. AMOUNT PAID is left
                  // out rather than shown as $0.00: no payment-capture
                  // tracking exists for a business booking at all (see this
                  // file's top doc comment), so "$0" would assert a fact
                  // this page cannot actually confirm either way.
                  <div className="bgColor-white p-3 shadow-sm rounded-3">
                    <div className="accordion" id="hotelPriceSummary">
                      <div className="accordion-item bg-transparent border-0">
                        <div className="accordion-header d-flex justify-content-between align-items-center border-bottom pb-2">
                          <h3 className="subHeading fw-bold text-lg text-capitalize mb-0">Price Summary</h3>
                          <button
                            className="accordion-button p-0 text-md bg-transparent color-text-first w-auto shadow-none ms-auto collapsed"
                            type="button"
                            data-bs-toggle="collapse"
                            data-bs-target="#hotelPriceSummaryCollapse"
                            aria-expanded="false"
                            aria-controls="hotelPriceSummaryCollapse"
                          >
                            Show Breakup&nbsp;
                          </button>
                        </div>
                        <div id="hotelPriceSummaryCollapse" className="accordion-collapse collapse" data-bs-parent="#hotelPriceSummary">
                          <div className="accordion-body p-0">
                            <p className="mb-0 border-bottom d-flex justify-content-between py-2">
                              <small className="text-sm">Hotel fare</small>
                              <small className="text-sm">{formatMoney(row.cost.fare, currency)}</small>
                            </p>
                            {hasFees && (
                              <p className="mb-0 border-bottom d-flex justify-content-between py-2">
                                <small className="text-sm">Fees</small>
                                <small className="text-sm">{formatMoney(row.cost.additionalCost, currency)}</small>
                              </p>
                            )}
                          </div>
                        </div>
                        <p className="mb-0 d-flex justify-content-between pt-2">
                          <strong className="text-md">Total Price</strong>
                          <strong className="text-md">{formatMoney(row.cost.estTotal ?? row.cost.fare, currency)}</strong>
                        </p>
                      </div>
                    </div>
                  </div>
                ) : (
                  <>
                    {/* Trip summary — ported from FlightBookingDetailsSidebar.tsx */}
                    <div className="bgColor-white p-3 shadow-sm rounded-3">
                      <h3 className="subHeading fw-bold text-lg mb-3 border-bottom pb-2">Trip summary</h3>
                      {flight && (
                        <div className="d-flex align-items-center justify-content-between">
                          <div className="text-center">
                            <div className="text-md fw-bold color-text-black">{formatShortDate(flight.departDate)}</div>
                            <div className="text-xs flight-detail-label">{flight.origin}</div>
                          </div>
                          <div className="flex-grow-1 text-center px-2">
                            <PlaneIcon className="iconSize-15 stroke-first" />
                          </div>
                          <div className="text-center">
                            <div className="text-md fw-bold color-text-black">{flight.returnDate ? formatShortDate(flight.returnDate) : "—"}</div>
                            <div className="text-xs flight-detail-label">{flight.destination}</div>
                          </div>
                        </div>
                      )}
                      {row.travellers.length > 0 && (
                        <div className="d-flex align-items-center gap-2 mt-3 pt-3 border-top text-sm flight-detail-label">
                          <svg width="15" height="15" viewBox="0 0 16 16" fill="currentColor">
                            <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6m2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0m4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4m-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10s-3.516.68-4.168 1.332c-.678.678-.83 1.418-.832 1.664z" />
                          </svg>
                          {row.travellers.length} traveler{row.travellers.length === 1 ? "" : "s"}
                        </div>
                      )}
                    </div>

                    {/* Total amount paid — ported from FlightBookingDetailsSidebar.tsx */}
                    <div className="bgColor-white p-3 shadow-sm rounded-3">
                      <h3 className="subHeading fw-bold text-lg mb-2 border-bottom pb-2">{cancelled ? "Total" : "Total amount paid"}</h3>
                      <p className="mb-0 text-xxl fw-bold color-text-first">{formatMoney(row.cost.estTotal ?? row.cost.fare, currency)}</p>
                    </div>

                    {/* Need help — ported from FlightBookingDetailsSidebar.tsx */}
                    <div className="bgColor-white p-3 shadow-sm rounded-3">
                      <h3 className="subHeading mb-2 text-lg fw-600">Need help?</h3>
                      <p className="text-sm text-secondary mb-2">For changes to this flight, please contact support with your booking reference above.</p>
                      <a href={SUPPORT_LINKS.contact} target="_blank" rel="noreferrer" className="text-sm fw-600 color-text-second">
                        Contact support
                      </a>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

/** The outcome shown on an already-CANCELLED trip (LEIS-1034). Rendered
 *  unconditionally once cancelled — this is the one place the refund/fee/date
 *  actually lands, not a status badge elsewhere. `cancellation` is only ever
 *  null for a trip cancelled before this feature shipped — that fallback
 *  copy, not a blank card, is the honest state for those. */
function CancellationOutcomeCard({
  cardChrome,
  cancellation,
}: {
  cardChrome: string;
  cancellation: MyRequestRow["cancellation"];
}) {
  return (
    <div className={cardChrome}>
      <h3 className="subHeading mb-3 fw-bold">Cancellation</h3>
      {cancellation ? (
        <>
          <div className="d-flex justify-content-between text-sm py-1">
            <span className="flight-detail-label">Refunded</span>
            <span className="fw-bold color-text-first">{formatMoney(cancellation.refundAmount, cancellation.currency)}</span>
          </div>
          {Number.parseFloat(cancellation.fee || "0") > 0 && (
            <div className="d-flex justify-content-between text-sm py-1">
              <span className="flight-detail-label">Cancellation fee</span>
              <span className="color-text-black">{formatMoney(cancellation.fee, cancellation.currency)}</span>
            </div>
          )}
          <div className="d-flex justify-content-between text-sm py-2 mt-1 border-top">
            <span className="flight-detail-label">Cancelled on</span>
            <span className="color-text-black">{formatPlainDateTime(cancellation.cancelledAt)}</span>
          </div>
        </>
      ) : (
        <p className="text-sm color-text-black mb-0">This trip was cancelled.</p>
      )}
    </div>
  );
}

/** The refund preview + the actual cancel action, for a still-live trip
 *  (LEIS-1034). Reuses `RequestActions` rather than a second button — that
 *  component already reads `actionsFor(row)` and renders Change alongside
 *  whichever cancel action this trip's `approvalRequired` gives it.
 *
 * The quote is only fetched when a cancel action actually exists — not on a
 * trip with an open linked change/cancellation (actionsFor returns none
 * there), where fetching one would be pure waste. */
function CancellationCard({ row, cardChrome }: { row: MyRequestRow; cardChrome: string }) {
  const canSelfCancel = actionsFor(row).some((a) => a.kind === "cancellation" || a.kind === "cancel_direct");

  const { data: quote } = useQuery({
    queryKey: ["employee-requests", "cancellation-quote", row.id],
    queryFn: async () => {
      const res = await getCancellationQuote(row.id);
      if (!res.success) throw new Error(res.message ?? "Could not load the cancellation quote.");
      return res.data!;
    },
    enabled: canSelfCancel,
    staleTime: 30_000,
  });

  // The one documented exception (LEIS-1034): a flight past its
  // free-cancellation window, on a trip booked with no approval required,
  // has nobody else in the transaction to confirm a guessed refund —
  // `cancelDirect` itself answers 409 MANUAL_REVIEW_REQUIRED here, so the
  // button is hidden rather than offered and left to fail on press. A
  // cancellation *request* (approval required) is unaffected — the admin
  // confirms the amount there, so that action stays offered either way.
  const blockDirectCancel = Boolean(quote && !quote.eligible && !row.approvalRequired);

  return (
    <div className={cardChrome}>
      <h3 className="subHeading mb-3 fw-bold">Cancellation policy</h3>

      {canSelfCancel && quote?.eligible && (
        <div className="mb-3 p-3 rounded-3" style={{ background: "rgba(47,98,113,0.06)" }}>
          <div className="d-flex justify-content-between text-sm">
            <span className="flight-detail-label">Refund if cancelled now</span>
            <span className="fw-bold color-text-first">{formatMoney(quote.refundAmount, quote.currency)}</span>
          </div>
          {Number.parseFloat(quote.fee || "0") > 0 && (
            <div className="d-flex justify-content-between text-sm mt-1">
              <span className="flight-detail-label">Cancellation fee</span>
              <span className="color-text-black">{formatMoney(quote.fee, quote.currency)}</span>
            </div>
          )}
          <p className="text-xs color-text-grey mb-0 mt-2">{quote.note}</p>
        </div>
      )}

      {blockDirectCancel && (
        <>
          <p className="text-sm color-text-black mb-2">{quote!.note}</p>
          <a href={SUPPORT_LINKS.contact} target="_blank" rel="noreferrer" className="text-sm fw-600 color-text-second">
            Contact support to cancel
          </a>
        </>
      )}

      <BookedTripActions row={row} hideKinds={blockDirectCancel ? ["cancel_direct"] : undefined} />
    </div>
  );
}

function Skeleton() {
  return (
    <section className="py-md-5 py-3 booking-detail-listing-section travelContent">
      <div className="container webNewContent" aria-hidden>
        <div className="row">
          <div className="col-lg-8">
            <div className="bgColor-white border shadow-sm rounded-3 p-4 mb-3" style={{ height: 140, opacity: 0.6 }} />
            <div className="bgColor-white border shadow-sm rounded-3 p-4 mb-3" style={{ height: 220, opacity: 0.6 }} />
            <div className="bgColor-white border shadow-sm rounded-3 p-4" style={{ height: 160, opacity: 0.6 }} />
          </div>
          <div className="col-lg-4">
            <div className="bgColor-white shadow-sm rounded-3 p-4" style={{ height: 200, opacity: 0.6 }} />
          </div>
        </div>
      </div>
    </section>
  );
}

function NotFound({ reason }: { reason: string }) {
  return (
    <section className="py-5 booking-detail-listing-section travelContent">
      <div className="container webNewContent text-center">
        <h2 className="subHeading fw-bold mb-2">Booking not found</h2>
        <p className="text-secondary mb-4">{reason}</p>
        <Link href="/my-trips" className="buttons btnColor-first py-2 px-4 text-sm text-uppercase">
          Back to My Trips
        </Link>
      </div>
    </section>
  );
}
