import { type FC, useEffect, useRef } from "react";
import type { ISimpleFlight } from "../../types.js";
import { FlightsMiniListItem } from "./FlightsMiniListItem.js";
import "./FlightsMiniList.scss";

export interface FlightsMiniListProps {
  flights: ISimpleFlight[];
  currentFlight: ISimpleFlight;
  lang: string;
}

export const FlightsMiniList: FC<FlightsMiniListProps> = ({
  flights,
  currentFlight,
  lang,
}) => {
  const itemRefs = useRef<Map<string, HTMLAnchorElement>>(new Map());

  useEffect(() => {
    const selected = itemRefs.current.get(currentFlight.id);
    if (selected) {
      selected.scrollIntoView({ block: "center", behavior: "smooth" });
    }
  }, [currentFlight.id]);

  // Angular parity: the sidebar renders even when the list is empty or
  // has a single flight — it falls back to showing the current flight so
  // the layout stays consistent with the stand-alone Angular details view.
  const renderFlights = flights.length > 0 ? flights : [currentFlight];

  return (
    <section className="mini-list" data-testid="flights-mini-list">
      {renderFlights.map((flight) => (
        <FlightsMiniListItem
          key={flight.id}
          ref={(el) => {
            if (el) {
              itemRefs.current.set(flight.id, el);
            } else {
              itemRefs.current.delete(flight.id);
            }
          }}
          flight={flight}
          isSelected={flight.id === currentFlight.id}
          lang={lang}
        />
      ))}
    </section>
  );
};
