"use client";

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

import {
  useBusinessSession,
  useBusinessSessionReady,
  useBusinessToken,
} from "@/components/employee-requests/use-session";
import { writeBookNowHandoff } from "@/services/employee-requests/book-now-handoff";
import FlightStepNav from "./FlightStepNav";
import {
  STEP_ADDONS,
  STEP_REQUEST,
  STEP_REVIEW,
  STEP_TRAVELER,
  activeStepOf,
  nextStep,
  prevStep,
  stepIdsFor,
  stepIndexOf,
  stepTitlesFor,
} from "@/services/employee-requests/request-steps";
import { useFlightPolicyLimits } from "@/components/flights/FarePolicyBadge";
import { gateFor } from "@/services/employee-requests/fare-policy";
import { airportsFromPair, airportsFromSegments } from "@/services/employee-requests/booking-for";
import { parseItinerary } from "@/services/flights/searchUrl";
import PaneReviewFlight from "./PaneReviewFlight";
import PaneTravelerDetails from "./PaneTravelerDetails";
import PaneAddOns from "./PaneAddOns";
import { PaneRequestApproval, type PaneRequestApprovalHandle } from "./PaneRequestApproval";
import { buildFlightOffer } from "@/services/employee-requests/buildFlightOffer";
import FlightPriceSummary from "./FlightPriceSummary";
import {
  bagSelectionKey,
  bagSelectionsFromState,
  catalogueAmountTotal,
} from "@/services/flights/bags";
import { mapFlightPriceToReviewView } from "@/services/flights/mapper";
import { selfTransferConnectionsRequiringAck } from "@/services/flights/selfTransferCopy";
import { parseFlightError } from "@/services/flights/errors";
import { logger } from "@/lib/logger";
import {
  readFlightRequestDraft,
  writeFlightRequestDraft,
} from "@/services/employee-requests/request-draft";
import type { FlightReviewViewModel } from "@/services/flights/types";
import type { TravelerDetailsFormData } from "@/services/flights/traveler-details.schema";

/**
 * The 4-step corporate flight request (LEIS-961).
 *
 * Ported from leisure-ui's booking wizard of the same name, with Payment
 * replaced by Request approval. The parts that survive unchanged are the ones
 * worth keeping byte-comparable: the panes all stay mounted and are toggled
 * with `d-none` so step state survives navigation, `?step=` is kept in the
 * address bar with `history.replaceState`, and the whole extra-bag pricing
 * machinery below is leisure-ui's.
 *
 * ── What corp removed, and why ──────────────────────────────────────────────
 *
 * **The price lock.** LEIS-963 says the stepper has "no Payment step and no
 * price lock timer". leisure-ui counts down the Redis TTL on the held offer and
 * replaces the whole flow with FlightReviewUnavailable when it runs out,
 * because continuing would only fail at the charge. Nothing here charges, so
 * the countdown would be pressure with no payoff — an employee is filling in a
 * form a human will read later, not racing a payment window.
 *
 * The offer can still go away; it just is not a clock on screen. The real
 * re-price happens when the ADMIN approves (PRD §9.1: "it books at the current
 * price, even if it has gone up since submission"), so a stale fare here costs
 * a corrected figure at approval, not a failed booking. The one path that CAN
 * discover the offer is gone — Price #2, when bags are added — reports it
 * inline on the add-ons step, where the employee is acting.
 *
 * **PanePayment and everything under it** — card tokenisation, the charge, the
 * order-create poll, the inline sign-in prompt. An employee never pays; the
 * company card is charged automatically after approval and they never see it.
 *
 * **The campaign funnel events.** leisure-ui fires ADD_ONS_SELECTED and
 * TRAVELER_DETAILS_SUBMITTED with `revenueAmount` on this screen. A request is
 * not revenue and may never become any, so firing them would put non-revenue
 * into the booking funnel's own numbers. Left out deliberately rather than
 * guessed at — if Business mode wants funnel analytics it needs its own events.
 */

/** Review Flight · Traveler Details · Add-ons · Request approval. */
const LAST_STEP = STEP_REQUEST;

/** Debounce before firing a background Price #2 after the last bag toggle. */
const BAG_PRICE_DEBOUNCE_MS = 700;

/**
 * What the add-on rows on a priced offer come to, as a number.
 *
 * This is the hinge of the whole money model on this screen, because of
 * something search-service does that is easy to miss: **Price #2 writes the
 * re-priced offer back into the clientRef's stored session.** So after a single
 * bag is added, a later `GET /flights/reviews` for the same clientRef no longer
 * returns the bare itinerary — it returns `grandTotal` WITH the bag in it, plus
 * an `additionalServices` row naming the bag.
 *
 * On a reload that means `initialReview.grandTotal` is not the fare. Treating
 * it as one was a real, measured bug: the restored bag selection was added on
 * top of a total that already contained it, and a $640.80 trip with one $131
 * bag came back as $902.80. It would also have fed a bag-inflated fare into the
 * PRD §7 maximum-fare check, which is the exact thing `fare` is defined to
 * exclude.
 *
 * Verified against the live service: GET after a bags call returns
 * `grandTotal 771.80`, `total 640.80`, `additionalServices [{131.00,
 * CHECKED_BAGS}]`.
 */
