/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";
import { writeFile } from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Spreadsheet copy preserves clipboard for extra modifiers", WEB, async ({ t3, app, browser, screen }) => {
  const zip = new JSZip();
  zip.file("xl/workbook.xml", '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Report" sheetId="1" r:id="s1"/></sheets></workbook>');
  zip.file("xl/_rels/workbook.xml.rels", '<Relationships><Relationship Id="s1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>');
  zip.file("xl/worksheets/sheet1.xml", '<worksheet><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Quarter</t></is></c></row></sheetData></worksheet>');
  const project = await t3.project("spreadsheet-proof", { "report.xlsx": await zip.generateAsync({ type: "uint8array" }) });
  const thread = await t3.thread({ project, title: "Spreadsheet copy proof", messages: ["Start"] });
  await writeFile(`${T3_HOME}/userdata/keybindings.json`, JSON.stringify([{ key: "mod+alt+shift+f9", command: "thread.copyReference" }]));
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("treeitem", "report.xlsx").tap();
  await screen.getByRole("grid", "Report").waitFor({ timeout: 120000 });
  const results: string[] = [];
  for (const chord of ["Control+Alt+c", "Meta+Alt+c", "Meta+Shift+c", "Control+Shift+c", "synthetic composition", "Control+c", "Meta+c"]) {
    await browser.evaluate(async () => { await navigator.clipboard.writeText("keep-me"); return null; });
    await browser.locator('[role="grid"]').focus();
    await browser.keyboard.press("Control+Home");
    if (chord === "synthetic composition") {
      await browser.evaluate(() => { document.querySelector('[role="grid"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "c", ctrlKey: true, isComposing: true, bubbles: true, cancelable: true })); return null; });
    } else await browser.keyboard.press(chord);
    const composer = browser.locator('[contenteditable="true"][role="textbox"]').first();
    await composer.fill("");
    await composer.focus();
    await browser.keyboard.press("Control+v");
    await browser.locator('[contenteditable="true"][role="textbox"]').filter({ hasText: /keep-me|Quarter/ }).waitFor();
    const result = await browser.evaluate(() => (document.querySelector('[contenteditable="true"][role="textbox"]') as HTMLElement).innerText.trim());
    results.push(result);
    await app.screenshot(chord.replaceAll("+", "-").replaceAll(" ", "-"));
    await composer.fill("");
  }
  await expect(results).toEqual(["keep-me", "keep-me", "keep-me", "keep-me", "keep-me", "Quarter", "Quarter"]);
});
