import { test, expect } from "./fixtures/console-gate";

// TIRREDESIGN-12 — when both schedule cities are filled, the date-picker
// must grey out the days the route does NOT operate. The schedule
// `/days` bitmask is anchored to the requested calendar minimum date:
// bit 0 maps to that exact date, not "base date minus one".

function ymd(date: Date): string {
  return [
    date.getFullYear(),
    String(date.getMonth() + 1).padStart(2, "0"),
    String(date.getDate()).padStart(2, "0"),
  ].join("");
}

function addDays(date: Date, days: number): Date {
  const next = new Date(date);
  next.setDate(next.getDate() + days);
  return next;
}

test("Schedule calendar greys out non-operating days for the route", async ({ page }) => {
  const minDate = addDays(new Date(), -1);
  minDate.setHours(0, 0, 0, 0);
  const dateTo = addDays(minDate, 6);

  await page.route("**/api/flights/v1/*/days/**/schedule/", async (route) => {
    await route.fulfill({
      contentType: "application/json",
      body: JSON.stringify({ days: `0${"1".repeat(381)}` }),
    });
  });

  await page.goto(`/ru-ru/schedule/route/LED-KUF-${ymd(minDate)}-${ymd(dateTo)}-C0`);

  // Open the picker.
  await page.locator("button.p-datepicker-trigger").first().click();
  const panel = page.locator(".p-datepicker-panel, .p-datepicker").first();
  await expect(panel).toBeVisible();

  const visibleDaySelector = ".p-datepicker td:not(.p-datepicker-other-month) span";
  const minDateDay = String(minDate.getDate());
  const nextDateDay = String(addDays(minDate, 1).getDate());

  await expect.poll(async () => {
    const cells = await page.locator(visibleDaySelector).evaluateAll((nodes) =>
      nodes.map((node) => ({
        text: node.textContent?.trim(),
        className: node.className,
      })),
    );
    return cells.find((cell) => cell.text === minDateDay)?.className ?? "";
  }, { timeout: 10000 }).toContain("p-disabled");

  const cells = await page.locator(visibleDaySelector).evaluateAll((nodes) =>
    nodes.map((node) => ({
      text: node.textContent?.trim(),
      className: node.className,
    })),
  );
  expect(cells.find((cell) => cell.text === nextDateDay)?.className ?? "").not.toContain("p-disabled");
});
