/// <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("Changes restores exact positions at the bottom of a long diff", WEB, async ({t3, app, browser, screen}) => {
  const notes = Array.from({length:100}, (_,i) => `Line ${i+1}: original review note`).join("\n") + "\n";
  const project = await t3.project("demo", {"notes.txt": notes});
  const thread = await t3.thread({project, title:"Review notes", messages:["Start"]});
  await runPromise(Effect.gen(function*(){const fs = yield* FileSystem.FileSystem; yield* fs.writeFileString(`${project}/notes.txt`, notes.replaceAll("original", "updated"));}));
  await browser.setViewport({width:1440,height:900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByText("Diff", {exact:true}).tap();
  const expand = screen.getByRole("button", "Expand notes.txt", {exact:true});
  await expand.waitFor(); await expand.tap();
  await screen.getByRole("button", "Collapse notes.txt", {exact:true}).waitFor();
  const position = (offset: number | null) => browser.evaluate(async (offset) => {
    const host = document.querySelector("diffs-container");
    if (!host) throw new Error("Missing diff");
    let scroller: HTMLElement | null = host as HTMLElement;
    while(scroller && !(scroller.scrollHeight > scroller.clientHeight && /auto|scroll/.test(getComputedStyle(scroller).overflowY))) scroller = scroller.parentElement;
    if(!scroller) throw new Error("Missing diff scroller");
    if(offset !== null) scroller.scrollTop = offset < 0 ? scroller.scrollHeight - scroller.clientHeight + offset + 1 : offset;
    await new Promise<void>(resolve => requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())));
    return {top:scroller.scrollTop,max:scroller.scrollHeight-scroller.clientHeight};
  }, offset);
  const results = [];
  for(const [label, offset] of [["bottom",-1],["near-bottom",-21],["middle",400]] as const){
    const saved = await position(offset);
    if(saved.max < 500) throw new Error(`Diff is not long enough: ${JSON.stringify(saved)}`);
    await app.screenshot(`${label}-saved`);
    await screen.getByRole("button", /^Diff scope:/).tap();
    await screen.getByRole("menuitemradio", "Uncommitted", {exact:true}).tap();
    await screen.getByRole("button", "Expand notes.txt", {exact:true}).waitFor();
    await screen.getByRole("button", /^Diff scope:/).tap();
    await screen.getByRole("menuitemradio", "Changes", {exact:true}).tap();
    await screen.getByRole("button", "Collapse notes.txt", {exact:true}).waitFor();
    const restored = await position(null);
    await app.screenshot(`${label}-restored`);
    results.push({label,saved,restored});
  }
  expect(results.map(({saved,restored})=>restored.top-saved.top)).toEqual([0,0,0]);
});
