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

const remote = "https://dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test";

test("PR video remains playable after a tab-indented list fence example", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1440,height:1000});
  const projects = [];
  for (const kind of ["control", "bug"]) {
    const project = await t3.project(`media-${kind}`);
    const git = (...args: string[]) => runPromise(run("git", args, {cwd:project}));
    await git("remote", "add", "origin", remote);
    await git("-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "fetch", "origin", `evidence-45268-${kind}`);
    await git("checkout", "-B", `evidence-45268-${kind}`, "FETCH_HEAD");
    const thread = await t3.thread({project,title:`Media ${kind}`,messages:[]});
    projects.push({thread,kind,number:kind === "control" ? 539 : 538});
  }
  for (const {thread,kind,number} of projects) {
    await t3.open(thread);
    await screen.getByRole("button", new RegExp(`#${number}`)).tap();
    await browser.locator('section[aria-label="Description"]').waitFor();
    if (kind === "bug") await browser.locator('section[aria-label="Description"] pre').getByText("- ~~~", {exact: true}).waitFor();
    try {
      if (kind === "bug") await expect(browser.locator('section[aria-label="Description"] video')).toBeVisible({timeout: 3000});
      await browser.evaluate(async () => {
        const video = document.querySelector<HTMLVideoElement>('section[aria-label="Description"] video')!;
        if (video.readyState < 2) await new Promise<void>((resolve, reject) => {
          video.addEventListener("loadeddata", () => resolve(), {once: true});
          video.addEventListener("error", () => reject(new Error("Video failed to load")), {once: true});
          video.load();
        });
        await video.play();
        await new Promise<void>(resolve => video.addEventListener("timeupdate", () => resolve(), {once: true}));
        video.pause();
        return null;
      });
    } finally {
      await app.screenshot(`description-${kind}`);
    }
  }
});
