/// <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";

const lines = Array.from({ length: 15 }, (_, i) => `line ${i + 1}`);
test("Mixed review selections show a count instead of a backwards range", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Review demo", {"notes.txt": lines.join("\n") + "\n"});
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/notes.txt`, ["added A", "added B", "added C", ...lines.filter(l => l !== "line 11")].join("\n") + "\n");
  }));
  const thread = await t3.thread({project, title:"Review selection", messages:["hello"]});
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", {exact:true}).tap();
  await screen.getByRole("button", "Expand notes.txt", {exact:true}).tap();
  const points = await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const root = host.shadowRoot;
      if (!root) continue;
      const result = ["line 10", "line 11"].map(text => {
        const line = Array.from(root.querySelectorAll("[data-line]")).find(e => e.textContent?.trim() === text);
        const index = line?.getAttribute("data-line-index");
        const gutter = root.querySelector(`[data-column-number][data-line-index="${index}"]`);
        const r = gutter?.getBoundingClientRect();
        return r ? {x:r.right-8, y:r.top+r.height/2} : null;
      });
      if (result.every(Boolean)) return result;
    }
    throw new Error("Diff line gutters missing");
  });
  await browser.mouse.move(points[0]!.x, points[0]!.y);
  await browser.mouse.down();
  await browser.mouse.move(points[1]!.x, points[1]!.y);
  await browser.mouse.up();
  const comment = screen.getByRole("textbox", /^Comment on lines /);
  await comment.fill("Check this deletion.");
  await app.screenshot("mixed-selection-comment");
  await screen.getByRole("button", "Comment", {exact:true}).tap();
  await app.screenshot("mixed-selection-chip");
  await expect(screen.getByRole("button", "Review comment, notes.txt 2 lines. Show details", {exact:true})).toBeVisible();
});
