/// <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(
  "A review comment preserves line numbers across diff hunks",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const contents = Array.from({ length: 28 }, (_, index) => `Line ${index + 1}\n`).join("");
    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.replace("Line 2\n", "First change\n").replace("Line 22\n", "Second change\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 firstLine = '[data-column-number="2"][data-line-type="change-addition"]';
    const secondLine = '[data-column-number="22"][data-line-type="change-addition"]';
    await expect.poll(() => point(secondLine)).not.toBeNull();
    const first = await point(firstLine);
    const second = await point(secondLine);
    if (!first || !second) throw new Error("Both changed lines must be visible");
    await browser.mouse.move(first.x, first.y);
    await expect.poll(() => point("[data-utility-button]")).not.toBeNull();
    const comment = await point("[data-utility-button]");
    if (!comment) throw new Error("The diff comment control is unavailable");
    await browser.mouse.move(comment.x, comment.y);
    await browser.mouse.down();
    await browser.mouse.move(second.x, second.y);
    await browser.mouse.up();

    await screen.getByRole("textbox", "Comment on lines 2 to 22").focus();
    await browser.keyboard.type("Please review both changes.");
    await screen.getByRole("button", "Comment", { exact: true }).tap();
    await screen.getByRole("button", "Submit message").tap();
    await screen.getByRole("button", "Review comment, notes.txt 2 to 22. Show details").tap();

    const displayedLine = () =>
      browser.evaluate(() => {
        for (const host of document.querySelectorAll(
          '[data-slot="popover-popup"] diffs-container',
        )) {
          for (const line of host.shadowRoot?.querySelectorAll("[data-line]") ?? []) {
            if (line.textContent?.trim() === "Second change") return line.getAttribute("data-line");
          }
        }
        return null;
      });
    await expect.poll(displayedLine).not.toBeNull();
    await app.screenshot("comment-excerpt");
    expect(await displayedLine()).toBe("22");
  },
);
