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

const root = "/tmp/factory-pr-46175-a1796054975-evidence-1/folders";
test("Double-quoted shell folder pastes select existing literal folders", WEB, async ({ t3, app, screen, browser }) => {
  await fs.mkdir(`${root}/$cash`, { recursive: true });
  await fs.mkdir(`${root}/say "hi"`, { recursive: true });
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Folder paste proof", messages: ["Hello"], model: "default" });
  await t3.open(thread);
  await screen.getByRole("combobox", "Projects").tap();
  await screen.getByRole("option", "Add project").tap();
  await screen.getByText("Local folder", { exact: true }).tap();
  const input = screen.getByRole("combobox");
  const observations: string[] = [];
  for (const [label, pasted, expected, selected] of [
    ["double-quoted-dollar", `"${root}/\\$cash"`, `${root}/$cash`, true],
    ["double-quoted-quotes", `"${root}/say \\"hi\\""`, `${root}/say "hi"`, false],
    ["single-quoted-control", `'${root}/say "hi"'`, `${root}/say "hi"`, false],
  ] as const) {
    await input.fill("~/");
    await browser.evaluate((selected) => {
      const input = document.activeElement as HTMLInputElement;
      input.setSelectionRange(selected ? 0 : input.value.length, input.value.length);
      return null;
    }, selected);
    await browser.evaluate((text) => {
      const input = document.activeElement as HTMLInputElement;
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", text);
      const event = new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true });
      if (input.dispatchEvent(event)) {
        const start = input.selectionStart ?? 0;
        const end = input.selectionEnd ?? start;
        const value = input.value.slice(0, start) + text + input.value.slice(end);
        Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
        input.dispatchEvent(new Event("input", { bubbles: true }));
      }
      return null;
    }, pasted);
    await screen.getByRole("button", /^(Create & Add|Add) \(Enter\)$/).waitFor();
    await browser.evaluate(() => {
      const input = document.activeElement as HTMLInputElement;
      input.setSelectionRange(input.value.length, input.value.length);
      input.scrollLeft = input.scrollWidth;
      return null;
    });
    await app.screenshot(label);
    observations.push(await browser.evaluate(() => (document.activeElement as HTMLInputElement).value));
  }
  expect(observations).toEqual([`${root}/$cash`, `${root}/say "hi"`, `${root}/say "hi"`]);
});
