// src/features/online-board/scrollToCurrentTime.test.ts
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { findNearestFlightIndex } from "./scrollToCurrentTime.js";

describe("findNearestFlightIndex", () => {
  beforeEach(() => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date(2026, 4, 15, 12, 0, 0));
  });
  afterEach(() => vi.useRealTimers());

  it("returns index of flight closest to current time", () => {
    const flights = [
      { departure: { scheduled: "2026-05-15T08:00:00" } },
      { departure: { scheduled: "2026-05-15T11:30:00" } },
      { departure: { scheduled: "2026-05-15T14:00:00" } },
    ];
    expect(findNearestFlightIndex(flights as never, new Date(2026, 4, 15, 12, 0))).toBe(1);
  });

  it("returns 0 when list is empty", () => {
    expect(findNearestFlightIndex([], new Date())).toBe(0);
  });

  it("returns the last flight when all flights are in the past", () => {
    const flights = [
      { departure: { scheduled: "2026-05-15T06:00:00" } },
      { departure: { scheduled: "2026-05-15T08:00:00" } },
    ];
    expect(findNearestFlightIndex(flights as never, new Date(2026, 4, 15, 23, 0))).toBe(1);
  });

  it("returns the first flight when all flights are in the future", () => {
    const flights = [
      { departure: { scheduled: "2026-05-15T18:00:00" } },
      { departure: { scheduled: "2026-05-15T20:00:00" } },
    ];
    expect(findNearestFlightIndex(flights as never, new Date(2026, 4, 15, 6, 0))).toBe(0);
  });

  it("handles arrival-mode flights (sorts by arrival time)", () => {
    const flights = [
      { arrival: { scheduled: "2026-05-15T10:00:00" } },
      { arrival: { scheduled: "2026-05-15T13:00:00" } },
    ];
    expect(findNearestFlightIndex(flights as never, new Date(2026, 4, 15, 12, 0), "arrival")).toBe(1);
  });
});
