/// <reference lib="dom" />
import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

test("IME keys preserve a diff comment draft", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("server", { "apps/server/README.md": "# Server\n\nSynthetic example\n\n" });
  await writeFile(`${project}/apps/server/README.md`, "# Server\n\nSynthetic example\n\nAdded line five\nAdded line six\n");
  const thread = await t3.thread({ project, title: "Diff comment IME", messages: ["first"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff").tap();
  await screen.getByRole("button", "Expand apps/server/README.md", { exact: true }).tap();
  const draft = screen.getByRole("textbox", "Comment on lines +5", { exact: true });
  const openDraft = async () => {
    const point = await browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const line = host.shadowRoot?.querySelector<HTMLElement>('[data-column-number="5"]');
        if (line) { const r = line.getBoundingClientRect(); return { x: r.right - 5, y: r.y + r.height / 2 }; }
      }
      throw new Error("Changed line 5 not rendered");
    });
    await browser.mouse.move(point.x, point.y);
    const utility = await browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const button = host.shadowRoot?.querySelector<HTMLElement>("[data-utility-button]");
        if (button) { const r = button.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }
      }
      throw new Error("Line comment utility missing");
    });
    await browser.mouse.move(utility.x, utility.y);
    await browser.mouse.down();
    await browser.mouse.up();
    await draft.waitFor();
    await draft.focus();
    await browser.keyboard.type("Draft");
  };
  // Replay the browser events IMEs deliver. This does not exercise an OS IME.
  const composeKey = async (key: string, ctrlKey = false, keyCode = 0, metaKey = false) => {
    await browser.evaluate(() => {
      const input = document.activeElement as HTMLTextAreaElement;
      input.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "" }));
      Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(input, "Draftにほん");
      input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertCompositionText", data: "にほん", isComposing: true }));
      return null;
    });
    await browser.evaluate(({ key, ctrlKey, keyCode, metaKey }) => {
      document.activeElement!.dispatchEvent(new KeyboardEvent("keydown", { key, ctrlKey, keyCode, metaKey, isComposing: keyCode !== 229, bubbles: true, cancelable: true }));
      return null;
    }, { key, ctrlKey, keyCode, metaKey });
  };
  const state = () => browser.evaluate(() => {
    const input = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on lines +5"]');
    return { exists: !!input, focused: !!input && document.activeElement === input, value: input?.value ?? "" };
  });
  const results = [];
  for (const [label, key, ctrl, code, meta] of [
    ["composing-escape", "Escape", false, 0, false],
    ["composing-control-enter", "Enter", true, 0, false],
    ["keycode229-escape", "Escape", false, 229, false],
    ["keycode229-control-enter", "Enter", true, 229, false],
    ["composing-command-enter", "Enter", false, 0, true],
    ["keycode229-command-enter", "Enter", false, 229, true],
  ] as const) {
    await openDraft();
    await app.screenshot(`draft-before-${label}`);
    await composeKey(key, ctrl, code, meta);
    await app.screenshot(label);
    results.push(await state());
    if ((await state()).exists) await browser.keyboard.press("Escape");
  }
  await openDraft();
  await browser.keyboard.press("Escape");
  const plainEscape = await state();
  await openDraft();
  await browser.keyboard.press("Control+Enter");
  await app.screenshot("ordinary-control-enter");
  const plainEnter = await state();
  await browser.setViewport({ width: 700, height: 800 });
  await screen.getByRole("dialog", "Workspace panel", { exact: true }).waitFor();
  await openDraft();
  await app.screenshot("narrow-draft-before-escape");
  await composeKey("Escape");
  await app.screenshot("narrow-composing-escape");
  const narrowState = await state();
  expect(narrowState).toEqual({ exists: true, focused: true, value: "Draftにほん" });
  expect(results).toEqual(Array.from({ length: 6 }, () => ({ exists: true, focused: true, value: "Draftにほん" })));
  expect(plainEscape.exists).toBe(false);
  expect(plainEnter.exists).toBe(false);
});
