import type { FC } from "react";
import type { ISimpleFlight, IFlightLeg } from "../../types.js";
import { DetailsHeaderBadge } from "./DetailsHeaderBadge.js";
import { FlightActions } from "./FlightActions.js";
import { FlightEvents } from "./FlightEvents.js";
import { LastUpdate } from "./LastUpdate.js";
import "./BoardDetailsHeader.scss";

export interface BoardDetailsHeaderProps {
  flight: ISimpleFlight;
  locale: string;
}

function getLegs(flight: ISimpleFlight): IFlightLeg[] {
  if (flight.routeType === "Direct") return [flight.leg];
  return flight.legs;
}

function anyLegFlag(flight: ISimpleFlight, key: "routeChanged" | "returnToAirport"): boolean {
  return getLegs(flight).some((l) => l.flags[key]);
}

export const BoardDetailsHeader: FC<BoardDetailsHeaderProps> = ({ flight, locale }) => {
  const changeRoute = anyLegFlag(flight, "routeChanged");
  const reroute = anyLegFlag(flight, "returnToAirport");

  return (
    <div className="board-details-header" data-testid="board-details-header">
      <div className="board-details-header__badge">
        <DetailsHeaderBadge flight={flight} locale={locale} large />
      </div>
      <div className="board-details-header__actions-row">
        <FlightActions flight={flight} locale={locale} />
      </div>
      <div className="board-details-header__events-row">
        <FlightEvents changeRoute={changeRoute} reroute={reroute} showDescription />
        <LastUpdate flight={flight} locale={locale} />
      </div>
    </div>
  );
};
