'use client';

import { memo, useState, type ComponentType } from 'react';
import { BAGGAGE_NOT_PUBLISHED } from '@/services/flights/baggage';
import { refundTone } from '@/services/flights/refundTone';
import Modal from '@/components/ui/Modal';
import AirlineLogo from './AirlineLogo';
import type { FlightData, FlightLegItinerary, FlightSegmentDetail, FlightLayoverDetail, FlightBaggageAllowance, FareRules, LayoverSeverity } from './types';
import { buildSelfTransferReasonLines, bookingSeparationLine, SELF_TRANSFER_LEVELS, checkedBagTransferNote } from '@/services/flights/selfTransferCopy';
import SelfTransferExplainerModal from './SelfTransferExplainerModal';
import KnowYourLayoverLink from './layover/KnowYourLayoverLink';
import { legSliceKey } from '@/services/flights/layoverScope';

interface FlightItineraryProps {
  flight: FlightData;
}

/**
 * Which shell renders the "Flight Details" panel — flip this one constant to switch
 * every flight card (one-way, round-trip, multi-city) between the two implementations.
 * Not an env var: it's a build-time UI choice, not something that should vary per
 * environment/deployment.
 */
export const FLIGHT_DETAILS_VIEW: 'inline' | 'modal' = 'inline';

const PLANE_PATH =
  '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';

function PlaneIcon({ size = 14, color = 'var(--color-second)' }: { size?: number; color?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <path d={PLANE_PATH} />
    </svg>
  );
}

function LuggageIcon({ size = 14, color = '#bdbdbd' }: { size?: number; color?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
      <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>
  );
}

export function WarningIcon({ size = 14 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="m10.29 3.86-8.18 14A2 2 0 0 0 3.82 21h16.36a2 2 0 0 0 1.71-3.14l-8.18-14a2 2 0 0 0-3.42 0z" />
      <line x1={12} y1={9} x2={12} y2={13} />
      <line x1={12} y1={17} x2={12.01} y2={17} />
    </svg>
  );
}

export function ClockIcon({ size = 14 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx={12} cy={12} r={10} />
      <polyline points="12 6 12 12 16 14" />
    </svg>
  );
}

function ChangeIcon({ size = 14 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M17 2.1l4 4-4 4" /><path d="M3 12.2v-2a4 4 0 0 1 4-4h12.8" />
      <path d="M7 21.9l-4-4 4-4" /><path d="M21 11.8v2a4 4 0 0 1-4 4H4.2" />
    </svg>
  );
}

function AlertIcon({ size = 14 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx={12} cy={12} r={10} />
      <line x1={12} y1={8} x2={12} y2={12} />
      <line x1={12} y1={16} x2={12.01} y2={16} />
    </svg>
  );
}

/** LEIS-929 — the Overnight Layover banner's icon. */
export function MoonIcon({ size = 14 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z" />
    </svg>
  );
}

/** LEIS-930 — IMMIGRATION reason-line icon. */
function PassportIcon({ size = 12 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x={5} y={2} width={14} height={20} rx={2} />
      <circle cx={12} cy={10} r={3} />
      <path d="M8 17h8" />
    </svg>
  );
}

/** LEIS-930 — SEPARATE_CHECK_IN reason-line icon. */
function TicketIcon({ size = 12 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v2a2 2 0 0 0 0 4v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2a2 2 0 0 0 0-4z" />
      <path d="M13 5v2m0 10v2m0-14v2M13 15v2" strokeDasharray="0.1 3" />
    </svg>
  );
}

/** LEIS-930 — small circled "?" for the "What is a self-transfer?" link. */
function HelpCircleIcon({ size = 13 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx={12} cy={12} r={10} />
      <path d="M9.1 9a3 3 0 1 1 4.6 2.5c-.8.5-1.7 1-1.7 2.1" />
      <line x1={12} y1={17} x2={12.01} y2={17} />
    </svg>
  );
}

/** LEIS-930 — external-link glyph for the visa-info link. */
function ExternalLinkIcon({ size = 12 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
      <path d="M15 3h6v6" />
      <path d="M10 14 21 3" />
    </svg>
  );
}

/** LuggageIcon defaults to a fixed grey (`#bdbdbd`) elsewhere on this page
 *  (the standalone "Collect and re-check your bags" note), unlike every
 *  other reason icon here, which uses stroke="currentColor" and picks up the
 *  severity tone automatically. This wrapper forces currentColor so the
 *  baggage reason-line icon matches its siblings' color. */
