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

test("Rejected empty project names restore the saved name", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("server");
  const thread = await t3.thread({ project, title: "Project settings proof", messages: ["first"] });
  await t3.open(thread);
  await t3.open("/settings/projects");
  await screen.getByRole("button", /^Project scope:/).tap();
  await screen.getByRole("menuitemradio", "server", { exact: true }).tap();
  const name = screen.getByRole("textbox", "Project name", { exact: true });
  await name.waitFor();
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    });
    await app.screenshot(label);
  };
  await browser.evaluate(() => {
    const seen = new WeakSet<Element>();
    (window as any).warningCount = 0;
    new MutationObserver(() => {
      for (const el of document.querySelectorAll("[data-slot='toast-title']")) {
        if (el.textContent === "Project title cannot be empty" && !seen.has(el)) {
          seen.add(el);
          (window as any).warningCount++;
        }
      }
    }).observe(document.body, { subtree: true, childList: true });
  });
  await name.tap();
  await name.press("ControlOrMeta+a");
  await name.press("Backspace");
  await name.press("Enter");
  await capture("empty-name-enter");
  const empty = await browser.evaluate(() => (document.querySelector('input[aria-label="Project name"]') as HTMLInputElement).value);
  await name.tap();
  await name.press("Tab");
  await capture("unchanged-name-tab");
  await name.fill("   ");
  await screen.getByText("Name", { exact: true }).tap();
  await capture("whitespace-click-away");
  const whitespace = await browser.evaluate(() => (document.querySelector('input[aria-label="Project name"]') as HTMLInputElement).value);
  await name.tap();
  await screen.getByText("Name", { exact: true }).tap();
  await capture("unchanged-name-click-away");
  const warnings = await browser.evaluate(() => (window as any).warningCount);
  expect({ empty, whitespace, warnings }).toEqual({ empty: "server", whitespace: "server", warnings: 2 });
});
