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

async function setEditor(page: Page, testId: string, value: string) {
  await page.getByTestId(testId).locator(".cm-content").fill(value);
}

async function waitForSyntax(page: Page) {
  await expect(
    page.getByRole("button", { name: "Run", exact: true }),
  ).toBeEnabled({ timeout: 15_000 });
}

test("ECMAScript analysis runs static, benchmark and growth slices in local workers", async ({
  page,
}) => {
  const pageErrors: string[] = [];
  page.on("pageerror", (error) => pageErrors.push(error.message));
  await page.goto("./");
  await page.getByLabel("Live").uncheck();
  await setEditor(page, "editor-regular-expression-pattern", "(a+)+$");
  await setEditor(page, "editor-test-text", "aaaa!");
  await waitForSyntax(page);

  await page.getByRole("button", { name: "Analysis", exact: true }).click();
  const dialog = page.getByRole("dialog", {
    name: "Performance & risk analysis",
  });
  await expect(dialog).toBeVisible();
  await expect(dialog).toBeInViewport();
  await expect(
    dialog.getByText("Potential nested-quantifier risk"),
  ).toBeVisible();
  await expect(dialog).toContainText(/does not mean.*safe/iu);

  await dialog.getByRole("tab", { name: "Benchmark" }).click();
  await dialog.getByRole("spinbutton", { name: "Warm-up samples" }).fill("1");
  await dialog.getByRole("spinbutton", { name: "Measured samples" }).fill("3");
  await dialog.getByRole("button", { name: "Run bounded benchmark" }).click();
  const metrics = dialog.getByRole("table", {
    name: "Cold and warm benchmark metrics",
  });
  await expect(metrics).toBeVisible();
  await expect(metrics).toContainText("Warm median");
  await expect(metrics).toContainText("Warm p95");
  await expect(dialog).toContainText("Native ECMAScript RegExp");
  await expect(dialog).toContainText("3 measured");

  await dialog.getByRole("tab", { name: "Risk & growth" }).click();
  await dialog
    .getByRole("spinbutton", { name: "Maximum repetitions" })
    .fill("64");
  await dialog.getByRole("spinbutton", { name: "Maximum steps" }).fill("3");
  await dialog
    .getByRole("button", { name: "Run bounded growth probe" })
    .click();
  await expect(
    dialog.getByRole("table", { name: "Dynamic growth samples" }),
  ).toBeVisible();
  await expect(
    dialog.getByRole("img", { name: /Execution-time growth plot/u }),
  ).toBeVisible();
  await expect(
    dialog.getByRole("img", { name: /Outcome plot/u }),
  ).toBeVisible();
  expect(pageErrors).toEqual([]);
});
