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

test("PR media survives a tab-indented list example", WEB, async ({t3,app,browser,screen}) => {
  const threads = [];
  for (const kind of ["control", "bug"]) {
    const project = await t3.project(`media-${kind}`, {"t3.json": JSON.stringify({defaultThreadEnvMode:"local"})});
    const git = (args: string[]) => runPromise(run("git", args, {cwd:project}));
    await git(["remote","add","origin","https://dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test"]);
    await git(["-c",'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f',"fetch","origin",`proof-45268-a1795923145-${kind}`]);
    await git(["checkout","-B",`proof-45268-a1795923145-${kind}`,"FETCH_HEAD"]);
    threads.push(await t3.thread({project,title:`Media preview ${kind}`,messages:["Hello"]}));
  }
  await browser.emulateMedia({colorScheme:"dark"});
  for (const [index,number] of [534,533].entries()) {
    await t3.open(threads[index]!);
    await screen.getByRole("link", new RegExp(`PR #${number} -`)).tap();
    await screen.getByRole("button","Description",{exact:true}).waitFor();

    await browser.locator('section[aria-label="Description"] pre').waitFor({state:index === 0 ? "hidden" : "visible"});
    await browser.evaluate(async () => {
      const video = document.querySelector('section[aria-label="Description"] video') as HTMLVideoElement | null;
      if (video && 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});
      });
      if (video) { await video.play(); video.pause(); }
      return null;
    });
    if(index === 0) {
      await browser.locator('section[aria-label="Description"] video').waitFor();
      await app.screenshot("control-plain-video");
    } else {
      await app.screenshot("tab-indented-example-video");
      await expect(browser.locator('section[aria-label="Description"] video')).toBeVisible();
      await expect.poll(() => browser.evaluate(() => {
        const v=document.querySelector('section[aria-label="Description"] video') as HTMLVideoElement | null;
        return v ? {duration:v.duration, error:!!v.error} : null;
      })).toEqual({duration:3,error:false});
    }
  }
});