function LuggageReasonIcon({ size = 12 }: { size?: number }) {
  return <LuggageIcon size={size} color="currentColor" />;
}

/** LEIS-930 — one icon per reason code, so each bullet in the self-transfer
 *  banner reads at a glance instead of every line looking the same. Falls
 *  back to WarningIcon for any reason code not mapped here. */
const REASON_ICONS: Record<string, ComponentType<{ size?: number }>> = {
  AIRPORT_CHANGE: ChangeIcon,
  BAGGAGE_RECHECK: LuggageReasonIcon,
  IMMIGRATION: PassportIcon,
  SEPARATE_CHECK_IN: TicketIcon,
  UNPROTECTED_CONNECTION: AlertIcon,
  TERMINAL_CHANGE: ChangeIcon,
  OVERNIGHT: MoonIcon,
};

/** "1 Piece x 23 Kgs" / "23 Kgs" / "1 Piece" — whatever the carrier actually
 *  filed. A zero allowance ("quantity": 0, no weight — the real shape Amadeus
 *  files for a piece-concept fare with no checked bag) is not a figure worth
 *  stating; isZeroAllowance below turns that case into its own warning line
 *  instead of a "0 Pieces / Adult" that reads like a real entitlement. */
function formatAllowance(b?: FlightBaggageAllowance): string | undefined {
  if (!b) return undefined;
  const { pieces, weightKg } = b;
  if (pieces === 0 || weightKg === 0) return undefined;
  if (pieces != null && weightKg != null) return `${weightKg} Kgs (${pieces} Piece x ${weightKg} Kgs) / Adult`;
  if (weightKg != null) return `${weightKg} Kgs / Adult`;
  if (pieces != null) return `${pieces} Piece${pieces === 1 ? '' : 's'} / Adult`;
  return undefined;
}

function isZeroAllowance(b?: FlightBaggageAllowance): boolean {
  return b != null && (b.pieces === 0 || b.weightKg === 0);
}

/** Bold time + gray date — the departure or arrival column-1 cell of a segment's vertical timeline. */
function StopTime({ time, date, dayOffset }: { time: string; date: string; dayOffset?: number }) {
  return (
    <div>
      <div className="fw-bold color-text-dark">
        {time}
        {dayOffset ? (
          <sup className="text-xs fw-600 ms-1 color-text-second" title={`Arrives ${dayOffset} day${dayOffset > 1 ? 's' : ''} later`}>
            +{dayOffset}
          </sup>
        ) : null}
      </div>
      <div className="text-sm color-text-muted">{date}</div>
    </div>
  );
}

/** Airport name + IATA code + terminal — the column-3 cell alongside a StopTime.
 *  IATA is always shown next to the name (spec: never a name with no code to
 *  anchor it); terminal is only shown when the airport actually has one on
 *  file, never as a placeholder. */
function StopPlace({ city, airportName, iataCode, terminal }: { city: string; airportName?: string; iataCode: string; terminal?: string }) {
  return (
    <div>
      <div className="fw-600 color-text-dark">{city}</div>
      <div className="text-sm color-text-muted">
        {airportName ? `${airportName} (${iataCode})` : iataCode}
        {terminal ? `, Terminal ${terminal}` : ''}
      </div>
    </div>
  );
}

function AircraftPill({ label }: { label: string }) {
  return <span className="flight-aircraft-pill text-xs fw-500">{label}</span>;
}

