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

test("Gallery keeps active strokes and finishes lost capture without trapping an empty press", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Drawing gallery");
  const thread = await t3.thread({ project, title: "Drawing proof", messages: ["Start"], model: "default" });
  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 [["first.png", "#f1f5f9"], ["second.png", "#dbeafe"]]) {
      const canvas = document.createElement("canvas");
      canvas.width = 640; canvas.height = 360;
      const ctx = canvas.getContext("2d")!;
      ctx.fillStyle = color!; ctx.fillRect(0, 0, 640, 360);
      ctx.fillStyle = "#475569"; ctx.font = "24px sans-serif";
      ctx.fillText(name!, 24, 42);
      const blob = await new Promise<Blob>((resolve) => canvas.toBlob((blob) => resolve(blob!)));
      files.items.add(new File([blob], name!, { type: "image/png" }));
    }
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
  }, input);
  const svg = 'svg[aria-label="Draw on first.png"]';
  const read = () => browser.evaluate((selector) => {
    const surface = document.querySelector(selector);
    return {
      first: !!document.querySelector('[role="dialog"] img[alt="first.png"]'),
      committed: surface?.querySelectorAll(":scope > path[d]").length ?? 0,
      live: surface?.querySelectorAll("g path[d]").length ?? 0,
      navigation: ["Previous media", "Next media"].map((name) => !(document.querySelector(`button[aria-label="${name}"]`) as HTMLButtonElement)?.disabled),
    };
  }, svg);
  const begin = async () => {
    await screen.getByRole("button", "Preview first.png").tap();
    await screen.getByRole("button", "Draw on image").tap();
    await browser.locator(svg).waitFor();
    return browser.evaluate((selector) => {
      const surface = document.querySelector(selector)!;
      surface.addEventListener("gotpointercapture", (event) => surface.setAttribute("data-pointer", String((event as PointerEvent).pointerId)));
      const r = surface.getBoundingClientRect();
      return { x: r.x + 120, y: r.y + 150, outside: r.right + 20 };
    }, svg);
  };
  const close = async () => { await browser.keyboard.press("Escape"); await browser.keyboard.press("Escape"); };
  const stroke = async (p: {x: number; y: number}) => {
    await browser.mouse.move(p.x, p.y); await browser.mouse.down();
    for (let i = 1; i <= 10; i++) await browser.mouse.move(p.x + i * 15, p.y + i * 4);
  };
  const loseCapture = () => browser.evaluate((selector) => {
    const surface = document.querySelector(selector)!;
    const id = Number(surface.getAttribute("data-pointer"));
    if (!surface.hasPointerCapture(id)) throw new Error("Native pointer capture was not established");
    surface.releasePointerCapture(id);
  }, svg);
  const observations: Record<string, unknown> = {};

  // First stroke: keyboard navigation while the real mouse button remains held.
  let p = await begin();
  await stroke(p);
  observations.held = await read();
  await app.screenshot("held-first-stroke");
  await browser.keyboard.press("ArrowRight");
  await app.screenshot("arrow-right-while-held");
  await browser.mouse.up();
  await browser.mouse.move(20, 20);
  await browser.evaluate(() => { (document.querySelector('[role="dialog"]') as HTMLElement).focus(); });
  await browser.locator('[data-slot="tooltip-popup"]').waitFor({ state: "hidden" });
  observations.released = await read();
  await app.screenshot("released-after-arrow");
  await browser.keyboard.press("ArrowLeft");
  await browser.mouse.move(20, 20);
  await browser.evaluate(() => { (document.querySelector('[role="dialog"]') as HTMLElement).focus(); });
  await browser.locator('[data-slot="tooltip-popup"]').waitFor({ state: "hidden" });
  await app.screenshot("return-after-arrow");
  await close();

  // A genuine browser lostpointercapture, forced through the public DOM capture API.
  p = await begin(); await stroke(p);
  await loseCapture();
  await browser.mouse.move(p.outside, p.y);
  observations.lostMoved = await read();
  await app.screenshot("lost-capture-with-movement");
  await browser.keyboard.press("ArrowRight");
  observations.lostArrow = await read();
  await browser.mouse.up();
  await app.screenshot("lost-capture-arrow-and-release");
  await close();

  // One-point stroke: establish native capture without delivering a second point to React.
  p = await begin();
  await browser.mouse.move(p.x, p.y); await browser.mouse.down();
  observations.emptyHeld = await read();
  await app.screenshot("empty-press-held");
  await browser.evaluate((selector) => {
    document.querySelector(selector)!.addEventListener("pointermove", (event) => event.stopPropagation(), { once: true });
  }, svg);
  await browser.mouse.move(p.x, p.y);
  await loseCapture(); await browser.mouse.move(p.outside, p.y);
  observations.lostEmpty = await read();
  await app.screenshot("lost-capture-empty-navigation-restored");
  await browser.mouse.up();
  await browser.keyboard.press("ArrowRight");
  observations.emptyNavigated = (await read()).first;
  await app.screenshot("empty-press-can-navigate");
  await close();

  // Also exercise the under-two-points pointerup path on an otherwise empty drawing.
  p = await begin(); await browser.mouse.move(p.x, p.y); await browser.mouse.down();
  await browser.mouse.up();
  observations.emptyReleased = await read();
  await app.screenshot("empty-pointerup-navigation-restored");

  expect(observations).toEqual({
    held: {first:true, committed:0, live:1, navigation:[false,false]},
    released: {first:true, committed:1, live:0, navigation:[false,false]},
    lostMoved: {first:true, committed:1, live:0, navigation:[false,false]},
    lostArrow: {first:true, committed:1, live:0, navigation:[false,false]},
    emptyHeld: {first:true, committed:0, live:0, navigation:[false,false]},
    lostEmpty: {first:true, committed:0, live:0, navigation:[true,true]},
    emptyNavigated: false,
    emptyReleased: {first:true, committed:0, live:0, navigation:[true,true]},
  });
});
