'use client';

import * as Tooltip from '@radix-ui/react-tooltip';
import { useState } from 'react';
import FlightNumbers from './FlightNumbers';
import FlightAmenityList from './FlightAmenityList';
import type { FlightLegData, LayoverSeverity, StopDetail } from './types';
import AirlineLogo from './AirlineLogo';
import { BAGGAGE_NOT_PUBLISHED } from '@/services/flights/baggage';
import { refundTone } from '@/services/flights/refundTone';
import { WarningIcon, ClockIcon, MoonIcon } from './FlightItinerary';
import { SELF_TRANSFER_LEVELS, shortReasonLine } from '@/services/flights/selfTransferCopy';
import KnowYourLayoverLink from './layover/KnowYourLayoverLink';
import { useOpenLayoverKey } from './layover/useLayoverDrawer';

/** LEIS-930 — most severe wins when a leg has more than one self-transfer
 *  connection, same convention as LAYOVER_SEVERITY_ORDER above. */
const TRANSFER_RISK_ORDER: Array<'HIGH' | 'MEDIUM' | 'LOW'> = ['HIGH', 'MEDIUM', 'LOW'];

/** LEIS-929 — most severe wins when a leg has more than one labelled
 *  layover; matches the ticket's own ordering exactly. */
const LAYOVER_SEVERITY_ORDER: NonNullable<LayoverSeverity>[] = ['very-tight', 'tight', 'overnight', 'extended'];

/** Short, casual chip copy — deliberately NOT the same wording as the
 *  expanded-view banner's formal titles (LayoverConnector's
 *  LAYOVER_BANNERS); this is the ticket's own literal chip examples ("⚠ Very
 *  tight · 40m", "🌙 Overnight in Amman", "🕐 Long layover · 7h 10m"). */
const LAYOVER_CHIPS: Record<
  NonNullable<LayoverSeverity>,
  {
    icon: typeof WarningIcon;
    tone: 'high' | 'medium' | 'info' | 'purple';
    text: (stop: StopDetail) => string;
    tooltip: (stop: StopDetail) => string;
  }
> = {
  'very-tight': {
    icon: WarningIcon,
    tone: 'high',
    text: (s) => `Very tight · ${s.layoverDuration}`,
    tooltip: (s) => `Only ${s.layoverDuration} to change planes in ${s.city || s.airport} (${s.airport}). Delays could make you miss your next flight.`,
  },
  tight: {
    icon: ClockIcon,
    tone: 'medium',
    text: (s) => `Tight connection · ${s.layoverDuration}`,
    tooltip: (s) => `About ${s.layoverDuration} to change planes in ${s.city || s.airport} (${s.airport}). Stay close to your gate and follow "Transfers" signs.`,
  },
  overnight: {
    icon: MoonIcon,
    tone: 'purple',
    text: (s) => `Overnight in ${s.city || s.airport}`,
    tooltip: (s) => `Overnight stop in ${s.city || s.airport} (${s.airport}), ${s.layoverDuration}. You may need a transit hotel or place to rest.`,
  },
  extended: {
    icon: ClockIcon,
    tone: 'info',
    text: (s) => `Long layover · ${s.layoverDuration}`,
    tooltip: (s) => `${s.layoverDuration} wait in ${s.city || s.airport} (${s.airport}). Consider a lounge or a place to relax.`,
  },
};

/**
 * Open state for one tooltip.
 *
 * Emphatically *one*. All three tooltips on this card briefly shared a single
 * boolean, which made them toggle each other: the "+1 next day" tooltip sits in
 * the arrival column, and moving the pointer from the stops tooltip toward its
 * "Know your layover airport" link crossed out of that trigger. Radix reported
 * the close, the shared state went false, and the stops tooltip was unmounted —
 * taking the link out of the DOM before the click could land on it. Cards
 * arriving the same day have no "+1" tooltip, so the link worked there, which is
 * what made it look like a single misbehaving flight.
 *
 * `suppressed` forces closed regardless of hover: these are hover surfaces at
 * z-index 9999 and would otherwise float over the layover drawer they opened.
 */
function useTooltipOpen(suppressed: boolean): { open: boolean; onOpenChange: (next: boolean) => void } {
  const [hovered, setHovered] = useState(false);
  return { open: hovered && !suppressed, onOpenChange: setHovered };
}

