import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Malformed Settings scope URLs do not hide controls or stick across categories", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("scope-proof");
  const results: { label: string; url: string; body: string }[] = [];
  const capture = async (label: string) => {
    await browser.locator('nav[aria-label="Settings breadcrumb"]').waitFor();
    await screen.getByText("Applying settings for", { exact: true }).waitFor();
    await browser.locator('[data-slot="skeleton"]').first().waitFor({ state: "hidden", timeout: 120_000 });
    if (label === "numeric-scope-source-control-after-navigation" && !(await screen.getByText("This environment is no longer available.", { exact: true }).isVisible())) {
      await browser.locator('button[aria-label="Rescan server environment"]:not(:disabled)').waitFor({ timeout: 120_000 });
    }
    await app.screenshot(label);
    results.push({ label, url: await browser.url(), body: await browser.evaluate(() => document.body.innerText) ?? "" });
  };
  await t3.open("/settings/threads?checkout=true");
  await capture("boolean-checkout-threads");
  await screen.getByRole("button", "Worktrees", { exact: true }).tap();
  await capture("boolean-checkout-worktrees-after-navigation");
  await t3.open("/settings/worktrees");
  await capture("worktrees-without-params-baseline");
  await t3.open("/settings/integrations?project=123&machine=456&checkout=789");
  await capture("numeric-scope-browser-redirect");
  await screen.getByRole("button", "Source control & issues", { exact: true }).tap();
  await capture("numeric-scope-source-control-after-navigation");
  await t3.open("/settings/worktrees?project=%20");
  await capture("blank-project-worktrees");
  await screen.getByRole("button", "Threads", { exact: true }).tap();
  await capture("blank-project-threads-after-navigation");
  for (const result of results) {
    expect(result.body, result.label).not.toMatch(/Select a project to choose one of its checkouts\.|This project is no longer available\.|This environment is no longer available\./);
    expect(new URL(result.url).search, result.label).toBe("");
  }

});
