/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

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

test(
  "Escape from a diff comment button cancels the comment and keeps the right panel sheet open",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await browser.setViewport({ width: 900, height: 800 });
    const contents = "Line 1\nLine 2\nLine 3\nLine 4\n";
    const project = await t3.project("demo", { "notes.txt": contents });
    const thread = await t3.thread({ project, title: "Review notes", messages: ["Start"] });
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) =>
        fs.writeFileString(`${project}/notes.txt`, `${contents}Line 5\n`),
      ),
    );

    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByText("Diff", { exact: true }).tap();
    await screen.getByRole("button", "Expand notes.txt").tap();

    // The diff viewer puts the gutters and the comment control in a shadow root.
    const point = (selector: string) =>
      browser.evaluate((selector) => {
        const element = document
          .querySelector("diffs-container")
          ?.shadowRoot?.querySelector(selector);
        const box = element?.getBoundingClientRect();
        return box?.width && box.height
          ? { x: box.x + box.width / 2, y: box.y + box.height / 2 }
          : null;
      }, selector);
    const addedLine = '[data-column-number="5"][data-line-type="change-addition"]';
    await expect.poll(() => point(addedLine)).not.toBeNull();
    const line = await point(addedLine);
    if (!line) throw new Error("The added line must be visible");
    await browser.mouse.move(line.x, line.y);
    await expect.poll(() => point("[data-utility-button]")).not.toBeNull();
    const control = await point("[data-utility-button]");
    if (!control) throw new Error("The diff comment control is unavailable");
    await browser.mouse.move(control.x, control.y);
    await browser.mouse.down();
    await browser.mouse.up();

    const draft = 'textarea[aria-label^="Comment on lines"]';
    await browser.locator(draft).focus();
    await browser.keyboard.type("Please rename this");
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Escape");

    const dialogs = () =>
      browser.evaluate(() => document.querySelectorAll('[role="dialog"]').length);
    await expect
      .poll(() => browser.evaluate((draft) => document.querySelectorAll(draft).length, draft))
      .toBe(0);
    await app.screenshot("after-escape");
    expect(await dialogs()).toBeGreaterThan(0);
  },
);
