/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

declare global {
  interface Window { projectGate: { started: Promise<void>; release: () => void } }
}

test("Late project creation preserves a reopened settings search", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Welcome", messages: ["Hello" ] });
  await browser.addInitScript(() => {
    const started = Promise.withResolvers<void>();
    const held: Array<() => void> = [];
    let active = true;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (!active || typeof data !== "string") return send.call(this, data);
      const parsed = JSON.parse(data);
      const messages = [parsed].flat();
      const isCreate = (m: { _tag?: string; tag?: string }) => m?._tag === "Request" && m.tag === "projects.createNew";
      if (!messages.some(isCreate)) return send.call(this, data);
      const others = messages.filter(m => !isCreate(m));
      if (others.length) send.call(this, JSON.stringify(others));
      held.push(() => send.call(this, JSON.stringify(Array.isArray(parsed) ? messages.filter(isCreate) : messages.find(isCreate))));
      started.resolve();
    };
    window.projectGate = { started: started.promise, release: () => { active = false; held.splice(0).forEach(f => f()); } };
  });
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Welcome", { exact: true }).waitFor();
  // Hide local filesystem descriptions in public recordings; controls and behavior stay visible.
  await browser.evaluate(() => {
    const style = document.createElement("style");
    style.textContent = '[data-slot="toast-description"], [data-slot="command-dialog-popup"] span[class*="text-muted-foreground/85"] { visibility: hidden !important; }';
    document.head.append(style);
    return null;
  });
  await browser.keyboard.press("Control+k");
  await screen.getByRole("dialog").waitFor();
  await browser.keyboard.type("New project");
  await screen.getByRole("option", "New project", { exact: true }).tap();
  await screen.getByRole("dialog").getByRole("combobox").fill("palette-proof");
  await screen.getByRole("button", "Create (Enter)", { exact: true }).waitFor();
  await browser.keyboard.press("Enter");
  await browser.evaluate(() => window.projectGate.started.then(() => null));
  await browser.keyboard.press("Escape");
  await screen.getByRole("dialog").waitFor({ state: "hidden" });
  await browser.keyboard.press("Control+k");
  await screen.getByRole("dialog").waitFor();
  await browser.keyboard.type("settings");
  await screen.getByText("Open settings", { exact: true }).waitFor();
  await app.screenshot("reopened-settings-search");
  await browser.evaluate(() => { window.projectGate.release(); return null; });
  await screen.getByText("Created palette-proof", { exact: true }).waitFor();
  // Let the successful hook finish its navigation and the originating submit handler resume.
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 1500)));
  await app.screenshot("after-project-completes");
  expect(await screen.getByText("Open settings", { exact: true }).isVisible()).toBe(true);
  await expect(screen.getByRole("dialog").getByRole("combobox")).toHaveValue("settings");
});
