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

test("Sidebar New uses the single selected project", WEB, async ({ t3, app, screen, browser }) => {
  const a = await t3.project("Project A");
  const b = await t3.project("Project B");
  await t3.thread({ project: a, title: "Work in A", messages: ["hello"] });
  const viewed = await t3.thread({ project: b, title: "Work in B", messages: ["hello"] });
  await t3.open(viewed);
  const hideDetails = async () => {
    const toggle = screen.getByRole("button", "Toggle thread details panel");
    if (await toggle.getAttribute("aria-pressed") === "true") await toggle.tap();
  };
  const capture = async (label: string) => {
    await new Promise(resolve => setTimeout(resolve, 700));
    await app.screenshot(label);
  };
  const filter = () => screen.getByRole("combobox", /^Filter threads by project/);
  const newThread = () => screen.getByRole("button", "New thread", { exact: true });
  await hideDetails();

  await newThread().tap();
  await screen.getByRole("dialog", "Command palette").waitFor();
  await capture("all-projects-picker");
  await browser.keyboard.press("Escape");

  await filter().tap();
  await screen.getByRole("option", "Project A", { exact: true }).tap();
  await filter().tap();
  await screen.getByRole("option", "Project B", { exact: true }).tap({ modifiers: ["Shift"] });
  await browser.keyboard.press("Escape");
  await newThread().tap();
  await screen.getByRole("dialog", "Command palette").waitFor();
  await capture("multiple-projects-picker");
  await browser.keyboard.press("Escape");

  await filter().tap();
  await screen.getByRole("option", "Project A", { exact: true }).tap();
  await newThread().tap({ modifiers: ["Shift"] });
  await screen.getByRole("button", "New thread in Project B", { exact: true }).waitFor();
  await hideDetails();
  await capture("shift-new-follows-project-b");

  await t3.open(viewed);
  await hideDetails();
  await filter().tap();
  await screen.getByRole("option", "Project A", { exact: true }).tap();
  await capture("project-a-filter-viewing-b");
  await newThread().tap();
  await new Promise(resolve => setTimeout(resolve, 700));
  if (!await screen.getByRole("dialog", "Command palette").isVisible()) await hideDetails();
  await capture("single-project-new");
  await expect(screen.getByRole("button", "New thread in Project A", { exact: true })).toBeVisible();
  await expect(screen.getByRole("heading", "New thread", { exact: true })).toBeVisible();
});
