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

const videoUrl = "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm";
const description = "This section describes how the release was verified on every platform.\n\n".repeat(240) + "\t~~~\n\n" + videoUrl + "\n\nEnd of description.";

test("Long PR descriptions keep a standalone video after a tab-indented example", WEB, async ({ t3, app, browser, screen }) => {
  const workspaceRoot = await t3.project("release");
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open("/");
  const projectId = await browser.evaluate(async ({ workspaceRoot }) => {
    const { projects } = await (await fetch("/api/projects")).json();
    const project = projects.find((p: { workspaceRoot: string }) => p.workspaceRoot === workspaceRoot);
    const { environmentId } = await (await fetch("/.well-known/t3/environment")).json();
    const detail = {
      provider: "github", projectId: project.id, projectTitle: "release", workspaceRoot,
      repository: "scenario/release", number: 42, title: "Verify the release on every platform",
      body: "Release verification notes.", url: "https://github.com/scenario/release/pull/42",
      author: { login: "scenario", name: null, avatarUrl: null }, viewer: "scenario",
      state: "open", isDraft: false, mergeability: "mergeable", additions: 1, deletions: 0, changedFiles: 1,
      headBranch: "release-notes", baseBranch: "main", createdAt: "2026-11-01T00:00:00Z", updatedAt: "2026-11-01T00:00:00Z",
      mergedAt: null, closedAt: null, reviewers: [], labels: [], checks: [],
      mergeCapabilities: { merge: false, squash: false, rebase: false },
      capabilities: { diff: true, comment: true, search: true, actions: [], mergeMethods: [],
        review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
        reviewers: { request: false, listCandidates: false }, edit: { changeRequest: true, comment: true } },
      viewerPermissions: { actions: [], comment: true, resolve: false, verdicts: [], requestReviewers: false }
    };
    localStorage.setItem(`t3.pullRequests.detail:${environmentId}:${project.id}:scenario/release#42`, JSON.stringify(detail));
    return project.id as string;
  }, { workspaceRoot });
  await t3.open(`/pull-requests?${new URLSearchParams({ repository: "scenario/release", number: "42", selectedProjectId: projectId, selectedUrl: "https://github.com/scenario/release/pull/42" })}`);
  await screen.getByRole("button", "Edit description", { exact: true }).tap();
  await screen.getByRole("textbox", "Pull request description", { exact: true }).fill(description);
  await screen.getByRole("button", "Preview", { exact: true }).tap();
  await screen.getByText("End of description.", { exact: true }).waitFor();
  await browser.evaluate(() => {
    const end = [...document.querySelectorAll("p")].find(p => p.textContent === "End of description.");
    end?.scrollIntoView({ block: "end" });
    return null;
  });
  await screen.getByText("~~~", { exact: true }).waitFor();
  await browser.evaluate(async () => {
    await document.fonts.ready;
    const video = document.querySelector("video");
    if (video && (video.readyState < 4 || video.seeking)) {
      await new Promise<void>((resolve, reject) => {
        const ready = () => {
          if (video.readyState >= 4 && !video.seeking) {
            video.removeEventListener("canplaythrough", ready);
            video.removeEventListener("seeked", ready);
            resolve();
          }
        };
        video.addEventListener("canplaythrough", ready);
        video.addEventListener("seeked", ready);
        video.addEventListener("error", () => reject(new Error("Public sample video failed to load")), { once: true });
        ready();
      });
    }
    return null;
  });
  // Capture settling: allow native video controls to finish their loading transition.
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 1000)));
  await app.screenshot("settled-preview");
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 500)));
  await app.screenshot("long-description-video-after-indented-example");
  expect(await browser.evaluate(() => document.querySelectorAll("video").length), "The standalone webm URL renders as one inline video").toBe(1);
});
