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

test("env argv0 options preserve Node script mention icons", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("shebang-demo", {
    run: "#!/usr/bin/env -a myapp node\nconsole.log('hello')\n",
    "run-argv0": "#!/usr/bin/env --argv0 myapp node\nconsole.log('hello')\n",
    "run-plain": "#!/usr/bin/env node\nconsole.log('hello')\n",
  });
  const startThread = async () => {
    for (let attempt = 0; attempt < 5; attempt++) {
      try {
        return await t3.thread({ project, title: "Node script file types", messages: ["Start"] });
      } catch (error) {
        if (attempt === 4 || !String(error).includes("not advertised")) throw error;
      }
    }
    throw new Error("Replay model discovery did not complete");
  };
  const thread = await startThread();
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  for (const file of ["run", "run-argv0", "run-plain"]) {
    await composer.pressSequentially(` @${file}`);
    await screen.getByRole("option", file, { exact: true }).tap();
  }
  await browser.locator('[data-composer-mention-chip="true"] [data-icon-token]').last().waitFor();
  await app.screenshot("node-script-mention-icons");
  await expect.poll(() => browser.evaluate(() =>
    [...document.querySelectorAll('[data-composer-mention-chip="true"]')].map(chip => ({
      name: chip.textContent?.trim(),
      icon: chip.querySelector('[data-icon-token]')?.getAttribute('data-icon-token'),
    }))
  )).toEqual([
    { name: "run", icon: "javascript" },
    { name: "run-argv0", icon: "javascript" },
    { name: "run-plain", icon: "javascript" },
  ]);
});
