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

test("Message search finds Bangla and Hindi prefixes and Thai substrings", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Bangladesh Residency", messages: ["Start"] });
  await t3.open(thread);
  const samples = [
    { message: "আমি বাংলাদেশে থাকি", control: "বাংলাদেশে", query: "বাংলা", label: "bangla" },
    { message: "पास में किताबघर है", control: "किताबघर", query: "किताब", label: "hindi" },
    { message: "ช่วยค้นหาไฟล์นี้", control: "ช่วยค้นหาไฟล์นี้", query: "ค้นหา", label: "thai" },
  ];
  for (const sample of samples) {
    await screen.getByRole("textbox").fill(sample.message);
    await screen.getByRole("textbox").press("Enter");
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await browser.locator("[data-user-message-body]").getByText(sample.message, { exact: true }).waitFor();
  }
  await browser.keyboard.press("Control+k");
  const search = screen.getByPlaceholder("Search commands, projects, and threads...");
  const found: string[] = [];
  for (const sample of samples) {
    await search.fill(sample.control);
    await screen.getByRole("option").filter({ hasText: sample.message }).waitFor();
    await screen.getByText("Searching messages…", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot(`${sample.label}-whole-word-control`);
    await search.fill("");
    await screen.getByRole("option").filter({ hasText: sample.message }).waitFor({ state: "hidden" });
    await search.fill(sample.query);
    await expect.poll(() => browser.evaluate(() => {
      const root = document.querySelector('[role="dialog"]');
      const text = root?.textContent ?? "";
      return text.includes("Searching") ? "" : text;
    })).toMatch(/No matching commands, projects, or threads\.|You:/);
    await app.screenshot(`${sample.label}-partial-word`);
    found.push(await browser.evaluate(() => document.querySelector('[role="dialog"]')?.textContent ?? ""));
  }
  for (const [index, sample] of samples.entries()) {
    await expect(found[index]).toContain(sample.message);
  }
});
