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

test("Map search keeps composition Enter and Escape with the input", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  await t3.thread({ project, title: "Map search", messages: ["Hello"] });
  await t3.open("/settings/connections");
  const search = screen.getByRole("searchbox", "Find a machine on the map");
  await search.waitFor({ timeout: 60000 });
  await search.fill("Scenario");
  const outcomes: Array<{query: string | null; selected: boolean; open: boolean}> = [];
  const state = () => browser.evaluate(() => ({
    query: document.querySelector<HTMLInputElement>('[aria-label="Find a machine on the map"]')?.value ?? null,
    selected: !!document.querySelector('[data-fleet-node][aria-pressed="true"]'),
    open: !!document.querySelector('[role="dialog"]'),
  }));
  for (const key of ["Enter", "Escape"]) {
    for (const safari of [false, true]) {
      await search.fill("Scenario");
      await search.click();
      await browser.evaluate(({key, safari}) => {
        const input = document.querySelector('[aria-label="Find a machine on the map"]')!;
        input.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "し" }));
        input.dispatchEvent(new KeyboardEvent("keydown", { key, isComposing: !safari, keyCode: safari ? 229 : key === "Enter" ? 13 : 27, bubbles: true, cancelable: true }));
        input.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "" }));
      }, {key, safari});
      await app.screenshot(`composition-${key}-${safari ? "keycode229" : "isComposing"}`);
      outcomes.push(await state());
      // Restore the initial selection with the map's own clear control for the next independent key.
      await t3.open("/settings/connections");
      await search.waitFor({ timeout: 60000 });
    }
  }
  await search.fill("Scenario");
  await search.press("Enter");
  const ordinaryEnter = await state();
  await app.screenshot("ordinary-enter-selects");
  await search.click();
  await search.press("Escape");
  const ordinaryEscape = await state();
  await app.screenshot("ordinary-escape-clears");
  await search.press("Escape");
  await expect(screen.getByRole("dialog")).toBeHidden();
  const secondEscape = await state();
  await app.screenshot("second-escape-closes");
  expect(outcomes).toEqual(Array.from({length: 4}, () => ({ query: "Scenario", selected: false, open: true })));
  expect(ordinaryEnter.selected).toBe(true);
  expect(ordinaryEscape).toEqual({ query: "", selected: true, open: true });
  expect(secondEscape.open).toBe(false);
});
