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

test("Dotfile searches retain the leading dot in ranking and highlighting", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1280, height: 900 });
  const project = await t3.project("proj", {
    ".gitattributes": "* text=auto\n",
    "gitattributes-help.md": "# Attributes help\n",
    "README.md": "# Dotfile search example\n",
  });
  const seedThread = () => t3.thread({ project, title: "Dotfile search", messages: ["Ready"], model: "multi-turn" });
  let thread;
  for (let attempt = 0; attempt < 5; attempt++) {
    try { thread = await seedThread(); break; }
    catch (error) {
      if (!String(error).includes("Advertised models: default") || attempt === 4) throw error;
    }
  }
  if (!thread) throw new Error("Replay model did not become available");
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  const observations = [];
  for (const query of [".gitattributes", "./.gitattributes"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(query);
    await screen.getByRole("option", "gitattributes-help.md", { exact: false }).waitFor();
    await screen.getByRole("option", "README.md", { exact: false }).waitFor({ state: "hidden" });
    await app.screenshot(query.startsWith("./") ? "relative-dotfile-picker" : "dotfile-picker");
    observations.push(await browser.evaluate(() => {
      const rows = Array.from(document.querySelectorAll('[role="option"]'));
      const dotfile = rows.find(row => row.textContent?.includes(".gitattributes"));
      return { first: rows[0]?.textContent, bold: dotfile?.querySelector("strong")?.textContent };
    }));
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
  }
  await screen.getByRole("textbox").tap();
  await browser.keyboard.type("@.gitattributes");
  await screen.getByText("gitattributes-help.md", { exact: true }).waitFor();
  await app.screenshot("dotfile-mention");
  const mention = await browser.evaluate(() => {
    const rows = Array.from(document.querySelectorAll('[role="option"]'));
    return rows.map(row => ({ text: row.textContent, selected: row.getAttribute("aria-selected") }));
  });
  for (const observation of observations) {
    expect(observation.first?.includes("gitattributes-help.md")).toBe(false);
    expect(observation.first?.includes(".gitattributes")).toBe(true);
    expect(observation.bold).toBe(".gitattributes");
  }
  expect(mention[0]?.text?.includes(".gitattributes")).toBe(true);
  expect(mention[0]?.text?.includes("gitattributes-help.md")).toBe(false);
});
