'use client';

import { useEffect, useRef, useState, useMemo, useCallback } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { fetchFlightOffers, setActiveSort, resetFilters, setFilters, applyFlightFilters, sortFlights, setHasOutboundSelection, searchCacheKey, searchIdentityKey } from '@/store/slices/flightSearch.slice';
import { applySmartPredicates } from '@/services/flights/smartFilters/applySmartPredicates';
import { describeActiveFilters, directOnlyOffers, dropDuplicateItineraries, type ActiveFilterChip } from '@/services/flights/filterSort';
import { AwaitingReturnDateNotice, SearchFailedNotice } from './FlightResultsNotice';
import { readRoundTripView, rememberRoundTripView, type RoundTripView } from '@/services/flights/searchPreferences';
import { useCachedFlightSearch } from './useCachedFlightSearch';
import { useCompareTray } from './useCompareTray';
import CompareTray from './CompareTray';
import { buildCompareUrl } from '@/services/flights/compareUrl';
import type { CompareStep } from '@/store/slices/flightCompare.slice';
import { formatFlightMoney } from '@/services/flights/formatPrice';
import type { SortKey } from '@/store/slices/flightSearch.slice';
import type { FlightData } from './types';
import { requestFlightApproval } from '@/services/flights/approvalRequest';
import { describeFlightSelection, trackFlightEvent, trackFlightEventOnce } from '@/services/flights/tracking';
import { trackMetaPixelEventOnce } from '@/lib/meta-pixel';
import { parseItinerary, parseChildren, parseInfants, decodeCabinClass } from '@/services/flights/searchUrl';
import { parseFiltersFromParams } from '@/services/flights/filtersUrl';
import { useSyncSearchUrl } from './useSyncSearchUrl';
import type { ResolvedLocation } from '@/services/flights/resolveFlightCityNames';
import FlightSortTabs from './FlightSortTabs';
import FlightDateStrip from './FlightDateStrip';
import FlightsFilteredEmptyState from './FlightsFilteredEmptyState';
import FlightFilterSidebar from './FlightFilterSidebar';
import FlightMobileFilterBar from './FlightMobileFilterBar';
import SmartFiltersPinned from './smartFilters/SmartFiltersPinned';
import FlightsEmptyState from './FlightsEmptyState';
import FlightsSearchingState from './FlightsSearchingState';
import { NO_SEARCH_YET } from './noSearchYet';
import FlightsErrorState from './FlightsErrorState';
import { buildFlightError } from '@/services/flights/errors';
import { toastFlightError, toastDevUpstreamFailure } from '@/services/flights/errors.client';
import { TOAST_IDS } from '@/lib/toast';
import MultiCityFlightCard from './MultiCityFlightCard';
import FlightsList from './FlightsList';
import FlightFaresModal from './FlightFaresModal';
import RoundTripPairBar from './RoundTripPairBar';
import { toast } from '@/lib/toast';
import {
  buildOutboundOptions,
  buildReturnOptions,
  findPair,
  resolvePairOffers,
  type RoundTripOption,
} from '@/services/flights/roundTripPairs';

interface RoundTripSearchClientProps {
  /** Server-resolved code -> {city, country}, shown before the search API's own resolution lands. */
  initialLocationNames?: Record<string, ResolvedLocation>;
}

/**
 * Round trip defaults to picking outbound and return independently, one step
 * at a time (any carrier/time combination on either leg) — with an opt-in
 * toggle to Amadeus's own whole-journey bundle fares instead (one price, one
 * card, browsed like a one-way search) when search-service actually has
 * bundle-priced offers for this route (see flightOffersMapper.js's
 * buildRoundTripIndex). That toggle only appears when there's something real
 * to switch to — round-trip-only inventory with no separate legs at all would
 * make an empty "combined" tab pointless.
 */
