/// <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="Summary" sheetId="1" r:id="s1"/><sheet name="Details" sheetId="2" r:id="s2"/></sheets></workbook>`);
  zip.file('xl/_rels/workbook.xml.rels', `<Relationships><Relationship Id="s1" Type="${ns}/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="s2" Type="${ns}/worksheet" Target="worksheets/sheet2.xml"/></Relationships>`);
  const cell = (ref: string, text: string) => `<c r="${ref}" t="inlineStr"><is><t>${text}</t></is></c>`;
  zip.file('xl/worksheets/sheet1.xml', `<worksheet xmlns:r="${ns}"><sheetFormatPr defaultColWidth="24" defaultRowHeight="24"/><sheetData>${['Details link','External link','Jump to A10'].map((s,i)=>`<row r="${i+1}" ht="24" customHeight="1">${cell(`A${i+1}`,s)}${cell(`B${i+1}`,'Select here first')}</row>`).join('')}<row r="10">${cell('A10','Jump target')}</row></sheetData><hyperlinks><hyperlink ref="A1" location="Details!A1"/><hyperlink ref="A2" r:id="external"/><hyperlink ref="A3" location="Summary!A10"/></hyperlinks></worksheet>`);
  zip.file('xl/worksheets/_rels/sheet1.xml.rels', `<Relationships><Relationship Id="external" Type="${ns}/hyperlink" Target="https://example.com" TargetMode="External"/></Relationships>`);
  zip.file('xl/worksheets/sheet2.xml', `<worksheet><sheetData><row r="1">${cell('A1','Details target')}</row></sheetData></worksheet>`);
  return zip.generateAsync({type:'uint8array'});
}

test('Shift click extends selection without following spreadsheet hyperlinks', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('Hyperlink selection', {'links.xlsx':await workbook()});
  const thread = await t3.thread({project,title:'Review spreadsheet hyperlinks',messages:['Start']});
  await t3.open(thread);
  await screen.getByText('fixture turn complete',{exact:false}).waitFor();
  await screen.getByRole('button','Toggle right panel',{exact:true}).tap();
  await screen.getByRole('button','Files F',{exact:true}).tap();
  await screen.getByRole('treeitem','links.xlsx',{exact:true}).tap();
  await screen.getByRole('tab','Summary').waitFor({timeout:120000});
  await screen.getByRole('button','Maximize panel',{exact:true}).tap();
  await screen.getByRole('button','Hide file explorer',{exact:true}).tap();
  await browser.evaluate(() => {
    const original = window.open;
    (window as any).openedLinks = [];
    window.open = function(...args: Parameters<typeof window.open>) {
      (window as any).openedLinks.push(args[0]);
      return original.apply(window,args);
    };
    return null;
  });
  const clickCell = async (col: number,row: number,shift=false) => {
    const point = await browser.evaluate(({col,row}) => {
      const r=document.querySelector('[role="grid"]')!.getBoundingClientRect();
      return {x:r.x+44+col*168+70,y:r.y+20+row*18+9};
    },{col,row});
    if(shift) await browser.keyboard.down('Shift');
    await browser.mouse.move(point.x,point.y);
    await browser.mouse.down();
    await browser.mouse.up();
    if(shift) await browser.keyboard.up('Shift');
  };
  const state = () => browser.evaluate(()=>({sheet:document.querySelector('[role="grid"]')?.getAttribute('aria-label'),active:document.querySelector('[role="grid"]')?.getAttribute('aria-activedescendant')}));
  await clickCell(1,0);
  await app.screenshot('B1-selected');
  await clickCell(0,0,true);
  await app.screenshot('shift-cross-sheet-link');
  const cross = await state();
  await screen.getByRole('tab','Summary',{exact:true}).tap();
  await clickCell(1,2);
  await clickCell(0,2,true);
  await app.screenshot('shift-same-sheet-link');
  const same = await state();
  await screen.getByRole('tab','Summary',{exact:true}).tap();
  await clickCell(1,1);
  await clickCell(0,1,true);
  await app.screenshot('shift-external-link');
  const external = await browser.evaluate(() => (window as any).openedLinks.length);
  await clickCell(0,0);
  await screen.getByRole('grid','Details',{exact:true}).waitFor();
  await app.screenshot('plain-click-cross-sheet-control');
  await screen.getByRole('tab','Summary',{exact:true}).tap();
  await clickCell(0,1);
  await app.screenshot('plain-click-external-control');
  const plainExternal = await browser.evaluate(() => (window as any).openedLinks.length);
  expect(external).toBe(0);
  expect(plainExternal).toBe(1);
  expect(cross).toEqual({sheet:'Summary',active:'office-cell-0-0'});
  expect(same).toEqual({sheet:'Summary',active:'office-cell-2-0'});
});
