/**
 * Schedule flight-card mini-list — a flat vertical list of the open
 * flight's instances across the [-1, +1] day window.
 *
 * Originally we wrapped the rows in per-day accordion headers
 * (Суббота / Воскресенье / Понедельник with chevrons), but that
 * grouping was unnecessary noise: every `FlightsMiniListItem` already
 * carries its own date and clicking the day to expand it added a
 * step the user had to take just to see what flight was selected.
 * Drop the accordions; render rows in chronological order, scroll
 * the selected one into view on mount.
 */

import { type FC, useEffect, useMemo, useRef } from "react";
import type { ISimpleFlight } from "@/features/online-board/types.js";
import { FlightsMiniListItem } from "@/features/online-board/components/FlightsMiniList/FlightsMiniListItem.js";
import "@/features/online-board/components/FlightsMiniList/FlightsMiniList.scss";
import "./ScheduleFlightsMiniList.scss";

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

/** Scheduled local-departure ISO timestamp of the flight's primary leg. */
function primaryDepartureIso(f: ISimpleFlight): string {
  const leg = f.routeType === "Direct" ? f.leg : f.legs[0];
  return leg?.departure.times.scheduledDeparture.local ?? "";
}

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

  const sorted = useMemo(() => {
    // Always include the open flight — the search results cover the
    // [-1, +1] window but the open flight itself loads via a separate
    // details endpoint, so it can be absent from `flights`.
    const seen = new Set<string>();
    const merged: ISimpleFlight[] = [];
    for (const f of [...flights, currentFlight]) {
      if (seen.has(f.id)) continue;
      seen.add(f.id);
      merged.push(f);
    }
    return merged.sort((a, b) =>
      primaryDepartureIso(a).localeCompare(primaryDepartureIso(b)),
    );
  }, [flights, currentFlight]);

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

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