import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A tiny release move does not swallow thread switching or its quick retry", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Sidebar click demo");
  for (const title of ["go one", "go two", "go three"]) {
    await t3.thread({ project, title, messages: [`Content for ${title}`] });
  }
  await t3.open();
  await screen.getByText("go one", { exact: true }).first().waitFor({ state: "visible" });
  const gesture = async (title: string, zeroMove: boolean, detail: number) => {
    for (const phase of ["down", "move", ...(zeroMove ? ["zero"] : []), "up", "click"]) {
      await browser.evaluate(({ title, phase, detail }) => {
        const row = Array.from(document.querySelectorAll('[data-testid="sidebar-row-card"]')).find(row => row.textContent?.includes(title));
        if (!row) throw new Error(`Missing sidebar row ${title}`);
        const box = row.getBoundingClientRect();
        const init = { bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", isPrimary: true, button: 0, clientX: box.x + 30, clientY: box.y + box.height / 2 };
        if (phase === "down") {
          row.dispatchEvent(new PointerEvent("pointerdown", { ...init, buttons: 1 }));
          row.dispatchEvent(new MouseEvent("mousedown", { ...init, buttons: 1, detail }));
        } else if (phase === "move" || phase === "zero") {
          row.dispatchEvent(new PointerEvent("pointermove", { ...init, clientX: init.clientX + (phase === "zero" ? 2 : 1), buttons: phase === "zero" ? 0 : 1 }));
        } else if (phase === "up") {
          row.dispatchEvent(new PointerEvent("pointerup", { ...init, buttons: 0 }));
          row.dispatchEvent(new MouseEvent("mouseup", { ...init, buttons: 0, detail }));
        } else row.dispatchEvent(new MouseEvent("click", { ...init, buttons: 0, detail }));
      }, { title, phase, detail });
    }
  };
  const selected = () => browser.evaluate(() => Array.from(document.querySelectorAll('[data-testid="sidebar-row-card"][aria-current="page"]')).map(row => row.textContent).join(" "));
  await gesture("go one", false, 1);
  await expect.poll(selected).toContain("go one");
  await app.screenshot("plain-click-opens-go-one");
  await gesture("go two", true, 1);
  await app.screenshot("release-move-click-go-two");
  const afterRelease = await selected();
  await gesture("go two", false, 2);
  await app.screenshot("immediate-retry-go-two");
  const afterRetry = await selected();
  await gesture("go two", false, 1);
  await app.screenshot("fresh-single-click-go-two");
  await expect.poll(selected).toContain("go two");
  expect(afterRelease).toContain("go two");
  expect(afterRetry).toContain("go two");
});
