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

function archive(binary: boolean) {
  const bytes = new Uint8Array(2048);
  const put = (offset: number, value: string) => bytes.set(new TextEncoder().encode(value), offset);
  put(0, "hello.txt");
  put(100, "0000644\0");
  put(108, "0000000\0");
  put(116, "0000000\0");
  if (binary) { bytes[124] = 0x80; bytes[135] = 3; }
  else put(124, "00000000003\0");
  put(136, "00000000000\0");
  bytes.fill(32, 148, 156);
  put(156, "0");
  put(257, "ustar  \0");
  const checksum = bytes.slice(0, 512).reduce((sum, byte) => sum + byte, 0);
  put(148, checksum.toString(8).padStart(6, "0") + "\0 ");
  put(512, "hi\n");
  return bytes;
}

test("GNU binary size members list and open", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("tar-preview", {
    "README.md": "Synthetic GNU TAR preview reproduction.\n",
    "sample.tar": archive(true),
    "control.tar": archive(false),
  });
  const thread = await t3.thread({ project, title: "GNU TAR preview", model: "default", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "README.md").tap();
  await screen.getByText("Synthetic GNU TAR preview reproduction.", { exact: true }).waitFor();
  await screen.getByRole("treeitem", "sample.tar").tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  try {
    await expect(screen.getByRole("button", "hello.txt", { exact: true })).toBeVisible({ timeout: 60_000 });
    await expect(screen.getByText("1 KB", { exact: true })).toBeVisible();
  } finally {
    await app.screenshot("binary-size-archive");
  }
  await screen.getByRole("button", "hello.txt", { exact: true }).tap();
  try {
    await expect.poll(() => browser.evaluate(() => {
      // Cold Vite optimization can reload the archive after the first selection.
      const member = [...document.querySelectorAll<HTMLButtonElement>('table[aria-label="Archive entries"] button')]
        .find((button) => button.textContent?.trim() === "hello.txt");
      member?.click();
      const panel = document.querySelector("[data-right-panel-surface-content]");
      for (const host of panel?.querySelectorAll("*") ?? []) {
        const content = host.shadowRoot?.querySelector("[data-content]");
        if (content) return [...content.querySelectorAll("[data-line]")].map((line) => line.textContent).join("\n");
      }
      return panel?.textContent;
    })).toBe("hi\n");
  } finally {
    await app.screenshot("extracted-hello");
  }
});
