'use client';

import { useState, type CSSProperties } from 'react';
import { DEFAULT_AIRLINE_LOGO, logoForCarrier } from '@/services/flights/airlineLogo';

interface AirlineLogoProps {
  /** IATA carrier code, e.g. "AT". Falls back to the placeholder when unknown. */
  code?: string | null;
  /**
   * Prebuilt logo URL, for callers that already carry one on their view model
   * (`leg.airline.logo`). Ignored when `code` is given.
   */
  src?: string;
  /** Airline name, used as alt text. */
  name?: string;
  className?: string;
  width?: number;
  height?: number;
  style?: CSSProperties;
}

/**
 * An airline logo that degrades to a placeholder instead of a broken image.
 *
 * Logos come from S3 (docs/airline-logos.md) and the set is not exhaustive, so
 * a carrier outside it — a new airline, or Amadeus' 6X test carrier — has no
 * object and the raw <img> renders as a broken icon with the alt text showing
 * through. The onError swap is the only thing that can catch this: whether a
 * given code has an object is not knowable until the request fails (S3 answers
 * 403 rather than 404, since anonymous callers cannot list the bucket).
 */
export default function AirlineLogo({
  code,
  src,
  name,
  className,
  width,
  height,
  style,
}: AirlineLogoProps) {
  const initialSrc = code ? logoForCarrier(code) : src || DEFAULT_AIRLINE_LOGO;
  const [failed, setFailed] = useState(false);

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      // Remount on a carrier change so a previous failure doesn't stick to the
      // next airline's logo.
      key={initialSrc}
      src={failed ? DEFAULT_AIRLINE_LOGO : initialSrc}
      alt={name || code || 'Airline'}
      className={className}
      width={width}
      height={height}
      style={style}
      onError={() => setFailed(true)}
    />
  );
}
