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

test("An attached file reports a refused clipboard write", WEB, async ({ t3, app, browser, screen }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  await browser.route(/.*/, async (route) => {
    if (new URL(route.request.url).pathname !== "/") return route.continue();
    const response = await route.fetch();
    await route.fulfill({ status: response.status, headers: { ...response.headers, "permissions-policy": "clipboard-write=()" }, body: await response.body() });
  });
  await t3.project("demo");
  await t3.open();
  await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
  const allowed = await browser.evaluate(() => (document as Document & { featurePolicy: { allowsFeature(name: string): boolean } }).featurePolicy.allowsFeature("clipboard-write"));
  if (allowed) throw new Error("Clipboard policy did not take effect");
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    const transfer = new DataTransfer();
    transfer.items.add(new File(["attached notes\nsecond line\n"], "notes.txt", { type: "text/plain" }));
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  await screen.getByRole("button", "File attachment, notes.txt, 1 KB", { exact: true }).tap();
  await screen.getByText("second line", { exact: false }).waitFor();
  await screen.getByRole("button", "Copy contents", { exact: true }).tap();
  try {
    await expect(screen.getByText("Could not copy file", { exact: true })).toBeVisible();
    await expect(screen.getByRole("button", "Copied", { exact: true })).not.toBeVisible();
  } finally {
    await app.screenshot("clipboard-refused");
  }
});
