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

// ZIP_STORED, flags=0, no Unicode extras: café.txt=FIRST and cafè.txt=SECOND.
const zip = Uint8Array.from(Buffer.from("UEsDBBQAAAAAAJUCel3nLCVlBQAAAAUAAAAIAAAAY2Fmgi50eHRGSVJTVFBLAwQUAAAAAACVAnpd79bnRgYAAAAGAAAACAAAAGNhZooudHh0U0VDT05EUEsBAhQDFAAAAAAAlQJ6XecsJWUFAAAABQAAAAgAAAAAAAAAAAAAAIABAAAAAGNhZoIudHh0UEsBAhQDFAAAAAAAlQJ6Xe/W50YGAAAABgAAAAgAAAAAAAAAAAAAAIABKwAAAGNhZooudHh0UEsFBgAAAAACAAIAbAAAAFcAAAAAAA==", "base64"));

test("CP437 ZIP filenames remain distinct and open their own contents", WEB, async ({ t3, app, screen, browser }) => {
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return null;
  });
  const project = await t3.project("project", { "legacy-cp437.zip": zip });
  const thread = await t3.thread({ project, title: "Inspect legacy archive", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("legacy-cp437.zip");
  await screen.getByRole("option", "legacy-cp437.zip", { exact: false }).tap();
  await screen.getByText("Archive contents", { exact: false }).waitFor({ timeout: 120_000 });
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await app.screenshot("archive-list");
  await expect(screen.getByText("café.txt", { exact: true })).toBeVisible();
  await expect(screen.getByText("cafè.txt", { exact: true })).toBeVisible();
  await screen.getByText("café.txt", { exact: true }).tap();
  await expect.poll(async () => {
    // Reopen after the one-time Vite reload if it reset the selected archive entry.
    if (await browser.evaluate(() => document.querySelector('table[aria-label="Archive entries"]') !== null)) {
      await screen.getByText("café.txt", { exact: true }).tap();
    }
    return editorText();
  }).toContain("FIRST");
  await app.screenshot("cafe-first");
  // Cold Vite optimization can reload after the first text preview, returning to the list.
  try {
    await screen.getByRole("button", "Back to archive", { exact: true }).tap({ timeout: 3000 });
  } catch {
    await screen.getByText("Archive contents", { exact: true }).waitFor();
  }
  await screen.getByText("cafè.txt", { exact: true }).tap();
  await expect.poll(editorText).toContain("SECOND");
  await app.screenshot("cafe-second");
});
