'use client';

import { useMemo, useState } from 'react';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { setFilters, resetFilters, setActiveSort, durationToMins, applyFlightFilters, removeSmartPredicate } from '@/store/slices/flightSearch.slice';
import type { FlightFilters } from '@/store/slices/flightSearch.slice';
import { TIME_WINDOWS, describeActiveFilters, type ActiveFilterChip, type SortKey } from '@/services/flights/filterSort';
import type { SmartFilterRouteContext } from '@/services/flights/smartFilters/types';
import type { FlightData } from './types';
import AirlineLogo from './AirlineLogo';
import SmartFiltersCard from './smartFilters/SmartFiltersCard';
import './flight-filter-chips.css';

type StopBucket = '0' | '1' | '2+';

/** For the Applied Filters row — Smart Filters can set sort ("cheapest
 *  first") same as any manual filter, so it gets a chip here too, matching
 *  the reference's "Sort By: price asc" chip. "best" is the page-load
 *  default and stays silent then (same as an unset filter never getting a
 *  chip) — it only gets chips when `sortTouched` marks it as an explicit
 *  Smart Filters "cheap and fast" resolution (see FlightSearchState.sortTouched
 *  and filterSort.ts's lexicographic `best` sort), shown as its own two
 *  chips since it's really two criteria (price, then duration as tie-break). */
const SORT_CHIP_LABELS: Partial<Record<SortKey, string>> = {
  cheapest: 'Sort: cheapest first',
  fastest: 'Sort: fastest first',
  earliest: 'Sort: earliest departure',
  'earliest-arrival': 'Sort: earliest arrival',
};
const BEST_SORT_CHIP_LABELS = ['Sort: cheapest first', 'Sort: fastest first'];

interface FlightFilterSidebarProps {
  onClearFilters?: () => void;
  isLoading?: boolean;
  /**
   * Where this is being rendered.
   *
   * `sidebar` (default) is the desktop column: a sticky white card, and a body
   * hidden below lg because that column is ordered after the whole result list
   * there and was never meant to be read on a phone.
   *
   * `sheet` is the mobile Sort & Filters drawer. It needs the same controls
   * with none of that: no sticky offset inside a scrolling drawer, no card
   * chrome inside a card, and emphatically no `d-none` — that gate is exactly
   * why the drawer's Filters tab came up empty.
   */
  variant?: 'sidebar' | 'sheet';
  /**
   * Offers to derive the filter facets from. Pass the set the current view
   * actually renders (round-trip: bundles vs independent legs) so an airline
   * only ever appears when selecting it would really return flights. Falls back
   * to the full store result when omitted.
   */
  offers?: FlightData[];
  /**
   * Round trip only: whether the traveller is picking outbound/return
   * independently or browsing whole-journey bundle fares. Renders the
   * "Flight selection view" toggle at the top of the panel (MMT calls the
   * same choice "Individual Flights" / "Combined Flights") when both this and
   * `onViewModeChange` are supplied — omit both to get a plain filter panel
   * with no toggle, which is what multi-city passes, since it has no combined
   * whole-itinerary fares to switch to.
   */
  viewMode?: 'stepByStep' | 'combined';
  onViewModeChange?: (mode: 'stepByStep' | 'combined') => void;
  /**
   * Renders Smart Filters (LEIS-924) as the panel's own first section, inside
   * the same sticky/scrollable box as everything below it — mounting it as a
   * separate sibling card put it outside .flight-filter-panel's scroll
   * container, so hovering over it scrolled the page instead of the panel.
   * Omitted, the panel has no Smart Filters section at all (used nowhere
   * today, but keeps this prop honestly optional rather than required).
   */
  smartFiltersContext?: SmartFilterRouteContext & {
    onLegHint?: (leg: 'outbound' | 'return' | 'current') => void;
  };
}

