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

test("Draft project picker retains its draft through new, clone and registered-folder paths", WEB, async ({ t3, app, screen, browser }) => {
  const alpha = await t3.project("alpha");
  const registered = await t3.project("registered");
  const observations: { path: string; retained: boolean; orphan: boolean }[] = [];
  for (const path of ["new", "clone", "registered"]) {
    await t3.open();
    const picker = browser.locator("[data-draft-project-trigger]");
    await picker.tap();
    await screen.getByRole("option", "alpha", { exact: true }).tap();
    const composer = screen.getByRole("textbox");
    const prompt = `Plan the ${path} project`;
    await composer.fill(prompt);
    await picker.tap();
    await screen.getByRole("option", "Add project").tap();
    if (path === "new") {
      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(`file://${alpha}`);
      await screen.getByRole("button", "Continue (Enter)").tap();
      await screen.getByRole("combobox").fill(`${alpha}/cloned-project`);
      await browser.keyboard.press("Enter");
    } else {
      await screen.getByText("Local folder", { exact: true }).tap();
      await screen.getByRole("combobox").fill(registered);
      await browser.keyboard.press("Enter");
    }
    await browser.locator('[data-slot="command-dialog-popup"]').waitFor({ state: "hidden" });
    await screen.getByRole("button", "Dismiss notification").tap().catch(() => {});
    await composer.waitFor();
    await app.screenshot(`${path}-after-add`);
    const retained = await browser.evaluate((prompt) => document.querySelector('[role="textbox"]')?.textContent?.includes(prompt) ?? false, prompt);
    await composer.fill(prompt);
    await composer.press("Enter");
    await screen.getByRole("button", "Stop generation").waitFor();
    await app.screenshot(`${path}-after-send`);
    const orphan = await browser.evaluate((prompt) => [...document.querySelectorAll('button')].some((button) => button.getAttribute('aria-label')?.includes(`${prompt}, Unsent draft`)), prompt);
    observations.push({ path, retained, orphan });
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  }
  expect(observations).toEqual([
    { path: "new", retained: true, orphan: false },
    { path: "clone", retained: true, orphan: false },
    { path: "registered", retained: true, orphan: false },
  ]);
});
