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

const variants = {
  alt: '<a href="a.xhtml#target"><img src="dot.svg" alt="Opening scene"/></a>',
  'link-title': '<a href="a.xhtml#target" title="Opening scene"><img src="dot.svg" alt=""/></a>',
  mixed: '<a href="a.xhtml#target"><span><img src="dot.svg" alt=" " title="Opening"/></span> scene</a>',
};
async function book(link: string) {
  return new JSZip()
    .file('mimetype', 'application/epub+zip')
    .file('META-INF/container.xml', '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>')
    .file('book.opf', '<package><metadata><title>Image contents</title></metadata><manifest><item id="a" href="a.xhtml" media-type="application/xhtml+xml"/><item id="b" href="b.xhtml" media-type="application/xhtml+xml"/><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="dot" href="dot.svg" media-type="image/svg+xml"/></manifest><spine><itemref idref="a"/><itemref idref="b"/></spine></package>')
    .file('nav.xhtml', `<html xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li>${link}</li><li><a href="b.xhtml">Next scene</a></li></ol></nav></body></html>`)
    .file('a.xhtml', `<html><head><title>A</title></head><body><h1>Chapter A</h1>${Array.from({length:120}, (_,i)=>`<p>Filler paragraph ${i+1}: The story continues along the quiet road.</p>`).join('')}<p id="target">TARGET: Opening scene destination</p><p>End of Chapter A.</p></body></html>`)
    .file('b.xhtml', '<html><head><title>B</title></head><body><h1>Chapter B</h1></body></html>')
    .file('dot.svg', '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><circle cx="5" cy="5" r="4"/></svg>')
    .generateAsync({type:'uint8array'});
}

test('Image-labeled EPUB contents retain labels and navigate to the section', WEB, async ({t3, app, screen, browser}) => {
  const files = Object.fromEntries(await Promise.all(Object.entries(variants).map(async ([name,link])=>[`${name}.epub`,await book(link)])));
  const project = await t3.project('epub-demo', files);
  const thread = await t3.thread({project, title:'EPUB contents proof', messages:['Start']});
  await t3.open(thread);
  await screen.getByText('fixture turn complete', {exact:false}).waitFor();
  const results: string[] = [];
  for (const name of Object.keys(variants)) {
    await browser.keyboard.press('Control+p');
    await screen.getByPlaceholder('Search files…').fill(`${name}.epub`);
    await screen.getByRole('option', `${name}.epub`, {exact:false}).tap();
    const picker = screen.getByRole('combobox', 'Chapter', {exact:true});
    await picker.waitFor({timeout:120_000});
    await picker.tap();
    await screen.getByRole('option', 'Next scene', {exact:true}).waitFor();
    await app.screenshot(`${name}-chapter-picker`);
    const labels = await browser.evaluate(() => [...document.querySelectorAll('[role="option"]')].map(x=>x.textContent?.trim()).join('|'));
    results.push(`${name}: ${labels}`);
    if (labels.includes('Opening scene')) {
      await screen.getByRole('option', 'Opening scene', {exact:true}).tap();
      await expect.poll(() => browser.evaluate(() => {
        const frame = [...document.querySelectorAll('iframe')].find(f=>f.contentDocument?.getElementById('target'));
        const target = frame?.contentDocument?.getElementById('target');
        const rect = target?.getBoundingClientRect();
        return !!rect && rect.top >= 0 && rect.bottom <= (frame?.clientHeight ?? 0);
      })).toBe(true);
      await app.screenshot(`${name}-section-destination`);
    } else {
      await browser.keyboard.press('Escape');
    }
  }
  expect(results).toEqual(['alt: Opening scene|Next scene', 'link-title: Opening scene|Next scene', 'mixed: Opening scene|Next scene']);
});
