/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Closing a directly opened thread modal preserves Back and dismisses Forward", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("History demo");
  const seed = async (input: Parameters<typeof t3.thread>[0]) => {
    for (let attempt = 0; attempt < 15; attempt++) {
      try { return await t3.thread(input); } catch (error) {
        if (!String(error).includes("Advertised models: default") || attempt === 14) throw error;
      }
    }
    throw new Error("Replay catalog unavailable");
  };
  const first = await seed({ project, title: "Conversation A", messages: ["Conversation A message"] });
  const second = await seed({ project, title: "Conversation B", messages: ["Conversation B message"] });
  const results: Array<{ modal: string; backReturnsToA: boolean; forwardDismissed: boolean }> = [];
  const traverse = async (direction: "back" | "forward") => {
    try { await browser.evaluate((direction) => new Promise<null>((resolve) => {
      addEventListener("popstate", () => resolve(null), { once: true });
      history[direction]();
    }), direction); } catch (error) {
      if (!String(error).includes("Execution context was destroyed")) throw error;
    }
    await screen.getByText(/^Conversation [AB] message$/).waitFor();
  };
  for (const modal of ["Settings", "Usage"]) {
    await t3.open(first);
    await screen.getByText("Conversation A message", { exact: true }).waitFor();
    const firstPath = await browser.evaluate(() => location.pathname);
    await t3.open(second);
    await screen.getByText("Conversation B message", { exact: true }).waitFor();
    const secondPath = await browser.evaluate(() => location.pathname);
    await screen.getByRole("button", modal, { exact: true }).tap();
    await browser.locator("[role=dialog]").waitFor();
    await app.screenshot(`${modal}-open`);
    await screen.getByRole("button", "Close", { exact: true }).tap();
    await browser.locator("[role=dialog]").waitFor({ state: "detached" });
    await traverse("back");
    const backPath = await browser.evaluate(() => location.pathname);
    await screen.getByText(backPath === firstPath ? "Conversation A message" : "Conversation B message", { exact: true }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot(`${modal}-after-one-back`);
    const backReturnsToA = backPath === firstPath;
    let forwardDismissed = false;
    if (backReturnsToA) {
      await traverse("forward");
      await screen.getByText("Conversation B message", { exact: true }).waitFor();
      await traverse("forward");
      await expect.poll(() => browser.evaluate(() => location.pathname)).toBe(secondPath);
      await browser.locator("[role=dialog]").waitFor({ state: "detached" });
      await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
      await app.screenshot(`${modal}-forward-dismissed`);
      forwardDismissed = true;
    }
    results.push({ modal, backReturnsToA, forwardDismissed });
  }
  expect(results).toEqual([
    { modal: "Settings", backReturnsToA: true, forwardDismissed: true },
    { modal: "Usage", backReturnsToA: true, forwardDismissed: true },
  ]);
});
