'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { bumpSearchTrigger, setAwaitingReturnDate, setHasOutboundSelection, supersedeResults } from '@/store/slices/flightSearch.slice';
import { addDays, formatDateToYYYYMMDD, parseDateOnlyAsLocal } from '@/utils/date';
import { setCookie } from '@/utils/cookies';
import {
  buildOriginCookie,
  ORIGIN_COOKIE,
  ORIGIN_COOKIE_DAYS,
} from '@/services/flights/originCookie';
import {
  DEFAULT_DEST,
  DEFAULT_ORIGIN,
  EMPTY_LOCATION,
  defaultDestinationFor,
  type FlightLocationData,
} from '@/services/flights/search.types';
import {
  adultsSummary,
  clampPassengers,
  companionsSummary,
  type PassengerData,
} from '@/services/flights/passengers';
import {
  SRP_FLIGHTS_PATH,
  buildSearchUrl,
  CABIN_LABELS,
  decodeCabinClass,
  parseChildren,
  parseInfants,
  parseItinerary,
  tripTypeFromParams,
  type CabinClass,
  type ItinerarySegment,
  type TripType,
} from '@/services/flights/searchUrl';
import { BookingForField } from '@/components/booking-for/BookingForField';
import {
  BOOKING_FOR_PARAM,
  airportsFromPair,
  airportsFromSegments,
  parseBookingFor,
  withBookingFor,
} from '@/services/employee-requests/booking-for';
import FsAirportFieldV3 from './FsAirportFieldV3';
import FlightDateFieldV3 from './FlightDateFieldV3';
import FlightTravelersV3 from './FlightTravelersV3';
import { AddLegIcon, ChevronIcon, RemoveLegIcon, SearchFlightsIcon, SwapIcon } from './icons';
import { toTitleCase } from './displayText';
import { readLastReturnDate, rememberReturnDate } from '@/services/flights/searchPreferences';
import {
  readCachedLocationNames,
  resolveLocationNamesClient,
} from '@/services/flights/locationNames.client';
import type { ResolvedLocation } from '@/services/flights/resolveFlightCityNames';
import { toast, TOAST_IDS } from '@/lib/toast';
import './flight-search-v3.css';

const MAX_MULTICITY_LEGS = 6;
const MIN_MULTICITY_LEGS = 2;

/* CORP-ONLY: the CABIN_OPTIONS list that used to live here is gone with the
   separate Cabin Class field — the cabin chips are rendered inside the
   Travellers & Class panel now (FlightTravelersV3), which owns their order. */

const TRIP_TYPES: { value: TripType; label: string }[] = [
  { value: 'oneway', label: 'One Way' },
  { value: 'roundtrip', label: 'Round Trip' },
  { value: 'multicity', label: 'Multi City' },
];

/**
 * Seed dates for a field nobody has filled in yet: departure is tomorrow, and
 * every date that has to follow another one (a round trip's return, a
 * multi-city leg after the one before it) sits two days later. Only ever used
 * when neither the URL nor the traveller has said otherwise.
 */
/**
 * Every query param this form derives its state from. `ca` is the retired
 * children-ages spelling, still read so links already in the wild resolve.
 * Anything not on this list cannot reset the form — see `searchParams` below.
 */
const FORM_PARAM_KEYS = [
  'tripType',
  'itinerary',
  'adults',
  'children',
  'ca',
  'infants',
  'cabinClass',
  'directOnly',
  // CORP-ONLY (LEIS-934). Listed so the Back button and a pasted link restore
  // who the trip is for, like every other field on this bar.
  BOOKING_FOR_PARAM,
] as const;

/**
 * How long to wait after the last change before searching.
 *
 * Long enough that flipping between trip types to compare runs one search, short
 * enough that a single deliberate change feels immediate.
 */
const AUTO_SEARCH_DEBOUNCE_MS = 300;

/** Steppers (+/-) fire in bursts; see setPassengers. */
const STEPPER_DEBOUNCE_MS = 700;

/**
 * No wait at all, for a field whose change is already a single deliberate
 * commit: a cabin picked from the chips, an airport chosen from the dropdown, a
 * day clicked in the calendar, the route reversed. There is no burst to absorb
 * — the traveller cannot pick two cabins — so a debounce here buys nothing and
 * costs the one thing that matters: for its whole duration the previous
 * search's results sit under a form that already says something else. Measured
 * at 300ms that was two sampled frames of Economy fares under a Business form.
 *
 * Still a timer rather than a direct call, so the setState that precedes it has
 * flushed and cancelAutoSearch() can still supersede it.
 */
const COMMIT_IMMEDIATELY_MS = 0;

const DEFAULT_DEPART_OFFSET_DAYS = 1;
const DEFAULT_FOLLOWING_OFFSET_DAYS = 2;

function defaultDepartDate(): Date {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return addDays(today, DEFAULT_DEPART_OFFSET_DAYS);
}

function defaultFollowingDate(base: Date): Date {
  return addDays(base, DEFAULT_FOLLOWING_OFFSET_DAYS);
}

/**
 * Is `date` on the same calendar day as `other`, or later?
 *
 * Compared as YYYY-MM-DD rather than with `>=` on the Date objects. The form's
 * dates are midnight-normalised today, so the operator would work — but the
 * moment one arrives with a time on it (a URL, a picker that preserves the
 * current clock) a plain comparison starts rejecting a return on the very day
 * it should now allow, and does it only for part of the day.
 */
function isSameDayOrLater(date: Date, other: Date): boolean {
  return formatDateToYYYYMMDD(date) >= formatDateToYYYYMMDD(other);
}

/**
 * A date from the URL, or null if it is unusable.
 *
 * `minDate` stops a traveller *picking* yesterday, but nothing stops a URL
 * carrying one — a stale bookmark, a shared link, a search that sat in a tab
 * over a weekend. Treating a past date as absent means the field falls back to
 * the normal default instead of displaying, and submitting, a departure that
 * has already happened.
 */
function urlDateOrNull(value: string | undefined): Date | null {
  const parsed = parseDateOnlyAsLocal(value);
  if (!parsed) return null;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return parsed < today ? null : parsed;
}

/**
 * The empty return field's prompt on a one-way search.
 *
 * Doubles as the affordance: the field is visible on one-way precisely so it
 * can say this, and picking a date in it converts the search to round trip
 * (handleReturnChange) rather than sending the traveller to the trip-type
 * control first. Defined once because the hero panel and the results page's
 * sticky bar both show it, and copy that drifted between the two would read as
 * two different features.
 */
const RETURN_DATE_PROMPT = 'Tap to add a return date & save more';

/**
 * The same field's prompt in the results page's sticky bar.
 *
 * Short on purpose, and the same split MakeMyTrip makes: the hero panel has a
 * roomy two-line cell and can afford to sell the idea, a pinned single-line bar
 * cannot. The long copy there had to be shrunk and wrapped to two 11px lines to
 * fit at all, which made the one cell that was trying hardest to be noticed the
 * hardest one to read. The affordance does not depend on the sentence — the
 * field is visible and dated-or-empty either way, and picking a date still
 * converts the search to round trip.
 */
const RETURN_DATE_PROMPT_COMPACT = 'Select Return';

interface FlightLeg {
  origin: FlightLocationData;
  destination: FlightLocationData;
  departDate: Date | null;
}

interface FlightSearchData {
  origin: FlightLocationData;
  destination: FlightLocationData;
  departDate: Date | null;
  returnDate: Date | null;
  passengers: PassengerData;
  tripType: TripType;
  cabinClass: CabinClass;
  directOnly: boolean;
}

/**
 * A change to the search, as the field that made it describes it.
 *
 * Only the keys that actually changed; runSearchFor merges the rest from
 * `formData`. `legs` rides along because multi-city keeps its itinerary in its
 * own state rather than in FlightSearchData.
 */
type SearchPatch = Partial<FlightSearchData> & { legs?: FlightLeg[] };

function legsToSegments(legs: FlightLeg[]): ItinerarySegment[] {
  return legs.map((leg) => ({
    from: leg.origin.code,
    to: leg.destination.code,
    date: leg.departDate ? formatDateToYYYYMMDD(leg.departDate) : '',
  }));
}

export interface FlightSearchFormV3Props {
  /** Server-resolved code -> {city, country}, so fields show real names on first paint. */
  initialLocationNames?: Record<string, { city: string; country: string }>;
  /**
   * Origin detected server-side from the visitor's IP, used only when the URL
   * carries no itinerary. Outranked by the URL and by the traveller's own edit.
   */
  initialOrigin?: FlightLocationData;
  /** Country the detected origin came from — persisted alongside it in the cookie. */
  initialOriginCountry?: string | null;
  /**
   * `default` is the hero panel: trip type as radios above a full-width field
   * row, with a centred Search button. `compact` is the results page's sticky
   * bar — every field on one line, trip type as a select, and multi-city's legs
   * folded behind a single route summary that toggles them open.
   *
   * One component, two layouts, because everything below the markup — URL
   * parsing, leg management, validation, submit — is identical and duplicating
   * it is how the two would drift.
   */
  variant?: 'default' | 'compact';
}

/**
 * The flight search form, in the v3 design.
 *
 * One component serves both the home page hero and the SRP. The trip type comes
 * from `tripType` in the query, absent on `/` and so `oneway` there.
 *
 * The difference between the two is what a change to the form *means*:
 *
 *  - On the SRP, results are already on screen, and a form that disagrees with
 *    them is the bug this behaviour exists to prevent. Changing trip type or
 *    the direct-only toggle therefore re-runs the search itself, debounced.
 *  - On the home page there is nothing to keep in step. The form changes shape
 *    and navigates exactly once, when Search is pressed.
 *
 * `isResultsPage` is the only thing that separates them, and every auto-search
 * path is gated on it.
 */
