/**
 * FlightsMiniListItem — a single row in the flights mini-list sidebar.
 *
 * Renders a Link with flight number, departure/arrival times and station codes.
 * Applies a `--selected` modifier when the item matches the currently-viewed flight.
 */

import { forwardRef } from "react";
import { Link } from "@modern-js/runtime/router";
import type { ISimpleFlight, IFlightLeg } from "../../types.js";
import { buildOnlineBoardUrl } from "../../url.js";
import "./FlightsMiniList.scss";

export interface FlightsMiniListItemProps {
  flight: ISimpleFlight;
  isSelected: boolean;
  lang: string;
}

/**
 * Extract first-leg departure and last-leg arrival for display.
 * Direct flights use the single leg; MultiLeg uses first and last.
 */
function getEndpoints(flight: ISimpleFlight): { dep: IFlightLeg["departure"]; arr: IFlightLeg["arrival"] } {
  if (flight.routeType === "Direct") {
    return { dep: flight.leg.departure, arr: flight.leg.arrival };
  }
  const firstLeg = flight.legs[0]!;
  const lastLeg = flight.legs[flight.legs.length - 1]!;
  return { dep: firstLeg.departure, arr: lastLeg.arrival };
}

function getDepTime(dep: IFlightLeg["departure"]): string {
  return dep.times.actualBlockOff?.local ?? dep.times.scheduledDeparture.local;
}

function getArrTime(arr: IFlightLeg["arrival"]): string {
  return arr.times.actualBlockOn?.local ?? arr.times.scheduledArrival.local;
}

export const FlightsMiniListItem = forwardRef<HTMLAnchorElement, FlightsMiniListItemProps>(
  ({ flight, isSelected, lang }, ref) => {
    const { dep, arr } = getEndpoints(flight);
    const href = `/${lang}/${buildOnlineBoardUrl({
      type: "details",
      carrier: flight.flightId.carrier,
      flightNumber: flight.flightId.flightNumber,
      ...(flight.flightId.suffix ? { suffix: flight.flightId.suffix } : {}),
      date: flight.flightId.date,
    })}`;

    const className = `mini-list__item${isSelected ? " mini-list__item--selected" : ""}`;

    return (
      <Link
        ref={ref}
        to={href}
        className={className}
        data-testid={`mini-list-item-${flight.id}`}
      >
        <div className="mini-list__flight-number">
          {flight.flightId.carrier} {flight.flightId.flightNumber}
        </div>
        <div className="mini-list__content">
          <span className="mini-list__dep-time">{getDepTime(dep)}</span>
          <span className="mini-list__status-icon" aria-label={flight.status}>
            {"\u2708"}
          </span>
          <span className="mini-list__arr-time">{getArrTime(arr)}</span>
          <span className="mini-list__dep-station">{dep.scheduled.airportCode}</span>
          <span className="mini-list__arr-station">{arr.scheduled.airportCode}</span>
        </div>
      </Link>
    );
  },
);

FlightsMiniListItem.displayName = "FlightsMiniListItem";