interface FlightRouteProps {
  leg: FlightLegData;
  /**
   * `FlightData.sliceKeys[legIndex]` — scopes the layover drawer to this card's
   * stop. Without it the "Know more" link is not offered: an unscoped drawer
   * would fight every other card on the page for the same URL fragment.
   */
  sliceKey?: string;
  showMobilePrice?: boolean;
  /** Offer-level price shown in the mobile "from" block when showMobilePrice is true */
  price?: number;
  currency?: string;
  isReturn?: boolean;
}

export default function FlightRoute({ leg, sliceKey, showMobilePrice = false, price, currency, isReturn = false }: FlightRouteProps) {
  /**
   * The stops tooltip is controlled rather than left to hover alone, for one
   * reason: it must get out of the way when a layover drawer opens. It is a
   * hover surface at z-index 9999, so left to itself it floats over the panel
   * its own "Know more" link just opened — and the traveller reads the drawer
   * through a tooltip about the same stop.
   */
  const layoverDrawerOpen = useOpenLayoverKey() !== null;
  // One state each. See useTooltipOpen for why sharing one broke the stops
  // tooltip's "Know your layover airport" link.
  const stopsTooltip = useTooltipOpen(layoverDrawerOpen);
  const chipTooltip = useTooltipOpen(layoverDrawerOpen);
  const arrivalTooltip = useTooltipOpen(layoverDrawerOpen);
  // LEIS-930 — the self-transfer chip's tooltip can render alongside the
  // plain layover-time chip's (chip 1 vs chip 2b are independent slots), so
  // it needs its own state rather than sharing chipTooltip.
  const selfTransferChipTooltip = useTooltipOpen(layoverDrawerOpen);
  const stopsLabel =
    leg.stops === 0 ? 'Non-stop' : leg.stops === 1 ? '1 Stop' : `${leg.stops} Stops`;
  const stopClass =
    leg.stops === 0 ? 'non-stop' : leg.stops === 1 ? 'one-stop' : 'multi-stop';
  const arrivalDateLabel = leg.arrival.dateTime
    ? new Date(leg.arrival.dateTime).toLocaleDateString('en-US', { day: '2-digit', month: 'short', year: 'numeric' })
    : null;
  const hasStopDetails = leg.stops > 0 && leg.stopDetails && leg.stopDetails.length > 0;

  // LEIS-929 — the single most severe labelled layover on this leg, if any.
  // severity/label are never computed here; they arrive already decided from
  // search-service (see flightOfferAdapter.ts).
  const labelledStops = (leg.stopDetails ?? []).filter(
    (s): s is StopDetail & { severity: NonNullable<LayoverSeverity> } => Boolean(s.severity),
  );
  const worstStop = labelledStops.length
    ? labelledStops.reduce((worst, s) =>
        LAYOVER_SEVERITY_ORDER.indexOf(s.severity) < LAYOVER_SEVERITY_ORDER.indexOf(worst.severity) ? s : worst,
      )
    : undefined;
  const otherLabelledCount = labelledStops.length > 1 ? labelledStops.length - 1 : 0;
  const chip = worstStop ? LAYOVER_CHIPS[worstStop.severity] : undefined;
  const ChipIcon = chip?.icon;

  // LEIS-930 — ticket B4: self-transfer chip headlines when confirmed; an
  // airport-change chip (any transfer type) beats the plain layover-time
  // chip as the second slot; the Info/UNKNOWN state shows no chip at all on
  // the collapsed card (guide §7 row 4 — only the expanded view gets it).
  const selfTransferStops = (leg.stopDetails ?? []).filter((s) => s.transferType === 'SELF_TRANSFER' && s.riskLevel);
  const worstSelfTransferStop = selfTransferStops.length
    ? selfTransferStops.reduce((worst, s) =>
        TRANSFER_RISK_ORDER.indexOf(s.riskLevel as 'HIGH' | 'MEDIUM' | 'LOW') < TRANSFER_RISK_ORDER.indexOf(worst.riskLevel as 'HIGH' | 'MEDIUM' | 'LOW') ? s : worst,
      )
    : undefined;
  const otherSelfTransferCount = selfTransferStops.length > 1 ? selfTransferStops.length - 1 : 0;
  const selfTransferLevel = worstSelfTransferStop?.riskLevel ? SELF_TRANSFER_LEVELS[worstSelfTransferStop.riskLevel] : undefined;
  const reasonLine = worstSelfTransferStop
    ? shortReasonLine(worstSelfTransferStop.transferEvidence, worstSelfTransferStop.riskReasons)
    : '';

  const airportChangeStop = (leg.stopDetails ?? []).find((s) => s.airportChangeFrom && s.airportChangeTo);
  // Ticket B4: "Chip 2: airport change, if true. Otherwise the layover-time
  // chip." — strict either/or, not a fallback only when the other is absent.
  const showAirportChangeChip = Boolean(airportChangeStop);
  const showLayoverTimeChip = !showAirportChangeChip && Boolean(chip && worstStop);

  return (
    <>
      {/* Airline logo column */}
      <div className="col-xxl-2 text-center col-xl-2 ps-0 col-lg-2 col-md-2 col-sm-12 col-12 h-100 pt-2 pe-md-0 d-flex flex-wrap d-md-block order-1 order-md-1">
        <div className="flight-view ps-2 ps-sm-0">
          <AirlineLogo code={leg.airline.code} name={leg.airline.name} className="flight-airline-logo" />
          <div className="flight-details text-start text-md-center xs-2">
            <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0 mt-2">
              {leg.airline.name}
            </div>
            <FlightNumbers numbers={leg.airline.flightNumbers ?? [leg.airline.flightNumber]} />
          </div>
        </div>

        {showMobilePrice && price != null && (
          <div className="flight-starting-price d-block d-sm-none ms-auto text-end">
            <div className="listing-div text-end d-flex flex-column align-items-end">
              <small className="d-block mb-2 text-xs">from</small>
              <h5 className="mb-0">
                <span className="mainHeading color-text-dark fw-bold">
                  {currency}{price}
                </span>
              </h5>
              <small className="d-block color-text-dark text-xs mb-md-2">per adult</small>
            </div>
          </div>
        )}
      </div>

      {/* Flight details column */}
      <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-10 col-sm-12 col-12 h-100 booking-content-details p-0 pe-md-5 order-2 order-md-2">
        <div className="flight-routes d-flex flex-wrap flex-md-nowrap align-items-center border-bottom pb-3">

          {/* Path / duration — middle, order-md-2 */}
          <div className="flex-grow-1 px-3 w-s-100 order-md-2">
            <div className="flight-path position-relative w-100">
              <div className="path-line"></div>
              <span className="path-dot dot-start bg-white"></span>
              <span className="path-dot dot-end"></span>
              {leg.stops >= 1 && <span className="path-dot dot1"></span>}
              {leg.stops >= 2 && <span className="path-dot dot2"></span>}
              <span className="plane bgColor-white px-1 me-2">
                <svg xmlns="http://www.w3.org/2000/svg" width={18} height={18} viewBox="0 0 24 24" fill="none" stroke={isReturn ? '#f45d6b' : 'currentColor'} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-plane absolute top-1/2 right-0 -translate-y-1/2 translate-x-1/2 w-4 h-4">
                  <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
                </svg>
              </span>
            </div>

            <div className="time text-center">
              <span className="text-xs text-grey me-2">
                <svg xmlns="http://www.w3.org/2000/svg" width={11} height={11} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-clock w-3 h-3 text-gray-400">
                  <circle cx={12} cy={12} r={10} />
                  <polyline points="12 6 12 12 16 14" />
                </svg>
                {" "}{leg.duration}
              </span>
              {hasStopDetails ? (
                <Tooltip.Provider delayDuration={100}>
                  <Tooltip.Root {...stopsTooltip}>
                    <Tooltip.Trigger asChild>
                      <span className={`text-xs px-2 py-1 rounded-5 cursor-pointer ${stopClass}`}>
                        {stopsLabel}
                      </span>
                    </Tooltip.Trigger>
                    <Tooltip.Portal>
                      <Tooltip.Content
                        side="bottom"
                        align="center"
                        sideOffset={8}
                        style={{
                          zIndex: 9999,
                          background: '#fff',
                          border: '1px solid #e2e8f0',
                          borderRadius: '14px',
                          padding: '16px',
                          boxShadow: '0 8px 30px rgba(0,0,0,0.12)',
                          minWidth: '320px',
                          maxWidth: '400px',
                          fontFamily: 'inherit',
                        }}
                      >
                        {leg.stopDetails!.map((stop, i) => {
                          const airportLine = stop.name
                            ? `${stop.name} (${stop.airport})`
                            : stop.city
                            ? `${stop.city} (${stop.airport})`
                            : stop.airport;
                          return (
                            <div key={i}>
                              {/* dashed plane divider between stops */}
                              {i > 0 && (
                                <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '12px 0' }}>
                                  <div style={{ flex: 1, borderTop: '1.5px dashed #cbd5e1' }} />
                                  <svg width={13} height={13} viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
                                  </svg>
                                  <div style={{ flex: 1, borderTop: '1.5px dashed #cbd5e1' }} />
                                </div>
                              )}

                              {/* Stop N pill — uses theme secondary color */}
                              <div style={{ textAlign: 'center', marginBottom: 10 }}>
                                <span style={{
                                  background: 'rgba(47,98,113,0.09)',
                                  color: 'var(--color-second, #2f6271)',
                                  fontSize: 11,
                                  fontWeight: 600,
                                  borderRadius: 20,
                                  padding: '3px 12px',
                                  letterSpacing: '0.3px',
                                }}>
                                  Stop {i + 1}
                                </span>
                              </div>

                              {/* Layover line */}
                              <p style={{ margin: '0 0 10px', fontSize: 13, textAlign: 'center', lineHeight: 1.5 }}>
                                <span style={{ color: '#1e293b', fontWeight: 600 }}>
                                  {stop.layoverDuration} Layover at {stop.city || stop.airport}
                                </span>
                                {' • '}
                                <span style={{ color: 'var(--color-first, #f15a6a)', fontWeight: 600 }}>Plane Change</span>
                              </p>

                              {/* Airport name tag */}
                              <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: 6,
                                padding: '7px 12px',
                                background: 'rgba(47,98,113,0.06)',
                                borderRadius: 8,
                              }}>
                                <svg width={13} height={13} viewBox="0 0 24 24" fill="none" stroke="var(--color-second, #2f6271)" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
                                  <path d="M20 10c0 6-8 12-8 12S4 16 4 10a8 8 0 0 1 16 0Z" />
                                  <circle cx={12} cy={10} r={3} />
                                </svg>
                                <span style={{ fontSize: 12.5, fontWeight: 500, color: '#1e293b' }}>{airportLine}</span>
                              </div>

                              {/* An accelerator, not the only way in: the same
                                  link sits in the flight-details panel, which —
                                  unlike a hover tooltip — is keyboard reachable. */}
                              {sliceKey && (
                                <div style={{ textAlign: 'center', marginTop: 8 }}>
                                  <KnowYourLayoverLink
                                    variant="compact"
                                    sliceKey={sliceKey}
                                    layoverIndex={i}
                                    layover={{
                                      airport: stop.city || stop.airport,
                                      airportCode: stop.airport,
                                      duration: stop.layoverDuration,
                                      arriveTime: stop.arriveTime,
                                      departTime: stop.departTime,
                                      arriveTerminal: stop.terminal,
                                      departTerminal: stop.departTerminal,
                                    }}
                                  />
                                </div>
                              )}
                            </div>
                          );
                        })}
                        <Tooltip.Arrow style={{ fill: '#e2e8f0' }} />
                      </Tooltip.Content>
                    </Tooltip.Portal>
                  </Tooltip.Root>
                </Tooltip.Provider>
              ) : (
                <span className={`text-xs px-2 py-1 rounded-5 ${stopClass}`}>
                  {stopsLabel}
                </span>
              )}
              {leg.stopInfo && (
                <div className="route-diversion text-xs text-grey mt-2 w-100">
                  {leg.stopInfo}
                </div>
              )}
              {(worstSelfTransferStop || showAirportChangeChip || showLayoverTimeChip) && (
                // Centered to match the duration/stops-label text.text-center directly
                // above it — the default flex-start left-alignment looked fine with 2+
                // chips (the row filled more width) but glaringly off-center with just
                // one small chip (e.g. "Overnight in Mumbai") sitting flush-left under
                // centered text. Ported from leisure-ui.com's FlightRoute.tsx, where
                // this was already fixed — this copy had drifted out of sync with it.
                <div className="mt-2 w-100 d-flex flex-wrap justify-content-center gap-2 align-items-start">
                  {/* LEIS-930 — chip 1: confirmed self-transfer. */}
                  {worstSelfTransferStop && selfTransferLevel && (
                    <Tooltip.Provider delayDuration={100}>
                      <Tooltip.Root {...selfTransferChipTooltip}>
                        <Tooltip.Trigger asChild>
                          <button
                            type="button"
                            className={`flight-self-transfer-chip flight-self-transfer-chip-${selfTransferLevel.tone}`}
                            aria-label={`${selfTransferLevel.label}, ${worstSelfTransferStop.layoverDuration} in ${worstSelfTransferStop.city || worstSelfTransferStop.airport}`}
                          >
                            <WarningIcon size={12} />
                            <span>{selfTransferLevel.label} · {worstSelfTransferStop.layoverDuration}</span>
                            {otherSelfTransferCount > 0 && <span className="flight-layover-chip__more">+{otherSelfTransferCount}</span>}
                          </button>
                        </Tooltip.Trigger>
                        <Tooltip.Portal>
                          <Tooltip.Content
                            side="top"
                            align="center"
                            sideOffset={6}
                            style={{ zIndex: 9999, background: '#fff', border: '1px solid #e2e8f0', borderRadius: '10px', padding: '10px 12px', boxShadow: '0 8px 30px rgba(0,0,0,0.12)', fontSize: 12.5, lineHeight: 1.5, color: '#1e293b', fontFamily: 'inherit', maxWidth: '280px' }}
                          >
                            These flights are on separate bookings. See details for what this means for your bags, check-in, and missed flights.
                            <Tooltip.Arrow style={{ fill: '#e2e8f0' }} />
                          </Tooltip.Content>
                        </Tooltip.Portal>
                      </Tooltip.Root>
                    </Tooltip.Provider>
                  )}

                  {/* LEIS-930 — chip 2a: airport change (any transfer type). */}
                  {showAirportChangeChip && airportChangeStop?.airportChangeFrom && airportChangeStop?.airportChangeTo && (
                    <span className="flight-self-transfer-chip flight-self-transfer-chip-red" aria-label={`Airport change: arrive ${airportChangeStop.airportChangeFrom.name}, depart ${airportChangeStop.airportChangeTo.name}`}>
                      <WarningIcon size={12} />
                      <span>Airport change</span>
                    </span>
                  )}

                  {/* Chip 2b: plain layover-time chip — only when no airport change (LEIS-929). */}
                  {showLayoverTimeChip && chip && worstStop && ChipIcon && (
                    <Tooltip.Provider delayDuration={100}>
                      <Tooltip.Root {...chipTooltip}>
                        <Tooltip.Trigger asChild>
                          <button
                            type="button"
                            className={`flight-layover-chip flight-layover-chip-${chip.tone}`}
                            aria-label={`${worstStop.label}, ${worstStop.layoverDuration} in ${worstStop.city || worstStop.airport}`}
                          >
                            <ChipIcon size={12} />
                            <span>{chip.text(worstStop)}</span>
                            {otherLabelledCount > 0 && <span className="flight-layover-chip__more">+{otherLabelledCount}</span>}
                          </button>
                        </Tooltip.Trigger>
                        <Tooltip.Portal>
                          <Tooltip.Content
                            side="top"
                            align="center"
                            sideOffset={6}
                            style={{ zIndex: 9999, background: '#fff', border: '1px solid #e2e8f0', borderRadius: '10px', padding: '10px 12px', boxShadow: '0 8px 30px rgba(0,0,0,0.12)', fontSize: 12.5, lineHeight: 1.5, color: '#1e293b', fontFamily: 'inherit', maxWidth: '280px' }}
                          >
                            {chip.tooltip(worstStop)}
                            <Tooltip.Arrow style={{ fill: '#e2e8f0' }} />
                          </Tooltip.Content>
                        </Tooltip.Portal>
                      </Tooltip.Root>
                    </Tooltip.Provider>
                  )}
                </div>
              )}
              {/* LEIS-930 — ticket B4: muted reason line, Level 2/3 only (LOW gets the chip alone, no line). */}
              {worstSelfTransferStop && worstSelfTransferStop.riskLevel !== 'LOW' && reasonLine && (
                <div className="text-xs color-text-muted mt-1 w-100">{reasonLine}</div>
              )}
            </div>
          </div>

          {/* Departure — order-md-1 */}
          <div className="w-s-50 order-md-1 pe-sm-1 ps-2 ps-sm-0">
            <div className="color-text-dark font-inter fw-bolder text-xl">{leg.departure.time}</div>
            <div className="color-text-black fw-normal font-inter text-sm">{leg.departure.airport}</div>
            <div className="flight-detail-label text-sm">{leg.departure.city}</div>
          </div>

          {/* Arrival — order-md-3 */}
          <div className="w-s-50 text-end order-md-3">
            <div className="color-text-dark font-inter fw-bolder text-xl">
              {leg.arrival.time}
              {leg.arrival.nextDay && (
                arrivalDateLabel ? (
                  <Tooltip.Provider delayDuration={100}>
                    <Tooltip.Root {...arrivalTooltip}>
                      <Tooltip.Trigger asChild>
                        <sup className="text-xs color-danger ms-1 cursor-pointer">+1</sup>
                      </Tooltip.Trigger>
                      <Tooltip.Portal>
                        <Tooltip.Content
                          side="top"
                          align="center"
                          sideOffset={6}
                          style={{
                            zIndex: 9999,
                            background: '#fff',
                            border: '1px solid #e2e8f0',
                            borderRadius: '8px',
                            padding: '6px 10px',
                            boxShadow: '0 8px 30px rgba(0,0,0,0.12)',
                            fontSize: 12,
                            color: '#1e293b',
                            fontFamily: 'inherit',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          {arrivalDateLabel}
                          <Tooltip.Arrow style={{ fill: '#e2e8f0' }} />
                        </Tooltip.Content>
                      </Tooltip.Portal>
                    </Tooltip.Root>
                  </Tooltip.Provider>
                ) : (
                  <sup className="text-xs color-danger ms-1">+1</sup>
                )
              )}
            </div>
            <div className="color-text-black text-sm">{leg.arrival.airport}</div>
            <div className="flight-detail-label text-sm">{leg.arrival.city}</div>
          </div>
        </div>

        {/* Features row */}
        <div className="d-md-flex justify-content-between align-items-center gap-2">
          <div className="flight-features pt-3 d-flex flex-wrap align-items-center gap-md-3 gap-2 ps-2 ps-sm-0">
            {/* Which fare the baggage below belongs to. Rendered as the first
                item in the same row so it reads as the subject of that list,
                not as another feature in it — the price already says "from",
                and this is the baggage saying the same thing. */}
            {leg.fareName && (
              <div className="fare-name text-sm fw-600 color-text-dark">{leg.fareName}</div>
            )}
            {leg.cabin && (
              <div className="cabin text-sm text-grey">
                <svg xmlns="http://www.w3.org/2000/svg" width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400">
                  <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                  <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                  <path d="M10 20h4" />
                  <circle cx={16} cy={20} r={2} />
                  <circle cx={8} cy={20} r={2} />
                </svg> {" "}
                Cabin: {leg.cabin}
              </div>
            )}
            {leg.checkin && (
              <div className="checkin text-sm text-grey">
                <svg xmlns="http://www.w3.org/2000/svg" width={15} height={15} viewBox="0 0 24 24" fill="none" stroke="#bdbdbd" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400">
                  <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                  <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                  <path d="M10 20h4" />
                  <circle cx={16} cy={20} r={2} />
                  <circle cx={8} cy={20} r={2} />
                </svg> {" "}
                Check-in: {leg.checkin}
              </div>
            )}
            {((leg.amenityDetails?.length ?? 0) > 0 || (leg.amenities?.length ?? 0) > 0) && (
              <FlightAmenityList groups={leg.amenityDetails ?? []} preview={leg.amenities ?? []} />
            )}
            {/* Said once, only when both chips above are missing. More than half
                of all allowances come back empty from Amadeus, and the dash
                this replaces read as a page that had failed to load rather
                than as an airline that published nothing. */}
            {!leg.cabin && !leg.checkin && (
              <div className="baggage-unpublished text-sm text-grey">
                {BAGGAGE_NOT_PUBLISHED}
              </div>
            )}
            {/* Deliberately not a button: "View Fares" is already the action on
                this card, and a second control competing with it would split
                the one decision this row exists to prompt. */}
            {leg.fareChoice && leg.fareChoice.count > 1 && (
              <div className="fare-more text-sm color-text-muted w-100">
                {leg.fareChoice.count - 1} more{' '}
                {leg.fareChoice.count === 2 ? 'fare' : 'fares'} up to{' '}
                {leg.fareChoice.upToPrice} — baggage and benefits differ
              </div>
            )}
          </div>
          {leg.refundStatus && (
            <div className={`refund refund-${refundTone(leg.refundStatus) ?? 'refundable'} text-xs rounded-5 d-inline-block px-2 py-1 mt-3 ms-2 ms-sm-0`}>
              {leg.refundStatus}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
