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

test("Rendered HTML hides cached source copy and truncation controls", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("html-preview");
  const thread = await t3.thread({ project, title: "Review HTML attachments", messages: ["Start"] });
  await t3.open(thread);
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate((selector) => {
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    const files = new DataTransfer();
    const paragraphs = Array.from({ length: 11500 }, (_, i) => `<p>Paragraph ${i}: ${"Synthetic preview content. ".repeat(3)}</p>`).join("\n");
    for (const [name, body] of [["big-page.html", paragraphs], ["small-page.html", "<p>Small complete page</p>"]]) {
      files.items.add(new File([`<!doctype html><html><body><h1>HTML attachment preview</h1>${body}</body></html>`], name, { type: "text/html" }));
    }
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, input);
  const results = [];
  for (const name of ["big-page.html", "small-page.html"]) {
    await screen.getByRole("button", new RegExp(`^File attachment, ${name.replaceAll(".", "\\.")},`)).tap();
    await screen.getByRole("button", "Show HTML source", { exact: true }).waitFor();
    await app.screenshot(`${name}-initial-rendered`);
    await screen.getByRole("button", "Show HTML source", { exact: true }).tap();
    await screen.getByRole("button", name === "big-page.html" ? "Copy preview" : "Copy contents", { exact: true }).waitFor();
    await browser.locator("[data-line]").first().waitFor();
    await app.screenshot(`${name}-source`);
    await screen.getByRole("button", "Show rendered page", { exact: true }).tap();
    await screen.getByRole("button", "Show HTML source", { exact: true }).waitFor();
    await app.screenshot(`${name}-returned-rendered`);
    results.push(await browser.evaluate(() => ({
      copyVisible: [...document.querySelectorAll('button')].some(b => /^(Copy preview|Copy contents)$/.test(b.getAttribute('aria-label') ?? b.textContent ?? '')),
      noticeVisible: document.body.innerText.includes('Preview limited to the first 1 MB'),
    })));
    await browser.keyboard.press("Escape");
  }
  expect(results).toEqual([{ copyVisible: false, noticeVisible: false }, { copyVisible: false, noticeVisible: false }]);
});