function addOnsTotalOf(review: FlightReviewViewModel): number {
  const lines = review.passengerBreakdown?.addOns ?? [];
  return lines.reduce((sum, line) => {
    const amount = Number.parseFloat(line.amount || "0");
    return sum + (Number.isFinite(amount) ? amount : 0);
  }, 0);
}

/**
 * The bag picks the SERVER's stored offer already reflects.
 *
 * The offer is the only honest source for this. The sessionStorage draft covers
 * a reload in the same tab, but sessionStorage is per-tab: open the same link in
 * a second tab and the draft is simply not there, while the stored offer still
 * carries the bag somebody added. Trusting the draft alone left that tab showing
 * a total with a bag in it, zero bags selected, and a step-4 summary reporting
 * "Extra bags: 0 · additional cost $0.00" — understating the request by exactly
 * the bag, which an approver would then be asked to approve.
 *
 * Amadeus states it per traveller per segment as
 * `travelerPricings[].fareDetailsBySegment[].additionalServices
 * .chargeableCheckedBags.quantity`. The add-ons catalogue is keyed the same way,
 * so matching that quantity back to an option id is deterministic and needs no
 * extra API call. The highest quantity across a traveller's segments wins: a
 * selection is bought for the journey, and a leg that did not get it is missing
 * data rather than a different choice.
 */
function bagSelectionsFromOffer(review: FlightReviewViewModel): Record<string, string> {
  const quantities = new Map<string, number>();
  for (const offer of review.flightOffers ?? []) {
    const pricings = (offer as { travelerPricings?: unknown[] }).travelerPricings ?? [];
    for (const pricing of pricings) {
      const p = pricing as {
        travelerId?: string;
        fareDetailsBySegment?: Array<{
          additionalServices?: { chargeableCheckedBags?: { quantity?: number } };
        }>;
      };
      const travelerId = String(p.travelerId ?? "");
      if (!travelerId) continue;
      for (const segment of p.fareDetailsBySegment ?? []) {
        const qty = segment?.additionalServices?.chargeableCheckedBags?.quantity;
        if (typeof qty !== "number" || qty <= 0) continue;
        quantities.set(travelerId, Math.max(quantities.get(travelerId) ?? 0, qty));
      }
    }
  }
  if (quantities.size === 0) return {};

  const selections: Record<string, string> = {};
  for (const traveler of review.addOns.travelers ?? []) {
    const wanted = quantities.get(traveler.travelerId);
    if (!wanted) continue;
    for (const group of traveler.groups ?? []) {
      const option = group.options.find((o) => o.quantity === wanted);
      if (option) selections[bagSelectionKey(traveler.travelerId, group.groupId)] = option.id;
    }
  }
  return selections;
}

/**
 * Per-step copy for the sticky summary rail.
 *
 * Two deliberate departures from leisure-ui's wording:
 *
 *   totalLabel  "Total (est.)" everywhere, not "Total Amount to be paid" /
 *               "Grand Total" / "Total Payable". Nobody on this screen is
 *               paying anything, and the figure genuinely is an estimate — the
 *               fare is re-priced at approval. "Total (est.)" is also the PRD's
 *               own term for it (§6.5).
 *   step 3's    "Review request", per the brief: it opens the summary where the
 *   nextLabel   business reason is given and the request is actually filed.
 */
const STEP_META = [
  {
    title: "Price Breakup",
    nextLabel: "Continue with Travel Details",
    totalLabel: "Total (est.)",
    footerNote: "Your company admin reviews this request before anything is booked",
  },
  {
    title: "Traveler Summary",
    nextLabel: "Continue to Add-ons",
    totalLabel: "Total (est.)",
    footerNote: "Review traveller details before continuing",
  },
  {
    title: "Add-ons Summary",
    nextLabel: "Review request",
    totalLabel: "Total (est.)",
    footerNote: "You can skip add-ons and continue",
  },
  {
    title: "Request Summary",
    nextLabel: "Submit for approval",
    totalLabel: "Total (est.)",
    footerNote: "",
  },
] as const;

