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

test("Tab extends ambiguous folders across accent spellings", WEB, async ({ t3, app, screen, browser }) => {
  for (const folder of ["accents/e\u0301clair", "accents/école", "control/école", "control/écrou"]) {
    await mkdir(`/tmp/factory-pr-43649-evidence-1/${folder}`, { recursive: true });
  }
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("accent-demo", {
    "accents/e\u0301clair/README.md": "",
    "accents/\u00e9cole/README.md": "",
    "control/\u00e9cole/README.md": "",
    "control/\u00e9crou/README.md": "",
  });
  const thread = await t3.thread({ project, title: "Folder completion", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("Start", { exact: true }).waitFor();
  await browser.keyboard.press("Control+k");
  const palette = screen.getByRole("dialog");
  await palette.getByRole("combobox").fill("> Add project");
  await palette.getByText("Add project", { exact: true }).tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  const input = palette.getByRole("combobox");
  const folders = "/tmp/factory-pr-43649-evidence-1";
  await input.fill(`${folders}/control/é`);
  await palette.getByRole("option", "école", { exact: false }).waitFor();
  await palette.getByRole("option", "écrou", { exact: false }).waitFor();
  await input.press("Tab");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (input) input.scrollLeft = input.scrollWidth;
    return null;
  });
  await app.screenshot("control-after-tab");
  await input.fill(`${folders}/accents/é`);
  await palette.getByRole("option", "école", { exact: false }).waitFor();
  await palette.getByRole("option", "e\u0301clair", { exact: false }).waitFor();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (input) input.scrollLeft = input.scrollWidth;
    return null;
  });
  await app.screenshot("mixed-before-tab");
  await input.press("Tab");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (input) input.scrollLeft = input.scrollWidth;
    return null;
  });
  await app.screenshot("mixed-after-tab");
  await expect(input).toHaveValue(`${folders}/accents/éc`);
});
