import { expect } from "e2e";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, test, WEB } from "./t3.ts";

test("Palette keeps threads matched by project and environment", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("t3code");
  const local = await t3.thread({ project, title: "Local standup", messages: ["Start"], model: "default" });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    const second = makeState(SECOND_HOME);
    const remoteProject = await second.state.project("t3code");
    await second.state.thread({ project: remoteProject, title: "Weekly notes", messages: ["Start"], model: "default" });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60_000 });
    await screen.getByRole("button", "More actions for Scenario").tap();
    await screen.getByRole("menuitem", "Rename…").tap();
    await screen.getByRole("textbox", "Label").fill("BeeBox");
    await screen.getByRole("button", "Save", { exact: true }).tap();
    await screen.getByRole("button", "More actions for BeeBox").waitFor();
    await t3.open(local);
    await screen.getByTestId("composer-editor").waitFor();
    await browser.keyboard.press("Control+k");
    const palette = screen.getByRole("dialog", "Command palette");
    const query = palette.getByRole("combobox");
    const combinedResults: string[] = [];
    for (const words of ["t3code", "beebox", "t3code beebox", "beebox t3code", "t3code on beebox"]) {
      await query.fill(words);
      await screen.getByText("Searching messages…", { exact: true }).waitFor({ state: "hidden" });
      const text = await browser.evaluate(async () => {
        const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;
        return await new Promise<string>((resolve) => {
          let timer: ReturnType<typeof setTimeout>;
          const finish = () => { observer.disconnect(); resolve(dialog.innerText); };
          const reset = () => { clearTimeout(timer); timer = setTimeout(finish, 750); };
          const observer = new MutationObserver(reset);
          observer.observe(dialog, { childList: true, subtree: true, characterData: true });
          reset();
        });
      });
      await app.screenshot(words.replaceAll(" ", "-"));
      if (words.includes(" ")) combinedResults.push(text);
    }
    for (const text of combinedResults) {
      expect(text).toContain("Weekly notes");
      expect(text).toContain("Project:");
    }
  } finally {
    await server.stop();
  }
});
