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

const log = Array.from({ length: 150000 }, (_, i) =>
  (i === 139999 ? "NEEDLE_LINE_140000" : `Entry ${String(i + 1).padStart(6, "0")}`)
    .padEnd(63, ".") + "\n",
).join("");

test("A search result beyond the preview is centered when its file arrives", WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "README.md": "Demo\n", "big9.log": log });
    const thread = await t3.thread({ project, title: "Large file search", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByRole("textbox", "Message Large file search").waitFor();
    const search = async (query: string) => {
      await browser.keyboard.press("Control+Shift+f");
      await screen.getByPlaceholder("Search in demo").fill(query);
      await screen.getByRole("button", new RegExp(query)).waitFor();
      await browser.keyboard.press("Enter");
    };
    await search("Demo");
    await screen.getByRole("button", "README.md", { exact: true }).waitFor();
    await browser.locator('diffs-container [data-line="1"]').first().waitFor();
    await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
    await screen.getByRole("button", "Disable word wrap", { exact: true }).tap();
    await screen.getByRole("button", "Hide file explorer", { exact: true }).tap();

    // Deliver the real server response at 500 KiB/s; do not replace its contents.
    await browser.evaluate(() => {
      const original = window.fetch.bind(window);
      window.fetch = async (...args) => {
        const response = await original(...args);
        if (!response.body || !response.headers.get("content-disposition")?.includes("big9.log")) return response;
        const reader = response.body.getReader();
        const body = new ReadableStream({
          async pull(controller) {
            const part = await reader.read();
            if (part.done) { document.documentElement.dataset.proofDownload = "complete"; controller.close(); return; }
            await new Promise(resolve => setTimeout(resolve, part.value.byteLength / 512));
            controller.enqueue(part.value);
          },
          cancel(reason) { return reader.cancel(reason); },
        });
        return new Response(body, { status: response.status, headers: response.headers });
      };
      return null;
    });
    await search("NEEDLE_LINE_140000");
    await screen.getByRole("button", "big9.log", { exact: true }).waitFor();
    await browser.locator("diffs-container [data-line]").first().waitFor();
    await app.screenshot("requested-line-during-download");
    await browser.locator('html[data-proof-download="complete"]').waitFor({ timeout: 120000 });
    try {
      await expect.poll(() => browser.evaluate(() => {
        const roots: (Document | ShadowRoot)[] = [document];
        for (let i = 0; i < roots.length; i++) {
          for (const el of roots[i]!.querySelectorAll("*")) if (el.shadowRoot) roots.push(el.shadowRoot);
        }
        for (const root of roots) {
          const row = root.querySelector('[data-line="140000"]');
          if (!row) continue;
          const box = row.getBoundingClientRect();
          const viewport = document.querySelector(".file-preview-virtualizer")!.getBoundingClientRect();
          return row.hasAttribute("data-file-link-reveal") && box.height > 0 &&
            Math.abs((box.top + box.bottom) / 2 - (viewport.top + viewport.bottom) / 2) < 40;
        }
        return false;
      }), { timeout: 15000 }).toBe(true);
    } finally { await app.screenshot("requested-line-after-download"); }
  });
