import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
import { imeSession } from "./snooze-ime-browser.ts";

test("IME confirmation preserves the snooze amount draft until ordinary Enter", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await t3.open("/settings/threads");
  const amount = screen.getByRole("textbox", "Amount", { exact: true }).first();
  await amount.waitFor();
  await amount.fill("");
  const cdp = await imeSession(await browser.url());
  await browser.evaluate(() => {
    const input = document.activeElement as HTMLInputElement;
    input.scrollIntoView({ block: "center" });
    (window as any).imeActive = false;
    input.addEventListener("compositionstart", () => { (window as any).imeActive = true; });
    input.addEventListener("compositionend", () => { (window as any).imeActive = false; });
    const events: unknown[] = [];
    (window as any).imeEvidence = events;
    for (const type of ["compositionstart", "compositionupdate", "compositionend", "input", "keydown", "focusout", "focusin"]) {
      input.addEventListener(type, (event) => events.push({ type, key: (event as KeyboardEvent).key, keyCode: (event as KeyboardEvent).keyCode, isComposing: (event as InputEvent).isComposing, trusted: event.isTrusted, value: input.value }));
    }
    return null;
  });
  await cdp.send("Input.imeSetComposition", { text: "4", selectionStart: 1, selectionEnd: 1 });
  await cdp.send("Input.imeSetComposition", { text: "45", selectionStart: 2, selectionEnd: 2 });
  await app.screenshot("draft-before-ime-enter");
  await cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: "Enter", code: "Enter", windowsVirtualKeyCode: 229, nativeVirtualKeyCode: 229 });
  if (await browser.evaluate(() => (window as any).imeActive)) {
    await cdp.send("Input.insertText", { text: "45" });
  }
  await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: "Enter", code: "Enter", windowsVirtualKeyCode: 229, nativeVirtualKeyCode: 229 });
  console.log("Browser IME event evidence", await browser.evaluate(() => JSON.stringify((window as any).imeEvidence)));
  await app.screenshot("after-ime-confirm-enter");
  await expect(screen.getByText("Menu now:", { exact: false })).toContainText("In 1 hour");
  await expect(amount).toHaveValue("45");
  await expect(amount).toBeFocused();
  await amount.press("Enter");
  await app.screenshot("after-ordinary-enter");
  await expect(screen.getByText("Menu now:", { exact: false })).toContainText("In 45 hours");
  await cdp.detach();
});
