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

test("Every web add path carries the draft and removes the old draft after send", WEB, async ({ t3, app, screen, browser }) => {
  const workspace = await t3.project("alpha", { "next/README.md": "" });
  const existing = await t3.project("existing");
  const thread = await t3.thread({ project: workspace, title: "Earlier work", messages: ["Start"] });
  const results: Record<string, string | null> = {};
  const orphanCounts: number[] = [];
  for (const path of ["local-folder", "existing-folder", "clone", "new-project"]) {
    await t3.open(thread);
    await screen.getByRole("button", "New thread", { exact: true }).tap();
    await screen.getByRole("option", "alpha Current", { exact: false }).tap();
    const composer = screen.getByRole("textbox");
    const message = `Plan the ${path} project`;
    await composer.fill(message);
    const picker = browser.locator("[data-draft-project-trigger]");
    await picker.tap();
    await screen.getByRole("option", "Add project").tap();
    if (path === "new-project") {
      await screen.getByText("New project", { exact: true }).tap();
      await screen.getByRole("combobox").fill("created-project");
      await browser.keyboard.press("Enter");
    } else if (path === "clone") {
      await screen.getByText("Git URL", { exact: true }).tap();
      await screen.getByRole("combobox").fill("https://github.com/octocat/Hello-World.git");
      await browser.keyboard.press("Enter");
      await screen.getByRole("combobox").fill(`${workspace}/cloned-project`);
      await browser.keyboard.press("Enter");
    } else {
      await screen.getByText("Local folder", { exact: true }).tap();
      await screen.getByRole("combobox").fill(path === "local-folder" ? `${workspace}/next` : existing);
      await browser.keyboard.press("Enter");
    }
    await expect(picker).toHaveText(path === "local-folder" ? "next" : path === "existing-folder" ? "existing" : path === "clone" ? "cloned-project" : "created-project");
    await expect(screen.getByRole("dialog", "Command palette")).not.toBeAttached();
    await expect(screen.getByRole("button", "Dismiss notification")).toHaveCount(0);
    await app.screenshot(`${path}-after-add`);
    results[path] = await composer.textContent();
    // Use the same text on both sides so the post-send captures also expose an orphaned draft.
    await composer.fill(message);
    await composer.press("Enter");
    await expect(screen.getByRole("button", "Stop generation")).toBeVisible();
    await app.screenshot(`${path}-after-send`);
    orphanCounts.push(await browser.locator('[data-testid="sidebar-draft-row"]').count());
  }
  expect(orphanCounts).toEqual([0, 0, 0, 0]);
  expect(results).toEqual({
    "local-folder": "Plan the local-folder project",
    "existing-folder": "Plan the existing-folder project",
    clone: "Plan the clone project",
    "new-project": "Plan the new-project project",
  });
});
