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

test("PR video attributes preserve decoded query separators", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("video-attribute-proof");
  await runPromise(run("git", ["remote", "add", "origin", "https://dev.azure.com/t3code-factory-test/t3-factory-test/_git/t3-factory-test"], { cwd: project }));
  const thread = await t3.thread({ project, title: "Video attribute proof", messages: ["Ready"] });
  await t3.open(thread);
  await t3.open("/pull-requests");
  await screen.getByText("Video attribute playback proof 44726", { exact: true }).waitFor({ timeout: 60000 });
  await screen.getByText("Video attribute playback proof 44726", { exact: true }).tap();
  await screen.getByText(/^Case A: standalone video/).waitFor({ timeout: 60000 });
  const results = [];
  for (const name of ["A", "B", "C", "D"]) {
    await browser.evaluate((name) => {
      const label = Array.from(document.querySelectorAll('p')).find(p => p.textContent?.startsWith(`Case ${name}:`));
      label?.scrollIntoView({ block: 'center' });
      return null;
    }, name);
    const result = await browser.evaluate(async (name) => {
      const locate = () => Array.from(document.querySelectorAll('video')).find(v => new URL(v.getAttribute('src') ?? '', location.href).searchParams.get('case') === name);
      const video = locate();
      if (!video) return { name, playable: false };
      video.muted = true;
      try { await video.play(); } catch { return { name, playable: false }; }
      await new Promise<void>(resolve => {
        if (video.currentTime >= 1) return resolve();
        const update = () => {
          if (video.currentTime >= 1) {
            video.removeEventListener('timeupdate', update);
            resolve();
          }
        };
        video.addEventListener('timeupdate', update);
      });
      video.pause();
      return { name, playable: video.readyState >= 2 && video.currentTime > 0, source: video.currentSrc };
    }, name);
    results.push(result);
    await app.screenshot(`case-${name}-playback`);
  }
  expect(results.map(r => ({ name: r.name, playable: r.playable }))).toEqual(["A", "B", "C", "D"].map(name => ({ name, playable: true })));
});
