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

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

async function workbook() {
  const ns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  return new JSZip()
    .file(
      "xl/workbook.xml",
      `<workbook xmlns:r="${ns}"><sheets><sheet name="Budget" sheetId="1" r:id="sheet1"/></sheets></workbook>`,
    )
    .file(
      "xl/_rels/workbook.xml.rels",
      `<Relationships><Relationship Id="sheet1" Type="${ns}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`,
    )
    .file(
      "xl/worksheets/sheet1.xml",
      `<worksheet><cols><col min="2" max="2" hidden="1" width="12" customWidth="1"/></cols>
        <sheetData>
          <row r="2"><c r="B2" t="inlineStr"><is><t>Plan</t></is></c></row>
          <row r="3"><c r="C3"><v>42</v></c></row>
        </sheetData>
        <mergeCells count="1"><mergeCell ref="B2:C2"/></mergeCells>
      </worksheet>`,
    )
    .generateAsync({ type: "uint8array" });
}

test(
  "ArrowDown moves to C3 after clicking the visible side of a merged cell",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "budget.xlsx": await workbook() });
    const thread = await t3.thread({ project, title: "Review budget", messages: ["Start"] });
    await t3.open(thread);
    await screen.getByText("fixture turn complete", { exact: false }).waitFor();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("budget.xlsx");
    await screen.getByRole("option", "budget.xlsx", { exact: false }).tap();
    const grid = screen.getByRole("grid", "Budget");
    // Cold dev servers can reload while optimizing the Office workers.
    await grid.waitFor({ timeout: 120_000 });
    // The merge starts after the row header and the only preceding visible column (A).
    const x = 132;
    const y = 50;
    await browser.locator('[role="grid"][aria-activedescendant="office-cell-0-0"]').waitFor();
    const bounds = await browser.evaluate(
      ({ x, y }) => {
        const rect = document.querySelector('[role="grid"] canvas')!.getBoundingClientRect();
        return { x: rect.x + x, y: rect.y + y };
      },
      { x, y },
    );
    await browser.mouse.move(bounds.x, bounds.y);
    await browser.mouse.down();
    await browser.mouse.up();
    await browser
      .locator(
        '[role="grid"][aria-label="Budget"]:is([aria-activedescendant="office-cell-1-1"], [aria-activedescendant="office-cell-1-2"])',
      )
      .waitFor();
    await browser.keyboard.press("ArrowDown");

    try {
      await expect(grid).toHaveAttribute("aria-activedescendant", "office-cell-2-2");
    } finally {
      await app.screenshot("after-moving-down-from-the-merged-cell");
    }
  },
);
