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

test("Guest share and handoff close when leaving their thread and stay closed on return", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Dialog navigation demo");
  await t3.open("/settings/labs");
  await screen.getByRole("switch", "Guest links", { exact: true }).tap();
  await screen.getByRole("switch", "Linked environments", { exact: true }).tap();
  await t3.thread({ project, title: "Thread B", messages: ["Hello"] });
  const a = await t3.thread({ project, title: "Origin thread", messages: ["Hello"] });
  await t3.open(a);
  await screen.getByRole("textbox", "Message Origin thread", { exact: true }).waitFor();
  const command = async (text: string) => {
    await browser.keyboard.press("ControlOrMeta+k");
    await screen.getByPlaceholder("Search commands, projects, and threads...").fill(text);
    await browser.locator('[role="option"]').filter({ hasText: text }).first().waitFor();
    await browser.keyboard.press("Enter");
  };
  const retained: number[] = [];
  for (const dialogTitle of ["Share with guest", "Continue on another machine"]) {
    for (const destination of ["Thread B", "Open pull requests"]) {
      await command("Origin thread");
      await command(dialogTitle);
      const dialog = screen.getByRole("dialog", dialogTitle, { exact: true });
      await dialog.waitFor();
      await command(destination);
      if (destination === "Thread B") {
        await browser.locator('[data-testid="composer-editor"][aria-label="Message Thread B"]').waitFor();
      } else {
        await browser.locator('input[placeholder="Search pull requests, or label:bug"]').waitFor();
      }
      // Capture the navigated surface before checking or dismissing the originating dialog.
      await app.screenshot(`${dialogTitle}-${destination}`);
      retained.push(await browser.locator('[role="dialog"]:visible').count());
      await command("Origin thread");
      await browser.locator('[data-testid="composer-editor"][aria-label="Message Origin thread"]').waitFor();
      await app.screenshot(`${dialogTitle}-${destination}-return`);
      retained.push(await browser.locator('[role="dialog"]:visible').count());
      if (await browser.locator('[role="dialog"]:visible').count()) {
        await screen.getByRole("button", "Cancel", { exact: true }).tap();
      }
    }
  }
  await expect(retained).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
});