/** Placeholder for one filter section (title + a few option rows) shown while offers are loading */
function FilterSkeleton({ titleWidth = '90px', rowWidths = ['75%', '65%', '80%'] }: { titleWidth?: string; rowWidths?: string[] }) {
  return (
    <div className="accordion border-top filter-flight-accordion">
      <div className="accordion-item bg-transparent border-0 mb-3">
        <div className="accordion-header">
          {/*
            Matches the real header's box exactly. The loaded section titles are
            `.accordion-button`, which Bootstrap pads 16px/20px; this stood in
            for it with a bare `py-2` — 8px vertical and, more visibly, no
            horizontal padding at all, so every section title sat flush against
            the card edge while the option rows below it (which share the real
            `.card-body`) were correctly inset. The placeholder jumped into
            place on load.

            Reusing Bootstrap's own variables rather than the measured 16/20px
            keeps the two in step if the accordion is ever re-themed; they
            resolve here because the wrapper above carries `.accordion`, which
            is where Bootstrap defines them.
          */}
          <div
            style={{
              padding: 'var(--bs-accordion-btn-padding-y) var(--bs-accordion-btn-padding-x)',
            }}
          >
            <div className="skeleton-box" style={{ width: titleWidth, height: '16px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
          </div>
        </div>
        <div className="card border-0 bg-transparent">
          <div className="card-body py-0">
            {rowWidths.map((width, idx) => (
              <div key={idx} className="form-check p-0 mb-2">
                <div className="row g-0 align-items-center">
                  <div className="col-1 d-flex justify-content-center">
                    <div className="skeleton-box" style={{ width: '16px', height: '16px', backgroundColor: '#dee2e6', borderRadius: '2px' }}></div>
                  </div>
                  <div className="col-7 ps-2">
                    <div className="skeleton-box" style={{ width, height: '12px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
                  </div>
                  <div className="col-4 d-flex justify-content-end">
                    <div className="skeleton-box" style={{ width: '30px', height: '12px', backgroundColor: '#dee2e6', borderRadius: '4px' }}></div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * Where the sidebar pins, matching `.sticky-filter-sidebar` in flights.css —
 * just under the fixed site header.
 */
const STICKY_TOP_PX = 68;

/**
 * Gap between the fixed chrome above and the top of this panel.
 *
 * `--flight-chrome-h` is published by FlightSearchStickyBar as the real,
 * measured height of the site header plus the sticky search bar. Before that
 * existed this panel pinned at a hardcoded 68px — which was the header alone,
 * so once the search bar arrived the panel's own "Filters" heading sat
 * underneath it.
 */
const STICKY_GAP_PX = 6;

export default function FlightFilterSidebar({
  onClearFilters,
  isLoading = false,
  offers: offersProp,
  variant = 'sidebar',
  viewMode,
  onViewModeChange,
  smartFiltersContext,
}: FlightFilterSidebarProps) {
  const isSheet = variant === 'sheet';
  const dispatch = useAppDispatch();
  const { offersResult, filters, activeSort, sortTouched, smartPredicates } = useAppSelector((s) => s.flightSearch);
  const offers = useMemo(
    () => offersProp ?? offersResult?.offers ?? [],
    [offersProp, offersResult?.offers],
  );
  const showSkeleton = isLoading && offers.length === 0;
  const appliedChips = useMemo(
    () => describeActiveFilters(filters, { currency: offers[0]?.currency ?? '' }),
    [filters, offers],
  );
  const sortChipLabels = activeSort === 'best' && sortTouched ? BEST_SORT_CHIP_LABELS : [SORT_CHIP_LABELS[activeSort]].filter((l): l is string => Boolean(l));

  // Available airlines (IATA code → name + logo + min price). Built from the
  // offers that survive every OTHER active filter, so an airline only shows when
  // picking it would actually return flights — no dead-end options like the
  // "Royal Jordanian → No fares match" case. Keyed by code (what the server
  // wants as includedCarrierCodes), name as the fallback key.
  const airlines = useMemo(() => {
    const pool = applyFlightFilters(offers, { ...filters, airlines: [] });
    const map = new Map<string, { name: string; price: number; logo: string }>();
    for (const o of pool) {
      const code = o.outbound.airline.code ?? o.outbound.airline.name;
      const name = o.outbound.airline.name;
      const logo = o.outbound.airline.logo;
      const p = o.pricePerPerson;
      if (!map.has(code) || map.get(code)!.price > p) map.set(code, { name, price: p, logo });
    }
    // Keep an already-selected airline visible even if the other filters would
    // now hide it, so its checkbox can still be unticked.
    if (filters.airlines.length) {
      for (const o of offers) {
        const code = o.outbound.airline.code ?? o.outbound.airline.name;
        if (filters.airlines.includes(code) && !map.has(code)) {
          map.set(code, { name: o.outbound.airline.name, price: o.pricePerPerson, logo: o.outbound.airline.logo });
        }
      }
    }
    return Array.from(map.entries())
      .sort((a, b) => a[1].price - b[1].price)
      .map(([code, { name, price, logo }]) => ({ code, name, price, logo }));
  }, [offers, filters]);

  // Derive stop counts and min prices from current offers
  const stopStats = useMemo(() => {
    const counts: Record<StopBucket, number> = { '0': 0, '1': 0, '2+': 0 };
    const mins: Record<StopBucket, number> = { '0': Infinity, '1': Infinity, '2+': Infinity };
    for (const o of offers) {
      const bucket: StopBucket = o.outbound.stops === 0 ? '0' : o.outbound.stops === 1 ? '1' : '2+';
      counts[bucket]++;
      if (o.pricePerPerson < mins[bucket]) mins[bucket] = o.pricePerPerson;
    }
    return { counts, mins };
  }, [offers]);

  // Derive price range from current offers
  const { minPrice, maxPrice: maxAvailable } = useMemo(() => {
    if (!offers.length) return { minPrice: 0, maxPrice: 5000 };
    const prices = offers.map((o) => o.pricePerPerson);
    return { minPrice: Math.min(...prices), maxPrice: Math.max(...prices) };
  }, [offers]);

  const priceSliderVal = filters.maxPrice ?? maxAvailable;

  // Derive journey-duration range (minutes) from current offers, same pattern as price
  const { minDuration, maxDuration } = useMemo(() => {
    if (!offers.length) return { minDuration: 0, maxDuration: 1440 };
    const mins = offers.map((o) => durationToMins(o.outbound.duration));
    return { minDuration: Math.min(...mins), maxDuration: Math.max(...mins) };
  }, [offers]);

  const durationSliderVal = filters.maxDurationMinutes ?? maxDuration;

  // Derive layover-duration range (minutes) from current offers' own stops —
  // distinct from journey duration above (a offer's *total* time can be the
  // same whether its one layover is 1h or 6h). Offers with no stopDetails at
  // all (non-stop) contribute nothing here, same as they trivially pass the
  // filter itself; the section only renders when there's at least one real
  // layover to filter, same pattern the airline search box uses ("only show
  // once relevant").
  const { minLayover, maxLayover, hasAnyLayovers } = useMemo(() => {
    const mins = offers.flatMap((o) => (o.outbound.stopDetails ?? []).map((s) => durationToMins(s.layoverDuration)));
    if (mins.length === 0) return { minLayover: 0, maxLayover: 0, hasAnyLayovers: false };
    return { minLayover: Math.min(...mins), maxLayover: Math.max(...mins), hasAnyLayovers: true };
  }, [offers]);
  const layoverSliderVal = filters.maxLayoverMinutes ?? maxLayover;

  function formatDurationLabel(mins: number): string {
    const h = Math.floor(mins / 60);
    const m = mins % 60;
    return m ? `${h}h ${m}m` : `${h}h`;
  }

  // Airlines filter: MakeMyTrip-style. A search box appears only once the list
  // gets long (> 6), and the list itself collapses to the first 6 with a
  // "+ N more" toggle. Typing narrows to matches (and shows them all). Purely
  // client-side over the already-derived `airlines` list — no API involved.
  const AIRLINE_COLLAPSED_COUNT = 6;
  const [airlineQuery, setAirlineQuery] = useState('');
  const [airlinesExpanded, setAirlinesExpanded] = useState(false);
  const airlineSearch = airlineQuery.trim().toLowerCase();
  const filteredAirlines = useMemo(
    () =>
      airlineSearch
        ? airlines.filter(
            (a) =>
              a.name.toLowerCase().includes(airlineSearch) ||
              a.code.toLowerCase().includes(airlineSearch),
          )
        : airlines,
    [airlines, airlineSearch],
  );
  const showAirlineSearch = airlines.length > AIRLINE_COLLAPSED_COUNT;
  const visibleAirlines =
    airlineSearch || airlinesExpanded
      ? filteredAirlines
      : filteredAirlines.slice(0, AIRLINE_COLLAPSED_COUNT);

  const hasActiveFilters =
    filters.stops.length > 0 ||
    filters.airlines.length > 0 ||
    filters.maxPrice !== null ||
    filters.departureHourRange[0] !== 0 ||
    filters.departureHourRange[1] !== 24 ||
    filters.arrivalHourRange[0] !== 0 ||
    filters.arrivalHourRange[1] !== 24 ||
    filters.maxDurationMinutes !== null ||
    filters.maxLayoverMinutes !== null ||
    filters.refundableOnly ||
    filters.checkedBagsOnly ||
    smartPredicates.length > 0;

  function toggleStop(bucket: StopBucket) {
    const next = filters.stops.includes(bucket)
      ? filters.stops.filter((s) => s !== bucket)
      : ([...filters.stops, bucket] as FlightFilters['stops']);
    dispatch(setFilters({ stops: next }));
  }

  function toggleAirline(code: string) {
    const next = filters.airlines.includes(code)
      ? filters.airlines.filter((a) => a !== code)
      : [...filters.airlines, code];
    dispatch(setFilters({ airlines: next }));
  }

  function handleClear() {
    dispatch(resetFilters());
    dispatch(setActiveSort('best'));
    setAirlineQuery('');
    setAirlinesExpanded(false);
    onClearFilters?.();
  }

  // Height and overflow (max-height + always-on overflow-y:auto) live entirely
  // in .flight-filter-panel's own CSS now — see that rule's comment for why
  // this dropped the JS-measured "pinned" gate a scroll/resize timing issue
  // could leave stuck at overflow:hidden.
  return (
    <div
      className={
        isSheet
          ? 'mb-0 flight-filter-panel'
          : 'bgColor-white shadow-sm rounded-3 mb-0 sticky-top flight-filter-panel'
      }
      // calc() rather than the measured number, so the panel tracks a
      // breakpoint change in the same frame the CSS variable does. Omitted in
      // a sheet, where the drawer is the scroll container and a sticky offset
      // would push the panel down inside it.
      style={
        isSheet
          ? undefined
          : { top: `calc(var(--flight-chrome-h, ${STICKY_TOP_PX}px) + ${STICKY_GAP_PX}px)` }
      }
    >
      <div className={`justify-content-between align-items-center px-3 py-2 ${isSheet ? 'd-none' : 'd-lg-flex d-none'}`}>
        <h4 className="text-md mb-0 fw-600">Filters</h4>
        {hasActiveFilters && (
          <button
            className="bg-transparent border-0 color-second text-md fw-600 color-text-second no-bg-btn"
            type="button"
            onClick={handleClear}
          >
            Reset All
          </button>
        )}
      </div>

      {/* Both variants (unlike the header row above, which the sheet hides in
          favor of its own "Sort & Filters" title) — Smart Filters and Applied
          Filters belong in the drawer's Filters tab exactly as much as the
          desktop column. Rendered here, inside .flight-filter-panel itself,
          rather than as a sibling card above it: that's what makes them part
          of the same sticky/scrollable box everything below them is in,
          instead of separate static content the page scrolls past on its
          own. */}
      {smartFiltersContext && offers.length > 0 && (
        <SmartFiltersCard
          offers={offers}
          filters={filters}
          activeSort={activeSort}
          {...smartFiltersContext}
        />
      )}

      {(appliedChips.length > 0 || sortChipLabels.length > 0 || smartPredicates.length > 0) && (
        <div className="px-3 pt-3 pb-2 border-bottom">
          <div className="d-flex justify-content-between align-items-center mb-2">
            <p className="text-sm fw-600 color-text-black mb-0">Applied Filters</p>
            <button
              type="button"
              className="flights-filter-clear-all"
              onClick={handleClear}
            >
              Clear All
            </button>
          </div>
          <div className="d-flex flex-wrap gap-2">
            {sortChipLabels.map((label) => (
              <button
                key={label}
                type="button"
                className="flights-filter-chip d-inline-flex align-items-center gap-2"
                onClick={() => dispatch(setActiveSort('best'))}
                aria-label={`Remove sort: ${label}`}
              >
                <span>{label}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
                  <path d="m3 3 6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
              </button>
            ))}
            {appliedChips.map((chip: ActiveFilterChip) => (
              <button
                key={chip.key}
                type="button"
                className="flights-filter-chip d-inline-flex align-items-center gap-2"
                onClick={() => dispatch(setFilters(chip.reset))}
                aria-label={`Remove filter: ${chip.label}`}
              >
                <span>{chip.label}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
                  <path d="m3 3 6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
              </button>
            ))}
            {/* Smart-filter-only predicates (no filter-bar control) — same
                chip, but removing it dispatches removeSmartPredicate rather
                than a setFilters patch, since nothing here was ever ticked. */}
            {smartPredicates.map((p) => (
              <button
                key={p.id}
                type="button"
                className="flights-filter-chip d-inline-flex align-items-center gap-2"
                onClick={() => dispatch(removeSmartPredicate(p.id))}
                aria-label={`Remove filter: ${p.label}`}
              >
                <span>{p.label}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">
                  <path d="m3 3 6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
                </svg>
              </button>
            ))}
          </div>
        </div>
      )}

      <div className={`web-filter${isSheet ? '' : ' d-lg-block d-none'}`}>
        {showSkeleton ? (
          <>
            <FilterSkeleton titleWidth="60px" />
            <FilterSkeleton titleWidth="80px" rowWidths={['70%', '55%', '85%', '60%']} />
            <FilterSkeleton titleWidth="100px" rowWidths={['90%']} />
            <FilterSkeleton titleWidth="140px" rowWidths={['100%', '100%']} />
          </>
        ) : (
        <>

        {/* Flight selection view — round trip only, and only when there's a
            combined-fare option to switch to (see the prop comment above). */}
        {viewMode && onViewModeChange && (
          <div className="px-3 pt-3 pb-2 border-bottom">
            <p className="text-sm fw-600 color-text-black mb-2">Flight selection view</p>
            <div className="d-flex flight-view-mode-toggle" role="tablist" aria-label="Flight selection view">
              <button
                type="button"
                role="tab"
                aria-selected={viewMode === 'stepByStep'}
                className={`flight-view-mode-btn text-sm fw-500${viewMode === 'stepByStep' ? ' active' : ''}`}
                onClick={() => onViewModeChange('stepByStep')}
              >
                Individual Flights
              </button>
              <button
                type="button"
                role="tab"
                aria-selected={viewMode === 'combined'}
                className={`flight-view-mode-btn text-sm fw-500${viewMode === 'combined' ? ' active' : ''}`}
                onClick={() => onViewModeChange('combined')}
              >
                Combined Flights
              </button>
            </div>
          </div>
        )}

        {/* Stops */}
        <div className="accordion border-top filter-flight-accordion" id="stopsFilterAccordion">
          <div className="accordion-item bg-transparent border-0 mb-3">
            <div className="accordion-header">
              <button
                className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapsestops"
                aria-expanded="true"
              >
                Stops
              </button>
            </div>
            <div id="collapsestops" className="collapse show">
              <div className="card border-0 bg-transparent">
                <div className="card-body py-0">
                  {(['0', '1', '2+'] as StopBucket[])
                    .filter((b) => stopStats.counts[b] > 0)
                    .map((bucket) => {
                      const label = bucket === '0' ? 'Non-stop' : bucket === '1' ? '1 Stop' : '2+ Stops';
                      return (
                        <div key={bucket} className="form-check p-0 mb-2">
                          <div className="row g-0 align-items-center">
                            <div className="col-1 d-flex justify-content-center">
                              <input
                                className="form-check-input ms-0 mt-0"
                                type="checkbox"
                                id={`stop-${bucket}`}
                                checked={filters.stops.includes(bucket)}
                                onChange={() => toggleStop(bucket)}
                              />
                            </div>
                            <div className="col-7 ps-2">
                              <label className="form-check-label text-sm" htmlFor={`stop-${bucket}`}>
                                {label}
                              </label>
                            </div>
                            <div className="col-2 d-flex justify-content-end">
                              <span className="text-xs color-text-muted">
                                {stopStats.mins[bucket] !== Infinity ? `$${stopStats.mins[bucket]}` : ''}
                              </span>
                            </div>
                            <div className="col-2 d-flex justify-content-end">
                              <span className="text-xs color-text-muted">{stopStats.counts[bucket]}</span>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Airlines */}
        {airlines.length > 0 && (
          <div className="accordion border-top filter-flight-accordion" id="airlinesFilterAccordion">
            <div className="accordion-item bg-transparent border-0 mb-3">
              <div className="accordion-header">
                <button
                  className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                  type="button"
                  data-bs-toggle="collapse"
                  data-bs-target="#collapseairlines"
                  aria-expanded="true"
                >
                  Airlines
                </button>
              </div>
              <div id="collapseairlines" className="collapse show">
                <div className="card border-0 bg-transparent">
                  <div className="card-body py-0">
                    {showAirlineSearch && (
                      <input
                        type="text"
                        className="form-control form-control-sm text-sm mb-2"
                        placeholder="Search airlines"
                        value={airlineQuery}
                        onChange={(e) => setAirlineQuery(e.target.value)}
                        aria-label="Search airlines"
                        // Keep it looking like an editable field at rest and on
                        // focus — inline wins over .filterDetails input:focus,
                        // which otherwise swaps the background.
                        style={{ backgroundColor: '#f3f4f6', border: '1px solid #d9dde2' }}
                      />
                    )}

                    {visibleAirlines.length === 0 ? (
                      <p className="text-sm color-text-muted mb-2">
                        No airlines match &ldquo;{airlineQuery.trim()}&rdquo;
                      </p>
                    ) : (
                      visibleAirlines.map(({ code, name, price, logo }) => (
                        <div key={code} className="form-check p-0 mb-2">
                          <div className="row g-0 align-items-center">
                            <div className="col-1 d-flex justify-content-center">
                              <input
                                className="form-check-input ms-0 mt-0"
                                type="checkbox"
                                id={`airline-${code}`}
                                checked={filters.airlines.includes(code)}
                                onChange={() => toggleAirline(code)}
                              />
                            </div>
                            <div className="col-8 ps-2 d-flex align-items-center gap-2">
                              <AirlineLogo
                                code={code}
                                name={name}
                                width={18}
                                height={18}
                                className="flex-shrink-0 rounded-1"
                              />
                              <label className="form-check-label text-sm mb-0" htmlFor={`airline-${code}`}>
                                {name}
                              </label>
                            </div>
                            <div className="col-3 d-flex justify-content-end">
                              <span className="text-xs color-text-muted">${price}</span>
                            </div>
                          </div>
                        </div>
                      ))
                    )}

                    {!airlineSearch && airlines.length > AIRLINE_COLLAPSED_COUNT && (
                      <button
                        type="button"
                        className="bg-transparent border-0 p-0 color-second color-text-second text-sm fw-600 no-bg-btn d-block ms-auto mb-2"
                        onClick={() => setAirlinesExpanded((v) => !v)}
                      >
                        {airlinesExpanded
                          ? 'Show less'
                          : `+ ${airlines.length - AIRLINE_COLLAPSED_COUNT} more`}
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Max Price */}
        {offers.length > 0 && (
          <div className="accordion border-top filter-flight-accordion" id="budgetFilterAccordion">
            <div className="accordion-item bg-transparent border-0 mb-3">
              <div className="accordion-header">
                <button
                  className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                  type="button"
                  data-bs-toggle="collapse"
                  data-bs-target="#collapseBudget"
                  aria-expanded="true"
                >
                  Max Price
                </button>
              </div>
              <div id="collapseBudget" className="collapse show">
                <div className="card border-0 bg-transparent">
                  <div className="card-body py-3">
                    <div className="d-flex justify-content-between mb-2">
                      <span className="text-sm color-text-muted">${minPrice}</span>
                      <span className="text-sm color-text-muted">${maxAvailable}</span>
                    </div>
                    <input
                      type="range"
                      className="form-range"
                      min={minPrice}
                      max={maxAvailable}
                      value={priceSliderVal}
                      onChange={(e) => {
                        const val = Number(e.target.value);
                        dispatch(setFilters({ maxPrice: val >= maxAvailable ? null : val }));
                      }}
                    />
                    <p className="text-sm mb-0 mt-1 fw-500">Up to ${priceSliderVal} per adult</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Journey Duration */}
        {offers.length > 0 && (
          <div className="accordion border-top filter-flight-accordion" id="durationFilterAccordion">
            <div className="accordion-item bg-transparent border-0 mb-3">
              <div className="accordion-header">
                <button
                  className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                  type="button"
                  data-bs-toggle="collapse"
                  data-bs-target="#collapseDuration"
                  aria-expanded="true"
                >
                  Journey Duration
                </button>
              </div>
              <div id="collapseDuration" className="collapse show">
                <div className="card border-0 bg-transparent">
                  <div className="card-body py-3">
                    <div className="d-flex justify-content-between mb-2">
                      <span className="text-sm color-text-muted">{formatDurationLabel(minDuration)}</span>
                      <span className="text-sm color-text-muted">{formatDurationLabel(maxDuration)}</span>
                    </div>
                    <input
                      type="range"
                      className="form-range"
                      min={minDuration}
                      max={maxDuration}
                      value={durationSliderVal}
                      onChange={(e) => {
                        const val = Number(e.target.value);
                        dispatch(setFilters({ maxDurationMinutes: val >= maxDuration ? null : val }));
                      }}
                    />
                    <p className="text-sm mb-0 mt-1 fw-500">Up to {formatDurationLabel(durationSliderVal)}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Layover Duration — only when at least one current offer actually
            has a layover to filter by; a page of all non-stop flights has
            nothing for this control to do. */}
        {hasAnyLayovers && (
          <div className="accordion border-top filter-flight-accordion" id="layoverFilterAccordion">
            <div className="accordion-item bg-transparent border-0 mb-3">
              <div className="accordion-header">
                <button
                  className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                  type="button"
                  data-bs-toggle="collapse"
                  data-bs-target="#collapseLayover"
                  aria-expanded="true"
                >
                  Layover Duration
                </button>
              </div>
              <div id="collapseLayover" className="collapse show">
                <div className="card border-0 bg-transparent">
                  <div className="card-body py-3">
                    <div className="d-flex justify-content-between mb-2">
                      <span className="text-sm color-text-muted">{formatDurationLabel(minLayover)}</span>
                      <span className="text-sm color-text-muted">{formatDurationLabel(maxLayover)}</span>
                    </div>
                    <input
                      type="range"
                      className="form-range"
                      min={minLayover}
                      max={maxLayover}
                      value={layoverSliderVal}
                      onChange={(e) => {
                        const val = Number(e.target.value);
                        dispatch(setFilters({ maxLayoverMinutes: val >= maxLayover ? null : val }));
                      }}
                    />
                    <p className="text-sm mb-0 mt-1 fw-500">Up to {formatDurationLabel(layoverSliderVal)} layover</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Departure Time */}
        <div className="accordion border-top filter-flight-accordion" id="departureTimeFilterAccordion">
          <div className="accordion-item bg-transparent border-0 mb-3">
            <div className="accordion-header">
              <button
                className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseDepartureTime"
                aria-expanded="true"
              >
                Departure Time
              </button>
            </div>
            <div id="collapseDepartureTime" className="collapse show">
              <div className="card border-0 bg-transparent">
                <div className="card-body py-0 pb-2">
                  <div className="row g-2">
                    {TIME_WINDOWS.map((slot) => {
                      const isActive =
                        filters.departureHourRange[0] === slot.start &&
                        filters.departureHourRange[1] === slot.end;
                      return (
                        <div key={slot.id} className="col-6">
                          <div
                            className={`departure-time-btn border rounded-2 p-2 text-center cursor-pointer${isActive ? ' border-primary' : ''}`}
                            style={isActive ? { background: 'rgba(13,110,253,0.08)' } : {}}
                            onClick={() =>
                              dispatch(
                                setFilters({
                                  departureHourRange: isActive
                                    ? [0, 24]
                                    : [slot.start, slot.end],
                                }),
                              )
                            }
                          >
                            <p className="text-lg mb-0">{slot.icon}</p>
                            <p className="text-xs fw-600 mb-0">{slot.label}</p>
                            <p className="text-xs mb-0 color-text-muted">
                              {slot.start}:00&ndash;{slot.end === 24 ? '24:00' : `${slot.end}:00`}
                            </p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Arrival Time */}
        <div className="accordion border-top filter-flight-accordion" id="arrivalTimeFilterAccordion">
          <div className="accordion-item bg-transparent border-0 mb-3">
            <div className="accordion-header">
              <button
                className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseArrivalTime"
                aria-expanded="true"
              >
                Arrival Time
              </button>
            </div>
            <div id="collapseArrivalTime" className="collapse show">
              <div className="card border-0 bg-transparent">
                <div className="card-body py-0 pb-2">
                  <div className="row g-2">
                    {TIME_WINDOWS.map((slot) => {
                      const isActive =
                        filters.arrivalHourRange[0] === slot.start &&
                        filters.arrivalHourRange[1] === slot.end;
                      return (
                        <div key={slot.id} className="col-6">
                          <div
                            className={`departure-time-btn border rounded-2 p-2 text-center cursor-pointer${isActive ? ' border-primary' : ''}`}
                            style={isActive ? { background: 'rgba(13,110,253,0.08)' } : {}}
                            onClick={() =>
                              dispatch(
                                setFilters({
                                  arrivalHourRange: isActive
                                    ? [0, 24]
                                    : [slot.start, slot.end],
                                }),
                              )
                            }
                          >
                            <p className="text-lg mb-0">{slot.icon}</p>
                            <p className="text-xs fw-600 mb-0">{slot.label}</p>
                            <p className="text-xs mb-0 color-text-muted">
                              {slot.start}:00&ndash;{slot.end === 24 ? '24:00' : `${slot.end}:00`}
                            </p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Baggage */}
        <div className="accordion border-top filter-flight-accordion" id="baggageFilterAccordion">
          <div className="accordion-item bg-transparent border-0 mb-3">
            <div className="accordion-header">
              <button
                className="accordion-button shadow-none bg-transparent text-md fw-600 color-text-black"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseBaggage"
              >
                Baggage
              </button>
            </div>
            <div id="collapseBaggage" className="collapse show">
              <div className="card border-0 bg-transparent">
                <div className="card-body py-0">
                  <div className="form-check p-0 mb-2">
                    <div className="row g-0 align-items-center">
                      <div className="col-1 d-flex justify-content-center">
                        <input
                          className="form-check-input ms-0 mt-0"
                          type="checkbox"
                          id="checked-bags-only"
                          checked={filters.checkedBagsOnly}
                          onChange={(e) => dispatch(setFilters({ checkedBagsOnly: e.target.checked }))}
                        />
                      </div>
                      <div className="col-11 ps-2">
                        <label className="form-check-label text-sm" htmlFor="checked-bags-only">
                          Checked bag included
                        </label>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Refundable */}
        <div className="refundable-button py-2 px-3 border-top">
          <div className="form-check form-switch d-flex justify-content-between ps-0">
            <label className="form-check-label fw-500" htmlFor="refundable-only">
              Refundable Only
            </label>
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="refundable-only"
              checked={filters.refundableOnly}
              onChange={(e) => dispatch(setFilters({ refundableOnly: e.target.checked }))}
            />
          </div>
        </div>

        </>
        )}
      </div>
    </div>
  );
}
