import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Move dialog closes when Browser Back leaves its thread", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("proj-a");
  await t3.project("proj-b");
  await t3.thread({ project, title: "Thread A", model: "default", messages: ["go Thread A"] });
  const threadB = await t3.thread({ project, title: "Thread B", model: "default", messages: ["go Thread B"] });
  await browser.addInitScript(() => {
    const hidePaths = () => {
      if (document.getElementById("proof-privacy")) return;
      const style = document.createElement("style");
      style.id = "proof-privacy";
      style.textContent = '#thread-workspace-form code, #thread-workspace-form .font-mono { visibility: hidden; }';
      document.head?.append(style);
    };
    new MutationObserver(hidePaths).observe(document, { childList: true, subtree: true });
    hidePaths();
  });
  await t3.open(threadB);
  await screen.getByRole("button", "Thread actions for Thread B", { exact: true }).waitFor();
  await screen.getByText("Thread A", { exact: true }).tap();
  await screen.getByRole("button", "Thread actions for Thread A", { exact: true }).tap();
  await screen.getByRole("menuitem", "Move to project…", { exact: true }).tap();
  const dialog = screen.getByRole("dialog", "Move thread to project", { exact: true });
  await dialog.waitFor();
  await app.screenshot("move-dialog-open-on-thread-a");
  await browser.back();
  await browser.locator('button[aria-label="Thread actions for Thread B"]').waitFor();
  try {
    await expect(dialog).toBeHidden();
  } finally {
    await app.screenshot("after-browser-back-to-thread-b");
  }
});
