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

test("Folder browsing survives blank siblings and preserves leading spaces", WEB, async ({t3, app, screen, browser}) => {
  const workspace = await t3.project("folder-picker-demo", {
    "t3-browse/normal/README.md": "normal",
    "t3-browse/ /README.md": "blank",
    "t3-browse/padded /README.md": "trailing",
    "t3-browse/ lead/README.md": "leading",
    "lead-only/normal/README.md": "normal",
    "lead-only/ lead/inside/README.md": "leading",
    "control/normal/README.md": "normal",
  });
  await t3.open();
  await screen.getByTestId("composer-editor").waitFor();
  const palette = screen.getByRole("dialog", "Command palette");
  await browser.keyboard.press("Control+k");
  await palette.getByRole("combobox").fill("> Add project");
  await palette.getByText("Add project", {exact:true}).tap();
  await palette.getByRole("option", /^Local folder/).tap();
  const input = palette.getByRole("combobox");
  await input.fill(`${workspace}/control/`);
  await palette.getByRole("option", "normal", {exact:true}).waitFor();
  await browser.evaluate(() => {
    const field = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (field) field.scrollLeft = field.scrollWidth;
  });
  await app.screenshot("control-normal-folder");
  await input.fill(`${workspace}/t3-browse/`);
  // Wait for the browse operation to settle on either the success or empty-list UI.
  await browser.locator('[role="option"]:has-text("normal"), button:has-text("Create & Add")').first().waitFor();
  await browser.evaluate(() => {
    const field = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (field) field.scrollLeft = field.scrollWidth;
  });
  await app.screenshot("whitespace-siblings");
  const siblings = await palette.getByRole("option").allTextContents();
  await input.fill(`${workspace}/lead-only/`);
  await palette.getByRole("option", "normal", {exact:true}).waitFor();
  await browser.evaluate(() => {
    const field = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (field) field.scrollLeft = field.scrollWidth;
  });
  await app.screenshot("leading-space-before-navigation");
  await palette.getByRole("option", /^\s*lead\s*$/).tap();
  await browser.locator('[role="option"]:has-text("inside"), button:has-text("Create & Add")').first().waitFor();
  await browser.evaluate(() => {
    const field = document.querySelector<HTMLInputElement>('[role="dialog"] input');
    if (field) field.scrollLeft = field.scrollWidth;
  });
  await app.screenshot("leading-space-after-navigation");
  const navigated = await input.inputValue();
  expect(siblings.some(name => name.trim() === "normal")).toBe(true);
  expect(siblings.some(name => name.trim() === "padded")).toBe(false);
  expect(navigated).toBe(`${workspace}/lead-only/ lead/`);
  await expect(palette.getByRole("option", "inside", {exact:true})).toBeVisible();
});
