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

test("Escape from rename returns keyboard focus to the thread title", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("server");
  const thread = await t3.thread({ project, title: "Replay Provider Greeting", messages: ["Hello"] });
  await t3.open(thread);
  const title = screen.getByRole("button", "Thread actions for Replay Provider Greeting", { exact: true });
  await title.waitFor();
  const results = [];
  for (const findOpen of [false, true]) {
    if (findOpen) {
      await title.focus();
      await browser.keyboard.press("Enter");
      await screen.getByRole("menuitem", "Find in thread", { exact: true }).waitFor();
      await browser.keyboard.press("Enter");
      await screen.getByRole("searchbox", "Find in thread").waitFor();
    }
    await screen.getByRole("button", "New thread in server", { exact: true }).focus();
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Enter");
    await screen.getByRole("menuitem", "Find in thread", { exact: true }).waitFor();
    for (let i = 0; i < 5; i++) await browser.keyboard.press("ArrowDown");
    await browser.keyboard.press("Enter");
    const input = screen.getByRole("textbox", "Thread title", { exact: true });
    await input.fill(findOpen ? "Second unsaved edit" : "Unsaved edit");
    await app.screenshot(findOpen ? "find-open-renaming" : "renaming");
    await browser.keyboard.press("Escape");
    await input.waitFor({ state: "hidden" });
    await title.waitFor();
    await app.screenshot(findOpen ? "find-open-after-escape" : "after-escape");
    results.push(await browser.evaluate(`({
      focus: document.activeElement?.getAttribute('aria-label'),
      findOpen: !!document.querySelector('[data-thread-find-bar]')
    })`));
  }
  expect(results).toEqual([
    { focus: "Thread actions for Replay Provider Greeting", findOpen: false },
    { focus: "Thread actions for Replay Provider Greeting", findOpen: true },
  ]);
});
