/// <reference lib="dom" />
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const REMOTE = "https://t3code-factory-test@dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test";
const PRS = [{"kind": "split", "id": 486, "url": "https://t3code-factory-test@dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test/pullrequest/486"}, {"kind": "control", "id": 487, "url": "https://t3code-factory-test@dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test/pullrequest/487"}];

test("PR references preserve entity-like destinations when an attachment splits the description", WEB,
 async ({t3, app, browser, screen}) => {
  const workspace = await t3.project("reference-sample");
  await browser.setViewport({width: 1440, height: 1000});
  const repository = `${T3_HOME}/reference-repository`;
  await runPromise(run("git", ["clone", "--quiet", workspace, repository]));
  await runPromise(run("git", ["remote", "set-url", "origin", REMOTE], {cwd: repository}));
  const primary = makeState(T3_HOME);
  await runPromise(primary.cli(["project", "add", repository, "--title", "Reference rendering"]));
  const observed: Array<{kind: string; href: string | null; text: string | null}> = [];
  for (const pr of [...PRS].reverse()) {
    await t3.open("/pull-requests");
    await screen.getByRole("button", new RegExp(`^Open #${pr.id} Reference entities`)).tap();
    await screen.getByRole("link", "ref", {exact: true}).waitFor({timeout: 90_000});
    const value = await browser.evaluate(() => {
      const description = document.querySelector("[data-pr-description]");
      const link = [...(description ?? document).querySelectorAll("a")].find(a => a.textContent === "ref");
      return {href: link?.getAttribute("href") ?? null, text: description?.querySelector('[data-markdown-copy^="![logo]"]')?.getAttribute("data-markdown-copy") ?? null};
    });
    observed.push({kind: pr.kind, ...value});
    await browser.locator('[data-pr-description] a').filter({hasText: /^ref$/}).hover();
    await screen.getByText(/^https:\/\/example.com\/\?x=1/).waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => undefined)));
      return null;
    });
    await app.screenshot(`${pr.kind}-reference-destination`);
    await browser.evaluate(() => {
      const image = document.querySelector('[data-pr-description] [data-markdown-copy^="![logo]"]');
      if (!image) throw new Error("No reference image to copy");
      const range = document.createRange();
      range.selectNode(image);
      window.getSelection()?.removeAllRanges();
      window.getSelection()?.addRange(range);
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+C");
    await screen.getByRole("button", "Edit description", {exact: true}).tap();
    const editor = screen.getByRole("textbox", "Pull request description", {exact: true});
    await editor.tap();
    await browser.keyboard.press("ControlOrMeta+A");
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot(`${pr.kind}-copied-image-markdown-unsaved`);
    await screen.getByRole("button", "Cancel", {exact: true}).tap();
  }
  expect(observed.find(x => x.kind === "split")?.href, "Split reference keeps the same URL as the unsplit control").toBe("https://example.com/?x=1&copy;");
  expect(observed.find(x => x.kind === "split")?.text, "Reference image title keeps literal entity-like substrings").toContain('a &copy; &#65;');
 });
