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

test("Japanese shared dictionary label finds and opens the dictionary in both scopes", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("voice-demo");
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).tap();
  await screen.getByText("日本語", { exact: true }).tap();
  await screen.getByLabel("言語", { exact: true }).waitFor();
  const machine = await runPromise(environmentId(app.baseUrl!));
  const found: boolean[] = [];
  for (const [scope, suffix] of [["all", ""], ["environment", `?machine=${encodeURIComponent(machine)}`]]) {
    await t3.open(`/settings/voice${suffix}`);
    const row = browser.locator('[id="speech-project-dictionary"]');
    await row.getByText("共有辞書", { exact: true }).waitFor();
    const search = screen.getByRole("combobox", "設定を検索", { exact: true });
    await search.fill("プロジェクトの辞書");
    await browser.locator('#settings-search-result-speech-project-dictionary').waitFor();
    await search.fill("共有辞書");
    await row.scrollIntoView();
    await app.screenshot(`${scope}-shared-dictionary-search`);
    const result = browser.locator('#settings-search-result-speech-project-dictionary');
    const present = (await result.count()) === 1;
    found.push(present);
    if (!present) continue;
    await expect(result).toBeVisible();
    await result.tap();
    await browser.locator('#speech-project-dictionary:focus').waitFor();
    await row.scrollIntoView();
    await app.screenshot(`${scope}-shared-dictionary-opened`);
    await expect(row).toContainText("共有辞書");
    await expect(browser.locator('#speech-project-dictionary:focus')).toBeVisible();
    expect(await browser.evaluate(() => new URLSearchParams(location.search).get("machine"))).toBe(scope === "all" ? null : machine);
  }
  expect(found).toEqual([true, true]);
});
