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

test("Files viewer reads GBK and GB18030 with UTF-8 precedence and bounded binary safety", WEB, async ({t3, app, screen, browser}) => {
 const split = new Uint8Array(1048578).fill(120);
 split.set([47,47,32,214,208,206,196,10]);
 for(let i=1000;i<1048500;i+=1000) split[i]=10;
 split.set([10,69,78,68,10,214,208,65],1048570);
 const project = await t3.project("encoding-demo", {
 "main.c": new Uint8Array([47,47,32,214,208,206,196,215,162,202,205,10,105,110,116,32,97,32,61,32,49,59,10]),
 "gb18030.txt": new Uint8Array([71, 66, 49, 56, 48, 51, 48, 58, 32, 214, 208, 206, 196, 32, 148, 57, 252, 54, 10]),
 "utf8.txt": "UTF-8 precedence: 中文 café 😀\n",
 "binary.txt": new Uint8Array([65,0,66,255]),
 "split-gbk.txt": split,
 });
 const thread = await t3.thread({project, title:"Encoding preview", messages:["Review [main.c](main.c)"]});
 await t3.open(thread);
 await screen.getByText("fixture turn complete", {exact:false}).waitFor();
 const text = () => browser.evaluate(() => {
  const panel = document.querySelector("[data-right-panel-surface-content]");
  for(const host of panel?.querySelectorAll("*") ?? []) { const content=host.shadowRoot?.querySelector("[data-content]"); if(content) return content.textContent ?? ""; }
  return panel?.textContent ?? "";
 });
 const results: string[]=[];
 await screen.getByRole("button", /^Agent Review/).tap();
 await screen.getByRole("link", "main.c", {exact:true}).tap();
 // Wait for either the source or its decoding error before capturing both outcomes.
 await expect.poll(text).toMatch(/中文|UTF-8/);
 results.push(await text());
 await app.screenshot("message-link-gbk");
 const open = (path:string) => browser.evaluate((path) => {
  for(const host of document.querySelectorAll("*")) {const row=host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`); if(row){row.click();return true;}}
  return false;
 },path);
 for (const [file, pattern] of [["utf8.txt",/UTF-8 precedence/],["gb18030.txt",/GB18030: 中文 😀|UTF-8/],["binary.txt",/contains binary data/],["split-gbk.txt",/中文|UTF-8/],["main.c",/中文|UTF-8/]] as const) {
  await expect.poll(()=>open(file)).toBe(true);
  await expect.poll(text).toMatch(pattern);
  if(file === "split-gbk.txt") {
   await expect.poll(async () => {
    await browser.evaluate(() => {const scroller=document.querySelector<HTMLElement>(".file-preview-virtualizer"); if(scroller) scroller.scrollTop=scroller.scrollHeight;});
    return text();
   }).toMatch(/END|UTF-8/);
  }
  results.push(await text());
  await app.screenshot(file.replace(".","-"));
 }
 expect(results[0]).toContain("中文注释");
 expect(results[1]).toContain("中文 café 😀");
 expect(results[2]).toContain("GB18030: 中文 😀");
 expect(results[3]).toContain("binary");
 expect(results[4]).toContain("END");
 expect(results[4]).not.toContain("�");
 expect(results[4]).not.toContain("中");
 expect(results[5]).toContain("中文注释");
});
