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

test("Escape hides license search before dismissing Settings", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("license-search-demo");
  const thread = await t3.thread({ project, title: "License search demo", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/general");
  await screen.getByRole("button", "About", { exact: true }).tap();
  await screen.getByRole("link", "View licenses", { exact: true }).tap();
  const results: boolean[] = [];
  for (const query of ["react", ""]) {
    if (query === "") await t3.open("/settings/open-source-licenses");
    await screen.getByRole("button", "Search open-source licenses", { exact: true }).tap();
    const search = screen.getByRole("searchbox", "Search open-source licenses", { exact: true });
    if (query) await search.fill(query);
    await app.screenshot(query ? "populated-search-before-escape" : "empty-search-before-escape");
    await browser.keyboard.press("Escape");
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => undefined)));
    });
    await app.screenshot(query ? "populated-search-after-escape" : "empty-search-after-escape");
    results.push(await screen.getByRole("dialog").isVisible());
    results.push(!(await search.isVisible()));
    results.push(await screen.getByText("466 notices", { exact: true }).isVisible());
    await browser.keyboard.press("Escape");
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map((animation) => animation.finished.catch(() => undefined)));
    });
    await app.screenshot(query ? "populated-second-escape" : "empty-second-escape");
    results.push(!(await screen.getByRole("dialog").isVisible()));
  }
  expect(results, "Each first Escape keeps Settings with cleared, hidden search; second Escape closes Settings").toEqual(Array(8).fill(true));
});
