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

async function workbook(hidden: boolean) {
  const zip = new JSZip();
  const ns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  zip.file("xl/workbook.xml", `<workbook xmlns:r="${ns}"><sheets><sheet name="Edges" sheetId="1" r:id="sheet1"/></sheets></workbook>`);
  zip.file("xl/_rels/workbook.xml.rels", `<Relationships><Relationship Id="sheet1" Type="${ns}/worksheet" Target="worksheets/sheet1.xml"/></Relationships>`);
  zip.file("xl/worksheets/sheet1.xml", `<worksheet><dimension ref="A1:D5"/>${hidden ? '<cols><col min="1" max="1" hidden="1"/></cols>' : ''}<sheetData>${Array.from({length:5}, (_, r) => `<row r="${r+1}"${hidden && r === 0 ? ' hidden="1"' : ''}>${['A','B','C','D'].map((c,i) => `<c r="${c}${r+1}"><v>${(r+1)*10+i+1}</v></c>`).join('')}</row>`).join('')}</sheetData></worksheet>`);
  return zip.generateAsync({type:"uint8array"});
}

test("Spreadsheet jumps land on the nearest visible edge cell", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("spreadsheet-demo", {
    "hidden-edges.xlsx": await workbook(true),
    "control-nothing-hidden.xlsx": await workbook(false),
  });
  const thread = await t3.thread({project, title:"Spreadsheet navigation", messages:["Start"]});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor();
  const observed: string[] = [];
  for (const file of ["hidden-edges.xlsx", "control-nothing-hidden.xlsx"]) {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(file);
    await screen.getByRole("option", file, {exact:false}).tap();
    await screen.getByRole("grid", "Edges").waitFor();
    for (const [key, label] of [["Control+Home","ctrl-home"],["Home","home"],["PageUp","page-up"],["ArrowLeft","arrow-left"]]) {
      const point = await browser.evaluate((hidden) => {
        const rect = document.querySelector('[role="grid"][aria-label="Edges"]')!.getBoundingClientRect();
        return {x:rect.x + 44 + (hidden ? 2 : 3)*64 + 32, y:rect.y + 20 + (hidden ? 3 : 4)*20 + 10};
      }, file.startsWith("hidden"));
      await browser.mouse.move(point.x, point.y);
      await browser.mouse.down();
      await browser.mouse.up();
      await browser.keyboard.press(key!);
      observed.push(await browser.evaluate(() => document.querySelector('[role="grid"][aria-label="Edges"]')?.getAttribute("aria-activedescendant") ?? "missing"));
      await app.screenshot(`${file.startsWith('hidden') ? 'hidden' : 'control'}-${label}`);
    }
  }
  expect(observed).toEqual([
    "office-cell-1-1", "office-cell-4-1", "office-cell-1-3", "office-cell-4-2",
    "office-cell-0-0", "office-cell-4-0", "office-cell-0-3", "office-cell-4-2",
  ]);
});
