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

test("Annotation shortcuts respect modifiers and uppercase CapsLock key values", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Image work");
  const thread = await t3.thread({ project, title: "Annotation shortcuts", messages: ["Start"] });
  await t3.open(thread);
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(async (selector) => {
    const canvas = document.createElement("canvas"); canvas.width = 640; canvas.height = 360;
    const ctx = canvas.getContext("2d")!; ctx.fillStyle = "#eef2f7"; ctx.fillRect(0, 0, 640, 360);
    ctx.fillStyle = "#334155"; ctx.font = "24px sans-serif"; ctx.fillText("Image annotation shortcut sample", 80, 80);
    const blob = await new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
    const files = new DataTransfer(); files.items.add(new File([blob], "sample.png", { type: "image/png" }));
    const picker = document.querySelector<HTMLInputElement>(selector)!; picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, input);
  await screen.getByRole("button", "Preview sample.png").tap();
  await screen.getByRole("button", "Draw on image").tap();
  const drawing = 'svg[aria-label="Draw on sample.png"]';
  await browser.locator(drawing).waitFor();
  const draw = async () => {
    const point = await browser.evaluate((selector) => {
      const r = document.querySelector(selector)!.getBoundingClientRect(); return { x: r.x+r.width/3, y: r.y+r.height/2 };
    }, drawing);
    await browser.mouse.move(point.x, point.y); await browser.mouse.down();
    await browser.mouse.move(point.x+120, point.y+50); await browser.mouse.up();
  };
  const marks = () => browser.evaluate((selector) => document.querySelector(selector)?.querySelectorAll(':scope > path[d]').length ?? 0, drawing);
  const key = async (key: string, modifiers: Record<string, boolean> = {}) => {
    await browser.evaluate(({ key, modifiers }) => {
      (document.activeElement ?? document.body).dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...modifiers })); return null;
    }, { key, modifiers });
  };
  const results: Record<string, unknown> = {};
  await draw(); await key("z", { ctrlKey: true, altKey: true });
  results.ctrlAltKeepsStroke = await marks(); await app.screenshot("ctrl-alt-z-keeps-stroke");
  if (await marks()) await screen.getByRole("button", "Undo", { exact: true }).tap();
  await draw(); await key("z", { ctrlKey: true, metaKey: true });
  results.ctrlMetaKeepsStroke = await marks(); await app.screenshot("ctrl-meta-z-keeps-stroke");
  if (!(await marks())) await draw();
  await key("z", { ctrlKey: true }); results.plainUndoRemovesStroke = await marks();
  await key("d"); await key("e", { metaKey: true });
  results.metaELeavesDraw = await browser.evaluate(() => document.querySelector('[aria-label="Drawing tool"] button[aria-pressed="true"]')?.getAttribute("aria-label"));
  await app.screenshot("meta-e-keeps-draw");
  await key("e"); await key("A");
  results.capsASelectsArrow = await browser.evaluate(() => Array.from(document.querySelectorAll('[aria-label="Drawing tool"] button[aria-pressed="true"]')).map(b => b.getAttribute("aria-label")));
  await app.screenshot("capslock-a-selects-arrow");
  await key("d"); await key("E", { shiftKey: true });
  results.shiftELeavesDraw = await browser.evaluate(() => Array.from(document.querySelectorAll('[aria-label="Drawing tool"] button[aria-pressed="true"]')).map(b => b.getAttribute("aria-label")));
  await draw();
  await screen.getByText("sample.png", { exact: true }).tap();
  await key("Enter", { ctrlKey: true });
  // Wait for image saving to finish on the old implementation before capturing its result.
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1000)); return null; });
  results.ctrlEnterKeepsAnnotation = await browser.evaluate((selector) => !!document.querySelector(selector), drawing);
  await app.screenshot("ctrl-enter-keeps-annotation");
  if (results.ctrlEnterKeepsAnnotation) {
    await key("Enter");
    await browser.locator(drawing).waitFor({ state: "detached" });
  }
  await app.screenshot("plain-enter-saves");
  expect(results).toEqual({ ctrlAltKeepsStroke: 1, ctrlMetaKeepsStroke: 1, plainUndoRemovesStroke: 0, metaELeavesDraw: "Draw freehand (D)", capsASelectsArrow: ["Draw an arrow (A)"], shiftELeavesDraw: ["Draw freehand (D)"], ctrlEnterKeepsAnnotation: true });
});
