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]);

  if (flights.length <= 1) {
    return null;
  }

  return (
    <section className="mini-list" data-testid="flights-mini-list">
      {flights.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>
  );
};
