/// <reference lib="dom" />
import type { Browser } from "@e2e-dev/web";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const pick = (browser: Browser, names: string[]) => browser.evaluate(async (names) => {
  const canvas = new OffscreenCanvas(120, 80);
  const ctx = canvas.getContext("2d")!;
  const files = new DataTransfer();
  for (const [i, name] of names.entries()) {
    ctx.fillStyle = `hsl(${i * 37}, 70%, 55%)`;
    ctx.fillRect(0, 0, 120, 80);
    ctx.fillStyle = "white";
    ctx.font = "16px sans-serif";
    ctx.fillText(name, 5, 40);
    files.items.add(new File(name === "empty.png" ? [] : [await canvas.convertToBlob({type:"image/png"})], name, {type:"image/png"}));
  }
  const input = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
  input.files = files.files;
  input.dispatchEvent(new Event("change", {bubbles:true}));
  return null;
}, names);

const state = (browser: Browser) => browser.evaluate(() => ({
  unreadable: document.body.textContent!.includes("'empty.png' could not be read as an image."),
  empty: !!document.querySelector('[aria-label="Remove empty.png"]'),
  valid: !!document.querySelector('[aria-label="Remove valid.png"]'),
  limit: document.body.textContent!.includes("You can attach up to 100 files per message."),
}));

test("Empty images report unreadable and leave the last slot for readable images", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1920,height:1440});
  await t3.project("demo");
  await t3.open();
  await screen.getByRole("button", "New thread in demo", {exact:true}).first().tap();
  await browser.locator('[data-chat-composer-form] input[type="file"]').waitFor({state:"attached"});
  await pick(browser, ["empty.png", "valid.png"]);
  await screen.getByRole("button", "Remove valid.png", {exact:true}).waitFor();
  await browser.locator('[data-chat-composer-form] button[aria-label^="Preview "]:disabled').first().waitFor({state:"hidden"});
  await screen.getByText(/^\d+%$/).first().waitFor({state:"hidden"});
  await app.screenshot("mixed-pick-empty-and-valid");
  const mixed = await state(browser);
  // Clear the first case through the same attachment controls a user uses.
  await screen.getByRole("button", "Remove valid.png", {exact:true}).tap();
  const empty = screen.getByRole("button", "Remove empty.png", {exact:true});
  if (await empty.isVisible()) await empty.tap();
  await pick(browser, Array.from({length:99}, (_,i) => `image-${String(i+1).padStart(2,"0")}.png`));
  await screen.getByRole("button", "Remove image-99.png", {exact:true}).waitFor();
  await browser.locator('[data-chat-composer-form] button[aria-label^="Preview "]:disabled').first().waitFor({state:"hidden"});
  await screen.getByText(/^\d+%$/).first().waitFor({state:"hidden"});
  await pick(browser, ["empty.png", "valid.png"]);
  // Either outcome completes intake: the valid tile on the fix, the retry tile on base.
  await browser.locator('[aria-label="Remove valid.png"], [aria-label="Retry upload for empty.png"]').first().waitFor();
  await browser.locator('[data-chat-composer-form] button[aria-label^="Preview "]:disabled').first().waitFor({state:"hidden"});
  await screen.getByText(/^\d+%$/).first().waitFor({state:"hidden"});
  await browser.evaluate(() => {
    document.querySelector('[data-chat-composer-form] [contenteditable="true"]')!.scrollIntoView({block:"end"});
    return null;
  });
  await app.screenshot("last-slot-empty-before-valid");
  const last = await state(browser);
  expect({mixed,last}).toEqual({
    mixed:{unreadable:true,empty:false,valid:true,limit:false},
    last:{unreadable:true,empty:false,valid:true,limit:false},
  });
});
