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

test("Scrolling the PR header closes the outgoing base warning", WEB, async ({ t3, app, browser, screen }) => {
  const api = async (path: string, data?: object, method = "POST") => {
    const input = "/tmp/factory-pr-48815-evidence-1/api-input.json";
    if (data) writeFileSync(input, JSON.stringify(data));
    const result = await runPromise(run("glab", ["api", path, ...(data ? ["--method", method, "--input", input] : [])]));
    return JSON.parse(result.stdout);
  };
  const project = await api("projects", { name: `popover-scroll-proof-${Date.now()}`, visibility: "public", initialize_with_readme: true, default_branch: "main" });
  try {
    await api(`projects/${project.id}/repository/commits`, { branch: "feature", start_branch: "main", commit_message: "Add feature", actions: [{ action: "create", file_path: "feature.txt", content: "Feature\n" }] });
    await api(`projects/${project.id}/repository/commits`, { branch: "main", commit_message: "Advance base", actions: [{ action: "create", file_path: "base.txt", content: "Base update\n" }] });
    const title = "Keep the base warning attached to the visible header";
    await api(`projects/${project.id}/merge_requests`, { source_branch: "feature", target_branch: "main", title, description: Array.from({ length: 100 }, (_, i) => `Description line ${i + 1}: Review the scroll behavior of the base branch warning.\n`).join("\n") });
    const workspace = await t3.project("Header scroll proof");
    await runPromise(run("git", ["remote", "add", "origin", project.http_url_to_repo], { cwd: workspace }));
    await runPromise(run("git", ["fetch", "origin", "main", "feature"], { cwd: workspace }));
    const thread = await t3.thread({ project: workspace, title: "Header scroll proof", messages: [] });
    await t3.open(thread);
    await t3.open("/pull-requests");
    await screen.getByText(title, { exact: true }).tap();
    const active = () => browser.locator('button[aria-label^="This branch is out-of-date"]:not([inert] *)');
    await active().waitFor();
    await active().click();
    await screen.getByText("Changes can be cleanly merged.", { exact: true }).waitFor();
    const scroll = async (delta: number) => {
      const rect = await browser.evaluate(() => {
        const el = [...document.querySelectorAll("p")].find(el => el.textContent?.startsWith("Description line"))!;
        let parent = el.parentElement!;
        while (parent.scrollHeight <= parent.clientHeight || !["auto", "scroll"].includes(getComputedStyle(parent).overflowY)) parent = parent.parentElement!;
        const r = parent.getBoundingClientRect();
        return { x: r.x + r.width * 0.7, y: r.y + r.height * 0.7 };
      });
      await browser.mouse.move(rect.x, rect.y);
      await browser.mouse.wheel(0, delta);
      await expect.poll(() => browser.evaluate(() => document.querySelector('[data-workspace-scroll-swap]:has(button[aria-label^="This branch is out-of-date"])')?.hasAttribute("inert"))).toBe(delta < 0);
      await browser.evaluate(async () => {
        await new Promise<void>(r => requestAnimationFrame(() => requestAnimationFrame(() => r())));
        await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
      });
    };
    const count = () => browser.locator('[data-slot="popover-popup"]').filter({ hasText: "Changes can be cleanly merged." }).count();
    await scroll(1422);
    await expect.poll(() => browser.evaluate(() => !!document.querySelector('[inert] button[aria-label^="This branch is out-of-date"]'))).toBe(true);
    await app.screenshot("expanded-warning-after-scroll-down");
    const down = await count();
    await active().click();
    await scroll(-5000);
    await app.screenshot("condensed-warning-after-scroll-up");
    const up = await count();
    await active().hover();
    await browser.evaluate(async () => {
      await new Promise<void>(r => requestAnimationFrame(() => requestAnimationFrame(() => r())));
      await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    });
    await app.screenshot("visible-warning-after-hover");
    const hover = await count();
    await scroll(1422);
    await scroll(-5000);
    await app.screenshot("header-returned-without-reopening");
    expect({ down, up, hover, returned: await count() }).toEqual({ down: 0, up: 0, hover: 1, returned: 0 });
  } finally {
    const cleanup = await runPromise(run("glab", ["api", `projects/${project.id}`, "--method", "DELETE"], { allowExit: [0, 1] }));
    if (cleanup.exitCode) appendFileSync("/tmp/factory-pr-48815-evidence-1/cleanup.txt", `${project.id}\n`);
  }
});
