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

test("Reference labels preserve hosted thread URLs while standalone URLs become chips", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("reference-links");
  const thread = await t3.thread({ project, title: "New thread", messages: ["Ready"] });
  const environment = await runPromise(environmentId(app.baseUrl ?? ""));
  const href = `https://app.t3.codes/threads/${environment}/${encodeURIComponent(thread.threadId)}`;
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  const paste = async (text: string) => {
    await composer.tap();
    await browser.evaluate((value) => {
      const editor = document.activeElement;
      if (!(editor instanceof HTMLElement) || !editor.isContentEditable) throw new Error("Composer not focused");
      const clipboardData = new DataTransfer();
      clipboardData.setData("text/plain", value);
      editor.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
      return null;
    }, text);
  };
  const state = () => browser.evaluate(() => {
    const editor = document.querySelector('[data-testid="composer-editor"]');
    return { text: editor?.textContent ?? "", chips: editor?.querySelectorAll('[aria-label="Thread, New thread"]').length ?? -1 };
  });
  await paste(`[${href}][site]\n\n[site]: https://example.com`);
  await app.screenshot("reference-link-label");
  const link = await state();
  await composer.fill("");
  await paste(`![${href}][site]\n\n[site]: https://example.com\n\n${href}`);
  await app.screenshot("image-reference-and-standalone");
  const image = await state();
  expect(link.chips).toBe(0);
  expect(link.text).toContain(`[${href}][site]`);
  expect(image.chips).toBe(1);
  expect(image.text).toContain(`![${href}][site]`);
});