export default function FlightReviewMultiClient({
  review: initialReview,
  initialStep = 0,
  backHref,
  bookingFor = null,
}: {
  review: FlightReviewViewModel;
  initialStep?: number;
  /** Where Back from step 1 goes; already validated by the page. */
  backHref?: string;
  /** The colleague this request is for, or null for the employee themselves. */
  bookingFor?: string | null;
}) {
  const clientRef = initialReview.clientRef;

  // Read once, synchronously, from the lazy initialiser — never in an effect.
  // A setState-in-an-effect here is both the shape the React Compiler rejects
  // in corp's own code and a visible flash of the empty form before the draft
  // lands. Safe to touch storage during render because this component is only
  // ever reached from FlightReviewLoader's client-side fetch, so it never
  // server-renders.
  const [draft] = useState(() => readFlightRequestDraft(clientRef, bookingFor));

  const [currentStep, setCurrentStep] = useState(initialStep);
  /**
   * The offer wins over the draft.
   *
   * Both describe the same thing, but only the offer is shared across tabs and
   * only the offer is what the fare on screen was actually priced for. The
   * draft is the fallback for the case the offer cannot express — bags picked,
   * Price #2 not yet confirmed when the tab was closed.
   */
  const [bagSelections, setBagSelections] = useState<Record<string, string>>(() => {
    const fromOffer = bagSelectionsFromOffer(initialReview);
    return Object.keys(fromOffer).length > 0 ? fromOffer : (draft.bagSelections ?? {});
  });
  // Extra-bag pricing (Price #2), debounced on selection:
  //  - pricedReview   : the confirmed Price #2 view model, or null
  //  - optimisticTotal: client estimate (base + catalogue sum) shown instantly
  //                     on a toggle, replaced by the confirmed total when it lands
  //  - bagsPending    : a debounced / background confirm is scheduled or running
  //  - confirmingBags : a blocking confirm (from "Review request") is running
  const [pricedReview, setPricedReview] = useState<FlightReviewViewModel | null>(null);
  const [optimisticTotal, setOptimisticTotal] = useState<string | null>(null);
  const [bagsPending, setBagsPending] = useState(false);
  const [confirmingBags, setConfirmingBags] = useState(false);
  const [bagsError, setBagsError] = useState<string | null>(null);
  /**
   * What step 2 validated, kept for step 4.
   *
   * LEIS-964: these values — not the saved profile — become the request's
   * `traveler_profile_snapshot`.
   */
  const [travelerSubmission, setTravelerSubmission] = useState<TravelerDetailsFormData | null>(
    () => draft.travelers ?? null
  );
  // LEIS-930 ticket B6 — set the moment the employee ticks the box on step 1;
  // null means "not yet acknowledged". An ISO timestamp rather than a bool
  // because that is the value stored with the booking.
  const [selfTransferAckAt, setSelfTransferAckAt] = useState<string | null>(null);
  /** Step 4 is sending — the rail shows it and locks both buttons. */
  const [submittingRequest, setSubmittingRequest] = useState(false);
  /** Lets the Book Now button reuse PaneRequestApproval's own business-info
   *  fields instead of asking for them again on /flight-checkout. */
  const approvalFormRef = useRef<PaneRequestApprovalHandle>(null);
  /** Book Now's own brief busy state, while it validates the business-info
   *  fields above before navigating — distinct from `submittingRequest`,
   *  which is the Request-approval rail's. */
  const [bookNowPending, setBookNowPending] = useState(false);

  /**
   * The itinerary fare with any already-applied bags taken back off.
   *
   * On a first visit this is just `grandTotal`. On a reload after a bag was
   * priced it is `grandTotal` minus the add-on rows — see addOnsTotalOf. Every
   * downstream figure is built from THIS, never from `grandTotal` directly.
   */
  const baseFareExclBags = useMemo(() => {
    const total = Number.parseFloat(initialReview.grandTotal || "0");
    const bags = addOnsTotalOf(initialReview);
    return Math.max(0, Number(((Number.isFinite(total) ? total : 0) - bags).toFixed(2)));
  }, [initialReview]);

  /**
   * Was the restored draft already priced by the server?
   *
   * The stored offer carries the LAST Price #2 result. If its add-on total
   * matches what the restored selections cost in the catalogue, that priced
   * offer IS this selection's price — so the initial review doubles as the
   * confirmed one and no re-price is fired. If they disagree (the draft was
   * written and the tab closed mid-debounce), it stays unconfirmed and the
   * normal debounce re-prices it. Self-correcting either way.
   */
  const restored = useMemo(() => {
    const fromOffer = bagSelectionsFromOffer(initialReview);
    const seeded =
      Object.keys(fromOffer).length > 0 ? fromOffer : (draft.bagSelections ?? {});
    const selections = bagSelectionsFromState(seeded);
    if (selections.length === 0) return null;
    const bags = addOnsTotalOf(initialReview);
    if (bags <= 0) return null;
    const catalogue = initialReview.addOns.travelers.flatMap((t) =>
      t.groups.flatMap((g) => g.options)
    );
    const expected = catalogueAmountTotal(selections, catalogue);
    if (Math.abs(expected - bags) > 0.01) return null;
    return JSON.stringify(selections);
    // draft is fixed for this component's life.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialReview]);

  // JSON of the selections the confirmed pricedReview reflects — so an
  // unchanged pick is not re-priced; reset to "" on any change. Seeded from the
  // restored draft so a reload does not re-price what the server already has.
  const pricedForRef = useRef<string>(restored ?? "");
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const abortRef = useRef<AbortController | null>(null);

  const router = useRouter();

  /**
   * Business mode only — the same guard My requests uses.
   *
   * Read as an external store so there is no "checking…" render and no
   * setState in an effect; the redirect is a real side effect and stays in
   * one. `sessionReady` matters: without it a cold load bounces a signed-in
   * employee to sign-in, because the token cannot be read until hydration has
   * handed over. The whole step-2 prefill and the submit are scoped to this
   * token, so an unauthenticated visitor could otherwise fill in four steps
   * and only then be told to sign in.
   */
  const token = useBusinessToken();
  const sessionReady = useBusinessSessionReady();
  const session = useBusinessSession();
  const isAdmin = session?.role === "ADMIN";
  useEffect(() => {
    if (sessionReady && token === null) {
      const next = `${window.location.pathname}${window.location.search}`;
      router.replace(`/employee-login?next=${encodeURIComponent(next)}`);
    }
  }, [sessionReady, token, router]);

  // Flat bag catalogue (option id -> amount) for the optimistic estimate.
  const bagCatalogue = useMemo(
    () => initialReview.addOns.travelers.flatMap((t) => t.groups.flatMap((g) => g.options)),
    [initialReview.addOns]
  );

  // Everything downstream reads this:
  //  - Price #2 confirmed: take its money fields + re-priced offer, but KEEP the
  //    Price #1 `addOns` catalogue — Amadeus re-issues bag-option ids on Price #2
  //    and `bagSelections` is keyed on the Price #1 ids, so swapping the whole
  //    catalogue would visually deselect the employee's picks.
  //  - Otherwise: base view, with an optimistic grand total if bags are picked.
  const review = useMemo<FlightReviewViewModel>(() => {
    if (pricedReview) {
      return {
        ...initialReview,
        base: pricedReview.base,
        grandTotal: pricedReview.grandTotal,
        taxesTotal: pricedReview.taxesTotal,
        feesTotal: pricedReview.feesTotal,
        taxLines: pricedReview.taxLines,
        feeLines: pricedReview.feeLines,
        pricePerAdult: pricedReview.pricePerAdult,
        flightOffers: pricedReview.flightOffers,
        // Price #2 re-priced with the bags on board, so its breakdown already
        // carries them as additionalServices — take it wholesale.
        passengerBreakdown: pricedReview.passengerBreakdown,
      };
    }
    if (optimisticTotal != null) {
      // Bags picked, Price #2 not back yet. The passenger rows stay on the last
      // figures Amadeus actually confirmed — adding a bag does not change a fare
      // — and only the add-on row and the total carry the estimate.
      //
      // Measured against `baseFareExclBags`, not `grandTotal`: after a reload
      // the latter already contains a previously priced bag, and subtracting it
      // here would under-report the estimate by exactly that amount.
      const estimatedAddOn = (Number.parseFloat(optimisticTotal) - baseFareExclBags).toFixed(2);
      const base = initialReview.passengerBreakdown;
      return {
        ...initialReview,
        grandTotal: optimisticTotal,
        passengerBreakdown: base
          ? {
              ...base,
              // Same wording the confirmed CHECKED_BAGS row uses, so the label
              // does not change under the employee when Price #2 lands.
              addOns:
                Number.parseFloat(estimatedAddOn) > 0
                  ? [{ label: "Checked bags", amount: estimatedAddOn }]
                  : [],
              residual: "0.00",
              grandTotal: optimisticTotal,
            }
          : undefined,
      };
    }
    return initialReview;
  }, [pricedReview, optimisticTotal, initialReview, baseFareExclBags]);

  /**
   * The bag figures step 4 submits (LEIS-966: `extra_bags`, `extra_bags_cost`,
   * `additional_cost` = the bag cost).
   *
   * Quantity is summed off the catalogue, NOT off the number of selections: one
   * selection can be the "2 extra bags" option, so counting rows would report 1.
   *
   * The cost prefers the confirmed Price #2 delta and falls back to the
   * catalogue sum, which is what the employee is looking at while a re-price is
   * still in flight. `ensureBagsPriced` means the confirmed figure is the one
   * that actually reaches step 4.
   *
   * NOTE the money rule this half implements and step 4 completes: `fare` is the
   * Price #1 itinerary total with bags EXCLUDED — the only correct basis for the
   * PRD §7 maximum-fare check — and the bag cost rides separately as
   * `additionalCost`, so `estTotal = fare + bags`. Reporting Price #2's
   * grandTotal as the fare would double-count the bags in estTotal and could
   * push an in-policy request over its group's limit.
   */
  const bagSummary = useMemo(() => {
    const selections = bagSelectionsFromState(bagSelections);
    const byId = new Map(bagCatalogue.map((option) => [option.id, option]));
    const quantity = selections.reduce(
      (sum, sel) => sum + (byId.get(sel.optionId)?.quantity ?? 0),
      0
    );
    const catalogueCost = catalogueAmountTotal(selections, bagCatalogue);
    // The confirmed figure is the priced offer's own add-on rows, not a
    // subtraction against grandTotal — after a reload grandTotal already holds
    // a bag, so a delta would come out at zero for a selection that costs $131.
    const confirmed = pricedReview ? addOnsTotalOf(pricedReview) : null;
    const cost = confirmed != null && Number.isFinite(confirmed) ? confirmed : catalogueCost;
    return {
      quantity,
      cost: Math.max(0, Number(cost.toFixed(2))),
      /** The fare the policy check is judged on — bags excluded, always. */
      fare: baseFareExclBags.toFixed(2),
      confirmed: pricedReview != null || selections.length === 0,
    };
  }, [bagSelections, bagCatalogue, pricedReview, baseFareExclBags]);

  /**
   * The request payload for step 4, built from the PRICED offer.
   *
   * `buildFlightOffer` normally reads the SRP's display shape; here there is
   * none — the employee may have arrived by a link — so it is handed the raw
   * Amadeus offers from Price #1/#2 instead, plus the two things those offers
   * cannot tell it:
   *
   *   fareOverride  the bag-free fare. Once Price #2 has run, the stored
   *                 offer's grandTotal INCLUDES the bags, and `fare` must not —
   *                 PRD §7 judges the group's maximum on the itinerary alone.
   *   airlineName   the readable carrier, which the raw offer has only as a code.
   *
   * Rebuilt whenever the priced offer or the bags change, so the summary, the
   * policy preview and the submit always describe the same trip.
   */
  const requestOffer = useMemo(() => {
    const offers = review.flightOffers;
    if (!offers || offers.length === 0) return null;
    const built = buildFlightOffer({
      selectedOffers: offers,
      fareOverride: baseFareExclBags,
      airlineName: review.itineraries?.[0]?.carrierName ?? null,
      addOns: {
        extraBags: bagSummary.quantity,
        extraBagsCost: bagSummary.cost,
        fareOption: review.fareType || null,
      },
    });
    return built.ok ? built.offer : null;
  }, [review.flightOffers, review.itineraries, review.fareType, baseFareExclBags, bagSummary]);

  /**
   * Which steps this traveller's group actually has (LEIS-984).
   *
   * Add-ons is dropped when Extra baggage is Off: there are no paid bags to
   * add, and an empty step is worse than no step. The route comes from the
   * priced offer rather than the URL — `/flight-request` carries no
   * `itinerary` param, and an empty airport list resolves to the stricter
   * International tab, which would read the wrong tab's gate on a domestic
   * trip.
   *
   * While the gate is unknown — loading, or no business session — Add-ons
   * STAYS. The list can then only ever shrink, never grow, and it cannot
   * shrink under someone already standing on the step: reaching Add-ons means
   * passing a form first, by which time the gate has long resolved. Defaulting
   * the other way would pop a new step into a stepper mid-flow.
   */
  const policyAirports = useMemo(() => {
    // The priced offer is the authority, but it is null for the first render
    // or two while Price #1 runs — and an empty airport list is a DIFFERENT
    // react-query key, so the gate would start as a separate in-flight request
    // and the stepper would render its default (Add-ons shown) until it
    // landed. `backHref` is the SRP URL this page was reached from and carries
    // the itinerary, so the route is known from render 1 and the key matches
    // the entry the SRP already cached.
    const fromOffer = airportsFromPair(requestOffer?.origin, requestOffer?.destination);
    if (fromOffer.length > 0) return fromOffer;
    if (!backHref) return [];
    const itinerary = new URLSearchParams(backHref.split("?")[1] ?? "").get("itinerary");
    return airportsFromSegments(parseItinerary(itinerary));
  }, [requestOffer?.origin, requestOffer?.destination, backHref]);

  const policyLimits = useFlightPolicyLimits({
    travelerId: bookingFor,
    airports: policyAirports,
  });
  const addOnsAllowed = gateFor(policyLimits)?.extraBaggageAllowed ?? true;

  /**
   * Does this traveller's group need approval for this trip (LEIS-983)?
   *
   * Decides what step 4 is: "Request approval", which files it for the admin,
   * or "Checkout", which charges a company card and books it.
   *
   * Defaults to TRUE while the gate is unknown — loading, or no business
   * session. Approval is the conservative answer: showing the request form to
   * somebody who could have paid directly wastes a step, while showing a
   * payment form to somebody whose group requires approval would invite them
   * to charge a card they are not meant to use, and the server would refuse it
   * anyway.
   *
   * Always FALSE for an admin (LEIS-1004), regardless of the gate above — the
   * gate reads the TRAVELLER's group, which has a real answer for an employee
   * booking themselves or a colleague, but means nothing for an admin booking
   * company-wide: there is no one above an admin to approve anything, and the
   * backend (`payDirect`/`payDirectHotel`) already bypasses this same gate
   * unconditionally once the request gets there — this just stops the page
   * from showing "Submit for approval" and sending an admin into their own
   * approval queue to begin with.
   */
  const approvalRequired = isAdmin ? false : (gateFor(policyLimits)?.approvalRequired ?? true);

  const stepIds = useMemo(() => stepIdsFor(addOnsAllowed), [addOnsAllowed]);
  const stepIndex = stepIndexOf(stepIds, currentStep);

  /**
   * The step actually being shown.
   *
   * Every read below goes through this rather than `currentStep`, because the
   * two can disagree: `?step=2` is restored from the URL before the gate is
   * known, and on a group with Extra baggage off there is no step 2 to show.
   * Reading the raw value would render the Add-ons pane that the stepper does
   * not list and that `advance()` will never reach.
   */
  const activeStep = activeStepOf(stepIds, currentStep);

  const meta = (() => {
    const base = STEP_META[activeStep];
    // "Continue to Add-ons" is a lie when Add-ons is not in this group's flow.
    if (activeStep === STEP_TRAVELER && !addOnsAllowed) {
      return { ...base, nextLabel: STEP_META[STEP_ADDONS].nextLabel };
    }
    // Step 4 is always Request approval now (LEIS-1010) — Book Now is a
    // separate, parallel action with its own trigger and dialog, not
    // something the rail drives or relabels itself for.
    return base;
  })();

  // LEIS-930 — Level 2/3 self-transfer connections needing the checkbox on
  // step 1. Empty means nothing to acknowledge (Level 1 only, or none).
  const requiredSelfTransferConnections = useMemo(
    () => selfTransferConnectionsRequiringAck(review),
    [review]
  );
  const selfTransferAckRequired = requiredSelfTransferConnections.length > 0;

  // Abort any in-flight / scheduled Price #2 on unmount.
  useEffect(
    () => () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
      abortRef.current?.abort();
    },
    []
  );

  // Keep ?step= in the address bar so a reload lands back on this step instead
  // of resetting to Review Flight. history.replaceState, not next/navigation:
  // this page is force-dynamic, so a router.replace here would re-fetch the
  // route and re-run Amadeus Price on every single step change — exactly the
  // kind of extra call that trips Amadeus's rate limit.
  useEffect(() => {
    if (typeof window === "undefined") return;
    const url = new URL(window.location.href);
    const stepInUrl = Number.parseInt(url.searchParams.get("step") ?? "0", 10) || 0;
    if (stepInUrl === activeStep) return;
    if (activeStep === 0) {
      url.searchParams.delete("step");
    } else {
      url.searchParams.set("step", String(activeStep));
    }
    window.history.replaceState(null, "", `${url.pathname}${url.search}`);
    // `activeStep`, not `currentStep`: the two diverge when the gate resolves
    // and clamps a `?step=2` that this group has no Add-ons step for, and the
    // URL has to follow what is actually on screen.
  }, [activeStep]);

  /**
   * Price #2 — POST /api/flights/add-ons. search-service injects the chosen
   * chargeableCheckedBags onto the offer, re-prices via Amadeus, and returns
   * the confirmed grandTotal + price.additionalServices. Aborts any prior call.
   * `blocking` = triggered from "Review request" (shows "Confirming…");
   * otherwise a background refresh (shows "Updating price…").
   */
  async function priceBags(
    selections: ReturnType<typeof bagSelectionsFromState>,
    key: string,
    blocking: boolean
  ): Promise<boolean> {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    // This call owns the loading state — set both flags to their value for it,
    // so a background refresh that supersedes a blocking confirm clears it too.
    setConfirmingBags(blocking);
    setBagsPending(!blocking);
    setBagsError(null);
    try {
      const res = await fetch("/api/flights/add-ons", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        signal: controller.signal,
        body: JSON.stringify({
          clientRef,
          flightOffers: initialReview.flightOffers,
          bagsIncluded: initialReview.bagsIncluded,
          selections,
        }),
      });
      if (controller.signal.aborted) return false;
      const json = (await res.json().catch(() => ({}))) as {
        success?: boolean;
        data?: unknown;
        errors?: string[];
      };
      if (!res.ok || json.success !== true || !json.data) {
        // errors[0] can carry upstream text ("Amadeus Flight Error: ..."), so
        // go through the taxonomy: it shows written copy and keeps the raw
        // string in `detail` for the log. Rendered inline in the add-ons pane
        // rather than as a toast — the employee is acting right there, and an
        // in-context message beats one in the corner of the screen.
        const flightError = await parseFlightError(res, json);
        logger.error("[FlightReviewMultiClient] bag pricing failed", {
          code: flightError.code,
          detail: flightError.detail,
        });
        setBagsError(flightError.message);
        return false;
      }
      const nextView = mapFlightPriceToReviewView(
        json.data as Parameters<typeof mapFlightPriceToReviewView>[0]
      );
      setPricedReview(nextView);
      setOptimisticTotal(null);
      pricedForRef.current = key;
      return true;
    } catch (err) {
      if (controller.signal.aborted || (err as Error)?.name === "AbortError") return false;
      setBagsError("Could not confirm extra bags. Please try again.");
      return false;
    } finally {
      // Only the current (not superseded) call clears the loading flags.
      if (abortRef.current === controller) {
        abortRef.current = null;
        setConfirmingBags(false);
        setBagsPending(false);
      }
    }
  }

  // Debounced background re-price whenever the bag picks change.
  useEffect(() => {
    const selections = bagSelectionsFromState(bagSelections);
    const key = JSON.stringify(selections);

    // Mirrored to the draft on every change, not only on a confirmed price: a
    // reload mid-debounce must not come back with different bags than the ones
    // on screen.
    writeFlightRequestDraft(clientRef, bookingFor, { bagSelections });

    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
      debounceRef.current = null;
    }

    // Same as the last confirmed pick — nothing to do.
    if (key === pricedForRef.current) {
      setOptimisticTotal(null);
      setBagsPending(false);
      return;
    }

    // Any change invalidates the last confirmed Price #2.
    setPricedReview(null);
    setBagsError(null);

    if (selections.length === 0) {
      // No bags => no API; the Price #1 offer stands.
      setOptimisticTotal(null);
      setBagsPending(false);
      pricedForRef.current = key;
      return;
    }

    // Show a client estimate immediately, confirm in the background. Built on
    // the bag-free fare so a reload that restored an already-priced bag does
    // not add it a second time.
    const estimate = (baseFareExclBags + catalogueAmountTotal(selections, bagCatalogue)).toFixed(2);
    setOptimisticTotal(estimate);
    setBagsPending(true);

    debounceRef.current = setTimeout(() => {
      debounceRef.current = null;
      void priceBags(selections, key, false);
    }, BAG_PRICE_DEBOUNCE_MS);

    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
        debounceRef.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [bagSelections]);

  /**
   * "Review request" — make sure the current bag pick is confirmed by Price #2
   * (or is a genuine no-op) before advancing. Returns true when the step may
   * go on.
   *
   * This is the one gate that must not be skipped: step 4 submits a figure an
   * admin approves money against, so it has to be a price Amadeus actually
   * quoted rather than the client's catalogue arithmetic.
   */
  async function ensureBagsPriced(): Promise<boolean> {
    const selections = bagSelectionsFromState(bagSelections);
    const key = JSON.stringify(selections);
    if (key === pricedForRef.current) return true;
    if (selections.length === 0) {
      setPricedReview(null);
      setOptimisticTotal(null);
      pricedForRef.current = key;
      return true;
    }
    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
      debounceRef.current = null;
    }
    return priceBags(selections, key, true);
  }

  /** Forward along the steps this group actually has — so a group with Extra
   *  baggage off goes Traveler Details → Request approval, skipping Add-ons. */
  function advance() {
    setCurrentStep(nextStep(stepIds, currentStep));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function goNext() {
    // Traveler Details — hand off to the form. It validates, and its
    // `traveler-form-valid` event advances the step (listener below), so an
    // incomplete form cannot be walked past.
    if (activeStep === STEP_TRAVELER) {
      const form = document.getElementById("traveler-details-form") as HTMLFormElement | null;
      form?.requestSubmit();
      return;
    }

    // Add-ons — the bag picks must be confirmed by Price #2 before the summary.
    if (activeStep === STEP_ADDONS) {
      const ok = await ensureBagsPriced();
      if (!ok) return;
      advance();
      return;
    }

    // Request approval — the same requestSubmit() hand-off step 2 uses. The
    // pane owns the submit, the validation and where it navigates next; the
    // rail just presses its button, so there is one submit path and not two.
    // Always "request-approval-form" now (LEIS-1010) — PaneRequestApproval is
    // the only thing the rail ever drives; Book Now is a separate action with
    // its own dialog and its own (visible) submit button.
    if (activeStep >= LAST_STEP) {
      const form = document.getElementById("request-approval-form") as HTMLFormElement | null;
      form?.requestSubmit();
      return;
    }

    advance();
  }

  function goPrev() {
    if (activeStep === STEP_REVIEW) {
      // Back to the exact results they came from, which carries `bookingFor`
      // in its query string — rebuilding a bare /srp/flights here would
      // silently re-point the next request at whoever clicked. `backHref` is
      // already validated by the page; the fallback is for a pasted link.
      router.push(backHref ?? "/srp/flights");
      return;
    }
    setCurrentStep(prevStep(stepIds, currentStep));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function handleBookNow() {
    if (!requestOffer || bookNowPending) return;
    setBookNowPending(true);
    // The SAME business-info fields PaneRequestApproval owns, validated on
    // THIS form rather than asked for a second time on /flight-checkout —
    // see book-now-handoff.ts's own doc comment on why.
    const business = await approvalFormRef.current?.getValidBusinessInfo();
    setBookNowPending(false);
    if (!business) return;
    // Book Now is a full page (LEIS-1010), not an overlay — there is no
    // request id yet to route by (payDirect() creates one only after the
    // charge succeeds), so the offer rides over via sessionStorage instead
    // of a URL.
    writeBookNowHandoff(clientRef, bookingFor, {
      offer: requestOffer,
      bagCost: bagSummary.cost,
      extraBags: bagSummary.quantity,
      travelers: travelerSubmission,
      business,
    });
    const params = new URLSearchParams({ clientRef });
    if (bookingFor) params.set("bookingFor", bookingFor);
    router.push(`/flight-checkout?${params.toString()}`);
  }

  // Step 2 advances from here rather than from the button, so a failed
  // validation is never counted as progress. The payload is kept for step 4
  // and mirrored into the draft so a reload does not lose a whole party.
  useEffect(() => {
    const controller = new AbortController();
    document.addEventListener(
      "traveler-form-valid",
      (event) => {
        const detail = (event as CustomEvent<TravelerDetailsFormData>).detail;
        if (detail) {
          setTravelerSubmission(detail);
          writeFlightRequestDraft(clientRef, bookingFor, { travelers: detail });
        }
        setCurrentStep(nextStep(stepIds, STEP_TRAVELER));
        window.scrollTo({ top: 0, behavior: "smooth" });
      },
      { signal: controller.signal }
    );
    return () => controller.abort();
    // clientRef/bookingFor are fixed for this component's life — the page keys
    // on both, so a change remounts rather than re-running this.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <section className="py-md-5 py-3 booking-detail-listing-section">
      <div className="container webNewContent travelContent">
        <div className="row">
          <div className="col-12 mb-3">
            <FlightStepNav
              steps={stepTitlesFor(stepIds)}
              currentStep={stepIndex}
              locked={submittingRequest}
              // Backwards only, and the panes all stay mounted, so stepping
              // back is exactly what Back does — nothing to re-validate and
              // nothing lost (LEIS-963: "completed steps can be revisited").
              //
              // The stepper speaks in positions; this maps back to the step id.
              onStepSelect={(index) => {
                setCurrentStep(stepIds[index]);
                window.scrollTo({ top: 0, behavior: "smooth" });
              }}
            />
          </div>
        </div>

        <div className="row my-3">
          <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-8 col-12">
            <div className={activeStep === STEP_REVIEW ? undefined : "d-none"}>
              <PaneReviewFlight
                review={review}
                selfTransferConnections={requiredSelfTransferConnections}
                selfTransferAcknowledged={selfTransferAckAt !== null}
                onSelfTransferAcknowledgedChange={(checked) =>
                  setSelfTransferAckAt(checked ? new Date().toISOString() : null)
                }
                // corp (LEIS-981). The SAME payload step 4 previews and
                // submits, so the two steps cannot word the trip differently —
                // `fare` excludes bags on both, which is what the fare cap is
                // judged on.
                policyOffer={requestOffer}
                policyLimits={policyLimits}
                policyCurrency={review.currency}
              />
            </div>
            <div className={activeStep === STEP_TRAVELER ? undefined : "d-none"}>
              <PaneTravelerDetails
                review={review}
                bookingFor={bookingFor}
                draftTravelers={draft.travelers}
              />
            </div>
            <div className={activeStep === STEP_ADDONS ? undefined : "d-none"}>
              {bagsError ? (
                <div className="alert alert-danger py-2 px-3 text-sm mb-3" role="alert">
                  {bagsError}
                </div>
              ) : null}
              <PaneAddOns
                review={review}
                selections={bagSelections}
                onSelectionChange={(key, optionId) =>
                  // The [bagSelections] effect handles the debounced re-price,
                  // the optimistic total, the draft write, and clearing the
                  // stale confirmed view.
                  setBagSelections((prev) => ({ ...prev, [key]: optionId }))
                }
              />
            </div>
            <div className={activeStep === STEP_REQUEST ? undefined : "d-none"}>
              {/* LEIS-1010: Request approval is always the pane here, for
                  every group. A group with no approval requirement ALSO gets
                  a Book Now action, shown in the price rail directly below
                  Submit rather than under this form. */}
              <PaneRequestApproval
                offer={requestOffer}
                travelers={travelerSubmission}
                contact={travelerSubmission?.contact ?? null}
                bookingFor={bookingFor}
                currencySymbol={review.currencySymbol}
                bagCost={bagSummary.cost}
                clientRef={clientRef}
                onSubmitting={setSubmittingRequest}
                formRef={approvalFormRef}
              />
            </div>
          </div>

          <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-12 mt-3 mt-md-0 d-flex flex-column gap-3">
            <FlightPriceSummary
              review={review}
              nextLabel={meta.nextLabel}
              footerNote={meta.footerNote}
              stepTitle={meta.title}
              totalLabel={meta.totalLabel}
              // Never disabled, unlike leisure-ui, which disables Back on step
              // 0 and so makes its own `goPrev` branch for that step
              // unreachable. Here it is the way back to the exact results the
              // employee came from, which is the only thing carrying their
              // `bookingFor` selection. A bag re-price is recoverable, so it
              // does not lock the step either — leisure-ui only locks Back
              // mid-charge, and there is no charge here.
              // The one exception: a submit in flight must not be walked out
              // of, because the request may already exist by the time Back
              // lands. A bag re-price is recoverable; this is not.
              prevDisabled={submittingRequest}
              nextDisabled={
                confirmingBags ||
                submittingRequest ||
                // LEIS-930 ticket B6 — "Continue stays disabled until the box is
                // ticked", scoped to step 1 only. Once given, the
                // acknowledgement carries forward; later steps are never
                // re-gated on it.
                (activeStep === STEP_REVIEW && selfTransferAckRequired && selfTransferAckAt === null)
              }
              priceNote={
                submittingRequest
                  ? "Sending your request…"
                  : confirmingBags
                    ? "Confirming extra bags…"
                  : bagsPending
                    ? "Updating price…"
                    : pricedReview
                      ? undefined
                      : optimisticTotal != null
                        ? "Estimated — confirmed before you submit"
                        : undefined
              }
              onPrev={goPrev}
              onNext={goNext}
              showBookNow={activeStep === STEP_REQUEST && !approvalRequired}
              bookNowPending={bookNowPending}
              onBookNow={() => void handleBookNow()}
              // An admin's "Request approval" action at the final step would
              // file into their own approval queue, which the server already
              // refuses — see approvalRequired's own doc comment above.
              hideNext={activeStep === STEP_REQUEST && isAdmin}
              bookNowNote={
                isAdmin
                  ? "You're booking directly as an admin — this charges the company card right away, no approval needed."
                  : undefined
              }
            />
          </div>
        </div>
      </div>
    </section>
  );
}
