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

// TIRREDESIGN-11 — "Время рейса" slider must filter results.
//
// We exercise the full slider→submit→URL→filtered-list pipeline:
//   1. Drag the start thumb of the time-range slider
//   2. Click "Найти"
//   3. Assert URL gained the `-{timeFrom}{timeTo}` suffix
//   4. Assert the rendered list shrank to flights inside the new window

function todayYyyymmdd(): string {
  const today = new Date();
  return [
    today.getFullYear(),
    String(today.getMonth() + 1).padStart(2, "0"),
    String(today.getDate()).padStart(2, "0"),
  ].join("");
}

function routeUrl(): string {
  return `/ru-ru/onlineboard/route/MOW-LED-${todayYyyymmdd()}`;
}

test.describe("Onlineboard time-range filter (TIRREDESIGN-11)", () => {
  test("URL with time-range suffix filters the list (URL → state path)", async ({
    page,
    consoleMessages,
  }) => {
    // Baseline: no filter
    const baseUrl = routeUrl();
    await page.goto(baseUrl);
    await expect(page.locator(".flight-card").first()).toBeVisible({
      timeout: 15000,
    });
    const baseline = await page.locator(".flight-card").count();
    expect(baseline).toBeGreaterThan(15);

    // Filtered: 14:00–18:00
    const filteredRequest = page.waitForRequest((request) => {
      const url = new URL(request.url());
      return (
        url.pathname.endsWith("/api/flights/v1.1/ru/board") &&
        url.searchParams.get("timeFrom") === "14:00:00" &&
        url.searchParams.get("timeTo") === "18:00:00"
      );
    });
    await page.goto(`${baseUrl}-14001800`);
    await filteredRequest;
    await expect(page.locator(".flight-card").first()).toBeVisible({
      timeout: 15000,
    });
    const filtered = await page.locator(".flight-card").count();
    expect(filtered).toBeLessThan(baseline);

    // Slider label reflects the URL bounds
    await expect(page.locator(".time-selector__value").first()).toHaveText(
      "14:00 — 18:00",
    );
  });

  test("dragging the slider + clicking Найти persists time range to URL", async ({
    page,
    consoleMessages,
  }) => {
    await page.goto(routeUrl());
    await expect(page.locator(".flight-card").first()).toBeVisible({
      timeout: 15000,
    });

    // Click the track near the 50 % mark. PrimeReact moves the nearest
    // handle, which is the start handle while the range is 00:00-24:00.
    const slider = page.locator(".p-slider").first();
    const sliderBox = await slider.boundingBox();
    expect(sliderBox).toBeTruthy();
    if (!sliderBox) return;
    await slider.click({ position: { x: sliderBox.width * 0.5, y: sliderBox.height / 2 } });

    // The thumb should have left 0 — exact value depends on snap-to-step.
    const labelAfterDrag = await page
      .locator(".time-selector__value")
      .first()
      .textContent();
    expect(labelAfterDrag).not.toBe("00:00 — 24:00");

    // Submit.
    await page.locator('[data-testid="search-submit"]').click();

    // URL must have grown a time suffix.
    await expect(page).toHaveURL(/\/onlineboard\/route\/MOW-LED-\d{8}-\d{8}/);

    const firstFilteredUrl = page.url();

    await slider.click({
      position: { x: sliderBox.width * 0.75, y: sliderBox.height / 2 },
    });
    await expect(page.locator('[data-testid="search-submit"]')).toBeEnabled();
    await page.locator('[data-testid="search-submit"]').click();
    await page.waitForURL(
      (url) =>
        url.href !== firstFilteredUrl &&
        /\/onlineboard\/route\/MOW-LED-\d{8}-\d{8}$/.test(url.pathname),
    );
  });
});
