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

test("Composer menus open after ASCII, ideographic and non-breaking spaces", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("completion-demo", {
    "README.md": "# Completion demo\n",
    ".agents/skills/review/SKILL.md": "---\nname: review\ndescription: Review the current changes.\n---\nReview the changes.\n",
  });
  execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project });
  const thread = await t3.thread({ project, title: "Unicode space completions", messages: ["Hello"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  const results: { separator: string; token: string; text: string; codePoints: string[]; menuOpen: boolean; menuText: string }[] = [];
  for (const [separator, prefix] of [["ASCII-U0020", "日本語 "], ["Ideographic-U3000", "日本語\u3000"], ["NBSP-U00A0", "hello\u00a0"]]) {
    for (const [kind, token] of [["files", "@READ"], ["commands", "/mod"], ["skills", "$rev"], ["pull-requests", "#12"]]) {
      await composer.tap();
      await composer.press("ControlOrMeta+a");
      await composer.press("Backspace");
      await browser.evaluate(async (text) => { await navigator.clipboard.writeText(text); }, prefix!);
      await composer.press("ControlOrMeta+v");
      await composer.pressSequentially(token!);
      // The reported reproduction observes each menu after 1.5 seconds.
      await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1500)); });
      const result = await browser.evaluate(() => {
        const text = document.querySelector('[role="textbox"]')?.textContent ?? "";
        const menu = document.querySelector('[data-composer-command-drawer="true"]');
        return { text, codePoints: Array.from(text, char => `U+${char.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`), menuOpen: !!menu && menu.getBoundingClientRect().height > 0, menuText: menu?.textContent ?? "" };
      });
      results.push({ separator: separator!, token: token!, ...result });
      await app.screenshot(`${separator}-${kind}`);
      await composer.press("Escape");
    }
  }
  console.log(JSON.stringify({ completionResults: results }));
  expect(results.filter(result => !result.menuOpen), "Every trigger opens its completion menu after each separator").toEqual([]);
});
