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

const R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
async function word(target: string) {
  const z = new JSZip();
  z.file("[Content_Types].xml", '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>');
  z.file("_rels/.rels", `<Relationships><Relationship Id="doc" Type="${R}/officeDocument" Target="word/document.xml"/></Relationships>`);
  z.file("word/_rels/document.xml.rels", `<Relationships><Relationship Id="link" Type="${R}/hyperlink" TargetMode="External" Target="${target}"/></Relationships>`);
  z.file("word/document.xml", `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="${R}"><w:body><w:p><w:r><w:t>Hello from the Word body</w:t></w:r></w:p><w:p><w:hyperlink r:id="link"><w:r><w:t>External link</w:t></w:r></w:hyperlink></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>`);
  return z.generateAsync({type:"uint8array"});
}
async function sheet(name: string, malformed = false, external = false) {
  const z = new JSZip();
  z.file("xl/workbook.xml", `<workbook xmlns:r="${R}"><sheets><sheet name="Sample" sheetId="1" r:id="s"/></sheets></workbook>`);
  z.file("xl/_rels/workbook.xml.rels", `<Relationships><Relationship Id="s" Type="${R}/worksheet" Target="${external ? 'https://example.com/sheet.xml' : `worksheets/${name}`}"${external ? ' TargetMode="External"' : ''}/>${malformed ? `<Relationship Id="ext" Type="${R}/externalLinkPath" TargetMode="External" Target="http://[placeholder]/"/>` : ''}</Relationships>`);
  z.file(`xl/worksheets/${name}`, '<worksheet><sheetData><row r="1"><c r="A1"><v>42</v></c></row></sheetData></worksheet>');
  return z.generateAsync({type:"uint8array"});
}

test("Office previews tolerate malformed external links and literal worksheet ZIP names", WEB, async ({t3, app, screen, browser}) => {
  const files = {
    "word-control.docx": await word("https://example.com/"),
    "word-malformed-link.docx": await word("http://[placeholder]/"),
    "sheet-control.xlsx": await sheet("sheet1.xml"),
    "sheet-with-space.xlsx": await sheet("sheet 1.xml"),
    "sheet-umlaut.xlsx": await sheet("Blatt ä.xml"),
    "sheet-hash.xlsx": await sheet("sheet#1.xml"),
    "sheet-percent.xlsx": await sheet("sheet%20.xml"),
    "sheet-malformed-extlink.xlsx": await sheet("sheet1.xml", true),
    "sheet-external-worksheet.xlsx": await sheet("sheet1.xml", false, true),
  };
  const project = await t3.project("office-preview-demo", files);
  const thread = await t3.thread({project, title:"Office preview review", messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  const results: Record<string, boolean> = {};
  for (const file of Object.keys(files)) {
    await screen.getByRole("treeitem", file).tap();
    await screen.getByText(/No preview for this file|1 page|1 sheet/, {exact:false}).waitFor({timeout:120_000});
    if (file.endsWith(".docx")) {
      // Wait for the document body after its page count appears.
      const error = await browser.evaluate(() => document.body.innerText.includes("No preview for this file"));
      if (!error) await screen.getByText("Hello from the Word body").waitFor();
      results[file] = !error;
      if (!error && file.includes("malformed")) results["malformed link removed"] = await browser.evaluate(() => !document.querySelector('a[href*="placeholder"]'));
    } else {
      results[file] = await browser.evaluate(() => {
        const grid = document.querySelector('[role="grid"]');
        return !!grid && grid.textContent?.includes("42") === true;
      });
      if (file.includes("external-worksheet")) results[file] = !results[file] && await browser.evaluate(() => document.body.innerText.includes("No preview for this file"));
    }
    await app.screenshot(file.replace(/\./g,"-"));
  }
  expect(results).toEqual(Object.fromEntries([...Object.keys(files), "malformed link removed"].map(name => [name, true])));
});
