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

async function workbook() {
  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="Sheet1" 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>`);
  const rows = Array.from({length:9}, (_, r) => `<row r="${r+1}" ht="24" customHeight="1"${r===2||r===3?' hidden="1"':''}>${Array.from({length:6},(_,c)=>{const address=String.fromCharCode(65+c)+(r+1); const text=r===0&&c===0?'Go to D3':r===4&&c===2?'merged C5:E5':r===4&&(c===3||c===4)?'':address;return `<c r="${address}" t="inlineStr"><is><t>${text}</t></is></c>`;}).join('')}</row>`).join('');
  zip.file("xl/worksheets/sheet1.xml", `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="A1:F9"/><cols><col min="1" max="6" width="15" customWidth="1"/></cols><sheetData>${rows}</sheetData><mergeCells count="1"><mergeCell ref="C5:E5"/></mergeCells><hyperlinks><hyperlink ref="A1" location="Sheet1!D3" display="Go to D3"/></hyperlinks></worksheet>`);
  return zip.generateAsync({type:"uint8array"});
}

test("Links past hidden rows focus the merge anchor and navigate from its column", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("merge-link", {"merge-link.xlsx":await workbook()});
  const thread = await t3.thread({project,title:"Inspect spreadsheet",messages:["Start"]});
  await browser.setViewport({width:1440,height:900});
  await t3.open(thread);
  await screen.getByText("fixture turn complete", {exact:false}).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByRole("option","merge-link.xlsx",{exact:false}).click();
  const grid=screen.getByRole("grid","Sheet1");
  await grid.waitFor({timeout:120000});
  await screen.getByRole("button", "Maximize panel", {exact:true}).tap();
  await screen.getByRole("gridcell","C5",{exact:true}).waitFor();
  await expect.poll(() => browser.evaluate(() => {
    const canvas=document.querySelector<HTMLCanvasElement>('[role="grid"] canvas');
    const corner=canvas?.getContext("2d")?.getImageData(5,5,1,1).data;
    return !!corner && corner[3]===255 && corner[0]!<250;
  })).toBe(true);
  const point=await browser.evaluate(()=>{const r=document.querySelector('[role="grid"][aria-label="Sheet1"]')!.getBoundingClientRect();return {x:r.x+70,y:r.y+35};});
  await browser.mouse.move(point.x,point.y+32);
  await browser.mouse.down();
  await browser.mouse.up();
  await browser.locator('[role="grid"][aria-activedescendant="office-cell-1-0"]').waitFor();
  await browser.mouse.move(point.x,point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await browser.locator('[role="grid"][aria-activedescendant^="office-cell-4-"]').waitFor();
  const landed=await browser.evaluate(()=>document.querySelector('[role="grid"][aria-label="Sheet1"]')!.getAttribute('aria-activedescendant'));
  await app.screenshot("link-lands-in-merge");
  await browser.keyboard.press("ArrowDown");
  await app.screenshot("arrow-down-after-link");
  const afterArrow=await browser.evaluate(()=>document.querySelector('[role="grid"][aria-label="Sheet1"]')!.getAttribute('aria-activedescendant'));
  const mergePoint=await browser.evaluate(()=>{const r=document.querySelector('[role="grid"]')!.getBoundingClientRect();return {x:r.x+44+4*105+80,y:r.y+20+2*32+16};});
  await browser.mouse.move(mergePoint.x,mergePoint.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await browser.locator('[role="grid"][aria-activedescendant="office-cell-4-2"]').waitFor();
  await browser.keyboard.press("ArrowDown");
  await app.screenshot("arrow-down-after-direct-click-control");
  expect({landed,afterArrow}).toEqual({landed:"office-cell-4-2",afterArrow:"office-cell-5-2"});
});
