import type { FC } from "react";
import { useTranslation } from "@/i18n/provider.js";
import { OperatorLogo } from "@/ui/flights/OperatorLogo.js";
import { operatingCarrier, type ISimpleFlight, type IFlightLeg } from "../../types.js";
import { FlightStatusButton } from "./FlightStatusButton.js";
// Badge-composition styles (flex/gap/typography) live in the shared
// BoardDetailsHeader.scss. Import here so consumers that use
// DetailsHeaderBadge without the full BoardDetailsHeader wrapper
// (e.g. the schedule-details summary header) still get the layout.
import "./BoardDetailsHeader.scss";

export interface DetailsHeaderBadgeProps {
  flight: ISimpleFlight;
  locale: string;
  large?: boolean;
  /** Angular renders the per-flight badge with a small round airline
   *  icon (and no "Авиакомпания" caption) when the enclosing details
   *  page is for a connecting itinerary — the large wide logo only
   *  suits a single-flight view. Callers pass `round=true` for the
   *  connecting-summary layout. */
  round?: boolean;
  showStatus?: boolean;
}

function getCodeshareLegs(flight: ISimpleFlight): IFlightLeg[] {
  if (flight.routeType !== "MultiLeg") return [];
  const topCarrier = operatingCarrier(flight.operatingBy);
  return flight.legs.filter((l) => {
    const legCarrier = operatingCarrier(l.operatingBy);
    return legCarrier && legCarrier !== topCarrier;
  });
}

export const DetailsHeaderBadge: FC<DetailsHeaderBadgeProps> = ({
  flight,
  locale,
  round = false,
  showStatus = false,
}) => {
  const { t } = useTranslation();
  const codeshareLegs = getCodeshareLegs(flight);
  const primaryNumber = `${flight.flightId.carrier} ${flight.flightId.flightNumber}`;
  const carrier = operatingCarrier(flight.operatingBy) ?? flight.flightId.carrier;

  return (
    <div
      className={`details-header-badge${round ? " details-header-badge--round" : ""}`}
    >
      <div className="details-header-badge__flight-number">
        <div className="details-header-badge__primary">{primaryNumber}</div>
        {codeshareLegs.length > 0 && (
          <div className="details-header-badge__codesharing" data-testid="codesharing">
            {codeshareLegs
              .map((l) => {
                const c = operatingCarrier(l.operatingBy);
                if (!c) return "";
                const num = l.operatingBy?.flightNumber;
                return num ? `${c} ${num}` : c;
              })
              .filter(Boolean)
              .join(", ")}
          </div>
        )}
      </div>
      <div className="details-header-badge__airline">
        {!round && (
          <div className="details-header-badge__airline-caption">
            {t("SHARED.AVIACOMPANY")}
          </div>
        )}
        <OperatorLogo carrier={carrier} locale={locale} title={carrier} round={round} />
      </div>
      {showStatus && <FlightStatusButton flight={flight} locale={locale} small />}
    </div>
  );
};
