import { expect, test, type Page } from "@playwright/test";
import path from "node:path";

const updateAuditEvidence = process.env.UPDATE_AUDIT_EVIDENCE === "1";

async function login(page: Page) {
  await page.goto("/login");
  await page.getByLabel("Email").fill("e2e@example.test");
  await page.getByLabel("Current password").fill("E2ePassword123!");
  await page.getByRole("button", { name: "Sign in", exact: true }).click();
  await expect(page).toHaveURL(/\/dashboard$/);
}

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => window.localStorage.setItem("uiLanguage", "en"));
});

test("discovery remains usable across widths and opens the reviewed import", async ({ page }) => {
  test.setTimeout(60_000);
  await page.route("**/api/job-discovery/search**", async (route) => {
    await route.fulfill({ json: [
      {
        id: "long-no",
        title: "Senior systemutvikler for robuste og samfunnskritiske plattformer",
        company: "Eksempelbedriften for norske bokstaver Æ Ø Å",
        location: "TRONDHEIM",
        modifiedAt: "2026-08-09T10:00:00Z",
        deadline: "2026-08-20T23:59:59Z",
        url: "https://arbeidsplassen.nav.no/stillinger/stilling/long-no",
        source: "nav",
        sourceName: "NAV Arbeidsplassen",
        acquisitionType: "searched",
        retrievedAt: "2026-08-10T10:00:00Z",
        countryCode: "NO",
      },
      {
        id: "analyst",
        title: "Analyst",
        url: "https://arbeidsplassen.nav.no/stillinger/stilling/analyst",
        source: "nav",
        sourceName: "NAV Arbeidsplassen",
        acquisitionType: "searched",
        retrievedAt: "2026-08-10T10:00:00Z",
        countryCode: "NO",
      },
    ] });
  });
  await page.route("**/api/jobimport/preview", async (route) => {
    await route.fulfill({ json: { success: true, title: "Imported NAV role", company: "Synthetic AS", description: "Synthetic description", tags: [], sourceUrl: "https://arbeidsplassen.nav.no/stillinger/stilling/long-no", source: "nav", countryCode: "NO" } });
  });

  await login(page);
  await page.setViewportSize({ width: 375, height: 812 });
  await page.goto("/discover");

  await page.getByLabel("Role or company").fill("utvikler");
  await page.keyboard.press("Tab");
  await expect(page.getByLabel("Municipality")).toBeFocused();
  await page.keyboard.press("Tab");
  await expect(page.getByRole("button", { name: "Search NAV" })).toBeFocused();
  await page.keyboard.press("Enter");

  await expect(page.getByText("2 vacancies found")).toBeVisible();
  await expect(page.getByText("NAV Arbeidsplassen").first()).toBeVisible();
  await expect(page.getByText("Work arrangement not provided by this source").first()).toBeVisible();
  await expect(page.getByText(/Application deadline:/)).toBeVisible();
  expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
  if (updateAuditEvidence) await page.screenshot({ path: path.resolve("..", "docs", "audits", "evidence", "jobs-001-discovery-375-light.png"), fullPage: true });

  await page.getByLabel("Sort results").click();
  await page.getByRole("option", { name: "Title A–Z" }).click();
  await expect(page.getByRole("combobox", { name: "Sort results" })).toHaveText("Title A–Z");
  await expect(page.getByRole("heading", { name: "Analyst", exact: true })).toBeVisible();

  for (const width of [768, 1440]) {
    await page.setViewportSize({ width, height: 900 });
    expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);
  }

  await page.evaluate(() => {
    window.localStorage.setItem("jobtracker.themeMode", "dark");
  });
  await page.reload();
  await expect(page.locator("html")).toHaveAttribute("data-color-scheme", "dark");
  await page.getByRole("button", { name: "Search NAV" }).click();
  await expect(page.getByText("2 vacancies found")).toBeVisible();
  if (updateAuditEvidence) await page.screenshot({ path: path.resolve("..", "docs", "audits", "evidence", "jobs-001-discovery-1440-dark.png"), fullPage: true });

  await page.getByRole("button", { name: "Save to tracker" }).first().click();
  await expect(page.getByRole("dialog")).toBeVisible();
  await expect(page.getByLabel("Job title")).toHaveValue("Imported NAV role");
});
