import { expect, test } from "@playwright/test";

test.setTimeout(120_000);
const screenshotRoot = "../../../../specs/develop/20260623_2/m6_full_e2e";

test("loads repository, publication point, and object data on demand", async ({ page }) => {
  const apiRequests: string[] = [];
  const consoleErrors: string[] = [];

  page.on("request", (request) => {
    const url = new URL(request.url());
    if (url.pathname.startsWith("/api/v1")) {
      apiRequests.push(`${url.pathname}${url.search}`);
    }
  });
  page.on("console", (message) => {
    if (message.type() === "error") {
      consoleErrors.push(message.text());
    }
  });

  await page.goto("/");
  await page.getByRole("button", { name: /Repositories/i }).click();

  await expect(page.getByRole("heading", { name: "Repository / publication point / object browser" })).toBeVisible();
  await expect(page.getByText("Select a repository to load its publication points.")).toBeVisible();
  expect(apiRequests.some((request) => request.includes("/publication-points"))).toBe(false);
  expect(apiRequests.some((request) => request.includes("/objects?"))).toBe(false);

  const reposSection = page.locator('section[aria-label="Repositories"]');
  await expect(reposSection.locator(".stack-row").first()).toBeVisible({ timeout: 30_000 });
  await expect(reposSection.getByLabel("Cursor pagination")).toContainText("Page 1");
  await expect(reposSection.getByLabel("Cursor pagination")).toContainText(/1-\d+\/.+ shown/);
  await reposSection.getByRole("button", { name: "Collapse repositories column" }).click();
  await expect(reposSection.locator(".collapsed-panel-summary")).toContainText("Repositories");
  await expect(reposSection.getByRole("button", { name: "Expand repositories column" })).toBeVisible();
  await reposSection.getByRole("button", { name: "Expand repositories column" }).click();
  await reposSection.getByLabel("Filter repositories on current page").fill("sakuya");
  await expect(reposSection.locator(".stack-row")).toHaveCount(1);
  await reposSection.locator(".stack-row-select").first().click();

  const ppSection = page.locator('section[aria-label="Publication points"]');
  await expect(ppSection.locator(".stack-row").first()).toBeVisible({ timeout: 30_000 });
  await expect(ppSection.getByLabel("Cursor pagination")).toContainText("Page 1");
  await expect(ppSection.getByLabel("Cursor pagination")).toContainText(/1-\d+\/\d+ shown/);
  await ppSection.getByRole("button", { name: "Collapse publication points column" }).click();
  await expect(ppSection.getByRole("button", { name: "Expand publication points column" })).toBeVisible();
  await ppSection.getByRole("button", { name: "Expand publication points column" }).click();
  expect(apiRequests.some((request) => request.includes("/publication-points"))).toBe(true);
  expect(apiRequests.some((request) => request.includes("/objects?"))).toBe(false);

  await ppSection.locator(".stack-row-select").first().click();
  const objectsPanel = page.getByRole("region", { name: "Objects for publication point" });
  await expect(objectsPanel.locator("tbody tr").first()).toBeVisible({ timeout: 70_000 });
  expect(apiRequests.some((request) => request.includes("/publication-points/") && request.includes("/objects?limit=50"))).toBe(true);
  await expect(objectsPanel.getByRole("button", { name: "Open" }).first()).toBeVisible();
  await expect(objectsPanel.getByRole("button", { name: "Copy object URI" }).first()).toBeVisible();
  await expect(objectsPanel.getByRole("button", { name: "Copy object SHA256" }).first()).toBeVisible();
  await expect(objectsPanel.getByLabel("Filter objects on current page")).toBeVisible();
  await expect(objectsPanel.getByLabel("Cursor pagination")).toBeVisible();
  await expect(objectsPanel.getByLabel("Cursor pagination")).toContainText("Page 1");
  await expect(objectsPanel.getByLabel("Cursor pagination")).toContainText(/1-\d+\/\d+ shown/);
  expect(consoleErrors).toEqual([]);

  await page.screenshot({ path: `${screenshotRoot}/rpki-explorer-repository-browser.png`, fullPage: true });
});

test("keeps selected repository and publication point after opening object detail", async ({ page }) => {
  await page.goto("/");
  await page.getByRole("button", { name: /Repositories/i }).click();

  const reposSection = page.locator('section[aria-label="Repositories"]');
  await reposSection.getByLabel("Filter repositories on current page").fill("sakuya");
  await expect(reposSection.locator(".stack-row")).toHaveCount(1, { timeout: 30_000 });
  const selectedRepoUri = (await reposSection.locator(".stack-row-copy .copyable-value-text").first().innerText()).trim();
  await reposSection.locator(".stack-row-select").first().click();

  const ppSection = page.locator('section[aria-label="Publication points"]');
  await expect(ppSection.locator(".stack-row").first()).toBeVisible({ timeout: 30_000 });
  const selectedPpUri = (await ppSection.locator(".stack-row-copy .copyable-value-text").first().innerText()).trim();
  await ppSection.locator(".stack-row-select").first().click();

  const objectsPanel = page.getByRole("region", { name: "Objects for publication point" });
  await expect(objectsPanel.locator("tbody tr").first()).toBeVisible({ timeout: 70_000 });
  const selectedObjectUri = (await objectsPanel.locator(".uri-cell .copyable-value-text").first().innerText()).trim();
  await objectsPanel.getByRole("button", { name: "Open" }).first().click();
  await expect(page.locator(".object-detail-card")).toContainText(selectedObjectUri, { timeout: 70_000 });

  await page.getByRole("button", { name: /Repositories/i }).click();
  await expect(page.getByRole("heading", { name: "Repository / publication point / object browser" })).toBeVisible();
  await expect(reposSection.getByLabel("Filter repositories on current page")).toHaveValue("sakuya");
  await expect(reposSection.locator(".stack-row.active .stack-row-copy").first()).toContainText(selectedRepoUri);
  await expect(ppSection.locator(".stack-row.active .stack-row-copy").first()).toContainText(selectedPpUri);
  await expect(objectsPanel.locator("tbody tr").first()).toContainText(selectedObjectUri);
});
