/// <reference lib="dom" />
import { expect } from "e2e";
import JSZip from "jszip";

import { test, WEB } from "./t3.ts";

test(
  "Select All and Copy in an ODS preview includes the last row",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const zip = new JSZip();
    zip.file("mimetype", "application/vnd.oasis.opendocument.spreadsheet");
    const rows = Array.from({ length: 150 }, (_, index) => {
      if (index === 147)
        return '<table:table-row><table:table-cell office:value-type="float" office:value="-12.50"><text:p>-12.50</text:p></table:table-cell></table:table-row>';
      if (index === 148)
        return '<table:table-row><table:table-cell office:value-type="string"><text:p>+3</text:p></table:table-cell></table:table-row>';
      const value = index === 149 ? "Final shipment" : `Shipment ${index + 1}`;
      return `<table:table-row><table:table-cell office:value-type="string"><text:p>${value}</text:p></table:table-cell></table:table-row>`;
    });
    zip.file(
      "content.xml",
      `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
        xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"
        xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.2">
        <office:body><office:spreadsheet><table:table table:name="Shipments">
          ${rows.join("")}
        </table:table></office:spreadsheet></office:body>
      </office:document-content>`,
    );
    const project = await t3.project("demo", {
      "shipments.ods": await zip.generateAsync({ type: "nodebuffer" }),
    });
    await t3.open();
    await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Files F").tap();
    await screen.getByRole("treeitem", "shipments.ods").tap();
    const first = screen.getByRole("cell", "Shipment 1", { exact: true });
    await first.waitFor({ timeout: 60_000 });
    await browser.evaluate(() => {
      Object.defineProperty(navigator, "clipboard", { value: undefined });
      document.documentElement.dataset.copyEvents = "0";
      document.addEventListener("copy", (event) => {
        document.documentElement.dataset.copyEvents = String(Number(document.documentElement.dataset.copyEvents) + 1);
        document.documentElement.dataset.copyTrusted = String(event.isTrusted);
      }, true);
      return null;
    });
    await first.tap();
    await browser.keyboard.press("ControlOrMeta+a");
    await browser.keyboard.press("ControlOrMeta+c");

    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+v");
    await app.screenshot("composer-native-paste");
    await browser.evaluate(() => {
      const target = document.createElement("textarea");
      target.setAttribute("aria-label", "Pasted rows");
      Object.assign(target.style, {
        position: "fixed",
        zIndex: "99999",
        left: "24px",
        top: "80px",
        width: "360px",
        height: "480px",
        color: "white",
        background: "black",
      });
      document.body.append(target);
      target.focus();
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+v");
    const pasted = await browser.evaluate(
      () => document.querySelector<HTMLTextAreaElement>('[aria-label="Pasted rows"]')!.value,
    );
    await browser.evaluate(() => {
      const target = document.querySelector<HTMLTextAreaElement>('[aria-label="Pasted rows"]')!;
      const label = document.createElement("div");
      label.textContent = `Native paste: ${target.value.split("\n").filter(Boolean).length} lines · ${document.documentElement.dataset.copyEvents} trusted copy event (${document.documentElement.dataset.copyTrusted})`;
      Object.assign(label.style, { position: "fixed", zIndex: "100000", left: "24px", top: "52px", color: "white", background: "black", padding: "4px" });
      document.body.append(label);
      target.scrollTop = 0;
      return null;
    });
    await app.screenshot("clipboard-start");
    await browser.evaluate(() => {
      const target = document.querySelector<HTMLTextAreaElement>('[aria-label="Pasted rows"]')!;
      target.scrollTop = target.scrollHeight;
      return null;
    });
    await app.screenshot("clipboard-end-and-escaping");
    expect(pasted.replaceAll("\r\n", "\n").split("\n")).toEqual([
      ...Array.from({ length: 147 }, (_, index) => `Shipment ${index + 1}`),
      "-12.50",
      "'+3",
      "Final shipment",
    ]);
  },
);
