import { expect } from "e2e";
import { mkdir } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

const names = ["a".repeat(126) + "🚀", "a".repeat(127) + "🚀", " ".repeat(127) + "🚀"];
const root = "/tmp/factory-pr-42244-evidence-1/folders";

test("Manually added folder labels preserve complete emoji and trim before limiting", WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("Emoji folder proof");
    await t3.thread({ project, title: "Folder labels", messages: ["first"] });
    for (const name of names) await mkdir(`${root}/${name}`, { recursive: true });
    // Hide only the runner's synthetic checkout location in public captures.
    await browser.addInitScript((checkout) => {
      const hideDefaultPath = (input: HTMLInputElement) => {
        input.style.color = input.value.startsWith("/home/") ? "transparent" : "";
      };
      document.addEventListener("input", (event) => {
        if (event.target instanceof HTMLInputElement) hideDefaultPath(event.target);
      });
      const redact = () => {
        for (const input of document.querySelectorAll("input")) hideDefaultPath(input);
        const walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT);
        const nodes: Text[] = [];
        while (walker.nextNode()) nodes.push(walker.currentNode as Text);
        for (const node of nodes) {
          if (node.textContent?.includes(checkout)) node.textContent = node.textContent.replaceAll(checkout, "[synthetic checkout]");
        }
      };
      new MutationObserver(redact).observe(document, { subtree: true, childList: true, characterData: true });
    }, project);
    await t3.open("/settings/projects");
    await screen.getByRole("button", "Project scope: All projects").tap();
    await screen.getByRole("menuitemradio", "Emoji folder proof", { exact: false }).tap();
    for (const name of names) {
      await screen.getByRole("button", "Add folder", { exact: true }).tap();
      const input = screen.getByRole("textbox", "Folder path");
      await input.fill(`${root}/${name}`);
      await app.screenshot(`entered-folder-${names.indexOf(name) + 1}`);
      await input.press("Enter");
      await input.waitFor({ state: "hidden" });
    }
    await browser.evaluate(() => { location.reload(); return null; });
    await screen.getByRole("button", "Remove " + "a".repeat(126) + "🚀 from the project", { exact: true }).waitFor();
    // Bring the real repository rows into view; long labels normally clip before the boundary.
    await browser.evaluate(() => {
      const section = document.getElementById("project-repositories")!;
      section.scrollIntoView({ block: "start" });
      for (const title of section.querySelectorAll<HTMLElement>("h3 .truncate")) {
        title.style.whiteSpace = "normal";
        title.style.overflowWrap = "anywhere";
        title.style.overflow = "visible";
      }
      return null;
    });
    await app.screenshot("saved-folder-labels");
    const labels = await browser.evaluate(() => Array.from(document.querySelectorAll('#project-repositories [data-slot="settings-row"]')).filter(row => row.querySelector("code")).map(row => ({ name: row.querySelector("h3 .truncate")?.textContent, path: row.querySelector("code")?.textContent })));
    expect(labels).toEqual(names.map((name, i) => ({ name: i === 0 ? name : i === 1 ? "a".repeat(127) : "🚀", path: `${root}/${name}` })));
  });