const SegmentCard = memo(function SegmentCard({
  segment,
  cabinClass,
  onOpenFareRules,
  showBaggage = true,
  precedingLayover,
}: {
  segment: FlightSegmentDetail;
  /** e.g. "Economy" — the leg's cabin, same for every segment on it. */
  cabinClass: string;
  /** Undefined when this fare's rules haven't been fetched (search-stage
   *  offers often don't have them yet — see FlightItineraryContent). The
   *  cabin/fare text still shows either way; only the click-to-open affordance is conditional. */
  onOpenFareRules?: () => void;
  /** False when the leg's baggage is identical on every segment — LegPanel
   *  already shows it once, above the segment list, so repeating it here
   *  per segment would just say the same figure N times. */
  showBaggage?: boolean;
  /** LEIS-930 ticket B5 — the layover immediately before this segment, if
   *  any, so the baggage row can note "may not be transferred" for the
   *  flight departing right after a self-transfer connection. */
  precedingLayover?: FlightLayoverDetail;
}) {
  const cabinLabel = formatAllowance(segment.cabinBaggage);
  const checkedLabel = formatAllowance(segment.checkedBaggage);
  const noCheckedBaggage = isZeroAllowance(segment.checkedBaggage);
  const cabinFareText = `${cabinClass}${segment.fareName ? ` · ${segment.fareName}` : ''}`;
  const bagTransferNote = precedingLayover ? checkedBagTransferNote(precedingLayover) : null;

  return (
    <div className="flight-segment-card border rounded-3 p-3">
      {/* Airline row */}
      <div className="d-flex align-items-start justify-content-between flex-wrap gap-2 mb-3">
        <div className="d-flex align-items-center gap-2 flex-wrap">
          <AirlineLogo code={segment.airlineCode} name={segment.airline} width={24} height={24} className="rounded-1" />
          <span className="fw-600 color-text-dark text-sm">
            {segment.airline} {segment.flightNumber}
          </span>
          {segment.aircraft && <AircraftPill label={segment.aircraft} />}
        </div>
        {onOpenFareRules ? (
          <button type="button" className="flight-fare-link text-xs fw-500 bg-transparent border-0 p-0" onClick={onOpenFareRules}>
            {cabinFareText}
          </button>
        ) : (
          <span className="text-xs fw-500 color-text-muted">{cabinFareText}</span>
        )}
      </div>
      {segment.operatingCarrierName && (
        <div className="text-xs color-text-muted mb-2">Operated by {segment.operatingCarrierName}</div>
      )}

      {/* Vertical departure → arrival timeline: time | dot-rail | place */}
      <div className="flight-vtimeline">
        <div className="flight-vtimeline-time flight-vtimeline-dep">
          <StopTime time={segment.departure.time} date={segment.departure.date} />
        </div>
        <div className="flight-vtimeline-rail flight-vtimeline-dep">
          <span className="flight-vtimeline-dot" aria-hidden="true" />
        </div>
        <div className="flight-vtimeline-dep-content">
          <StopPlace city={segment.departure.city} airportName={segment.departure.airportName} iataCode={segment.departure.iataCode} terminal={segment.departure.terminal} />
        </div>

        <div className="flight-vtimeline-duration text-sm color-text-muted">{segment.duration}</div>
        <div className="flight-vtimeline-rail flight-vtimeline-mid">
          <span className="flight-vtimeline-plane-badge" aria-hidden="true"><PlaneIcon size={11} /></span>
        </div>

        <div className="flight-vtimeline-time flight-vtimeline-arr">
          <StopTime time={segment.arrival.time} date={segment.arrival.date} dayOffset={segment.arrivalDayOffset} />
        </div>
        <div className="flight-vtimeline-rail flight-vtimeline-arr">
          <span className="flight-vtimeline-dot" aria-hidden="true" />
        </div>
        <div className="flight-vtimeline-arr-content">
          <StopPlace city={segment.arrival.city} airportName={segment.arrival.airportName} iataCode={segment.arrival.iataCode} terminal={segment.arrival.terminal} />
        </div>
      </div>

      {/* Baggage — a full-width row under the timeline. Shown per segment only
          when it can actually differ from segment to segment; when the leg's
          checked allowance is uniform across every segment, LegPanel shows it
          once above the segment list instead (the spec's "Baggage for all
          flights" line) rather than repeating the same figure per segment.
          Stacks vertically on mobile. */}
      {showBaggage && (
        <div className="flight-segment-baggage-row d-flex flex-wrap align-items-center gap-4 gap-sm-5">
          {cabinLabel && (
            <div className="d-flex align-items-center gap-2 text-sm color-text-muted">
              <LuggageIcon size={15} />
              <span className="text-sm color-text-muted"><span className="fw-600 color-text-dark">Cabin Baggage:</span> {cabinLabel}</span>
            </div>
          )}
          {checkedLabel ? (
            <div className="d-flex align-items-center gap-2 text-sm color-text-muted">
              <LuggageIcon size={15} />
              <span className="text-sm color-text-muted"><span className="fw-600 color-text-dark">Check-In Baggage:</span> {checkedLabel}</span>
            </div>
          ) : noCheckedBaggage ? (
            <div className="d-flex align-items-center gap-2 text-sm flight-baggage-warning">
              <LuggageIcon size={15} color="currentColor" />
              <span className="text-sm fw-500">No checked baggage included</span>
            </div>
          ) : null}
          {!cabinLabel && !checkedLabel && !noCheckedBaggage ? (
            <div className="text-sm color-text-muted">{BAGGAGE_NOT_PUBLISHED}</div>
          ) : null}
        </div>
      )}
      {/* LEIS-930 ticket B3/B5 — "Included: X kg" (above) stays exactly as
          normal; this note is additive, never a replacement, since allowance
          and through-check are deliberately separate facts (guide §3.13). */}
      {bagTransferNote && (
        <div className="text-xs color-text-muted mt-2">{bagTransferNote}</div>
      )}
    </div>
  );
});

