import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Mouse search options preserve query typing and match navigation", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("search-demo", {
    "alpha.ts": 'export const alpha = "first";\n',
    "beta.ts": 'export const alpha = "second";\n',
    "gamma.ts": 'export const Alpha = "third";\n',
  });
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl!);
        yield* client.subscribeServerConfig({}).pipe(
          Stream.filter((event) => {
            const providers =
              event.type === "snapshot"
                ? event.config.providers
                : event.type === "providerStatuses"
                  ? event.payload.providers
                  : [];
            return providers.some(
              (provider) =>
                provider.instanceId === "devReplay" &&
                provider.models?.some((model) => model.slug === "multi-turn"),
            );
          }),
          Stream.runHead,
        );
      }).pipe(Effect.scoped, Effect.timeout("30 seconds")),
    );
  const thread = await t3.thread({ project, title: "Search options", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox").click();
  await browser.keyboard.press("Control+Shift+F");
  const input = browser.locator('[data-testid="project-content-search"] input[role="combobox"]');
  await input.fill("alph");
  await screen.getByText("3 results in 3 files", { exact: true }).waitFor();
  await screen.getByRole("button", "Match case", { exact: true }).click();
  await screen.getByText("2 results in 2 files", { exact: true }).waitFor();
  await app.screenshot("after-click-match-case");
  const caseFocused = await browser.evaluate(() => document.activeElement?.tagName === "INPUT");
  await browser.keyboard.type("a");
  await screen.getByText("2 results in 2 files", { exact: true }).waitFor();
  await browser.keyboard.press("ArrowDown");
  await app.screenshot("after-typing-and-arrow-down");
  const typed = await browser.evaluate(() => document.querySelector<HTMLInputElement>('[data-testid="project-content-search"] input[role="combobox"]')?.value);
  const selected = await browser.evaluate(() => document.querySelector('[data-testid="project-content-search"] button.bg-accent')?.closest("section")?.textContent);
  await browser.keyboard.press("Enter");
  const closed = await browser.evaluate(() => !!document.querySelector('[role="region"][aria-label^="Workspace panel:"]'));
  if (closed) {
    await input.waitFor({ state: "hidden" });
    await screen.getByRole("textbox", "beta.ts", { exact: true }).waitFor();
  }
  await app.screenshot("after-enter");
  if (closed) {
    await browser.keyboard.press("Control+Shift+F");
    await input.fill("alph");
    await screen.getByText("3 results in 3 files", { exact: true }).waitFor();
  }
  await screen.getByRole("button", "Match whole word", { exact: true }).click();
  await screen.getByRole("button", "Use regular expression", { exact: true }).click();
  await browser.keyboard.type("x");
  await screen.getByText("0 results in 0 files", { exact: true }).waitFor();
  await app.screenshot("after-other-option-clicks-and-typing");
  const otherTyped = await browser.evaluate(() => document.querySelector<HTMLInputElement>('[data-testid="project-content-search"] input[role="combobox"]')?.value);
  await expect(caseFocused).toBe(true);
  await expect(typed).toBe("alpha");
  await expect(selected).toContain("beta.ts");
  await expect(closed).toBe(true);
  await expect(otherTyped).toBe("alphx");
});
