import { expect } from "e2e";
import { writeFile, readFile } from "node:fs/promises";
import { MOBILE_T3_HOME, MOBILE } from "../e2e.config.ts";
import { makeState, runPromise } from "./t3.ts";
import { test, IOS } from "./t3-mobile.ts";

test("Mobile Latest turn follows completed turns and numbered turn stays pinned", IOS, async ({ t3, app, screen }) => {
  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(MOBILE_T3_HOME, {T3CODE_PORT: String(MOBILE.serverPort)});
  const turn = async (message: string, content: string) => {
    await writeFile(`${project}/notes.txt`, content);
    await runPromise(cli(["thread", "send", thread.threadId, message, "--wait", "--json"]));
  };
  const capture = async (label: string) => {
    for (let n = 0; n < 5; n++) {
      const a = await app.screenshot(`${label}-stability-${n}`);
      await new Promise(resolve => setTimeout(resolve, 500));
      const b = await app.screenshot(label);
      if ((await readFile(a)).equals(await readFile(b))) return;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  await turn("second", "Initial note\nSecond turn addition\n");
  await t3.open();
  await screen.getByText("Review file changes", {exact:false}).first().tap();
  await screen.getByRole("button", "Git controls").tap();
  await screen.getByRole("button", "Review changes", {exact:false}).tap();
  await screen.getByRole("button", "Select diff").tap();
  await screen.getByText("Latest turn", {exact:true}).tap();
  await capture("mobile-latest-selected");
  await screen.getByRole("button", "Select diff").tap();
  await capture("mobile-latest-selected-menu");
  await screen.getByText("Latest turn", {exact:true}).tap();
  await turn("third", "Initial note\nSecond turn addition\nThird turn addition\n");
  await capture("mobile-latest-after-new-turn");
  const followed = await screen.getByText("Turn 3", {exact:true}).count();
  await screen.getByRole("button", "Select diff").tap();
  await capture("mobile-latest-after-new-turn-menu");
  await screen.getByText("Turn", {exact:true}).tap();
  await capture("mobile-latest-turn-submenu");
  await screen.getByRole("button", "Turn 3", {exact:false}).tap();
  await capture("mobile-newest-picked-by-number");
  await screen.getByRole("button", "Select diff").tap();
  await capture("mobile-numbered-selected-menu");
  await screen.getByText("Turn", {exact:true}).tap();
  await capture("mobile-numbered-turn-submenu");
  await screen.getByRole("button", "Turn 3", {exact:false}).tap();
  await turn("fourth", "Initial note\nSecond turn addition\nThird turn addition\nFourth turn addition\n");
  await capture("mobile-numbered-after-another-turn");
  await expect(screen.getByText("Turn 3", {exact:true})).toBeVisible();
  expect(followed).toBe(1);
});
