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

test("Saving a drawing keeps keyboard focus inside image preview", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Image work");
  const thread = await t3.thread({ project, title: "Drawing preview", 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 files = new DataTransfer();
    for (const [name, color] of [["img1.png", "#d9edf7"], ["img2.png", "#f7e8d9"]]) {
      const canvas = new OffscreenCanvas(800, 500);
      const context = canvas.getContext("2d")!;
      context.fillStyle = color!;
      context.fillRect(0, 0, 800, 500);
      context.fillStyle = "#24445a";
      context.font = "32px sans-serif";
      context.fillText(name!, 30, 50);
      files.items.add(new File([await canvas.convertToBlob({ type: "image/png" })], name!, { 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 img1.png").tap();
  await screen.getByRole("button", "Draw on image").tap();
  await browser.keyboard.press("t");
  const drawing = 'svg[aria-label="Draw on img1.png"]';
  await browser.locator(drawing).waitFor();
  const point = await browser.evaluate((selector) => {
    const r = document.querySelector(selector)!.getBoundingClientRect();
    return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
  }, drawing);
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await screen.getByRole("textbox", "Text label").fill("hello");
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Enter");
  await browser.locator('button[aria-label="Draw on image"]:enabled').waitFor();
  const savedFocus = await browser.evaluate(() => {
    const a = document.activeElement;
    return { name: a?.getAttribute("aria-label") ?? a?.textContent, inDialog: !!a?.closest('[role="dialog"]') };
  });
  await app.screenshot("focus-after-saving-drawing");
  await browser.keyboard.press("Tab");
  const tabFocus = await browser.evaluate(() => {
    const a = document.activeElement;
    return { name: a?.getAttribute("aria-label") ?? a?.textContent, inDialog: !!a?.closest('[role="dialog"]') };
  });
  await app.screenshot("focus-after-tab-in-preview");
  expect(savedFocus).toEqual({ name: "Draw on image", inDialog: true });
  expect(tabFocus).toEqual({ name: "Next media", inDialog: true });
});
