import { readFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { IOS, test } from "./t3-mobile.ts";
import { MOBILE_T3_HOME } from "../e2e.config.ts";
import { emptyReplayThread } from "./zz-stopped-seed.ts";
import { runPromise } from "./t3.ts";

test("The mobile feed folds a stopped turn once a later turn runs", IOS, async ({ t3, app, screen, device }) => {
  await device.setAppearance("light");
  await t3.project("demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  await emptyReplayThread(MOBILE_T3_HOME);
  await t3.open();
  await screen.getByText("Stopped turn tour", { exact: false }).first().tap();
  await screen.getByRole("textbox").fill("Give me a short tour");
  await screen.getByRole("button", "Send", { exact: true }).tap();
  const stop = screen.getByRole("button", "Stop agent");
  await screen.getByText("The project has a single math module", { exact: false }).first().waitFor({ timeout: 60000 });
  await stop.tap();
  await stop.waitFor({ state: "hidden" });
  await device.dismissKeyboard();
  await app.screenshot("mobile-stopped-latest-turn");
  await screen.getByRole("textbox").fill("Continue please");
  await screen.getByRole("button", "Send", { exact: true }).tap();
  await screen.getByText("This turn is a replay.", { exact: false }).first().waitFor({ timeout: 60000 });
  await stop.waitFor({ state: "hidden" });
  await device.dismissKeyboard();
  await screen.swipe({ from: { x: 190, y: 240 }, to: { x: 190, y: 720 }, duration: 500 });
  await runPromise(Effect.sleep("2 seconds"));
  const first = await app.screenshot("mobile-after-resume-check");
  await runPromise(Effect.sleep("500 millis"));
  const second = await app.screenshot("mobile-after-resume");
  if (!readFileSync(first).equals(readFileSync(second))) throw new Error("Settled mobile screenshots differ");
  await expect(screen.getByText(/You stopped after/)).toBeVisible();
});