export default function FlightSearchFormV3({
  initialLocationNames,
  initialOrigin,
  initialOriginCountry,
  variant = 'default',
}: FlightSearchFormV3Props = {}) {
  const liveSearchParams = useSearchParams();

  /**
   * The search params this form reads, frozen into their own object.
   *
   * `useSearchParams()` returns a new object for *any* change to the query
   * string, including ones this form has no opinion about — the home page's
   * hero writes `?tab=hotels|flights` as the traveller flips between the two
   * search panels. Depending on the live object meant that flip re-ran the
   * re-derive effect below, which rebuilds the whole form from the URL: a
   * half-filled flight search was silently reset to defaults every time
   * someone glanced at the hotels tab and came back.
   *
   * Keying the memo on the joined values rather than the params object means
   * an unrelated param produces the identical object, and nothing downstream
   * re-derives.
   */
  const formParamsKey = FORM_PARAM_KEYS.map((k) => liveSearchParams.get(k) ?? '').join('\u0000');
  const searchParams = useMemo(() => {
    const frozen = new URLSearchParams();
    for (const key of FORM_PARAM_KEYS) {
      const value = liveSearchParams.get(key);
      if (value != null) frozen.set(key, value);
    }
    return frozen;
    // formParamsKey is the value-identity of exactly these params;
    // liveSearchParams is read through it.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formParamsKey]);
  const router = useRouter();
  const pathname = usePathname();

  /**
   * True when results are already on screen, so a change to the form has
   * something to keep in step with. False on the home page, where the form is
   * the whole interaction and Search is what runs one.
   */
  const isResultsPage = pathname.startsWith(SRP_FLIGHTS_PATH);
  const dispatch = useAppDispatch();

  const [isSearching, setIsSearching] = useState(false);
  // While the SRP is fetching offers for the current params, Search must not be
  // clickable again — grey it out so that is obvious.
  const offersLoading = useAppSelector((s) => s.flightSearch.offersStatus === 'loading');
  // Only whether one exists — the selection itself belongs to the round-trip
  // results client. See setHasOutboundSelection.
  const hasOutboundSelection = useAppSelector((s) => s.flightSearch.hasOutboundSelection);
  const searchInProgress = isSearching || offersLoading;

  /**
   * Exactly one popup is open at a time, addressed by key: 'origin',
   * 'destination', 'depart', 'return', 'travelers', or `leg-<i>-<part>`. A
   * single slot is what guarantees filling a field can hand focus to the next
   * one without two panels ever being on screen together.
   */
  const [openField, setOpenField] = useState<string | null>(null);

  /**
   * CORP-ONLY (LEIS-934): who this trip is being requested for — null is the
   * signed-in employee.
   *
   * **Read from the URL, not held in state.** Every other field on this bar
   * derives from the query string and is re-derived by the effect below when it
   * changes; a second copy here would need the same treatment, and a `setState`
   * in that effect is exactly what the React Compiler rejects. Deriving it
   * gives the Back button and a pasted link the right answer for free.
   *
   * Picking someone writes the param with `router.replace` rather than running
   * a search: `searchCacheKey()` is built from the search INPUT — route, dates,
   * party, cabin — so this param is not part of it and the results on screen
   * stay. The fares are the same whoever flies; what changes is only whose
   * policy the request is judged against, which happens in the overlay.
   */
  const bookingFor = parseBookingFor(searchParams);

  const fallbackOrigin = initialOrigin ?? DEFAULT_ORIGIN;

  // Once the traveller picks their own origin, a later re-derive from the URL
  // must not put the detected one back. See the searchParams effect below.
  const originEditedRef = useRef(false);

  /**
   * Set when the traveller changes the trip type without submitting.
   *
   * The trip type normally comes from the URL, which is authoritative — so any
   * other URL change (a nearby-date click, say) would re-derive it and silently
   * undo a pending choice. While this is set, the chosen type and the dates
   * that belong to it survive a re-derive. It clears the moment the URL agrees
   * again, which is what searching does.
   *
   * On the SRP this window is short — an auto-search follows within the debounce
   * — but it still exists, and round trip awaiting a return date can hold it
   * open indefinitely.
   */
  const tripTypeEditedRef = useRef(false);

  const locationFromCode = useCallback(
    (code: string, fallback: FlightLocationData): FlightLocationData => {
      if (!code) return fallback;
      const resolved = initialLocationNames?.[code.toUpperCase()];
      return resolved
        ? { destination: resolved.city, code, country: resolved.country }
        : { destination: code, code, country: '' };
    },
    [initialLocationNames],
  );

  const getInitialFormData = useCallback((): FlightSearchData => {
    const tripType = tripTypeFromParams(searchParams);
    const segments = parseItinerary(searchParams.get('itinerary'));
    const first = segments[0];
    const second = segments[1];
    const origin = first?.from ? locationFromCode(first.from, fallbackOrigin) : fallbackOrigin;
    const departDate = urlDateOrNull(first?.date) ?? defaultDepartDate();
    return {
      origin,
      destination: first?.to ? locationFromCode(first.to, DEFAULT_DEST) : defaultDestinationFor(origin),
      departDate,
      // A round-trip URL normally carries the return as its second segment. One
      // that doesn't — hand-edited, or truncated somewhere in a share — leaves
      // the field empty on the results page rather than inventing a date that
      // would immediately be searched and priced as though the traveller had
      // chosen it. The home page searches nothing until Search is pressed, so
      // there the pre-filled date is a convenience with no such cost.
      returnDate:
        tripType === 'roundtrip'
          ? urlDateOrNull(second?.date) ?? (isResultsPage ? null : defaultFollowingDate(departDate))
          : null,
      passengers: clampPassengers({
        adults: searchParams.get('adults') ? Number(searchParams.get('adults')) : 1,
        children: parseChildren(searchParams),
        infants: parseInfants(searchParams.get('infants')),
      }),
      tripType,
      cabinClass: decodeCabinClass(searchParams.get('cabinClass')),
      directOnly: searchParams.get('directOnly') === 'true',
    };
  }, [searchParams, locationFromCode, fallbackOrigin, isResultsPage]);

  const [formData, setFormData] = useState<FlightSearchData>(getInitialFormData);

  const [multiLegs, setMultiLegs] = useState<FlightLeg[]>(() => {
    // Built in order rather than mapped so a leg the URL leaves dateless can be
    // seeded from the leg before it.
    const fromUrl: FlightLeg[] = [];
    for (const s of parseItinerary(searchParams.get('itinerary'))) {
      const previousDate = fromUrl[fromUrl.length - 1]?.departDate ?? null;
      fromUrl.push({
        origin: locationFromCode(s.from, fallbackOrigin),
        destination: locationFromCode(s.to, DEFAULT_DEST),
        departDate:
          urlDateOrNull(s.date) ??
          (previousDate ? defaultFollowingDate(previousDate) : defaultDepartDate()),
      });
    }
    if (fromUrl.length >= MIN_MULTICITY_LEGS) return fromUrl;
    const firstLegDest = defaultDestinationFor(fallbackOrigin);
    const firstDepart = defaultDepartDate();
    return [
      { origin: fallbackOrigin, destination: firstLegDest, departDate: firstDepart },
      { origin: fallbackOrigin, destination: firstLegDest, departDate: defaultFollowingDate(firstDepart) },
    ];
  });

  const isMultiCity = formData.tripType === 'multicity';

  /**
   * Compact multi-city only: whether the per-leg editor is open beneath the
   * route summary. Collapsed by default because six legs of fields is the one
   * thing that cannot fit on a single pinned line.
   */
  const [multiExpanded, setMultiExpanded] = useState(false);

  // Switching away from multi-city leaves nothing for the layer to edit.
  useEffect(() => {
    if (!isMultiCity) setMultiExpanded(false);
  }, [isMultiCity]);

  /**
   * "Delhi → Bengaluru → Chennai" — the whole chain, in the names the traveller
   * picked, standing in for every leg field while they are folded away.
   *
   * Built as first origin plus each leg's destination rather than joining every
   * origin and destination, because consecutive legs share an airport and
   * listing both would read "Delhi → Bengaluru → Bengaluru → Chennai". A leg
   * with nothing chosen yet reads "Select", so an incomplete itinerary says so
   * instead of rendering a stray arrow.
   */
  const multiRouteSummary = useMemo(() => {
    if (multiLegs.length === 0) return '';
    const name = (loc: FlightLocationData) => toTitleCase(loc.destination || loc.code) || 'Select';
    return [name(multiLegs[0].origin), ...multiLegs.map((leg) => name(leg.destination))].join(' → ');
  }, [multiLegs]);

  // ── Late-arriving city names ───────────────────────────────────────────────

  /**
   * Codes on screen that are still standing in for their own name.
   *
   * `locationFromCode` falls back to the code itself when the server-resolved
   * map has nothing for it, so `destination === code` is precisely the "we
   * never learned what this airport is called" state — which is what the SRP
   * renders as "Lhr" where the home page rendered "London / United Kingdom".
   */
  const unresolvedKey = useMemo(() => {
    const shown = isMultiCity
      ? multiLegs.flatMap((leg) => [leg.origin, leg.destination])
      : [formData.origin, formData.destination];
    const codes = shown
      .filter((loc) => loc.code && loc.destination.trim().toUpperCase() === loc.code.trim().toUpperCase())
      .map((loc) => loc.code.trim().toUpperCase());
    // A joined string, not the array: the effects below run off it, and a fresh
    // array of the same codes on every render would re-run both of them.
    return Array.from(new Set(codes)).join(',');
  }, [isMultiCity, multiLegs, formData.origin, formData.destination]);

  const [resolvedNames, setResolvedNames] = useState<Record<string, ResolvedLocation>>({});

  useEffect(() => {
    setFormData((prev) => {
      const next = getInitialFormData();
      // A URL that names an origin always wins. One that doesn't must not undo
      // a choice the traveller already made — the detected default is only for
      // a form they haven't touched.
      const urlHasOrigin = !!parseItinerary(searchParams.get('itinerary'))[0]?.from;
      const merged = originEditedRef.current && !urlHasOrigin ? { ...next, origin: prev.origin } : next;

      // The URL has caught up with the pending choice — a search ran, whether
      // from Search or from the auto-search debounce — so it is pending no more.
      if (tripTypeEditedRef.current && next.tripType === prev.tripType) {
        tripTypeEditedRef.current = false;
        return merged;
      }
      // Still pending: keep the chosen type and the return date that belongs to
      // it. Returning `merged` here would snap the form back to whatever the
      // URL says, discarding the choice without the traveller doing anything.
      // On the results page this window is normally one debounce long, but a
      // round trip waiting for a return date holds it open until one is picked.
      if (tripTypeEditedRef.current) {
        return { ...merged, tripType: prev.tripType, returnDate: prev.returnDate };
      }
      return merged;
    });
  }, [getInitialFormData, searchParams]);

  /**
   * Fill in whatever the server could not.
   *
   * Declared below the re-derive effect on purpose. Both fire in the same
   * commit when a navigation changes the URL *and* brings an unnamed code with
   * it, and effects run in declaration order — so a patch declared above would
   * be applied and then thrown away by the re-derive that rebuilds `formData`
   * from the URL, and the name would only reappear a render later. Here the
   * patch lands on top, and the field never flickers name -> code -> name.
   *
   * Deliberately *not* fed back through `getInitialFormData`: that rebuilds the
   * whole form from the URL, so a name landing mid-edit would also throw away a
   * destination the traveller had changed but not yet searched. Names are
   * patched over the existing state instead, and only onto a location still
   * displaying its own code — anything the traveller has since picked is left
   * exactly as they left it.
   *
   * Read from storage before the network: the home page wrote "London" there
   * when the airport was picked, so the common home-page-to-SRP path resolves
   * with no request at all.
   */
  useEffect(() => {
    if (!unresolvedKey) return;
    const codes = unresolvedKey.split(',');

    const cached = readCachedLocationNames(codes);
    if (Object.keys(cached).length > 0) setResolvedNames((prev) => ({ ...prev, ...cached }));

    const missing = codes.filter((code) => !cached[code]);
    if (missing.length === 0) return;

    let cancelled = false;
    void resolveLocationNamesClient(missing).then((named) => {
      if (cancelled || Object.keys(named).length === 0) return;
      setResolvedNames((prev) => ({ ...prev, ...named }));
    });
    return () => {
      cancelled = true;
    };
  }, [unresolvedKey]);

  // Apply them. Keyed on `unresolvedKey` as well as the names themselves so a
  // URL that brings in a code already resolved earlier this session is filled
  // without asking anyone again.
  useEffect(() => {
    if (Object.keys(resolvedNames).length === 0) return;

    const fill = (loc: FlightLocationData): FlightLocationData => {
      if (!loc.code) return loc;
      const code = loc.code.trim().toUpperCase();
      // Already named — a traveller's own pick, or a name the server resolved.
      if (loc.destination && loc.destination.trim().toUpperCase() !== code) return loc;
      const hit = resolvedNames[code];
      return hit ? { destination: hit.city, code: loc.code, country: hit.country } : loc;
    };

    setFormData((prev) => {
      const origin = fill(prev.origin);
      const destination = fill(prev.destination);
      return origin === prev.origin && destination === prev.destination
        ? prev
        : { ...prev, origin, destination };
    });

    setMultiLegs((prev) => {
      let changed = false;
      const next = prev.map((leg) => {
        const origin = fill(leg.origin);
        const destination = fill(leg.destination);
        if (origin === leg.origin && destination === leg.destination) return leg;
        changed = true;
        return { ...leg, origin, destination };
      });
      return changed ? next : prev;
    });
  }, [resolvedNames, unresolvedKey]);

  // Remember the resolved origin so the next visit skips the IP lookup entirely.
  // Written here rather than server-side because Next forbids setting cookies
  // during a Server Component render.
  useEffect(() => {
    if (!initialOrigin?.code) return;
    setCookie(ORIGIN_COOKIE, buildOriginCookie(initialOrigin, initialOriginCountry ?? null), {
      // Carries no secrets, and must survive plain-http local development.
      days: ORIGIN_COOKIE_DAYS,
      secure: window.location.protocol === 'https:',
    });
  }, [initialOrigin, initialOriginCountry]);

  // Close whatever is open on a click elsewhere. The calendar renders through a
  // portal on <body>, so it is outside every `.fs-field` — without naming it
  // here, clicking a day would close the field before the day registered.
  useEffect(() => {
    const onDocClick = (e: MouseEvent) => {
      const target = e.target as Element | null;
      if (target?.closest('.fs-field') || target?.closest('.react-datepicker') || target?.closest('#v3-datepicker-portal')) {
        return;
      }
      setOpenField(null);
    };
    document.addEventListener('click', onDocClick);
    return () => document.removeEventListener('click', onDocClick);
  }, []);

  // ── Auto-search (results page only) ────────────────────────────────────────

  const autoSearchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const cancelAutoSearch = useCallback(() => {
    if (autoSearchTimer.current) clearTimeout(autoSearchTimer.current);
    autoSearchTimer.current = null;
  }, []);

  useEffect(() => cancelAutoSearch, [cancelAutoSearch]);

  /**
   * CORP-ONLY (LEIS-934). Write the chosen traveller to the URL.
   *
   * `replace`, not `push`: picking who a trip is for is a correction to the
   * search already on screen, not a step in it, and pushing would make the Back
   * button walk through every name tried. Built from the LIVE params so filters
   * and sort — which are not in FORM_PARAM_KEYS — survive the write.
   *
   * `cancelAutoSearch()` first — found live: changing cabin class, a date, or
   * any other field schedules a debounced `runSearchFor` (up to 700ms out)
   * that closes over `bookingFor` AT SCHEDULE TIME. Picking a traveller
   * inside that window updated the URL correctly, visibly, right up until
   * the stale timer fired and `router.push`ed a rebuilt search URL still
   * carrying the OLD `bookingFor` — silently reverting the field a moment
   * after it appeared to take. "Fares" clicked after that reversion filed
   * the request for whoever the field said before the correction, not the
   * colleague actually showing selected on screen. Cancelling here means a
   * traveller change always wins over whatever else was mid-debounce, which
   * matches this control's own "correction, not a step" framing above.
   */
  const setBookingFor = useCallback(
    (travellerId: string | null) => {
      cancelAutoSearch();
      const qs = withBookingFor(liveSearchParams.toString(), travellerId);
      router.replace(`${pathname}${qs ? `?${qs}` : ''}`, { scroll: false });
    },
    [liveSearchParams, pathname, router, cancelAutoSearch],
  );

  /**
   * CORP-ONLY (LEIS-934). Every airport on the itinerary, for the travellers
   * endpoint — not an origin/destination pair.
   *
   * One leg crossing a border makes the WHOLE trip international, and that is
   * what decides which policy tab's Colleague booking toggle applies. A
   * multi-city trip that ends abroad must not be judged as domestic because its
   * first leg was, so multi-city sends every leg's codes.
   */
  const travellerAirports = useMemo(
    () =>
      isMultiCity
        ? airportsFromSegments(legsToSegments(multiLegs))
        : airportsFromPair(formData.origin.code, formData.destination.code),
    [isMultiCity, multiLegs, formData.origin.code, formData.destination.code],
  );

  /** Open one field, closing every other. Deferred where a picker is mid-close. */
  const goToStep = useCallback((key: string | null) => setOpenField(key), []);
  /**
   * Open a field on the next tick, past anything closing in this one.
   *
   * Two separate closes land in the same pass and both would shut whatever we
   * opened synchronously:
   *
   *  - react-datepicker closing itself after a day is picked;
   *  - the document click handler above, for a control that is not inside a
   *    `.fs-field` — the hero panel's trip-type radios sit in `.fs-controls`,
   *    so the very click that selects Round Trip also closes the return
   *    calendar that selecting it just opened.
   *
   * Deferring is what lets the open win, since both closes are synchronous
   * within the click dispatch.
   */
  const advanceTo = useCallback(
    (key: string | null) => {
      setTimeout(() => setOpenField(key), 0);
    },
    [],
  );

  /**
   * The first field still missing something, as a field key — so a failed
   * search opens the field that needs answering instead of doing nothing, which
   * is all an empty destination used to produce.
   *
   * Takes the trip type and return date rather than reading them from state,
   * because the auto-search path has to validate a selection React has not
   * committed yet — checking `formData` there would validate the trip type the
   * traveller just left.
   */
  const incompleteFieldFor = useCallback(
    (tripType: TripType, returnDate: Date | null, legs: FlightLeg[]): string | null => {
      if (tripType === 'multicity') {
        for (let i = 0; i < legs.length; i++) {
          const { origin, destination, departDate } = legs[i];
          if (!origin.code) return `leg-${i}-origin`;
          // Leaving from and going to the same airport returns nothing, so it is
          // caught here rather than sent to Amadeus to come back empty.
          if (!destination.code || destination.code === origin.code) return `leg-${i}-destination`;
          if (!departDate) return `leg-${i}-depart`;
        }
        return null;
      }
      if (!formData.origin.code) return 'origin';
      if (!formData.destination.code || formData.destination.code === formData.origin.code) {
        return 'destination';
      }
      if (!formData.departDate) return 'depart';
      if (tripType === 'roundtrip' && !returnDate) return 'return';
      // A return before departure is not a trip. The date fields clamp this as
      // it is picked, so it only survives via a hand-edited URL — which is
      // exactly the case that must not reach Amadeus.
      if (tripType === 'roundtrip' && returnDate && !isSameDayOrLater(returnDate, formData.departDate)) {
        return 'return';
      }
      return null;
    },
    [formData.origin, formData.destination, formData.departDate],
  );

  /**
   * Run a search for a form state that is not in `formData` yet.
   *
   * React state updates are asynchronous, so a handler that changes a field and
   * then schedules a search cannot read the new value back from `formData` — it
   * would search for the value the traveller just left. The caller passes a
   * patch of exactly what it changed, and this merges it over the rest.
   *
   * A patch rather than a fixed triple because every search field now re-runs
   * the search (see scheduleAutoSearch); enumerating them in the signature meant
   * each new one had to be threaded through all three call sites, which is how
   * cabin class came to be settable without ever reaching the URL.
   */
  const runSearchFor = useCallback(
    (patch: SearchPatch) => {
      const next = { ...formData, ...patch };
      const legs = patch.legs ?? multiLegs;
      const isMulti = next.tripType === 'multicity';

      // An incomplete search is not sent. The results already on screen stay,
      // and the field that needs answering opens — the same treatment pressing
      // Search gives it, since the traveller did not ask for anything different.
      const incomplete = incompleteFieldFor(next.tripType, next.returnDate, legs);
      if (incomplete) {
        setOpenField(incomplete);
        return;
      }

      const qs = buildSearchUrl({
        tripType: next.tripType,
        origin: next.origin.code,
        destination: next.destination.code,
        departDate: next.departDate ? formatDateToYYYYMMDD(next.departDate) : undefined,
        returnDate:
          next.returnDate && next.tripType === 'roundtrip'
            ? formatDateToYYYYMMDD(next.returnDate)
            : undefined,
        legs: isMulti ? legsToSegments(legs) : undefined,
        adults: next.passengers.adults,
        children: next.passengers.children,
        infants: next.passengers.infants,
        cabinClass: next.cabinClass,
        directOnly: next.directOnly,
      });
      // CORP-ONLY: buildSearchUrl is shared verbatim with leisure-ui, which has
      // nobody to book for — so the param is appended here rather than taught
      // to a file whose value is that it has no divergence.
      const withTraveller = withBookingFor(qs, bookingFor);

      // Drop the results on screen NOW, not when the navigation lands.
      //
      // Next's client navigation takes ~200ms, and the store only clears stale
      // results once the request that follows it starts — so for that window
      // the previous search's fares sat under a form that already said
      // something else. Measured at ~190ms of Economy fares under a Business
      // cabin.
      //
      // Guarded on the query string actually differing, compared
      // order-insensitively so a bookmarked URL with the params in another
      // order does not read as a change: if it does not differ, Next treats the
      // push as a no-op, no request follows, and clearing would leave a
      // permanent loading state with nothing coming to replace it.
      //
      // `directOnly` is excluded for the same reason searchIdentityKey excludes
      // it: the toggle narrows the same inventory, and the SRP clients filter
      // the list they already hold so the change lands instantly. Clearing
      // there would trade that for a skeleton. BOOKING_FOR_PARAM is excluded
      // because it is not part of the search at all — see bookingFor above.
      const canonical = (q: string) =>
        [...new URLSearchParams(q)]
          .filter(([k]) => k !== 'directOnly' && k !== BOOKING_FOR_PARAM)
          .sort()
          .map(([k, v]) => `${k}=${v}`)
          .join('&');
      if (canonical(withTraveller) !== canonical(window.location.search)) {
        dispatch(supersedeResults());
      }

      // The URL is the search. Pushing rather than replacing is what gives the
      // Back button a previous trip type to return to; the debounce is what
      // stops rapid toggling from filling the history with intermediate states.
      dispatch(setAwaitingReturnDate(false));
      router.push(`${SRP_FLIGHTS_PATH}?${withTraveller}`);
    },
    [formData, multiLegs, router, dispatch, incompleteFieldFor, bookingFor],
  );

  /**
   * Search once the traveller has stopped changing their mind.
   *
   * EVERY field that defines the search goes through here on the results page —
   * route, dates, travellers, cabin, trip type, direct-only. That is the whole
   * rule, and it is the rule because the alternative was in production: three
   * fields re-searched and four did not, so choosing Economy over Premium left
   * Premium fares on screen under a form that said Economy, with nothing
   * anywhere admitting the two disagreed. Filters are the other half of the
   * split and stay where they are — they refine a response rather than redefine
   * the request.
   *
   * The timer restarts on every change, so four quick toggles run one search for
   * the final selection rather than four. Requests already in flight are
   * cancelled by the SRP client's own effect cleanup (useCachedFlightSearch),
   * and the slice drops an aborted request's rejection, so a slower superseded
   * response can never land over a newer one.
   *
   * Fields are deliberately NOT disabled while a search runs. The traveller
   * would be blocked by latency they cannot see the end of — which is exactly
   * what "the Search button keeps spinning but I can still change cabin class"
   * felt like — and superseding costs one aborted request.
   */
  const scheduleAutoSearch = useCallback(
    (patch: SearchPatch, delay: number = AUTO_SEARCH_DEBOUNCE_MS) => {
      if (!isResultsPage) return;
      cancelAutoSearch();
      autoSearchTimer.current = setTimeout(() => runSearchFor(patch), delay);
    },
    [isResultsPage, cancelAutoSearch, runSearchFor],
  );

  /**
   * The return date a trip type should carry after a switch.
   *
   * One-way has none. Round trip keeps whatever the traveller already chose, as
   * long as it has not fallen before departure — the departure day itself
   * counts — and otherwise falls back to the one remembered for this session,
   * so One Way -> Round Trip -> One Way -> Round Trip never asks twice.
   *
   * Returning null is meaningful: on the results page it is what opens the date
   * picker instead of searching. No default is invented there, because a date
   * the traveller did not choose would be searched, priced and shown as though
   * they had. The home page has no such risk — nothing is searched until Search
   * is pressed — so it keeps the old convenience of a pre-filled date.
   */
  const nextReturnDate = useCallback(
    (type: TripType, current: Date | null, departDate: Date): Date | null => {
      if (type !== 'roundtrip') return null;
      if (current && isSameDayOrLater(current, departDate)) return current;

      const remembered = parseDateOnlyAsLocal(readLastReturnDate(formatDateToYYYYMMDD(new Date())) ?? '');
      if (remembered && isSameDayOrLater(remembered, departDate)) return remembered;

      return isResultsPage ? null : defaultFollowingDate(departDate);
    },
    [isResultsPage],
  );

  // ── Single-leg handlers ────────────────────────────────────────────────────

  const handleDepartChange = useCallback(
    (date: Date | null) => {
      // A return that now falls *before* the new departure is re-seeded to the
      // same +2 default a fresh form gets, rather than emptied — the traveller
      // is moving their outbound, not withdrawing their return. A return on the
      // departure day itself stays: same-day is a legitimate trip.
      const returnStillValid =
        !date || !formData.returnDate || isSameDayOrLater(formData.returnDate, date);
      const nextReturn =
        formData.tripType === 'roundtrip' && date && !returnStillValid
          ? defaultFollowingDate(date)
          : formData.returnDate;

      setFormData((prev) => ({ ...prev, departDate: date, returnDate: nextReturn }));

      // Computed above rather than inside the updater because the search needs
      // both values now, and a functional updater only yields them on the next
      // render — a search scheduled from here would carry the old return date.
      if (date) scheduleAutoSearch({ departDate: date, returnDate: nextReturn }, COMMIT_IMMEDIATELY_MS);
    },
    [formData.returnDate, formData.tripType, scheduleAutoSearch],
  );

  const handleDepartSelect = useCallback(
    (date: Date | null) => {
      if (!date) {
        setOpenField(null);
        return;
      }
      advanceTo(formData.tripType === 'roundtrip' ? 'return' : 'travelers');
    },
    [formData.tripType, advanceTo],
  );

  const handleReturnChange = useCallback(
    (date: Date | null) => {
      // Picking a return date while in one-way mode is the traveller's own
      // signal to convert to round trip — mirrors the inline "add a return
      // date" field other OTAs show next to Depart, instead of making them
      // find the trip-type dropdown first. tripTypeEditedRef has to be set
      // the same way handleTripTypeChange sets it, or the next URL-driven
      // re-derive effect would silently snap this back to one-way — see that
      // ref's own comment.
      if (date && formData.tripType === 'oneway') {
        tripTypeEditedRef.current = true;
      }
      const nextTripType: TripType =
        date && formData.tripType === 'oneway' ? 'roundtrip' : formData.tripType;

      setFormData((prev) => ({
        ...prev,
        returnDate: date,
        tripType: date && prev.tripType === 'oneway' ? 'roundtrip' : prev.tripType,
      }));

      // Kept for the rest of the session, so switching away from round trip and
      // back does not ask for this date again.
      rememberReturnDate(date ? formatDateToYYYYMMDD(date) : null);

      advanceTo('travelers');

      // This is the moment the "select a return date" state resolves: a round
      // trip that could not be searched now can be.
      if (isResultsPage && date && nextTripType === 'roundtrip') {
        scheduleAutoSearch({ tripType: 'roundtrip', returnDate: date }, COMMIT_IMMEDIATELY_MS);
      }
    },
    [advanceTo, formData.tripType, isResultsPage, scheduleAutoSearch],
  );

  const handleSwap = useCallback(
    (legIndex?: number) => {
      // Swapping is an explicit statement about where they're leaving from.
      originEditedRef.current = true;
      if (legIndex !== undefined) {
        // Computed outside the updater: scheduling from inside one would run
        // the side effect twice under StrictMode's double-invoke.
        const swapped = multiLegs.map((leg, i) =>
          i === legIndex ? { ...leg, origin: leg.destination, destination: leg.origin } : leg,
        );
        setMultiLegs(swapped);
        scheduleAutoSearch({ legs: swapped }, COMMIT_IMMEDIATELY_MS);
        return;
      }
      setFormData((prev) => ({ ...prev, origin: prev.destination, destination: prev.origin }));
      // Reversing the route is as much a new search as typing either end.
      scheduleAutoSearch(
        { origin: formData.destination, destination: formData.origin },
        COMMIT_IMMEDIATELY_MS,
      );
    },
    [formData.origin, formData.destination, multiLegs, scheduleAutoSearch],
  );

  // ── Multi-city handlers ────────────────────────────────────────────────────

  /**
   * Sets one leg's departure and pushes forward only the later legs the edit has
   * made impossible (departing before the leg ahead of them). Legs still in a
   * workable order keep the dates the traveller chose — same-day connections
   * included.
   */
  const handleLegDepartChange = useCallback((idx: number, date: Date | null) => {
    setMultiLegs((prev) => {
      const next = prev.map((leg, i) => (i === idx ? { ...leg, departDate: date } : leg));
      if (!date) return next;
      for (let i = idx + 1; i < next.length; i++) {
        const previousDate = next[i - 1].departDate;
        const currentDate = next[i].departDate;
        if (previousDate && (!currentDate || currentDate < previousDate)) {
          next[i] = { ...next[i], departDate: defaultFollowingDate(previousDate) };
        }
      }
      return next;
    });
  }, []);

  const addLeg = useCallback(() => {
    setMultiLegs((prev) => {
      if (prev.length >= MAX_MULTICITY_LEGS) return prev;
      const previous = prev[prev.length - 1];
      return [
        ...prev,
        {
          origin: previous.destination,
          destination: EMPTY_LOCATION,
          departDate: previous.departDate ? defaultFollowingDate(previous.departDate) : defaultDepartDate(),
        },
      ];
    });
    // The new leg's origin is prefilled from the previous leg's destination, so
    // the first thing still to answer is where it is going.
    goToStep(`leg-${Math.min(multiLegs.length, MAX_MULTICITY_LEGS - 1)}-destination`);
  }, [multiLegs.length, goToStep]);

  const removeLeg = useCallback((idx: number) => {
    setMultiLegs((prev) => (prev.length <= MIN_MULTICITY_LEGS ? prev : prev.filter((_, i) => i !== idx)));
  }, []);

  /**
   * Direct flights only.
   *
   * Always re-runs the search rather than filtering what is on screen. Verified
   * against Amadeus: a broad search returns a representative mix rather than
   * every direct flight, so filtering locally both hides options and can quote
   * the wrong cheapest fare — on one test route a real nonStop search found the
   * cheapest direct at 628.80 where filtering a broad one said 644.80, and on
   * another it found 57 direct flights where filtering found 13. Wrong prices
   * are the failure this behaviour exists to prevent, so the server is asked.
   *
   * The SRP narrows the list it already has while that runs, so the change is
   * visible immediately — see the optimistic filter in the SRP clients.
   */
  const handleDirectOnlyChange = useCallback(
    (checked: boolean) => {
      setFormData((prev) => ({ ...prev, directOnly: checked }));
      if (!isResultsPage) return;
      scheduleAutoSearch({ directOnly: checked });
    },
    [isResultsPage, scheduleAutoSearch],
  );

  // ── Trip type ──────────────────────────────────────────────────────────────

  const handleTripTypeChange = (type: TripType) => {
    setOpenField(null);
    if (type === formData.tripType) return;

    // Source everything from current form state (the same state handleSubmit
    // already trusts) instead of re-parsing the URL.
    const wasMultiCity = formData.tripType === 'multicity';
    let newOrigin = formData.origin;
    let newDestination = formData.destination;
    let newDepartDate = formData.departDate ?? defaultDepartDate();
    let newMultiLegs = multiLegs;

    if (wasMultiCity) {
      // Coming FROM multicity — use its first leg as the new single-leg route.
      const first = multiLegs[0];
      if (first) {
        newOrigin = first.origin;
        newDestination = first.destination;
        newDepartDate = first.departDate ?? newDepartDate;
      }
    } else if (type === 'multicity') {
      // Going TO multicity — seed 2 legs from the current single-leg route.
      newMultiLegs = [
        { origin: formData.origin, destination: formData.destination, departDate: newDepartDate },
        {
          origin: formData.destination,
          destination: formData.origin,
          departDate: defaultFollowingDate(newDepartDate),
        },
      ];
    }

    const newReturnDate = nextReturnDate(type, formData.returnDate, newDepartDate);

    setFormData((prev) => ({
      ...prev,
      tripType: type,
      origin: newOrigin,
      destination: newDestination,
      departDate: newDepartDate,
      returnDate: newReturnDate,
    }));
    if (newMultiLegs !== multiLegs) setMultiLegs(newMultiLegs);

    // State and URL now disagree — the URL still says the old type — which the
    // re-derive effect has to respect until a search puts them back in step.
    tripTypeEditedRef.current = true;

    if (!isResultsPage) return;

    // Leaving round trip discards an outbound the traveller had already picked.
    // Said out loud: a selection disappearing from under them with no
    // explanation reads as the page losing their work.
    if (formData.tripType === 'roundtrip' && hasOutboundSelection) {
      dispatch(setHasOutboundSelection(false));
      toast.info('Your selection was cleared because the trip type changed.', {
        id: TOAST_IDS.flightSelectionCleared,
      });
    }

    // Multi-city is the one type that cannot be searched from a single-leg
    // route: the traveller has legs to add first. Expand the editor and wait
    // for Search, rather than running a search for a route they are mid-way
    // through describing.
    if (type === 'multicity') {
      cancelAutoSearch();
      dispatch(setAwaitingReturnDate(false));
      setMultiExpanded(true);
      return;
    }

    // Round trip with no usable return date. Nothing can be searched yet, so
    // the results already on screen stay put and the SRP explains why while the
    // date picker opens on the field that needs answering.
    if (type === 'roundtrip' && !newReturnDate) {
      cancelAutoSearch();
      dispatch(setAwaitingReturnDate(true));
      // Deferred, not set directly: the click that chose Round Trip is still
      // bubbling, and the document handler would close this before it painted.
      // See advanceTo.
      advanceTo('return');
      return;
    }

    scheduleAutoSearch({ tripType: type, returnDate: newReturnDate });
  };

  /**
   * The cross on the return field: drop the return date and go back to one way.
   *
   * Routed through handleTripTypeChange rather than clearing the date on its
   * own, because a round trip with no return is not a state this form can
   * search — leaving the traveller in it is what puts the SRP into "pick a
   * return date" with no results moving. Switching the type is therefore the
   * action; the empty date is what the switch already does (see nextReturnDate),
   * along with the outbound-selection warning and the auto-search on the SRP.
   *
   * The one thing the type switch does not do is forget the remembered date,
   * and here it has to: that memory exists so somebody who flips away from
   * round trip and back is not asked twice, which is the opposite of somebody
   * who just deleted their return. Leaving it would put the date they removed
   * straight back the next time they chose Round Trip.
   */
  const handleReturnClear = () => {
    rememberReturnDate(null);
    handleTripTypeChange('oneway');
  };

  // ── Submit ─────────────────────────────────────────────────────────────────

  /**
   * The first field still missing something, as a field key — so a failed
   * submit opens the field that needs answering instead of doing nothing, which
   * is all an empty destination used to produce.
   */
  const firstIncompleteField = useMemo(
    () => incompleteFieldFor(formData.tripType, formData.returnDate, multiLegs),
    [incompleteFieldFor, formData.tripType, formData.returnDate, multiLegs],
  );

  /** Names the same-airport case in the field that has to change, when it applies. */
  const sameAirportNote = (origin: FlightLocationData, destination: FlightLocationData) =>
    destination.code && destination.code === origin.code
      ? `You are already flying from ${toTitleCase(origin.destination)} — pick a different city.`
      : undefined;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchInProgress) return;

    if (firstIncompleteField) {
      setOpenField(firstIncompleteField);
      return;
    }

    // An explicit Search supersedes anything the debounce was about to do.
    cancelAutoSearch();
    dispatch(setAwaitingReturnDate(false));
    rememberReturnDate(
      formData.returnDate && formData.tripType === 'roundtrip'
        ? formatDateToYYYYMMDD(formData.returnDate)
        : null,
    );

    setIsSearching(true);
    try {
      const qs = buildSearchUrl({
        tripType: formData.tripType,
        origin: formData.origin.code,
        destination: formData.destination.code,
        departDate: formData.departDate ? formatDateToYYYYMMDD(formData.departDate) : undefined,
        returnDate:
          formData.returnDate && formData.tripType !== 'oneway'
            ? formatDateToYYYYMMDD(formData.returnDate)
            : undefined,
        legs: isMultiCity ? legsToSegments(multiLegs) : undefined,
        adults: formData.passengers.adults,
        children: formData.passengers.children,
        infants: formData.passengers.infants,
        cabinClass: formData.cabinClass,
        directOnly: formData.directOnly,
      });
      // See runSearchFor: corp carries the Booking for selection itself.
      const withTraveller = withBookingFor(qs, bookingFor);
      // Re-searching with identical params is a no-op navigation to Next's
      // router — the SRP client's fetch effect keys off the URL and would never
      // re-run. Bumping this counter forces a fresh dispatch on every submit.
      dispatch(bumpSearchTrigger());
      router.push(`${SRP_FLIGHTS_PATH}?${withTraveller}`);
    } finally {
      setIsSearching(false);
    }
  };

  // ── Render ─────────────────────────────────────────────────────────────────

  /**
   * Travellers, on a longer fuse than the rest.
   *
   * This is a stepper: going from 1 adult to 4 is four clicks a few hundred
   * milliseconds apart, and at the standard debounce each one would start a
   * search the next click cancels. The longer wait buys one search for the
   * number they actually settled on.
   */
  const setPassengers = (passengers: PassengerData) => {
    setFormData((prev) => ({ ...prev, passengers }));
    scheduleAutoSearch({ passengers }, STEPPER_DEBOUNCE_MS);
  };

  /**
   * Cabin class, from every control that offers it — corp renders the chips
   * inside the Travellers & Class panel, which appears in three layouts.
   * Shared rather than inlined at each: this field reaching the URL from two of
   * three places and not the third is the same bug in a smaller box.
   */
  const handleCabinChange = (cabinClass: CabinClass) => {
    setFormData((prev) => ({ ...prev, cabinClass }));
    scheduleAutoSearch({ cabinClass }, COMMIT_IMMEDIATELY_MS);
  };

  /**
   * Origin and destination, committed. Both fire on a pick from the dropdown,
   * never per keystroke — a half-typed city is not a search, and FsAirportFieldV3
   * only reports a resolved airport.
   */
  const handleOriginChange = (origin: FlightLocationData) => {
    originEditedRef.current = true;
    setFormData((prev) => ({ ...prev, origin }));
    scheduleAutoSearch({ origin }, COMMIT_IMMEDIATELY_MS);
  };

  const handleDestinationChange = (destination: FlightLocationData) => {
    setFormData((prev) => ({ ...prev, destination }));
    scheduleAutoSearch({ destination }, COMMIT_IMMEDIATELY_MS);
  };

  const travelersHeadline = adultsSummary(formData.passengers);
  const travelersCompanions = companionsSummary(formData.passengers);
  /**
   * CORP-ONLY: the companions line, but empty when there are none.
   *
   * `companionsSummary` always names children — "0 Children" — which reads fine
   * on its own line under "1 Adult", where leisure-ui puts it. Beside the cabin
   * in the merged field it becomes "Economy · 0 Children", which is noise on
   * the overwhelmingly common one-adult search.
   */
  const travelersExtras =
    formData.passengers.children > 0 || formData.passengers.infants > 0
      ? travelersCompanions
      : '';

  /**
   * A return may be booked for the departure day itself.
   *
   * This used to be departure + 1, which made a same-day there-and-back
   * unsearchable — a real trip, and a common one on short domestic routes. The
   * day is now the floor; whether a *particular* return can actually be caught
   * after the outbound lands is a question about flight times, not dates, and
   * is answered where the returns are listed (see MIN_SAME_DAY_TURNAROUND_MINUTES
   * in services/flights/roundTripPairs.ts).
   */
  const minReturnDate = formData.departDate ?? defaultDepartDate();


  /**
   * The sticky-bar layout.
   *
   * A separate return rather than conditionals threaded through the default
   * markup: the two arrangements share no rows, and interleaving them would
   * make the hero form — which is not changing — harder to read for the sake of
   * avoiding some duplicated JSX. Everything that actually matters (state, leg
   * management, validation, submit) is above this line and shared.
   */
  if (variant === 'compact') {
    return (
      <form className="fs-form flight-form fs-compact" onSubmit={handleSubmit} noValidate>
        <div className="fs-compact-row">
          {/*
            A panel, not a native <select>. The OS menu a bare select opens is
            styled by the platform — dark grey with a system highlight on macOS
            — which is jarring next to the airport and calendar panels the rest
            of this row opens. Reusing `.fs-field` + `.fs-dropdown` means it
            opens, closes and dismisses on an outside click exactly like they
            do, through the same `openField` slot.
          */}
          <div
            className={`fs-compact-cell fs-compact-trip fs-field${openField === 'triptype' ? ' open' : ''}`}
            data-dd="triptype"
          >
            <button
              type="button"
              className="fs-compact-trav-trigger"
              aria-expanded={openField === 'triptype'}
              onClick={(e) => {
                e.stopPropagation();
                goToStep(openField === 'triptype' ? null : 'triptype');
              }}
            >
              <span className="fs-compact-label">Trip Type</span>
              <span className="fs-compact-trav-value">
                {TRIP_TYPES.find((t) => t.value === formData.tripType)?.label}
                <span className="fs-compact-caret"><ChevronIcon /></span>
              </span>
            </button>
            <div className="fs-dropdown fs-choice-dd" role="listbox" aria-label="Trip type">
              {TRIP_TYPES.map(({ value, label }) => (
                <div
                  key={value}
                  role="option"
                  aria-selected={formData.tripType === value}
                  tabIndex={0}
                  className={`fs-list-item${formData.tripType === value ? ' is-selected' : ''}`}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleTripTypeChange(value);
                    goToStep(null);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      handleTripTypeChange(value);
                      goToStep(null);
                    }
                  }}
                >
                  {label}
                </div>
              ))}
            </div>
          </div>

          {isMultiCity ? (
            <div className="fs-compact-cell fs-compact-multi">
              {/* Deliberately not `fs-compact-grow`: that class zeroes the
                  cell's padding, because From/To wrap a shared `.fs-trigger`
                  that brings its own. This cell has no trigger inside it — its
                  label and route text are direct children — so inheriting
                  padding:0 left them flush against the border. It grows via
                  `.fs-compact-multi` instead. */}
              <span className="fs-compact-label">Flights</span>
              <button
                type="button"
                className="fs-compact-summary"
                aria-expanded={multiExpanded}
                aria-controls="fs-compact-legs"
                onClick={() => setMultiExpanded((v) => !v)}
              >
                <span className="fs-compact-summary-text">{multiRouteSummary}</span>
                <span className={`fs-compact-summary-caret${multiExpanded ? ' is-open' : ''}`}>
                  <ChevronIcon />
                </span>
              </button>
            </div>
          ) : (
            <>
              <div className="fs-compact-cell fs-compact-grow">
                <FsAirportFieldV3
                  role="origin"
                  excludeCode={formData.destination.code}
                  dd="from"
                  label="Leaving From"
                  icon="depart"
                  inputId="compact-leaving-from"
                  value={formData.origin}
                  open={openField === 'origin'}
                  onOpenChange={(open) => goToStep(open ? 'origin' : null)}
                  onChange={(origin) => {
                    handleOriginChange(origin);
                    goToStep('destination');
                  }}
                />
              </div>

              <button
                type="button"
                className="fs-swap fs-compact-swap"
                aria-label="Swap origin and destination"
                onClick={() => handleSwap()}
              >
                <SwapIcon />
              </button>

              <div className="fs-compact-cell fs-compact-grow">
                <FsAirportFieldV3
                  role="destination"
                  excludeCode={formData.origin.code}
                  dd="to"
                  label="Going to"
                  icon="arrive"
                  inputId="compact-going-to"
                  value={formData.destination}
                  note={sameAirportNote(formData.origin, formData.destination)}
                  open={openField === 'destination'}
                  onOpenChange={(open) => goToStep(open ? 'destination' : null)}
                  onChange={(destination) => {
                    handleDestinationChange(destination);
                    goToStep('depart');
                  }}
                />
              </div>

              <div className="fs-compact-cell fs-compact-date">
                <FlightDateFieldV3
                  dd="depart"
                  label="Depart"
                  placeholder="Depart"
                  selected={formData.departDate}
                  onChange={handleDepartChange}
                  onSelect={handleDepartSelect}
                  minDate={new Date()}
                  startDate={formData.departDate}
                  endDate={formData.returnDate}
                  selectsStart
                  open={openField === 'depart'}
                  onOpenChange={(open) => goToStep(open ? 'depart' : null)}
                />
              </div>

              {/* Shown on one-way as well as round trip, the same as the hero
                  panel — a traveller who is one tap from a cheaper return fare
                  should not have to find the trip-type control to discover it.
                  This cell was previously round-trip only because the row is
                  tight, but the round-trip row already carries it, so the
                  one-way row is now simply the same shape rather than a wider
                  one. `fs-compact-date` pins both date cells to one width so
                  the longer empty-state prompt cannot take space off From/To.
                  */}
              <div className="fs-compact-cell fs-compact-date">
                <FlightDateFieldV3
                  // Same remount-on-departure-change as the hero field: the
                  // calendar has to reopen on a month the new minDate allows.
                  key={formData.departDate?.toISOString()}
                  dd="return"
                  label="Return"
                  // One wording for both trip types here: it only ever shows
                  // while the field is empty, and "Select Return" reads the
                  // same whether the traveller has yet to add a return or has
                  // yet to pick one.
                  placeholder={RETURN_DATE_PROMPT_COMPACT}
                  selected={formData.returnDate}
                  onChange={handleReturnChange}
                  onSelect={() => advanceTo('travelers')}
                  minDate={minReturnDate}
                  startDate={formData.departDate}
                  endDate={formData.returnDate}
                  selectsEnd
                  open={openField === 'return'}
                  onOpenChange={(open) => goToStep(open ? 'return' : null)}
                  // Round trip only. On one way there is no return to clear and
                  // no trip type to fall back to, and the empty field is already
                  // inviting one — a cross there would offer to undo nothing.
                  onClear={formData.tripType === 'roundtrip' ? handleReturnClear : undefined}
                  clearLabel="Remove return date and switch to one way"
                />
              </div>
            </>
          )}

          {/*
            Its own trigger rather than the hero's `fs-trav-inline`, which lays
            headline, companions and a chevron out in a row sized for the
            multi-city controls bar. In a 134px cell that row did not fit:
            "0 Children" and the chevron spilled past the border and landed on
            top of the Cabin Class box next door — which is what looked like a
            stray arrow in the wrong place. Here the two halves stack like every
            other cell, and the cell clips rather than overflowing.
          */}
          <div
            className={`fs-compact-cell fs-compact-travelers fs-field${openField === 'travelers' ? ' open' : ''}`}
            data-dd="travelers"
          >
            <button
              type="button"
              className="fs-compact-trav-trigger"
              aria-expanded={openField === 'travelers'}
              onClick={(e) => {
                e.stopPropagation();
                goToStep(openField === 'travelers' ? null : 'travelers');
              }}
            >
              <span className="fs-compact-label">Travellers &amp; Class</span>
              <span className="fs-compact-trav-value">
                {travelersHeadline}, {CABIN_LABELS[formData.cabinClass]}
              </span>
            </button>
            <FlightTravelersV3
              value={formData.passengers}
              onChange={setPassengers}
              cabinClass={formData.cabinClass}
              onCabinChange={handleCabinChange}
            />
          </div>

          {/* CORP-ONLY (LEIS-934). Takes the column the separate Cabin Class
              cell used to hold — the merge above is what makes room for it. */}
          <div
            className={`fs-compact-cell fs-compact-bookingfor fs-field fs-bookingfor-field${openField === 'bookingfor' ? ' open' : ''}`}
            data-dd="bookingfor"
          >
            <BookingForField
              value={bookingFor}
              onChange={setBookingFor}
              airports={travellerAirports}
              open={openField === 'bookingfor'}
              onOpenChange={(next) => goToStep(next ? 'bookingfor' : null)}
              variant="compact"
            />
          </div>

          <button
            className="fs-compact-search"
            type="submit"
            disabled={searchInProgress}
            aria-busy={searchInProgress}
          >
            {searchInProgress ? (
              <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true" />
            ) : null}
            {searchInProgress ? 'Searching…' : 'Search'}
          </button>
        </div>

        {/* Second line, where MakeMyTrip puts fare type. It has to live
            somewhere: `directOnly=true` can arrive in the URL, and a filter
            applied with no way to see or clear it is a filter the traveller
            cannot escape without scrolling back to the hero form. */}
        <div className="fs-compact-second">
          <label className="fs-check">
            <input
              type="checkbox"
              className="fs-direct"
              checked={formData.directOnly}
              onChange={(e) => handleDirectOnlyChange(e.target.checked)}
            />
            <span>Direct flights only</span>
          </label>
        </div>

        {isMultiCity && multiExpanded && (
          <div id="fs-compact-legs" className="fs-compact-legs">
            {multiLegs.map((leg, idx) => (
              <div className="fs-seg fs-fields row g-0 align-items-stretch" key={idx}>
                <div className="col-lg col-md-6 col-12 fs-col">
                  <FsAirportFieldV3
                    role="origin"
                    excludeCode={leg.destination.code}
                    dd="from"
                    label="Leaving From"
                    icon="depart"
                    inputId={`compact-multi-from-${idx}`}
                    value={leg.origin}
                    open={openField === `leg-${idx}-origin`}
                    onOpenChange={(open) => goToStep(open ? `leg-${idx}-origin` : null)}
                    onChange={(origin) => {
                      originEditedRef.current = true;
                      setMultiLegs((prev) => prev.map((l, i) => (i === idx ? { ...l, origin } : l)));
                      goToStep(`leg-${idx}-destination`);
                    }}
                  />
                </div>

                <div className="col-auto fs-swap-col d-flex align-items-center justify-content-center">
                  <button
                    type="button"
                    className="fs-swap"
                    aria-label={`Swap origin and destination on flight ${idx + 1}`}
                    onClick={() => handleSwap(idx)}
                  >
                    <SwapIcon />
                  </button>
                </div>

                <div className="col-lg col-md-6 col-12 fs-col">
                  <FsAirportFieldV3
                    role="destination"
                    excludeCode={leg.origin.code}
                    dd="to"
                    label="Going to"
                    icon="arrive"
                    inputId={`compact-multi-to-${idx}`}
                    value={leg.destination}
                    note={sameAirportNote(leg.origin, leg.destination)}
                    open={openField === `leg-${idx}-destination`}
                    onOpenChange={(open) => goToStep(open ? `leg-${idx}-destination` : null)}
                    onChange={(destination) => {
                      setMultiLegs((prev) => prev.map((l, i) => (i === idx ? { ...l, destination } : l)));
                      goToStep(`leg-${idx}-depart`);
                    }}
                  />
                </div>

                <div className="col-lg col-md-6 col-12 fs-col fs-date-col">
                  <FlightDateFieldV3
                    dd="segdate"
                    label="Depart"
                    placeholder="From Date"
                    selected={leg.departDate}
                    onChange={(date) => handleLegDepartChange(idx, date)}
                    minDate={idx === 0 ? new Date() : multiLegs[idx - 1].departDate ?? new Date()}
                    open={openField === `leg-${idx}-depart`}
                    onOpenChange={(open) => goToStep(open ? `leg-${idx}-depart` : null)}
                  />
                </div>

                <div className="col-auto fs-seg-x-col d-flex align-items-center justify-content-center">
                  <button
                    type="button"
                    className="fs-seg-remove"
                    aria-label={`Remove flight ${idx + 1}`}
                    disabled={multiLegs.length <= MIN_MULTICITY_LEGS}
                    onClick={() => removeLeg(idx)}
                  >
                    <RemoveLegIcon />
                  </button>
                </div>
              </div>
            ))}

            <button
              type="button"
              className={`fs-add-flight${multiLegs.length >= MAX_MULTICITY_LEGS ? ' d-none' : ''}`}
              onClick={addLeg}
            >
              <AddLegIcon /> Add a Flight
            </button>
          </div>
        )}
      </form>
    );
  }

  return (
    <form className="fs-form flight-form" onSubmit={handleSubmit} noValidate>
      {/* Trip type, cabin, direct-only */}
      <div className="fs-controls d-flex flex-wrap align-items-center gap-3 gap-md-4 px-2 pt-1 pb-3">
        {TRIP_TYPES.map(({ value, label }) => (
          <label className="fs-radio" key={value}>
            <input
              type="radio"
              name="flight-trip"
              value={value}
              checked={formData.tripType === value}
              onChange={() => handleTripTypeChange(value)}
            />
            <span>{label}</span>
          </label>
        ))}

        <label className={`fs-check${isMultiCity ? ' d-none' : ''}`}>
          <input
            type="checkbox"
            className="fs-direct"
            checked={formData.directOnly}
            onChange={(e) => handleDirectOnlyChange(e.target.checked)}
          />
          <span>Direct flights only</span>
        </label>
      </div>

      {/* One way / round trip */}
      <div className={`fs-single${isMultiCity ? ' d-none' : ''}`}>
        <div className="fs-fields fs-single-row row g-0 align-items-stretch">
          <div className="col-lg col-md-6 col-12 fs-col">
            <FsAirportFieldV3
              role="origin"
              excludeCode={formData.destination.code}
              dd="from"
              label="Leaving From"
              icon="depart"
              inputId="flight-leaving-from"
              value={formData.origin}
              open={openField === 'origin'}
              onOpenChange={(open) => goToStep(open ? 'origin' : null)}
              onChange={(origin) => {
                handleOriginChange(origin);
                goToStep('destination');
              }}
            />
          </div>

          <div className="col-auto fs-swap-col d-flex align-items-center justify-content-center">
            <button
              type="button"
              className="fs-swap"
              aria-label="Swap origin and destination"
              onClick={() => handleSwap()}
            >
              <SwapIcon />
            </button>
          </div>

          <div className="col-lg col-md-6 col-12 fs-col">
            <FsAirportFieldV3
              role="destination"
              excludeCode={formData.origin.code}
              dd="to"
              label="Going to"
              icon="arrive"
              inputId="flight-going-to"
              value={formData.destination}
              note={sameAirportNote(formData.origin, formData.destination)}
              open={openField === 'destination'}
              onOpenChange={(open) => goToStep(open ? 'destination' : null)}
              onChange={(destination) => {
                handleDestinationChange(destination);
                goToStep('depart');
              }}
            />
          </div>

          <div className="col-lg col-md-6 col-12 fs-col fs-date-col">
            <FlightDateFieldV3
              dd="depart"
              label="Depart"
              placeholder="Depart"
              selected={formData.departDate}
              onChange={handleDepartChange}
              onSelect={handleDepartSelect}
              minDate={new Date()}
              selectsStart
              startDate={formData.departDate}
              endDate={formData.returnDate}
              open={openField === 'depart'}
              onOpenChange={(open) => goToStep(open ? 'depart' : null)}
            />
          </div>

          <div className="col-lg col-md-6 col-12 fs-col fs-date-col fs-return-col">
            <FlightDateFieldV3
              // Remount when departure moves so the calendar reopens on a month
              // the new minDate actually allows.
              key={formData.departDate?.toISOString()}
              dd="return"
              label="Return"
              // Shown even on one-way, like MakeMyTrip's inline "add a return
              // date" field next to Depart — picking a date here converts the
              // search to round trip itself (see handleReturnChange) instead of
              // making the traveller find the trip-type dropdown first.
              placeholder={formData.tripType === 'oneway' ? RETURN_DATE_PROMPT : 'Return'}
              // Only the one-way sell copy is sized down — it is a sentence
              // where every other placeholder is a field name. 'Return', and
              // the date that replaces either of them, keep the shared size.
              placeholderClassName={
                formData.tripType === 'oneway' ? 'fs-placeholder--sentence' : undefined
              }
              selected={formData.returnDate}
              onChange={handleReturnChange}
              onSelect={() => setOpenField(null)}
              minDate={minReturnDate}
              selectsEnd
              startDate={formData.departDate}
              endDate={formData.returnDate}
              open={openField === 'return'}
              onOpenChange={(open) => goToStep(open ? 'return' : null)}
              // See the compact bar's copy of this field: round trip only.
              onClear={formData.tripType === 'roundtrip' ? handleReturnClear : undefined}
              clearLabel="Remove return date and switch to one way"
            />
          </div>

          {/* CORP-ONLY (LEIS-934): Travellers and Cabin Class are one field here,
              the "Travellers & Class" pairing MakeMyTrip uses — which is what
              frees the column Booking For occupies beside it. The cabin options
              live inside this panel; see FlightTravelersV3. */}
          <div className="col-lg col-md-6 col-12 fs-col">
            <div className={`fs-field${openField === 'travelers' ? ' open' : ''}`} data-dd="travelers">
              <div
                className="fs-trigger"
                role="button"
                tabIndex={0}
                onClick={(e) => {
                  e.stopPropagation();
                  goToStep(openField === 'travelers' ? null : 'travelers');
                }}
              >
                <div className="fs-head">
                  <span className="fs-label">Travellers &amp; Class</span>
                  <ChevronIcon />
                </div>
                <div className="fs-value">{travelersHeadline}</div>
                <div className="fs-sub">
                  {[CABIN_LABELS[formData.cabinClass], travelersExtras].filter(Boolean).join(' · ')}
                </div>
              </div>
              <FlightTravelersV3
                value={formData.passengers}
                onChange={setPassengers}
                cabinClass={formData.cabinClass}
                onCabinChange={handleCabinChange}
              />
            </div>
          </div>

          {/* CORP-ONLY (LEIS-934): who the trip is for. */}
          <div
            className={`col-lg col-md-6 col-12 fs-col${openField === 'bookingfor' ? ' fs-col-open' : ''}`}
          >
            <div
              className={`fs-field fs-bookingfor-field${openField === 'bookingfor' ? ' open' : ''}`}
              data-dd="bookingfor"
            >
              <BookingForField
                value={bookingFor}
                onChange={setBookingFor}
                airports={travellerAirports}
                open={openField === 'bookingfor'}
                onOpenChange={(next) => goToStep(next ? 'bookingfor' : null)}
              />
            </div>
          </div>

        </div>
      </div>

      {/* Multi city */}
      <div className={`fs-multi${isMultiCity ? '' : ' d-none'}`}>
        <div className="fs-multi-rows">
          {multiLegs.map((leg, idx) => (
            <div className="fs-seg fs-fields row g-0 align-items-stretch" key={idx}>
              <div className="col-lg col-md-6 col-12 fs-col">
                <FsAirportFieldV3
                  role="origin"
                  excludeCode={leg.destination.code}
                  dd="from"
                  label="Leaving From"
                  icon="depart"
                  inputId={`multi-flight-from-${idx}`}
                  value={leg.origin}
                  open={openField === `leg-${idx}-origin`}
                  onOpenChange={(open) => goToStep(open ? `leg-${idx}-origin` : null)}
                  onChange={(origin) => {
                    originEditedRef.current = true;
                    setMultiLegs((prev) => prev.map((l, i) => (i === idx ? { ...l, origin } : l)));
                    goToStep(`leg-${idx}-destination`);
                  }}
                />
              </div>

              <div className="col-auto fs-swap-col d-flex align-items-center justify-content-center">
                <button
                  type="button"
                  className="fs-swap"
                  aria-label={`Swap origin and destination on flight ${idx + 1}`}
                  onClick={() => handleSwap(idx)}
                >
                  <SwapIcon />
                </button>
              </div>

              <div className="col-lg col-md-6 col-12 fs-col">
                <FsAirportFieldV3
                  role="destination"
                  excludeCode={leg.origin.code}
                  dd="to"
                  label="Going to"
                  icon="arrive"
                  inputId={`multi-flight-to-${idx}`}
                  value={leg.destination}
                  note={sameAirportNote(leg.origin, leg.destination)}
                  open={openField === `leg-${idx}-destination`}
                  onOpenChange={(open) => goToStep(open ? `leg-${idx}-destination` : null)}
                  onChange={(destination) => {
                    setMultiLegs((prev) => prev.map((l, i) => (i === idx ? { ...l, destination } : l)));
                    goToStep(`leg-${idx}-depart`);
                  }}
                />
              </div>

              <div className="col-lg col-md-6 col-12 fs-col fs-date-col">
                <FlightDateFieldV3
                  dd="segdate"
                  label="Depart"
                  placeholder="From Date"
                  selected={leg.departDate}
                  onChange={(date) => handleLegDepartChange(idx, date)}
                  onSelect={() =>
                    advanceTo(idx + 1 < multiLegs.length ? `leg-${idx + 1}-origin` : 'travelers')
                  }
                  minDate={idx > 0 && multiLegs[idx - 1].departDate ? multiLegs[idx - 1].departDate! : new Date()}
                  open={openField === `leg-${idx}-depart`}
                  onOpenChange={(open) => goToStep(open ? `leg-${idx}-depart` : null)}
                />
              </div>

              {/* Travelers/Cabin Class ride on flight 1's row only — same
                  columns One Way/Round Trip use in fs-single below, not a
                  field of their own per leg. Later legs render the same two
                  columns empty so "Remove flight" still lines up down the
                  page, matching MakeMyTrip's multi-city layout. */}
              {idx === 0 ? (
                <>
                  <div className="col-lg col-md-6 col-12 fs-col">
                    <div className={`fs-field${openField === 'travelers' ? ' open' : ''}`} data-dd="travelers">
                      <div
                        className="fs-trigger"
                        role="button"
                        tabIndex={0}
                        onClick={(e) => {
                          e.stopPropagation();
                          goToStep(openField === 'travelers' ? null : 'travelers');
                        }}
                      >
                        <div className="fs-head">
                          <span className="fs-label">Travellers &amp; Class</span>
                          <ChevronIcon />
                        </div>
                        <div className="fs-value">{travelersHeadline}</div>
                        <div className="fs-sub">
                          {[CABIN_LABELS[formData.cabinClass], travelersExtras]
                            .filter(Boolean)
                            .join(' · ')}
                        </div>
                      </div>
                      <FlightTravelersV3
                        value={formData.passengers}
                        onChange={setPassengers}
                        cabinClass={formData.cabinClass}
                        onCabinChange={handleCabinChange}
                      />
                    </div>
                  </div>

                  {/* CORP-ONLY (LEIS-934): one Booking For for the whole
                      itinerary, on flight 1's row with Travellers & Class.
                      A multi-city trip is one request for one traveller. */}
                  <div className="col-lg col-md-6 col-12 fs-col">
                    <div
                      className={`fs-field fs-bookingfor-field${openField === 'bookingfor' ? ' open' : ''}`}
                      data-dd="bookingfor"
                    >
                      <BookingForField
                        value={bookingFor}
                        onChange={setBookingFor}
                        airports={travellerAirports}
                        open={openField === 'bookingfor'}
                        onOpenChange={(next) => goToStep(next ? 'bookingfor' : null)}
                      />
                    </div>
                  </div>
                </>
              ) : (
                <>
                  <div className="col-lg col-md-6 col-12 fs-col" aria-hidden="true" />
                  <div className="col-lg col-md-6 col-12 fs-col" aria-hidden="true" />
                </>
              )}

              <div className="col-auto fs-seg-x-col d-flex align-items-center justify-content-center">
                <button
                  type="button"
                  className="fs-seg-remove"
                  aria-label={`Remove flight ${idx + 1}`}
                  disabled={multiLegs.length <= MIN_MULTICITY_LEGS}
                  onClick={() => removeLeg(idx)}
                >
                  <RemoveLegIcon />
                </button>
              </div>
            </div>
          ))}
        </div>

        <button
          type="button"
          className={`fs-add-flight${multiLegs.length >= MAX_MULTICITY_LEGS ? ' d-none' : ''}`}
          onClick={addLeg}
        >
          <AddLegIcon /> Add a Flight
        </button>
      </div>

      <div className="d-flex justify-content-center pt-3 px-2">
        <button
          className="button btn-subscribe h-45 px-4 rounded-2 d-flex align-items-center justify-content-center gap-2 w-sm-100"
          type="submit"
          disabled={searchInProgress}
          aria-busy={searchInProgress}
        >
          {searchInProgress ? (
            <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true" />
          ) : (
            <SearchFlightsIcon />
          )}
          {searchInProgress ? 'Searching…' : 'Search Flights'}
        </button>
      </div>
    </form>
  );
}
