import { describe, expect, it } from "vitest";
import type { TguPlanUi, TimelineRow } from "../../model/timelineTypes";
import { buildSequentialLinks, buildTimelineSegments, clipPlanToRange, timeToX } from "./tguTimelineLayout";

const range = {
  fromMs: Date.parse("2026-05-29T00:00:00"),
  toMs: Date.parse("2026-05-30T00:00:00")
};

function plan(id: string, startTime: string, endTime: string, spacecraftId = "56756"): TguPlanUi {
  return {
    planId: id,
    spacecraftId,
    startTime,
    endTime,
    kppId: "KPP-1",
    status: "PLANNED",
    startMs: Date.parse(startTime),
    endMs: Date.parse(endTime)
  };
}

describe("tguTimelineLayout", () => {
  it("maps time to x inside the selected interval", () => {
    expect(timeToX(Date.parse("2026-05-29T12:00:00"), range, 1200)).toBe(600);
  });

  it("clips partially visible plans to the selected interval", () => {
    const clipped = clipPlanToRange(plan("p1", "2026-05-28T23:00:00", "2026-05-29T02:00:00"), range);

    expect(clipped).toEqual({
      startMs: range.fromMs,
      endMs: Date.parse("2026-05-29T02:00:00")
    });
  });

  it("builds links only between sequential plans of the same spacecraft", () => {
    const rows: TimelineRow[] = [
      {
        spacecraftId: "56756",
        plans: [
          plan("p2", "2026-05-29T04:00:00", "2026-05-29T05:00:00"),
          plan("p1", "2026-05-29T01:00:00", "2026-05-29T02:00:00")
        ]
      },
      {
        spacecraftId: "777",
        plans: [
          plan("p3", "2026-05-29T01:00:00", "2026-05-29T02:00:00", "777")
        ]
      }
    ];

    expect(buildSequentialLinks(rows)).toEqual([
      { spacecraftId: "56756", fromPlanId: "p1", toPlanId: "p2" }
    ]);
  });

  it("places sequential plans on alternating timeline lanes", () => {
    const rows: TimelineRow[] = [
      {
        spacecraftId: "56756",
        plans: [
          plan("p1", "2026-05-29T01:00:00", "2026-05-29T02:00:00"),
          plan("p2", "2026-05-29T03:00:00", "2026-05-29T04:00:00"),
          plan("p3", "2026-05-29T05:00:00", "2026-05-29T06:00:00"),
          plan("p4", "2026-05-29T07:00:00", "2026-05-29T08:00:00"),
          plan("p5", "2026-05-29T09:00:00", "2026-05-29T10:00:00"),
          plan("p6", "2026-05-29T11:00:00", "2026-05-29T12:00:00")
        ]
      }
    ];

    expect(buildTimelineSegments(rows, range, 1200).map((segment) => segment.laneOffset)).toEqual([
      0,
      -12,
      0,
      12,
      0,
      -12
    ]);
  });
});
