/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
declare global { interface Window { finishUpload: () => void } }

test("Exact upload percentages retain their whole integer and partial percentages floor", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("upload-demo");
  const startThread = async (remaining = 10): Promise<{ threadId: string }> => {
    try { return await t3.thread({ project, title: "Attachment upload progress", messages: ["Start"], model: "multi-turn" }); }
    catch (error) { if (remaining === 0 || !String(error).includes("not advertised")) throw error; return startThread(remaining - 1); }
  };
  const thread = await startThread();
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await browser.evaluate(() => {
    const original = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function(body) {
      if (body instanceof File && body.name.startsWith("upload-")) {
        window.finishUpload = () => original.call(this, body);
        const loaded = Number(body.name.match(/upload-(\d+)/)![1]);
        this.upload.dispatchEvent(new ProgressEvent("progress", { lengthComputable: true, loaded, total: body.size }));
        return;
      }
      original.call(this, body);
    };
    return null;
  });
  const labels = [];
  for (const loaded of [475136, 933888, 950272, 475135]) {
    await browser.evaluate((loaded) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
      const data = new DataTransfer();
      data.items.add(new File([("x".repeat(63) + "\n").repeat(25600)], `upload-${loaded}.txt`, { type: "text/plain" }));
      input.files = data.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
      return null;
    }, loaded);
    await browser.locator(`[aria-label^="File attachment, upload-${loaded}.txt"][aria-label$="%"]`).waitFor();
    await app.screenshot(`upload-${loaded}`);
    labels.push(await browser.evaluate((loaded) => document.querySelector(`[aria-label^="File attachment, upload-${loaded}.txt"]`)!.getAttribute("aria-label"), loaded));
    await browser.evaluate(() => { window.finishUpload(); return null; });
    await browser.locator(`[aria-label^="File attachment, upload-${loaded}.txt"][aria-label$="%"]`).waitFor({ state: "hidden" });
    await screen.getByRole("textbox").press("Control+a");
    await screen.getByRole("textbox").press("Backspace");
  }
  expect(labels).toEqual([
    "File attachment, upload-475136.txt, 1.6 MB, 29%",
    "File attachment, upload-933888.txt, 1.6 MB, 57%",
    "File attachment, upload-950272.txt, 1.6 MB, 58%",
    "File attachment, upload-475135.txt, 1.6 MB, 28%",
  ]);
});
