/// <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="1" max="1" hidden="1" width="12" customWidth="1"/></cols><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Plan</t></is></c><c r="C1" t="inlineStr"><is><t>Go to plan</t></is></c></row><row r="2"><c r="B2"><v>42</v></c></row></sheetData><mergeCells count="1"><mergeCell ref="A1:B1"/></mergeCells><hyperlinks><hyperlink ref="C1" location="Budget!A1" display="Go to plan"/></hyperlinks></worksheet>`)
    .generateAsync({ type: "uint8array" });
}

test("Following a link to a hidden merge start keeps Down in the visible column", 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");
  await grid.waitFor({ timeout: 120_000 });
  await browser.locator('[role="grid"] canvas').waitFor();
  await expect.poll(() => browser.evaluate(() => {
    const canvas = document.querySelector<HTMLCanvasElement>('[role="grid"] canvas');
    const pixel = canvas?.getContext("2d")?.getImageData(5, 5, 1, 1).data;
    return !!pixel && pixel[3] === 255 && pixel[0]! < 250;
  })).toBe(true);
  const click = async (x: number, y: number) => {
    const point = await browser.evaluate(({ x, y }) => {
      const r = document.querySelector('[role="grid"] canvas')!.getBoundingClientRect();
      return { x: r.x + x, y: r.y + y };
    }, { x, y });
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down();
    await browser.mouse.up();
  };
  await click(140, 50);
  await browser.locator('[role="grid"][aria-activedescendant="office-cell-1-2"]').waitFor();
  await click(140, 30);
  await app.screenshot("after-following-link");
  await browser.keyboard.press("ArrowDown");
  try {
    await expect(grid).toHaveAttribute("aria-activedescendant", "office-cell-1-1");
  } finally {
    await app.screenshot("after-arrow-down");
  }
});
