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

test("Voice model language search clears after Escape and outside dismissal", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("voice-demo");
  await t3.thread({ project, title: "Voice settings demo", messages: ["Hello"], model: "multi-turn" });
  await t3.open("/settings/voice");
  await screen.getByRole("combobox", "Transcribe with", { exact: true }).tap();
  const localOption = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="option"]')).map(e => e.textContent?.trim()).find(t => t && t !== "Off" && !/OpenAI|ElevenLabs|Groq|Deepgram|Google/i.test(t)));
  if (!localOption) throw new Error("Local environment option not found");
  await screen.getByRole("option", localOption, { exact: true }).tap();
  const filter = screen.getByRole("button", /^Filter by language:/);
  await filter.tap();
  await screen.getByRole("textbox", "Search languages", { exact: true }).fill("japanese");
  await app.screenshot("search-japanese");
  await browser.keyboard.press("Escape");
  await filter.tap();
  await app.screenshot("reopened-after-escape");
  const escapeState = await browser.evaluate(() => ({ query: (document.querySelector('input[aria-label="Search languages"]') as HTMLInputElement)?.value ?? null, all: Array.from(document.querySelectorAll('[role="menuitemcheckbox"]')).some(e => e.textContent?.trim() === "All languages"), english: document.querySelector('[role="menuitemcheckbox"][aria-checked="true"]')?.textContent?.trim() ?? null }));
  await screen.getByRole("textbox", "Search languages", { exact: true }).fill("fren");
  await screen.getByText("Transcription", { exact: true }).tap();
  await filter.tap();
  await app.screenshot("reopened-after-outside-click");
  const outsideState = await browser.evaluate(() => ({ query: (document.querySelector('input[aria-label="Search languages"]') as HTMLInputElement)?.value ?? null, all: Array.from(document.querySelectorAll('[role="menuitemcheckbox"]')).some(e => e.textContent?.trim() === "All languages"), english: document.querySelector('[role="menuitemcheckbox"][aria-checked="true"]')?.textContent?.trim() ?? null }));
  expect(escapeState).toEqual({ query: "", all: true, english: "English" });
  expect(outsideState).toEqual({ query: "", all: true, english: "English" });
});
