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

async function workbook(count: number) {
  const zip = new JSZip();
  zip.file('[Content_Types].xml', `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>${Array.from({length:count},(_,i)=>`<Override PartName="/xl/worksheets/sheet${i+1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`).join('')}</Types>`);
  zip.file('_rels/.rels', '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>');
  zip.file('xl/workbook.xml', `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><bookViews><workbookView activeTab="0"/></bookViews><sheets>${Array.from({length:count},(_,i)=>`<sheet name="Sheet ${i+1}" sheetId="${i+1}" r:id="rId${i+1}"/>`).join('')}</sheets></workbook>`);
  zip.file('xl/_rels/workbook.xml.rels', `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${Array.from({length:count},(_,i)=>`<Relationship Id="rId${i+1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${i+1}.xml"/>`).join('')}</Relationships>`);
  for(let i=1;i<=count;i++) {
    const cell=(r:number,c:string,text:string)=>`<c r="${c}${r}" t="inlineStr"><is><t>${text}</t></is></c>`;
    zip.file(`xl/worksheets/sheet${i}.xml`, `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="A1:C2000"/><sheetViews><sheetView workbookViewId="0"/></sheetViews><cols><col min="1" max="3" width="30" customWidth="1"/></cols><sheetData><row r="1">${cell(1,'A',`YOU ARE ON SHEET ${i}`)}${cell(1,'B','Rapid-arrow navigation proof')}</row>${Array.from({length:1999},(_,j)=>`<row r="${j+2}">${cell(j+2,'A',`Sheet ${i} - row ${j+2}`)}${cell(j+2,'B','Synthetic workbook data')}${cell(j+2,'C',`Value ${j+1}`)}</row>`).join('')}</sheetData></worksheet>`);
  }
  return zip.generateAsync({type:'uint8array'});
}

test('Two quick Right Arrow presses advance from focus and wrap without stale selection', WEB, async ({t3, app, screen, browser})=>{
  const project=await t3.project('Workbook navigation',{'three-sheets.xlsx':await workbook(3),'two-sheets.xlsx':await workbook(2)});
  const thread=await t3.thread({project,title:'Review workbook sheets',messages:['Start']});
  await t3.open(thread);
  await screen.getByText('fixture turn complete',{exact:false}).waitFor();
  const results: boolean[]=[];
  for (const [file,label,expected] of [
    ['three-sheets.xlsx','three-sheets-after-two-right-arrows','Sheet 3'],
    ['two-sheets.xlsx','two-sheets-wrap-after-worker-replies','Sheet 1'],
  ] as const) {
    await browser.keyboard.press('Control+p');
    await screen.getByPlaceholder('Search files…').fill(file);
    await screen.getByRole('option',file,{exact:false}).tap();
    await screen.getByRole('tablist','Sheets').waitFor({timeout:120000});
    await screen.getByRole('tab','Sheet 1',{exact:true}).tap();
    await app.screenshot(`${label}-start`);
    // Dispatch both keys in one browser task: the second press precedes the worker's reply.
    await browser.evaluate(()=>{
      for(let i=0;i<2;i++) document.activeElement?.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowRight',code:'ArrowRight',bubbles:true,cancelable:true}));
      return null;
    });
    // Observe after the real worker replies and React commits, including the two-sheet wrap.
    await browser.evaluate(async()=>{await new Promise(resolve=>setTimeout(resolve,1500));return null;});
    await app.screenshot(label);
    results.push(await browser.evaluate((name)=>document.querySelector('[role="tablist"][aria-label="Sheets"] [role="tab"][aria-selected="true"]')?.textContent===name,expected));
  }
  expect(results).toEqual([true,true]);
});
