import type { FC } from "react";
import type { ISimpleFlight, IFlightLeg } from "../../types.js";
import { OperatorLogo } from "./OperatorLogo.js";
import { FlightStatusButton } from "./FlightStatusButton.js";

export interface DetailsHeaderBadgeProps {
  flight: ISimpleFlight;
  locale: string;
  large?: boolean;
  round?: boolean;
  showStatus?: boolean;
}

function getCodeshareLegs(flight: ISimpleFlight): IFlightLeg[] {
  if (flight.routeType !== "MultiLeg") return [];
  return flight.legs.filter(
    (l) => l.operatingBy?.carrier && l.operatingBy.carrier !== flight.flightId.carrier,
  );
}

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

  return (
    <div className="details-header-badge">
      <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) => `${l.operatingBy.carrier} ${l.operatingBy.flightNumber}`)
              .join(", ")}
          </div>
        )}
      </div>
      <OperatorLogo flight={flight} locale={locale} large={large} round={round} />
      {showStatus && <FlightStatusButton flight={flight} locale={locale} small />}
    </div>
  );
};
