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

test("Large GBK CSV attachments preview Chinese text like small attachments", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("CSV preview");
  await t3.open();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await screen.getByRole("option", /Showcase/).waitFor();
  await browser.keyboard.press("Escape");
  const thread = await t3.thread({ project, title: "GBK CSV attachments", messages: ["Review CSV attachments"], model: "showcase" });
  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 ascii = (text: string) => new TextEncoder().encode(text);
    const header = [ascii("Name,Status\n"), new Uint8Array([0xd6, 0xd0, 0xce, 0xc4]), ascii(",Done\n")];
    const files = new DataTransfer();
    files.items.add(new File([...header, ascii("Other,x\n".repeat(20))], "short-gbk.csv", { type: "text/csv" }));
    files.items.add(new File([...header, ascii(("Other," + "x".repeat(180) + "\n").repeat(6000))], "large-gbk.csv", { type: "text/csv" }));
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, input);
  await screen.getByText("short-gbk.csv", { exact: true }).tap();
  await screen.getByText("中文", { exact: true }).waitFor();
  await screen.getByText(/21 rows · 2 columns/).waitFor();
  await app.screenshot("small-gbk-preview");
  await browser.keyboard.press("Escape");
  await screen.getByText("large-gbk.csv", { exact: true }).tap();
  await browser.locator('[role="dialog"]').waitFor();
  try {
    await expect(screen.getByText("中文", { exact: true })).toBeVisible();
    await screen.getByText(/6,001 rows · 2 columns/).waitFor();
  } finally {
    await app.screenshot("large-gbk-preview");
  }
});