export default function RoundTripSearchClient({ initialLocationNames }: RoundTripSearchClientProps = {}) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const dispatch = useAppDispatch();

  const { offersResult, offersIdentity, offersStatus, offersError, offersCapped, activeSort, filters, smartPredicates, searchTrigger, awaitingReturnDate } =
    useAppSelector((state) => state.flightSearch);

  // Fares modal — opened from the sticky bar's Continue for a last look before
  // handing off; that modal owns its own auth-check + /flight-review navigation.
  const [isFaresModalOpen, setIsFaresModalOpen] = useState(false);
  // True while Continue is skipping straight to review (every leg has only
  // one fare option — nothing to actually pick in the modal).
  const [isGoingToReview, setIsGoingToReview] = useState(false);

  // Default: pick outbound and return independently (the paired step-by-step
  // flow below) — any carrier/time combination on either leg. "combined" is
  // an opt-in for travellers who'd rather browse Amadeus's own whole-journey
  // bundle offers (one card, one price for both legs) instead of two steps.
  const [viewMode, setViewModeState] = useState<RoundTripView>('stepByStep');

  // Applied after mount rather than as the initial value: this reads
  // sessionStorage, which the server cannot, and seeding state from it directly
  // would make the first client render disagree with the server's and fail
  // hydration. The cost is one frame in the default layout.
  useEffect(() => {
    setViewModeState(readRoundTripView());
  }, []);

  /** Remembered for the session, so returning to round trip opens how they left it. */
  const setViewMode = useCallback((next: RoundTripView) => {
    setViewModeState(next);
    rememberRoundTripView(next);
  }, []);

  // ── Paired flow ────────────────────────────────────────────────────────────
  // Which outbound the traveller picked, as its slice key. Held in memory rather
  // than the URL: it is a choice within a search, not part of the search, and
  // putting it in the URL would mean re-deriving a flight from a key on every
  // navigation. The step itself IS in the URL — see `step` below.
  const [selectedOutboundKey, setSelectedOutboundKey] = useState<string | null>(null);

  /**
   * Publish whether an outbound is chosen, for the search form to consult.
   *
   * Changing the trip type discards this selection, and the form is what
   * changes the trip type — but the selection itself lives here. Only the fact
   * of it is shared. Cleared on unmount so leaving round trip by any route,
   * including the browser's Back button, cannot leave a stale flag behind.
   */
  useEffect(() => {
    dispatch(setHasOutboundSelection(Boolean(selectedOutboundKey)));
  }, [selectedOutboundKey, dispatch]);

  useEffect(() => () => { dispatch(setHasOutboundSelection(false)); }, [dispatch]);
  const [selectedReturnKey, setSelectedReturnKey] = useState<string | null>(null);
  /** The 1-or-2 offers the chosen pair resolves to, handed to the fares modal. */
  const [pairOffers, setPairOffers] = useState<FlightData[] | null>(null);
  /** The step heading, so a step change moves focus there rather than stranding it. */
  const stepHeadingRef = useRef<HTMLHeadingElement>(null);

  // Parsed once per render, reused by both effects below instead of each
  // independently re-parsing the same params.
  const segments = parseItinerary(searchParams.get('itinerary'));
  useSyncSearchUrl(segments, filters);

  // One-shot: hydrate filters from a shared/bookmarked/refreshed URL — see
  // FlightsSearchClient.tsx's identical effect for why this is guarded to
  // run only once rather than folded into useSyncSearchUrl itself.
  const filtersHydratedRef = useRef(false);
  useEffect(() => {
    if (filtersHydratedRef.current) return;
    filtersHydratedRef.current = true;
    const patch = parseFiltersFromParams(searchParams);
    if (Object.keys(patch).length > 0) dispatch(setFilters(patch));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fromCode = segments[0]?.from ?? '';
  const toCode = segments[0]?.to ?? '';
  const departDate = segments[0]?.date ?? '';
  const returnDate = segments[1]?.date ?? '';
  const fromCity = offersResult?.fromCity || initialLocationNames?.[fromCode]?.city || fromCode || 'Origin';
  const toCity = offersResult?.toCity || initialLocationNames?.[toCode]?.city || toCode || 'Destination';
  const adults = Number(searchParams.get('adults') || 1);
  const children = parseChildren(searchParams);
  const infants = parseInfants(searchParams.get('infants'));
  const cabin = decodeCabinClass(searchParams.get('cabinClass'));
  const directOnly = searchParams.get('directOnly') === 'true';

  // Serves a recent identical search from memory before asking the server —
  // see useCachedFlightSearch. `null` until a return date exists: a round trip
  // without one is not a searchable question, and the SRP says so rather than
  // searching for a date nobody chose.
  const searchInput = useMemo(
    () =>
      fromCode && toCode && departDate && returnDate
        ? {
            tripType: 'roundtrip' as const,
            from: fromCode,
            fromCity,
            to: toCode,
            toCity,
            departDate,
            returnDate,
            adults,
            children,
            infants,
            cabin,
            directOnly,
          }
        : null,
    [fromCode, toCode, fromCity, toCity, departDate, returnDate, adults, children, infants, cabin, directOnly],
  );

  /**
   * The store's results, but only when they answer the search the URL is
   * asking for — see FlightsSearchClient for the full reasoning. Browser Back
   * changes the URL without going through the form, so nothing supersedes the
   * previous search's offers there; this is what keeps them off screen until
   * the request for the new URL has an answer.
   */
  const currentResult =
    searchInput !== null && offersIdentity !== null && offersIdentity === searchIdentityKey(searchInput)
      ? offersResult
      : null;

  useCachedFlightSearch({
    input: searchInput,
    searchTrigger,
    onRejected: (action) => {
      if (action.payload) {
        toastDevUpstreamFailure(action.payload, { id: TOAST_IDS.flightUpstreamDev, context: 'Flight search' });
      }
    },
  });

  // Re-runs the exact same search that just failed — same params, fresh call.
  function handleRetrySearch() {
    dispatch(fetchFlightOffers({
      tripType: 'roundtrip',
      from: fromCode,
      fromCity,
      to: toCode,
      toCity,
      departDate,
      returnDate,
      adults,
      children,
      infants,
      cabin,
      directOnly,
    }));
  }

  // Server-side filter refinement: a *fallback*, not an automatic companion to
  // price/airline/refundable/bags filters. Those four are already filtered
  // correctly from whatever offers are already fetched (applyFlightFilters
  // reads outbound.checkin/refundStatus/etc. straight off each offer) — the
  // only thing a server round-trip can add is recovering matches *beyond* the
  // capped ~250-offer batch, which is only worth it when local filtering has
  // nothing to show at all (either view — combined or per-leg). Merges into
  // the existing set in the background (see fetchFlightOffers.fulfilled
  // reducer), so this only ever adds results, never blocks the page.
  const lastRefinementKey = useRef<string | null>(null);
  useEffect(() => {
    if (!fromCode || !toCode || !departDate || !returnDate) return;

    // Only bother refining if the broad search actually hit the offers cap
    // (otherwise Amadeus has nothing more to give) AND local filtering left
    // nothing to show across the whole fetched set — a thin-but-nonempty
    // local match, in either view, is left alone rather than topped up.
    // `rawOffers` (the memoized version) isn't declared until further down
    // this component, so this reads offersResult directly the same way it does.
    const currentRawOffers = currentResult?.tripType === 'roundtrip' ? currentResult.offers : [];
    const hasServerFilters =
      offersCapped &&
      currentRawOffers.length > 0 &&
      applyFlightFilters(currentRawOffers, filters).length === 0 &&
      (filters.maxPrice != null || filters.airlines.length > 0 || filters.refundableOnly || filters.checkedBagsOnly);
    const key = `${fromCode}|${toCode}|${departDate}|${returnDate}|${adults}|${children}|${infants}|${cabin}|${directOnly}|${filters.maxPrice}|${filters.airlines.join(',')}|${filters.refundableOnly}|${filters.checkedBagsOnly}`;
    if (!hasServerFilters || lastRefinementKey.current === key) return;

    let abort: (() => void) | undefined;
    const timer = setTimeout(() => {
      lastRefinementKey.current = key;
      const promise = dispatch(fetchFlightOffers({
        tripType: 'roundtrip',
        from: fromCode,
        fromCity,
        to: toCode,
        toCity,
        departDate,
        returnDate,
        adults,
        children,
        infants,
        cabin,
        directOnly,
        maxPrice: filters.maxPrice ?? undefined,
        includedCarriers: filters.airlines.length ? filters.airlines : undefined,
        refundableOnly: filters.refundableOnly || undefined,
        includedCheckedBagsOnly: filters.checkedBagsOnly || undefined,
        isRefinement: true,
      }));
      // A refinement failure used to be swallowed entirely: the reducer returns
      // early for isRefinement, so the user silently kept an unrefined list with
      // no hint their filter never reached the server. That was the right call
      // when the only alternative was replacing the whole page with an error —
      // a dismissible toast is the proportionate weight. Handled here rather
      // than in the reducer so reducers stay pure. Aborted refinements (the
      // debounce superseding itself) are not failures and stay silent.
      promise.then((action) => {
        if (fetchFlightOffers.rejected.match(action) && !action.meta.aborted && action.payload) {
          toastFlightError(action.payload, {
            id: TOAST_IDS.flightRefinement,
            context: 'refinement search',
          });
        }
      });
      abort = () => promise.abort();
    }, 400);

    return () => {
      clearTimeout(timer);
      abort?.();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fromCode, toCode, departDate, returnDate, adults, children, infants, cabin, directOnly, offersCapped, filters.maxPrice, filters.airlines.join(','), filters.refundableOnly, filters.checkedBagsOnly]);

  const isLoading = offersStatus === 'loading';
  const rawOffers = useMemo(() => {
    const result = currentResult?.tripType === 'roundtrip' ? currentResult.offers : [];
    // Narrowed the moment the toggle flips, before the authoritative
    // direct-only search returns — and a standing guarantee that nothing with a
    // connection on either leg appears under one. See directOnlyOffers.
    return directOnly ? directOnlyOffers(result) : result;
  }, [currentResult, directOnly]);

  // ── Combined flow: derived ──────────────────────────────────────────────────
  // Amadeus's own whole-journey bundle offers (single fare covering both legs)
  // — search-service keeps these as-is alongside any separately-combinable legs
  // (see flightOffersMapper.js / flightOffersSearchService.js). Independent of
  // the pairing index below: FlightCard already renders `outbound` + `inbound`
  // in one card and owns its own fare modal, so this mode needs nothing from
  // roundTripPairs at all — a real fallback if that index is ever unavailable.
  const combinationOffers = useMemo(
    // Deduped for the same reason the paired lists are: Amadeus returns the
    // identical whole journey more than once — same flights, same brand, same
    // price — and each repeat is a card the traveller has to read before
    // discovering it is the one above it again. See dropDuplicateItineraries.
    () => dropDuplicateItineraries(rawOffers.filter((o) => o.oneWay !== true)),
    [rawOffers],
  );
  const visibleCombinationOffers = useMemo(
    () => sortFlights(applySmartPredicates(applyFlightFilters(combinationOffers, filters), smartPredicates), activeSort),
    [combinationOffers, filters, smartPredicates, activeSort],
  );
  const combinedIsEmpty = !isLoading && combinationOffers.length === 0;

  const combinedFilterChips = useMemo(
    () => describeActiveFilters(filters, { currency: combinationOffers[0]?.currency ?? '' }),
    [filters, combinationOffers],
  );

  // Campaign funnel: results for this search are on screen. One event per search, not per
  // view mode — flipping between the bundled and choose-separately tabs, sorting, or
  // filtering is the same set of results looked at differently. totalListings counts every
  // offer the search returned, both modes included, since that is what "this campaign
  // produced N results" means.
  useEffect(() => {
    if (offersStatus !== 'success' || offersResult?.tripType !== 'roundtrip') return;
    const search = searchParams.toString();
    void trackFlightEventOnce(
      `roundtrip:${search}`,
      'SRP_LISTINGS_VIEWED',
      {
        originLocationCode: fromCode,
        destinationLocationCode: toCode,
        departureDate: departDate,
        returnDate,
        tripType: 'ROUNDTRIP',
      },
      {
        metadata: {
          path: pathname,
          search,
          totalListings: rawOffers.length,
          visibleListings: visibleCombinationOffers.length,
          cabin,
          directOnly,
          adults,
          children,
          infants,
        },
      }
    );
    return trackMetaPixelEventOnce(`Search:flights:${search}`, 'Search', {
      search_string: `${fromCode}-${toCode} ${departDate} / ${returnDate}`,
      content_type: 'product',
      content_category: 'Flight',
      value: visibleCombinationOffers[0]?.pricePerPerson ?? 0,
      currency: visibleCombinationOffers[0]?.currency ?? 'USD',
    });
  // Derived counts are read for context only; the dedupe key is the search itself.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [offersStatus, offersResult, searchParams, pathname]);

  // ── Paired flow: derived ───────────────────────────────────────────────────

  /**
   * search-service's pairing index, converted to slice keys by the thunk.
   *
   * Required, not optional: Amadeus's two response shapes (whole-journey bundles
   * and independently combinable legs) are reconciled there, and this screen has
   * no other way to know which pairs exist or what they cost. A response without
   * it is a version mismatch between this app and search-service, handled as the
   * deploy problem it is rather than silently rendering something else.
   */
  const pairIndex = currentResult?.tripType === 'roundtrip' ? currentResult.roundTripPairs : null;
  /** Offers arrived, but with no pairing index — see pairIndex. */
  const isIndexMissing = !isLoading && !pairIndex && rawOffers.length > 0;

  // Rows are built from the UNFILTERED offers: the index resolves a slice
  // through whichever offer carries it, and a filtered-out offer would make a
  // flight that is perfectly valid disappear from the list. Filtering happens
  // to the rows afterwards, where it acts on the leg being chosen and on the
  // trip total.
  const outboundRows = useMemo(
    () => (pairIndex ? buildOutboundOptions(rawOffers, pairIndex) : []),
    [rawOffers, pairIndex],
  );
  const returnRows = useMemo(
    () => (pairIndex && selectedOutboundKey ? buildReturnOptions(rawOffers, pairIndex, selectedOutboundKey) : []),
    [rawOffers, pairIndex, selectedOutboundKey],
  );

  const selectedOutbound = useMemo(
    () => outboundRows.find((row) => row.sliceKey === selectedOutboundKey) ?? null,
    [outboundRows, selectedOutboundKey],
  );
  const selectedReturn = useMemo(
    () => returnRows.find((row) => row.sliceKey === selectedReturnKey) ?? null,
    [returnRows, selectedReturnKey],
  );

  /**
   * Step 0 picks the outbound, step 1 the return. It lives in the URL so Back
   * returns to the outbound list instead of leaving the SRP — and safely so:
   * both fetch effects key off derived search values, never the raw params
   * object, so an extra `leg` param cannot trigger a refetch.
   *
   * An arriving `?leg=return` with no outbound chosen (a shared link, a reload)
   * falls back to step 0 rather than rendering an empty return list.
   */
  const step: 0 | 1 = searchParams.get('leg') === 'return' && selectedOutbound ? 1 : 0;

  // Scoped to the step on screen: an outbound and a return are not alternatives
  // to each other, and a return row is priced as the whole trip with that
  // return. Switching step therefore starts a fresh comparison.
  const compareStep: CompareStep = step === 1 ? 'return' : 'outbound';
  const compare = useCompareTray({
    searchKey: searchInput ? searchCacheKey(searchInput) : null,
    step: compareStep,
  });

  const openCompare = useCallback(() => {
    const href = buildCompareUrl({
      searchParams: new URLSearchParams(searchParams.toString()),
      sliceKeys: compare.entries.map((e) => e.sliceKey),
      step: compareStep,
      // Return columns are priced as whole trips with this outbound.
      outboundKey: compareStep === 'return' ? selectedOutboundKey : null,
    });
    const isTouch =
      typeof window !== 'undefined' &&
      !window.matchMedia('(hover: hover) and (pointer: fine)').matches;
    if (isTouch) router.push(href);
    else window.open(href, '_blank', 'noopener,noreferrer');
  }, [compare.entries, searchParams, router, compareStep, selectedOutboundKey]);


  const goToStep = useCallback(
    (next: 0 | 1) => {
      const params = new URLSearchParams(searchParams.toString());
      if (next === 1) params.set('leg', 'return');
      else params.delete('leg');
      router.push(`${pathname}?${params.toString()}`, { scroll: false });
    },
    [pathname, router, searchParams],
  );

  // A URL claiming the return step with nothing selected is corrected rather
  // than merely ignored, so the address bar keeps matching what is on screen.
  useEffect(() => {
    if (searchParams.get('leg') === 'return' && !selectedOutbound && outboundRows.length > 0) {
      goToStep(0);
    }
  }, [searchParams, selectedOutbound, outboundRows.length, goToStep]);

  // A new search invalidates both choices — the flights they named are gone.
  useEffect(() => {
    setSelectedOutboundKey(null);
    setSelectedReturnKey(null);
    setPairOffers(null);
  }, [searchTrigger, fromCode, toCode, departDate, returnDate]);

  // Changing step swaps the whole list under a keyboard user without moving
  // their focus, which would leave them tabbing from wherever the old list was.
  // The heading is the right landing place: it names the step they just entered.
  // Skipped on first paint, which is not a step *change*.
  const lastAnnouncedStep = useRef<0 | 1 | null>(null);
  useEffect(() => {
    if (lastAnnouncedStep.current === null) {
      lastAnnouncedStep.current = step;
      return;
    }
    if (lastAnnouncedStep.current === step) return;
    lastAnnouncedStep.current = step;
    stepHeadingRef.current?.focus();
  }, [step]);

  const stepRows: RoundTripOption[] = step === 1 ? returnRows : outboundRows;
  const visibleRows = useMemo(
    () => sortFlights(applySmartPredicates(applyFlightFilters(stepRows, filters), smartPredicates), activeSort) as RoundTripOption[],
    [stepRows, filters, smartPredicates, activeSort],
  );

  function fmtDate(iso: string) {
    if (!iso) return '';
    return new Date(iso).toLocaleDateString('en-US', { weekday: 'short', day: '2-digit', month: 'short' });
  }

  const departLabel = fmtDate(departDate);
  const returnLabel = fmtDate(returnDate);
  const summaryLabel = departLabel && returnLabel
    ? `${fromCity} · ${toCity} · ${departLabel} – ${returnLabel}`
    : `${fromCity} · ${toCity}`;

  // "Depart: DEL - BOM" / "Return: BOM - DEL" — matches FlightFaresModal's own
  // documented multi-flight label convention, doubles as the SRP's leg tabs.
  const legLabels = [
    { label: `Depart: ${fromCode} - ${toCode}`, date: departLabel },
    { label: `Return: ${toCode} - ${fromCode}`, date: returnLabel },
  ];

  // Applying a filter can shrink the list to fewer rows than the user has
  // already scrolled past, leaving them stranded near the footer. When the
  // filter set changes, if the results block has scrolled above the viewport,
  // pull its top back in. Skips the first run and only nudges when the user is
  // actually past the top.
  const contentRef = useRef<HTMLDivElement>(null);
  const filterSignature = JSON.stringify(filters);
  const filterScrollPrimed = useRef(false);
  useEffect(() => {
    if (!filterScrollPrimed.current) {
      filterScrollPrimed.current = true;
      return;
    }
    const el = contentRef.current;
    if (!el) return;
    const top = el.getBoundingClientRect().top;
    if (top < 0) {
      window.scrollTo({ top: window.scrollY + top - 90, behavior: 'smooth' });
    }
  }, [filterSignature]);

  // Nothing to choose from — hand the whole width to the empty state. Still
  // hidden during loading, when the outcome is not known yet.
  const isEmpty = !isLoading && !isIndexMissing && outboundRows.length === 0;
  // Nothing was searched for, so "no flights found" would be untrue — see NO_SEARCH_YET.
  const noSearchYet = !fromCode || !toCode || !departDate || !returnDate;
  // First paint of a search — nothing has ever come back yet, so there's no
  // list to keep visible underneath a skeleton. Same isFirstLoad gate as the
  // one-way results page (FlightsSearchClient) — a filter-driven refinement
  // of results already on screen (isLoading but rawOffers.length > 0) keeps
  // the lighter skeleton treatment instead.
  const isFirstLoad = isLoading && rawOffers.length === 0;

  /**
   * The strip is hidden while the first results are still being fetched — a
   * row of dates above a searching state is navigation for a page that has not
   * arrived yet. After that it stays, including while a later search runs:
   * clicking a date in the strip reloads the results, and having the control
   * you just used blink out from under the cursor and back is worse than a
   * moment of stale-looking dates. It reads its selected date from the URL, so
   * it is already correct the instant the navigation happens.
   */
  const hasShownResults = useRef(false);
  useEffect(() => {
    if (rawOffers.length > 0) hasShownResults.current = true;
  }, [rawOffers.length]);
  /**
   * `idle` counts as waiting, not as "done with nothing".
   *
   * On the server `offersStatus` is idle — the search is dispatched from an
   * effect, so it has not started yet — and testing only `isLoading` rendered
   * the strip into the SSR markup, then tore it out the instant the client
   * began fetching and put it back when results landed. Two flashes before the
   * page had shown anything.
   *
   * A finished search with zero results deliberately still shows the strip:
   * that is precisely when a nearby date is the most useful thing on screen.
   */
  const awaitingFirstResults = (offersStatus === 'idle' || isLoading) && rawOffers.length === 0;
  const showDateStrip = !awaitingFirstResults || hasShownResults.current;


  /**
   * Picking a row in the paired flow.
   *
   * Choosing an outbound moves straight on to the return step — that is the
   * whole point of the two steps, and stopping to click "next" would be a beat
   * with nothing in it. Re-choosing the same outbound is treated the same way,
   * so a traveller who came back to check their choice can carry on without
   * having to deselect and reselect.
   */
  function handleSelectRow(row: RoundTripOption) {
    if (step === 1) {
      setSelectedReturnKey(row.sliceKey);
      return;
    }
    // A return chosen against the previous outbound is kept when it still pairs
    // with the new one — most returns pair with most outbounds, and silently
    // discarding a choice the traveller can still have is worse than the small
    // cost of checking. Its price may well differ, which the bar picks up on its
    // own because the row is re-derived for the new outbound.
    if (row.sliceKey !== selectedOutboundKey && selectedReturnKey && pairIndex) {
      if (!findPair(pairIndex, row.sliceKey, selectedReturnKey)) {
        setSelectedReturnKey(null);
        toast.info('Your return does not pair with that outbound — please choose another.');
      }
    }
    setSelectedOutboundKey(row.sliceKey);
    goToStep(1);
  }

  /**
   * Continue from a complete pair.
   *
   * The pair is resolved to real offers only now, not when it was displayed: a
   * row is a price and a pair of slices, and which offers actually book it
   * depends on whether the bundle or the two legs came out cheaper. The modal
   * takes it from here — fare tiers, then the review handoff.
   *
   * Skipped when both resolved offers have exactly one fare option each:
   * there's nothing to actually choose between (the modal would just
   * pre-select both and wait for another Continue click), so this goes
   * straight to review instead.
   */
  async function handlePairContinue() {
    if (isGoingToReview) return;
    if (!pairIndex || !selectedOutboundKey || !selectedReturnKey) return;
    const resolved = resolvePairOffers(rawOffers, pairIndex, selectedOutboundKey, selectedReturnKey);
    if (!resolved) {
      // The pair was on screen a moment ago, so this means the offers behind it
      // have gone — a refinement replaced them, or the search moved on. Sending
      // them to an error screen would overstate it; the fix is to pick again.
      toast.error('That combination is no longer available. Please choose your return again.');
      setSelectedReturnKey(null);
      return;
    }

    // The round-trip equivalent of singling out a card: a specific outbound and return
    // have been chosen together.
    void trackFlightEvent('SEE_AVAILABILITY_CLICK', describeFlightSelection(resolved.offers, 'ROUNDTRIP'), {
      revenueAmount: resolved.offers.reduce((total, f) => total + (f.pricePerPerson ?? 0), 0) || undefined,
      currency: resolved.offers[0]?.currency,
      metadata: { offerIds: resolved.offers.map((f) => f.id), view: 'pair' },
    });

    const onlyOneFareEach = resolved.offers.every((f) => (f.fareOptions?.length ?? 0) === 1);
    if (onlyOneFareEach) {
      setIsGoingToReview(true);
      // corp: every leg has a single fare, so there is nothing to pick —
      // request approval directly. leisure-ui booked here instead.
      const ok = await requestFlightApproval({ flights: resolved.offers, tripType: 'ROUNDTRIP' });
      if (!ok) setIsGoingToReview(false);
      return;
    }

    setPairOffers(resolved.offers);
    setIsFaresModalOpen(true);
  }

  return (
    <>
      <div className="row g-3" ref={contentRef}>
        {/* Phone only. One bar for both view modes, fed whichever offer set is
            actually on screen — the combined itineraries, or the rows of the
            leg being chosen — so its airline chips never offer a carrier the
            current view cannot show. */}
        {!isFirstLoad && (viewMode === 'combined' ? !combinedIsEmpty : !isEmpty) && (
          <div className="col-12 order-0 d-lg-none">
            <SmartFiltersPinned
              offers={viewMode === 'combined' ? combinationOffers : stepRows}
              filters={filters}
              activeSort={activeSort}
              tripType="roundtrip"
              origin={fromCode}
              destination={toCode}
              departDate={departDate}
              returnDate={returnDate}
              currency={(viewMode === 'combined' ? combinationOffers[0]?.currency : stepRows[0]?.currency) ?? ''}
              {...(viewMode === 'stepByStep' ? { step } : {})}
              onLegHint={(leg) => {
                if (leg === 'return' && selectedOutbound) goToStep(1);
                else if (leg === 'outbound') goToStep(0);
              }}
            />
          </div>
        )}
        {!isFirstLoad && (viewMode === 'combined' ? !combinedIsEmpty : !isEmpty) && (
          <FlightMobileFilterBar
            offers={viewMode === 'combined' ? combinationOffers : stepRows}
            resultCount={viewMode === 'combined' ? combinationOffers.length : stepRows.length}
            totalCount={rawOffers.length}
            searchContext={{
              tripType: 'roundtrip',
              origin: fromCode,
              destination: toCode,
              departDate,
              returnDate,
              currency: (viewMode === 'combined' ? combinationOffers[0]?.currency : stepRows[0]?.currency) ?? '',
              ...(viewMode === 'stepByStep' ? { step } : {}),
            }}
          />
        )}


        {/* Above the empty-state branch on purpose: a date pair that returns
            nothing is exactly when the strip matters most. Each cell moves the
            whole trip and keeps its length — see dateStrip.ts. */}
        <div className="col-12 order-0 flight-date-strip-col">
          {showDateStrip && <FlightDateStrip tripType="roundtrip" />}
        </div>

        {!isFirstLoad && (isLoading || (viewMode === 'combined' ? !combinedIsEmpty : !isEmpty)) && (
          <div className="col-12 order-1">
            <h3 ref={stepHeadingRef} tabIndex={-1} className="text-xxl color-text-dark fw-semibold mb-0 pt-2">
              {isLoading
                ? 'Searching...'
                : viewMode === 'combined'
                  ? `${visibleCombinationOffers.length} combined fare${visibleCombinationOffers.length === 1 ? '' : 's'}`
                  : step === 1
                    ? `Choose your return · ${visibleRows.length} option${visibleRows.length === 1 ? '' : 's'}`
                    : `Choose your outbound · ${visibleRows.length} flight${visibleRows.length === 1 ? '' : 's'}`}
            </h3>
            <p className="mb-0 text-sm">{summaryLabel}</p>

            {/* Above the list, never in place of it — the previous results are
                still the best answer on screen. */}
            {awaitingReturnDate ? <AwaitingReturnDateNotice /> : null}
            {offersError && rawOffers.length > 0 ? (
              <SearchFailedNotice error={offersError} onRetry={handleRetrySearch} isRetrying={isLoading} />
            ) : null}

            {viewMode === 'stepByStep' && (
              <p className="visually-hidden" role="status" aria-live="polite">
                {step === 1
                  ? `Step 2 of 2, choose your return flight. ${visibleRows.length} options.`
                  : `Step 1 of 2, choose your outbound flight. ${visibleRows.length} flights.`}
              </p>
            )}

            <FlightSortTabs
              activeTab={activeSort}
              onTabChange={(tab) => dispatch(setActiveSort(tab as SortKey))}
              cheapestLabel={
                viewMode === 'combined'
                  ? (visibleCombinationOffers.length
                      ? formatFlightMoney(
                          visibleCombinationOffers[0].currency,
                          Math.min(...visibleCombinationOffers.map((r) => r.pricePerPerson)),
                        )
                      : undefined)
                  : (visibleRows.length
                      ? formatFlightMoney(
                          visibleRows[0].currency,
                          Math.min(...visibleRows.map((r) => r.pricePerPerson)),
                        )
                      : undefined)
              }
              fastestLabel={
                viewMode === 'combined'
                  ? sortFlights(visibleCombinationOffers, 'fastest')[0]?.outbound.duration
                  : sortFlights(visibleRows, 'fastest')[0]?.outbound.duration
              }
            />
          </div>
        )}

        {isFirstLoad ? (
          <div className="col-12 order-2">
            <FlightsSearchingState routeLabel={summaryLabel} />
          </div>
        ) : viewMode === 'combined' ? (
          combinedIsEmpty ? (
            <div className="col-12 order-2">
              {offersError ? (
                <FlightsErrorState error={offersError} onRetry={handleRetrySearch} />
              ) : noSearchYet ? (
                <FlightsEmptyState title={NO_SEARCH_YET.title} description={NO_SEARCH_YET.description} />
              ) : (
                <FlightsEmptyState
                  title="No combined fares match your filters"
                  description="Try relaxing a filter, or switch to selecting flights separately."
                />
              )}
            </div>
          ) : (
            <>
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-12 col-12 order-lg-2 order-3 filterDetails sticky-filter-sidebar position-sticky top-0 mb-3 mb-lg-0 d-none d-lg-block">
                <FlightFilterSidebar
                  offers={combinationOffers}
                  onClearFilters={() => dispatch(resetFilters())}
                  isLoading={isLoading}
                  viewMode={viewMode}
                  onViewModeChange={setViewMode}
                  smartFiltersContext={{
                    tripType: 'roundtrip',
                    origin: fromCode,
                    destination: toCode,
                    departDate,
                    returnDate,
                    currency: combinationOffers[0]?.currency ?? '',
                  }}
                />
              </div>
              <div className="col-lg-9 col-md-12 col-sm-12 col-12 order-lg-3 order-2">
                {/* Bundle fares exist but the filters exclude all of them.
                    Without this, FlightsList falls through to its own generic
                    FlightsEmptyState — "try different dates or a nearby
                    airport" — which blames the route for something the sidebar
                    two columns over is doing. */}
                {!isLoading && combinationOffers.length > 0 && visibleCombinationOffers.length === 0 ? (
                  <FlightsFilteredEmptyState
                    totalBeforeFilters={combinationOffers.length}
                    chips={combinedFilterChips}
                    onRemove={(chip: ActiveFilterChip) => dispatch(setFilters(chip.reset))}
                    onClearAll={() => dispatch(resetFilters())}
                    offers={combinationOffers}
                    filters={filters}
                    currency={combinationOffers[0]?.currency ?? ''}
                    onRelax={(patch) => dispatch(setFilters(patch))}
                  />
                ) : (
                  <FlightsList flights={visibleCombinationOffers} isLoading={isLoading} />
                )}
              </div>
            </>
          )
        ) : isIndexMissing ? (
          <div className="col-12 order-2">
            {/* Offers came back without meta.roundTripIndex, which this screen
                cannot pair without. That is a version skew between this app and
                search-service, not an empty result — say so plainly and offer a
                retry rather than claiming there are no flights. */}
            <FlightsErrorState
              error={buildFlightError('UNKNOWN', 'We could not prepare these results. Please try again.')}
              onRetry={handleRetrySearch}
            />
          </div>
        ) : isEmpty ? (
          <div className="col-12 order-2">
            {offersError ? (
              <FlightsErrorState error={offersError} onRetry={handleRetrySearch} />
            ) : noSearchYet ? (
              <FlightsEmptyState title={NO_SEARCH_YET.title} description={NO_SEARCH_YET.description} />
            ) : (
              <FlightsEmptyState />
            )}
          </div>
        ) : (
          <>
            <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-12 col-12 order-lg-2 order-3 filterDetails sticky-filter-sidebar position-sticky top-0 mb-3 mb-lg-0 d-none d-lg-block">
              <FlightFilterSidebar
                offers={stepRows}
                onClearFilters={() => dispatch(resetFilters())}
                isLoading={isLoading}
                // Only offered when there's a combined-fare option to switch
                // to — same gate the old inline toggle used.
                {...(combinationOffers.length > 0
                  ? { viewMode, onViewModeChange: setViewMode }
                  : {})}
                smartFiltersContext={{
                  tripType: 'roundtrip',
                  origin: fromCode,
                  destination: toCode,
                  departDate,
                  returnDate,
                  step,
                  currency: stepRows[0]?.currency ?? '',
                  onLegHint: (leg) => {
                    if (leg === 'return' && selectedOutbound) goToStep(1);
                    else if (leg === 'outbound') goToStep(0);
                  },
                }}
              />
            </div>

            <div className="col-lg-9 col-md-12 col-sm-12 col-12 order-lg-3 order-2">
              {/* Outbound/return step tabs — same position (first thing in
                  this column, above the results) and the same stretched/
                  connected treatment (.top-flight-legs-tabs) as multi-city's
                  leg tabs, in its own Bootstrap column so it gets the same
                  row-gutter gap above it that multi-city gets for free. The
                  mode toggle itself (individual vs combined bundle fares)
                  lives in FlightFilterSidebar's "Flight selection view"
                  section. */}
              {viewMode === 'stepByStep' && !isLoading && (
                <div
                  className="nav nav-pills flight-legs-tabs top-flight-legs-tabs mb-3 flex-wrap"
                  role="tablist"
                  aria-label="Round trip steps"
                >
                  {/* Same {label, date [+ Selected ✓]} shape as multi-city's
                      leg tabs — a route pair and its date, not step
                      numbering or a picked-flight summary. */}
                  <button
                    type="button"
                    role="tab"
                    aria-selected={step === 0}
                    className={`nav-link w-250 border p-2 text-center d-flex flex-column gap-1${step === 0 ? ' active' : ''}`}
                    onClick={() => goToStep(0)}
                  >
                    <span className="text-md fw-600 color-text-dark">{fromCity} → {toCity}</span>
                    <span className="d-flex align-items-center justify-content-center gap-2">
                      <span className="text-sm color-text-dark">{departLabel}</span>
                      {selectedOutbound && (
                        <span className="text-xs color-text-second fw-600">Selected ✓</span>
                      )}
                    </span>
                  </button>
                  <button
                    type="button"
                    role="tab"
                    aria-selected={step === 1}
                    className={`nav-link w-250 border p-2 text-center d-flex flex-column gap-1${step === 1 ? ' active' : ''}`}
                    onClick={() => selectedOutbound && goToStep(1)}
                    disabled={!selectedOutbound}
                  >
                    <span className="text-md fw-600 color-text-dark">{toCity} → {fromCity}</span>
                    <span className="d-flex align-items-center justify-content-center gap-2">
                      <span className="text-sm color-text-dark">{returnLabel}</span>
                      {selectedReturn && (
                        <span className="text-xs color-text-second fw-600">Selected ✓</span>
                      )}
                    </span>
                  </button>
                </div>
              )}
              {
                isLoading ? (
                  <div className="d-flex flex-column gap-3">
                    {Array.from({ length: 4 }).map((_, k) => (
                      <div key={k} className="card rounded-3 bgColor-white p-3" style={{ height: 130 }}>
                        <div className="skeleton-box w-100 h-100 rounded-2" style={{ backgroundColor: '#dee2e6' }} />
                      </div>
                    ))}
                  </div>
                ) : visibleRows.length === 0 ? (
                  <>
                    <FlightsEmptyState
                      title={step === 1 ? 'No returns match your filters' : 'No flights match your filters'}
                      description={
                        step === 1
                          ? 'Try relaxing a filter, or go back and pick a different outbound.'
                          : 'Try relaxing a filter to see more outbound flights.'
                      }
                    />
                    {/* Both ways out, next to the message saying they are needed —
                        on step 2 a filter is only half the reason the list is
                        empty; the chosen outbound is the other half. */}
                    <div className="d-flex justify-content-center gap-2 mt-3 flex-wrap">
                      <button
                        type="button"
                        className="buttons btnColor-second color-text-white-same rounded-2 px-4 py-2 text-sm fw-normal"
                        onClick={() => dispatch(resetFilters())}
                      >
                        Clear filters
                      </button>
                      {step === 1 && (
                        <button
                          type="button"
                          className="buttons btnColor-first-outline rounded-2 px-4 py-2 text-sm fw-normal"
                          onClick={() => goToStep(0)}
                        >
                          Choose a different outbound
                        </button>
                      )}
                    </div>
                  </>
                ) : (
                  <div className="d-flex flex-column gap-3">
                    {/* A filter can hide the row the traveller already chose. The
                        choice stays valid — it is resolved against the unfiltered
                        rows — so the row is pinned back to the top rather than
                        vanishing while the bar still shows it. */}
                    {step === 1 && selectedReturn && !visibleRows.some((r) => r.sliceKey === selectedReturn.sliceKey) && (
                      <div>
                        <p className="text-xs flight-detail-label mb-1">Your choice, hidden by the current filters</p>
                        <MultiCityFlightCard
                          flight={selectedReturn}
                          index={-1}
                          isSelected
                          onSelect={() => handleSelectRow(selectedReturn)}
                          priceMain={`+${formatFlightMoney(selectedReturn.currency, selectedReturn.priceDelta ?? 0)}`}
                          priceSecondary={`${formatFlightMoney(selectedReturn.currency, selectedReturn.pricePerPerson)} Total round-trip price`}
                        />
                      </div>
                    )}
                    {visibleRows.map((row, i) => (
                      <MultiCityFlightCard
                        key={row.id}
                        flight={row}
                        index={i}
                        isSelected={
                          step === 1 ? selectedReturnKey === row.sliceKey : selectedOutboundKey === row.sliceKey
                        }
                        onSelect={() => handleSelectRow(row)}
                        showCompare
                        priceLead={step === 0 ? 'from' : undefined}
                        priceNote={
                          step === 0 && row.returnCount
                            ? `${row.returnCount} return option${row.returnCount === 1 ? '' : 's'}`
                            : undefined
                        }
                        // Return step: the number worth comparing card-to-card is
                        // what THIS return adds over the cheapest one for the
                        // chosen outbound, not the full trip total repeated on
                        // every row — see the "+$0"/"+$142.10" framing in the
                        // price-comparison spec. The full total moves to a
                        // smaller secondary line underneath.
                        priceMain={
                          step === 1
                            ? `+${formatFlightMoney(row.currency, row.priceDelta ?? 0)}`
                            : undefined
                        }
                        priceSecondary={
                          step === 1
                            ? `${formatFlightMoney(row.currency, row.pricePerPerson)} Total round-trip price`
                            : undefined
                        }
                        priceAriaLabel={
                          step === 1
                            ? `Trip total ${formatFlightMoney(row.currency, row.pricePerPerson)} per adult` +
                              (row.priceDelta
                                ? `, ${formatFlightMoney(row.currency, row.priceDelta)} more than the cheapest return with this outbound`
                                : ', the cheapest return with this outbound')
                            : `From ${formatFlightMoney(row.currency, row.pricePerPerson)} per adult, across ${row.returnCount} return option${row.returnCount === 1 ? '' : 's'}`
                        }
                        selectLabel={step === 0 ? 'Select' : 'Choose return'}
                      />
                    ))}
                  </div>
                )}
            </div>
          </>
        )}
      </div>

      <CompareTray
        entries={compare.entries}
        minimised={compare.minimised}
        onToggleMinimised={compare.setMinimised}
        onRemove={compare.remove}
        onClear={compare.clear}
        onCompare={openCompare}
      />

      {viewMode === 'stepByStep' && selectedOutbound && (
        <RoundTripPairBar
          outbound={selectedOutbound}
          returnOption={selectedReturn}
          onChangeOutbound={() => goToStep(0)}
          onContinue={handlePairContinue}
          isContinuing={isFaresModalOpen || isGoingToReview}
        />
      )}

      {viewMode === 'stepByStep' && isFaresModalOpen && pairOffers && (
        // One offer means Amadeus priced the whole journey as a single fare, so
        // there is one set of fare tiers to choose from rather than a tab per leg.
        pairOffers.length === 1 ? (
          <FlightFaresModal
            isOpen
            onClose={() => { setIsFaresModalOpen(false); setPairOffers(null); }}
            flight={pairOffers[0]}
            tripType="ROUNDTRIP"
            onSelectFare={() => {}}
          />
        ) : (
          <FlightFaresModal
            isOpen
            onClose={() => { setIsFaresModalOpen(false); setPairOffers(null); }}
            flights={pairOffers}
            flightLabels={legLabels.map((l) => l.label)}
            tripType="ROUNDTRIP"
            onSelectFares={() => {}}
          />
        )
      )}
    </>
  );
}