/// <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(
  "Pure insertion and deletion review excerpts keep their line numbers",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const results: Array<string | null> = [];
    for (const mode of ["insertion", "deletion", "whole-insertion", "whole-deletion"] as const) {
    const whole = mode.startsWith("whole-");
    const insertion = mode.endsWith("insertion");
    const number = whole ? "2" : "22";
    const contents = Array.from({ length: 28 }, (_, index) => `Line ${index + 1}\n`).join("");
    const project = await t3.project(mode, { "notes.txt": mode === "whole-insertion" ? "" : contents });
    const thread = await t3.thread({ project, title: `Review ${mode}`, messages: ["Start"] });
    await runPromise(
      Effect.flatMap(FileSystem.FileSystem, (fs) =>
        fs.writeFileString(
          `${project}/notes.txt`,
          whole ? (insertion ? "Line 1\nInserted line\nLine 3\n" : "") : insertion ? contents.replace("Line 22\n", "Inserted line\nLine 22\n") : contents.replace("Line 22\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="${number}"][data-line-type="${insertion ? "change-addition" : "change-deletion"}"]`;
    const secondLine = firstLine;
    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(comment.x, comment.y);
    await browser.mouse.up();

    await screen.getByRole("textbox", /Comment on line/).focus();
    await browser.keyboard.type(`Please review this ${mode}.`);
    await screen.getByRole("button", "Comment", { exact: true }).tap();
    await screen.getByRole("button", "Submit message").tap();
    await screen.getByRole("button", new RegExp(`Review comment, notes.txt.*${number}.*Show details`)).tap();

    const displayedLine = () =>
      browser.evaluate(({insertion, number}) => {
        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() === (insertion ? "Inserted line" : `Line ${number}`)) return line.getAttribute("data-line");
          }
        }
        return null;
      }, {insertion, number});
    await expect.poll(displayedLine).not.toBeNull();
    await app.screenshot(`${mode}-excerpt`);
    results.push(await displayedLine());
    }
    expect(results).toEqual(["22", "22", "2", "2"]);
  },
);