/**
 * LEIS-929 — the "Know your layover" banner, one entry per label. Copy is
 * the ticket's own table verbatim, interpolating {duration}/{city}/
 * {arr}-{dep} exactly as specified. `severity`/`label` themselves always
 * come from search-service's layover rules engine (see
 * flightOfferAdapter.ts) — this lookup only decides how to *display* a value
 * that's already been decided, never re-derives it.
 */
const LAYOVER_BANNERS: Record<
  NonNullable<LayoverSeverity>,
  {
    icon: ComponentType<{ size?: number }>;
    /** Matches the ticket's own 4-color severity scheme (🔴/🟠/🔵/🟣) — Overnight
     *  gets its own 'purple' tone, distinct from Extended's 'info' blue. */
    tone: 'high' | 'medium' | 'info' | 'purple';
    title: string;
    body: (layover: FlightLayoverDetail, arriveTime?: string, departTime?: string) => string;
  }
> = {
  'very-tight': {
    icon: WarningIcon,
    tone: 'high',
    title: 'Very Tight Connection',
    body: (l) => `Only ${l.duration} to change planes. Delays could make you miss your next flight.`,
  },
  tight: {
    icon: ClockIcon,
    tone: 'medium',
    title: 'Tight Connection',
    body: (l) => `About ${l.duration} to transfer. Stay close to your gate and follow "Transfers" signs.`,
  },
  extended: {
    icon: ClockIcon,
    tone: 'info',
    title: 'Extended Layover',
    body: (l) => `${l.duration} wait in ${l.airport}. Consider a lounge or a place to relax.`,
  },
  overnight: {
    icon: MoonIcon,
    tone: 'purple',
    title: 'Overnight Layover',
    body: (l, arriveTime, departTime) =>
      arriveTime && departTime
        ? `Overnight stop in ${l.airport} (${arriveTime} – ${departTime}). You may need a transit hotel or place to rest.`
        : `Overnight stop in ${l.airport}. You may need a transit hotel or place to rest.`,
  },
};

/** "1 hour 5 minutes" — the exact phrasing LEIS-929's accessibility
 *  acceptance criterion asks screen readers to read ("Tight connection, 1
 *  hour 5 minutes in Amman"), distinct from the compact visual "1h 05m". */
function spokenDuration(totalMinutes: number): string {
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  const parts: string[] = [];
  if (hours > 0) parts.push(`${hours} hour${hours === 1 ? '' : 's'}`);
  if (minutes > 0 || hours === 0) parts.push(`${minutes} minute${minutes === 1 ? '' : 's'}`);
  return parts.join(' ');
}

/**
 * Sits between two segment cards, not as its own boxed element — a dashed rail
 * (same grid track widths as .flight-vtimeline, so its line lands exactly under
 * the rail line above/below it) with the layover's own notices beside it.
 */
