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

test("Escape clears the project icon search before dismissing the picker", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("server");
  const thread = await t3.thread({ project, title: "Project icon demo", messages: ["Start"] });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  await t3.open("/settings/projects");
  await screen.getByRole("button", /^Project scope:/).tap();
  await screen.getByRole("menuitemradio", "server", { exact: false }).tap();
  const settle = () => browser.evaluate(async () => {
    for (const animation of document.getAnimations()) {
      if (Number.isFinite(animation.effect?.getComputedTiming().endTime)) animation.finish();
    }
    await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    return null;
  });
  const open = async () => {
    await screen.getByRole("button", "Choose a project icon", { exact: true }).tap();
    await screen.getByRole("button", "Red", { exact: true }).tap();
    await screen.getByRole("searchbox", "Search Lucide icons").fill("rocket");
  };
  const state = () => browser.evaluate(() => {
    const search = document.querySelector<HTMLInputElement>('[aria-label="Search Lucide icons"]');
    return {
      open: !!search && !!search.closest('[role="dialog"]'),
      query: search?.value ?? null,
      focused: !!search && document.activeElement === search,
      red: document.querySelector('[aria-label="Red"]')?.getAttribute("aria-pressed") === "true",
    };
  });
  await open();
  await settle();
  await app.screenshot("query-before-escape");
  await browser.keyboard.press("Escape");
  await settle();
  await app.screenshot("after-first-escape");
  const first = await state();
  if (first.open) await browser.keyboard.press("Escape");
  await open();
  await browser.keyboard.down("Escape");
  await browser.keyboard.down("Escape");
  await browser.keyboard.down("Escape");
  await settle();
  await app.screenshot("while-escape-is-held");
  const held = await state();
  await browser.keyboard.up("Escape");
  await browser.keyboard.press("Escape");
  await settle();
  await app.screenshot("after-separate-escape");
  const closed = await state();
  await t3.open("/settings/projects");
  await screen.getByRole("button", /^Project scope:/).tap();
  await screen.getByRole("menuitemradio", "server", { exact: false }).tap();
  await open();
  const attached = await chromium.connectOverCDP("http://127.0.0.1:19281");
  const url = await browser.url();
  const page = attached.contexts().flatMap(context => context.pages()).find(page => page.url() === url)!;
  const cdp = await page.context().newCDPSession(page);
  await browser.emulateMedia({ colorScheme: "dark" });
  await cdp.send("Input.imeSetComposition", { text: "ろ", selectionStart: 1, selectionEnd: 1, replacementStart: 6, replacementEnd: 6 });
  await settle();
  await app.screenshot("during-ime-composition");
  await browser.keyboard.press("Escape");
  await settle();
  await app.screenshot("after-ime-escape");
  const composition = await state();
  await cdp.detach();
  await attached.close();
  expect(first, "First Escape clears only the query and preserves focus and the Red draft").toEqual({ open: true, query: "", focused: true, red: true });
  expect(held, "Auto-repeat does not dismiss the picker").toEqual({ open: true, query: "", focused: true, red: true });
  expect(composition, "Composition Escape preserves the query and picker").toEqual({ open: true, query: "rocketろ", focused: true, red: true });
  expect(closed.open, "A separate Escape dismisses the empty picker").toBe(false);
});
