import { expect } from "e2e";
import { writeFile, readFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Latest scope follows completed turns; numbered scope stays pinned", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Diff scope demo", { "notes.txt": "Initial note\n" });
  const thread = await t3.thread({ project, title: "Review file changes", messages: ["first"] });
  const { cli } = makeState(T3_HOME);
  const turn = async (message: string, content: string) => {
    await writeFile(`${project}/notes.txt`, content);
    await runPromise(cli(["thread", "send", thread.threadId, message, "--wait", "--json"]));
  };
  await turn("second", "Initial note\nSecond turn addition\n");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Diff D", { exact: true }).tap();
  const scope = () => browser.locator('button[aria-label^="Diff scope:"]');
  const capture = async (label: string) => {
    for (let n = 0; n < 5; n++) {
      const first = await app.screenshot(`${label}-stability-${n}`);
      await new Promise(resolve => setTimeout(resolve, 500));
      const second = await app.screenshot(label);
      if ((await readFile(first)).equals(await readFile(second))) return;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  const settled = async () => {
    await screen.getByText("Loading checkpoint diff...").waitFor({state:"hidden"});
    await screen.getByText("Loading code...").waitFor({state:"hidden"});
    // A refetch leaves the previous body visible with reduced opacity.
    await screen.getByRole("button", "Refreshing diff", {exact:true}).waitFor({state:"hidden"});
    if (await screen.getByRole("button", "Expand all files", {exact:true}).isVisible()) await screen.getByRole("button", "Expand all files", {exact:true}).tap();
    await screen.getByText("Loading code...").waitFor({state:"hidden"});
  };
  await scope().tap();
  await screen.getByRole("menuitemradio", "Latest turn").tap();
  await settled();
  await scope().tap();
  await screen.getByRole("menuitem", "Turn", {exact:true}).hover();
  await capture("latest-selected-menu");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  await turn("third", "Initial note\nSecond turn addition\nThird turn addition\n");
  await settled();
  await capture("latest-after-new-turn");
  const latestLabel = await scope().getAttribute("aria-label");
  await scope().tap();
  await screen.getByRole("menuitem", "Turn", {exact:true}).hover();
  await capture("latest-after-new-turn-menu");
  await screen.getByRole("menuitemradio", "Turn 3", {exact:false}).tap();
  await settled();
  await capture("newest-picked-by-number");
  const numberedLabel = await scope().getAttribute("aria-label");
  await scope().tap();
  await screen.getByRole("menuitem", "Turn", {exact:true}).hover();
  await capture("numbered-selected-menu");
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  await turn("fourth", "Initial note\nSecond turn addition\nThird turn addition\nFourth turn addition\n");
  await settled();
  await capture("numbered-after-another-turn");
  await expect(scope()).toHaveAttribute("aria-label", "Diff scope: Turn 3");
  expect(numberedLabel).toBe("Diff scope: Turn 3");
  expect(latestLabel).toBe("Diff scope: Latest turn");
});