const LayoverConnector = memo(function LayoverConnector({
  layover,
  finalDestinationCity,
  sliceKey,
  layoverIndex,
  arriveTime,
  departTime,
}: {
  layover: FlightLayoverDetail;
  finalDestinationCity: string;
  /** Stable identity of the leg this stop belongs to. Absent on surfaces with
   *  no offer identity to scope a drawer to (the booking-details view builds
   *  its own layover rows); the link is simply not offered there rather than
   *  opening a drawer that fights every other card for the same fragment. */
  sliceKey?: string;
  layoverIndex: number;
  /** LEIS-929 — only used by the Overnight banner's "(arr – dep)" copy;
   *  every other label's copy doesn't need clock times. */
  arriveTime?: string;
  departTime?: string;
}) {
  const notice = layover.severity ? LAYOVER_BANNERS[layover.severity] : undefined;
  const NoticeIcon = notice?.icon;
  const terminalChangeText = layover.terminalChange
    ? ` You'll also change terminals (${layover.terminalChange.from} → ${layover.terminalChange.to}).`
    : '';

  // LEIS-930 — self-transfer banner renders alongside (not instead of) the
  // LEIS-929 layover-severity notice below: per ticket B9 row 1 the layover
  // label (Very Tight/Tight/Extended/Overnight) keeps its own thresholds and
  // stays visible on the collapsed card's second chip, so it stays visible
  // here too. Info state (transferType UNKNOWN) gets its own smaller,
  // neutral box per ticket B1/B5 — never the word "self-transfer".
  const selfTransferLevel =
    layover.transferType === 'SELF_TRANSFER' && layover.riskLevel ? SELF_TRANSFER_LEVELS[layover.riskLevel] : undefined;
  const isPotentialSelfTransfer = layover.transferType === 'UNKNOWN';
  const reasonLines = selfTransferLevel ? buildSelfTransferReasonLines(layover) : [];
  const separationLine = selfTransferLevel ? bookingSeparationLine(layover.transferEvidence) : null;
  const [explainerOpen, setExplainerOpen] = useState(false);

  return (
    <div className="flight-layover-connector">
      <span />
      <span className="flight-layover-dash" aria-hidden="true" />
      <div className="py-3">
        <div className="text-sm d-flex align-items-center justify-content-between flex-wrap gap-2">
          <span className="color-text-muted">
            {layover.changeOfPlane && <span className="fw-600 flight-layover-change">Change of planes</span>}
            {layover.changeOfPlane && <span className="color-text-muted"> · </span>}
            <span className="fw-600 color-text-dark">{layover.duration}</span> layover in {layover.airport} ({layover.airportCode})
          </span>
          {sliceKey && (
            <KnowYourLayoverLink layover={layover} sliceKey={sliceKey} layoverIndex={layoverIndex} />
          )}
        </div>

        {/* LEIS-930 — confirmed self-transfer banner. */}
        {selfTransferLevel ? (
          <div
            className={`flight-self-transfer-banner flight-self-transfer-banner-${selfTransferLevel.tone} mt-2`}
            role="note"
            aria-label={`${selfTransferLevel.label}, ${spokenDuration(layover.durationMinutes)} in ${layover.airport}`}
          >
            <div className="flight-self-transfer-banner__title">
              <span className="flight-self-transfer-banner__icon-badge">
                <WarningIcon size={13} />
              </span>
              <span className="flight-self-transfer-banner__title-text">{selfTransferLevel.label}</span>
              <span className="flight-self-transfer-banner__duration">{layover.duration}</span>
            </div>
            {separationLine && <p className="flight-self-transfer-banner__body mb-1">{separationLine}</p>}
            {reasonLines.length > 0 && (
              <ul className="flight-self-transfer-banner__reasons mb-0">
                {reasonLines.map((r) => {
                  const ReasonIcon = REASON_ICONS[r.code] || WarningIcon;
                  return (
                    <li key={r.code}>
                      <span className="flight-self-transfer-banner__reason-icon" aria-hidden="true">
                        <ReasonIcon size={11} />
                      </span>
                      <span>{r.text}</span>
                    </li>
                  );
                })}
              </ul>
            )}
            <div className="flight-self-transfer-banner__links mt-2 d-flex gap-2 flex-wrap">
              {layover.visaCheckRequired && (
                <a
                  href={`/visa-info?city=${encodeURIComponent(layover.airport)}&code=${encodeURIComponent(layover.airportCode)}&duration=${encodeURIComponent(layover.duration)}`}
                  className="flight-self-transfer-link"
                >
                  <ExternalLinkIcon />
                  Visa requirements
                </a>
              )}
              <button type="button" className="flight-self-transfer-link" onClick={() => setExplainerOpen(true)}>
                <HelpCircleIcon />
                What is a self-transfer?
              </button>
            </div>
          </div>
        ) : isPotentialSelfTransfer ? (
          /* LEIS-930 — Info state (guide §7 row 4): never says "self-transfer". */
          <div className="flight-self-transfer-banner flight-self-transfer-banner-neutral mt-2" role="note">
            <p className="mb-0 text-xs color-text-muted">This connection may involve separate handling. We&apos;ll confirm before you pay.</p>
          </div>
        ) : null}
        {/* LEIS-929 — the labelled-layover banner (Very Tight/Tight/Extended/
            Overnight), independent of the self-transfer banner above — per
            ticket B9 row 1 it "still shown as the second chip" alongside the
            self-transfer chip on the collapsed card, using its own
            thresholds, so it stays visible here too rather than being
            replaced. Genuinely additive over the self-transfer banner's own
            OVERNIGHT bullet: this one carries the real arrive/depart clock
            times when known. aria-label carries the acceptance criterion's
            exact spoken phrasing ("Tight connection, 1 hour 5 minutes in
            Amman"), separate from the compact visual text this component
            otherwise renders. */}
        {notice && NoticeIcon && (
          <div
            className={`flight-layover-banner flight-layover-banner-${notice.tone} mt-2`}
            role="note"
            aria-label={`${notice.title}, ${spokenDuration(layover.durationMinutes)} in ${layover.airport}`}
          >
            <div className="flight-layover-banner__title">
              <NoticeIcon size={12} />
              <span>{notice.title}</span>
            </div>
            <p className="flight-layover-banner__body">
              {notice.body(layover, arriveTime, departTime)}
              {terminalChangeText}
            </p>
          </div>
        )}
        <SelfTransferExplainerModal isOpen={explainerOpen} onClose={() => setExplainerOpen(false)} />

        <div className="d-flex flex-column gap-1 mt-3">
          {/* Same changeOfPlane-driven heuristic the flight-summary chat
              already uses (build-template.service.ts) — kept in sync rather
              than inventing a second rule, since neither is a real "was this
              bag actually checked through" flag from search-service. */}
          <div className="d-flex align-items-center gap-2 text-xs color-text-muted">
            <LuggageIcon size={13} color="currentColor" />
            <span>
              {layover.changeOfPlane
                ? 'Collect and re-check your bags'
                : `Checked through to ${finalDestinationCity}`}
            </span>
          </div>
          {/* Only when there's no banner already saying so (its own body text
              includes the terminal-change addendum per the ticket's copy
              table, or — for a self-transfer connection — its own reason
              lines cover it) — avoids stating the same fact twice on one
              layover. */}
          {layover.terminalChange && !notice && !selfTransferLevel && (
            <div className="d-flex align-items-center gap-2 text-xs flight-layover-notice-info">
              <ChangeIcon size={13} />
              <span>Arrive Terminal {layover.terminalChange.from}, depart Terminal {layover.terminalChange.to}</span>
            </div>
          )}
          {/* Ticket AC: an airport change always shows this notice, even on a
              protected itinerary — the one exception is when the self-transfer
              banner above is already stating the identical fact as its own
              first bullet (buildSelfTransferReasonLines' AIRPORT_CHANGE line). */}
          {layover.airportChange && !selfTransferLevel && (
            <div className="d-flex align-items-center gap-2 text-xs flight-layover-notice-high">
              <AlertIcon size={13} />
              <span>
                Change airport: arrive {layover.airportChange.fromName} ({layover.airportChange.fromCode}), depart{' '}
                {layover.airportChange.toName} ({layover.airportChange.toCode})
              </span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
});

/** "1 Stop · 18h 50m" — the spec's own summary-line shape. Total duration is
 *  the leg's own already-computed figure (FlightLegData.duration), not
 *  re-derived here, so it can never drift from what the SRP card shows for
 *  the same flight. */
function LegSummary({ leg, totalDuration }: { leg: FlightLegItinerary; totalDuration: string }) {
  const stops = leg.segments.length - 1;
  return (
    <p className="text-sm color-text-muted mb-0">
      {stops === 0 ? 'Non-stop' : `${stops} Stop${stops > 1 ? 's' : ''}`} · {totalDuration}
      {leg.selfTransferCount > 0 && (
        <span> · {leg.selfTransferCount > 1 ? `${leg.selfTransferCount} self-transfers` : 'Self-transfer'}</span>
      )}
    </p>
  );
}

/** Shown once above the segment list instead of repeating the same figure on
 *  every segment card, when a leg's checked baggage (leg.uniformBaggage) is
 *  identical across all of its segments. */
function UniformBaggageSummary({ segment }: { segment: FlightSegmentDetail }) {
  const cabinLabel = formatAllowance(segment.cabinBaggage);
  const checkedLabel = formatAllowance(segment.checkedBaggage);
  const noCheckedBaggage = isZeroAllowance(segment.checkedBaggage);
  if (!cabinLabel && !checkedLabel && !noCheckedBaggage) return null;

  return (
    <div className="flight-segment-baggage-row flight-segment-baggage-row-uniform d-flex flex-wrap align-items-center gap-4 gap-sm-5 mb-3">
      <span className="text-xs fw-600 color-text-dark text-uppercase">Baggage for all flights:</span>
      {cabinLabel && (
        <div className="d-flex align-items-center gap-2 text-sm color-text-muted">
          <LuggageIcon size={15} />
          <span className="text-sm color-text-muted"><span className="fw-600 color-text-dark">Cabin Baggage:</span> {cabinLabel}</span>
        </div>
      )}
      {checkedLabel ? (
        <div className="d-flex align-items-center gap-2 text-sm color-text-muted">
          <LuggageIcon size={15} />
          <span className="text-sm color-text-muted"><span className="fw-600 color-text-dark">Check-In Baggage:</span> {checkedLabel}</span>
        </div>
      ) : noCheckedBaggage ? (
        <div className="d-flex align-items-center gap-2 text-sm flight-baggage-warning">
          <LuggageIcon size={15} color="currentColor" />
          <span className="text-sm fw-500">No checked baggage included</span>
        </div>
      ) : null}
    </div>
  );
}

/** Exported so the review/price pipeline's ReviewFlightCard can render the
 *  exact same per-segment/layover UI as the search-results card, fed by a
 *  FlightLegItinerary built via buildLegItinerary from its own raw segments,
 *  instead of a second implementation of this layout. */
export function LegPanel({
  leg,
  cabinClass,
  onOpenFareRules,
  sliceKey,
}: {
  leg: FlightLegItinerary;
  cabinClass: string;
  onOpenFareRules?: () => void;
  /** Stable identity of *this leg* — FlightData.sliceKeys[legIndex]. Scopes the
   *  layover drawer's URL fragment so Back closes this card's drawer and not
   *  another card's stop at the same airport. Omit to hide the links. */
  sliceKey?: string;
}) {
  // "For all flights" only means something once there's more than one — a
  // single-segment leg just shows its own baggage on its own card, same as
  // always (leg.uniformBaggage is trivially true for one segment).
  const collapseBaggage = leg.segments.length > 1 && leg.uniformBaggage;
  const finalDestinationCity = leg.segments[leg.segments.length - 1]?.arrival.city ?? '';

  return (
    <div className="d-flex flex-column">
      {collapseBaggage && <UniformBaggageSummary segment={leg.segments[0]} />}
      {leg.segments.map((segment, i) => (
        <div key={i}>
          <SegmentCard
            segment={segment}
            cabinClass={cabinClass}
            onOpenFareRules={onOpenFareRules}
            showBaggage={!collapseBaggage}
            precedingLayover={i > 0 ? leg.layovers[i - 1] : undefined}
          />
          {leg.layovers[i] && (
            <LayoverConnector
              layover={leg.layovers[i]}
              finalDestinationCity={finalDestinationCity}
              sliceKey={sliceKey}
              layoverIndex={i}
              arriveTime={segment.arrival.time}
              departTime={leg.segments[i + 1]?.departure.time}
            />
          )}
        </div>
      ))}
    </div>
  );
}

/** Route title + accent bar, date chip, stop/duration summary, refund badge,
 *  and the "View Fare Rules" trigger — one per direction (outbound/inbound),
 *  matching the tab it sits above. */
/** Exported for the same reason as LegPanel above — reused as-is by
 *  ReviewFlightCard. */
export function ItineraryHeader({
  leg,
  title,
  date,
  totalDuration,
  refundStatus,
  onOpenFareRules,
  hasFareRules,
}: {
  leg: FlightLegItinerary;
  title: string;
  date: string;
  totalDuration: string;
  refundStatus?: string;
  onOpenFareRules: () => void;
  hasFareRules: boolean;
}) {
  const tone = refundTone(refundStatus);
  return (
    <div className="flight-itinerary-header d-flex flex-wrap justify-content-between gap-2 mb-3">
      <div className="flight-itinerary-header-accent ps-3">
        <div className="fw-bold color-text-dark text-lg">{title}</div>
        <div className="d-flex align-items-center flex-wrap gap-2 mt-2">
          <span className="flight-itinerary-date-chip text-sm fw-600">{date}</span>
        </div>
        <LegSummary leg={leg} totalDuration={totalDuration} />
        <p className="text-xs color-text-muted mb-0 mt-1">Times shown are local</p>
      </div>
      <div className="d-flex flex-column align-items-end gap-2">
        {refundStatus && (
          <div className={`refund refund-${tone ?? 'refundable'} text-xs fw-600 rounded-2 d-inline-block px-2 py-1 text-uppercase`}>
            {refundStatus}
          </div>
        )}
        {hasFareRules && (
          <button type="button" className="flight-fare-link text-xs fw-500 bg-transparent border-0 p-0" onClick={onOpenFareRules}>
            View Fare Rules
          </button>
        )}
      </div>
    </div>
  );
}

/** Shared tabs + per-segment content — reused by both the inline panel and the modal shell. */
const FlightItineraryContent = memo(function FlightItineraryContent({ flight }: FlightItineraryProps) {
  const outbound = flight.itineraryDetails?.outbound;
  const inbound = flight.itineraryDetails?.inbound;
  const [activeLeg, setActiveLeg] = useState<'outbound' | 'inbound'>('outbound');
  const [openRules, setOpenRules] = useState<FareRules | null>(null);

  if (!outbound || outbound.segments.length === 0) return null;

  const activeItinerary = activeLeg === 'inbound' && inbound ? inbound : outbound;
  const activeLegData = activeLeg === 'inbound' && flight.inbound ? flight.inbound : flight.outbound;
  // The fare this offer is actually priced/booked on — buildFareOptionsList
  // marks exactly that one `recommended: true` (the base/originally-searched
  // tier, not an upsell sibling).
  const bookedFare = flight.fareOptions?.find((o) => o.recommended) ?? flight.fareOptions?.[0];
  const fareRules = bookedFare?.fareRules;

  const firstSeg = activeItinerary.segments[0];
  const lastSeg = activeItinerary.segments[activeItinerary.segments.length - 1];
  const routeTitle = firstSeg && lastSeg ? `${firstSeg.departure.city} → ${lastSeg.arrival.city}` : activeItinerary.label;

  return (
    <>
      {inbound && (
        <div className="flight-leg-tabs d-flex mb-3">
          <button type="button" className={`flight-leg-tab flight-leg-tab-start${activeLeg === 'outbound' ? ' active' : ''}`} onClick={() => setActiveLeg('outbound')}>
            {outbound.label}
          </button>
          <button type="button" className={`flight-leg-tab flight-leg-tab-end${activeLeg === 'inbound' ? ' active' : ''}`} onClick={() => setActiveLeg('inbound')}>
            {inbound.label}
          </button>
        </div>
      )}
      <ItineraryHeader
        leg={activeItinerary}
        title={routeTitle}
        date={firstSeg?.departure.date ?? ''}
        totalDuration={activeLegData?.duration ?? ''}
        refundStatus={activeLegData?.refundStatus}
        hasFareRules={!!fareRules}
        onOpenFareRules={() => fareRules && setOpenRules(fareRules)}
      />
      <LegPanel
        leg={activeItinerary}
        cabinClass={activeLegData?.cabinClass ?? 'Economy'}
        onOpenFareRules={fareRules ? () => setOpenRules(fareRules) : undefined}
        sliceKey={legSliceKey(flight, activeLeg === 'inbound' ? 1 : 0)}
      />

      <Modal
        isOpen={!!openRules}
        onClose={() => setOpenRules(null)}
        title={bookedFare ? `Fare Rules — ${bookedFare.name}` : 'Fare Rules'}
        titleClassName="subHeading fw-600 pe-5"
        size="md"
        className="modalZoom modal-class"
      >
        <div className="bgColor-white booking-form-section px-3">
          {openRules?.cancellation && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Cancellation</h2>
              <p className="color-text-grey text-sm">{openRules.cancellation}</p>
            </>
          )}
          {openRules?.dateChange && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Date Change</h2>
              <p className="color-text-grey text-sm">{openRules.dateChange}</p>
            </>
          )}
          {openRules?.baggage && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Baggage</h2>
              <p className="color-text-grey text-sm">{openRules.baggage}</p>
            </>
          )}
          {openRules?.seatSelection && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Seat Selection</h2>
              <p className="color-text-grey text-sm">{openRules.seatSelection}</p>
            </>
          )}
          {openRules?.nameChange && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Name Change</h2>
              <p className="color-text-grey text-sm">{openRules.nameChange}</p>
            </>
          )}
        </div>
      </Modal>
    </>
  );
});

/** Inline, expand-in-card version — used when FLIGHT_DETAILS_VIEW === 'inline'. */
export default function FlightItinerary({ flight }: FlightItineraryProps) {
  return (
    <div className="flight-card-panel bgColor-light border-0 border-top p-3 mt-2">
      <FlightItineraryContent flight={flight} />
    </div>
  );
}

interface FlightItineraryModalProps extends FlightItineraryProps {
  isOpen: boolean;
  onClose: () => void;
}

/** Popup version — used when FLIGHT_DETAILS_VIEW === 'modal'. */
export function FlightItineraryModal({ flight, isOpen, onClose }: FlightItineraryModalProps) {
  return (
    <Modal isOpen={isOpen} onClose={onClose} size="lg" scrollable title="Flight Details" titleClassName="subHeading fw-600 mb-0" className="modalZoom modal-class">
      <div className="px-3">
        <FlightItineraryContent flight={flight} />
      </div>
    </Modal>
  );
}
