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

test("SVG image previews omit word wrap while text retains its toggle", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("preview-samples", {
    "icon.svg": '<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><rect width="128" height="128" rx="24" fill="#7c3aed"/><circle cx="64" cy="64" r="32" fill="#fbbf24"/></svg>',
    "sample.txt": "A long text line to demonstrate working word wrap. ".repeat(30),
  });
  const thread = await t3.thread({ project, title: "File preview", messages: ["first"] });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openFile = (file: string) => screen.getByRole("treeitem", file, { exact: true }).tap();
  const textHeight = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector<HTMLElement>("[data-content]");
      if (content?.textContent?.includes("A long text line")) return content.getBoundingClientRect().height;
    }
    return null;
  });
  await openFile("sample.txt");
  await screen.getByRole("button", "Disable word wrap", { exact: true }).waitFor();
  await expect.poll(textHeight).toBeGreaterThan(100);
  await app.screenshot("text-wrap-on");
  await screen.getByRole("button", "Disable word wrap", { exact: true }).tap();
  await screen.getByRole("button", "Enable word wrap", { exact: true }).waitFor();
  await expect.poll(textHeight).toBeLessThan(50);
  await app.screenshot("text-wrap-off");
  await screen.getByRole("button", "Enable word wrap", { exact: true }).tap();
  await openFile("icon.svg");
  await screen.getByText("128 × 128", { exact: false }).waitFor();
  await app.screenshot("svg-image-preview");
  const hasWrap = await browser.evaluate(() => document.querySelector('button[aria-label="Disable word wrap"]') !== null);
  if (hasWrap) {
    await screen.getByRole("button", "Disable word wrap", { exact: true }).tap();
    await screen.getByRole("button", "Enable word wrap", { exact: true }).waitFor();
  }
  await app.screenshot("svg-after-toggle-attempt");
  await expect(screen.getByRole("button", /(?:Enable|Disable) word wrap/)).not.toBeVisible();
});
