/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Escape clears Voice model search and keeps Settings open", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Voice search", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with").tap();
  await screen.getByRole("option").nth(1).tap();
  const results = [];
  for (const query of ["tiny", "   "]) {
    await t3.open("/settings/voice");
    const search = screen.getByRole("searchbox", "Search transcription models");
    await search.fill(query);
    await search.tap();
    await browser.evaluate(() => {
      document.querySelector('[aria-label="Search transcription models"]')?.scrollIntoView({ block: "center" });
      return null;
    });
    await app.screenshot(query === "tiny" ? "filtered-search-before-escape" : "spaces-before-escape");
    await browser.keyboard.press("Escape");
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
      await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      return null;
    });
    await app.screenshot(query === "tiny" ? "tiny-after-escape" : "spaces-after-escape");
    results.push(await browser.evaluate(() => {
      const input = document.querySelector<HTMLInputElement>('[aria-label="Search transcription models"]');
      return { open: !!input, value: input?.value ?? null, focused: input === document.activeElement };
    }));
  }
  expect(results, "Escape clears both text and spaces while keeping Settings open and search focused").toEqual([
    { open: true, value: "", focused: true },
    { open: true, value: "", focused: true },
  ]);
});
