/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { APP_DIR } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Firefox file icon releases preserve the whole selected and cited prefix at all 25 positions", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("citation-demo", {"src/math.ts":"export const sum = (a: number, b: number) => a + b;\n"});
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  await writeFile(fixture, original.replace("I added `clamp` next to `sum` and the tests pass.", "I added `clamp` next to `sum` in [math.ts](src/math.ts) and the tests pass."));
  const thread = await t3.thread({project, title:"Math update", model:"showcase", messages:["Add clamp next to sum"]});
  await writeFile(fixture, original);
  await t3.open(thread);
  await screen.getByText("I added clamp next to sum in", {exact:false}).waitFor({state:"visible"});
  const results = [];
  for (let row=0; row<5; row++) for(let col=0; col<5; col++) {
    await browser.keyboard.press("Escape");
    await browser.locator('[data-testid="composer-editor"]').fill("");
    const points = await browser.evaluate(({row,col}) => {
      window.getSelection()?.removeAllRanges();
      const p = [...document.querySelectorAll('[data-assistant-citation-source] p')].find(p=>p.textContent?.startsWith('I added clamp next to sum in'))!;
      const text = p.firstChild!;
      const range = document.createRange(); range.setStart(text,0); range.setEnd(text,1);
      const start=range.getBoundingClientRect();
      const icon=p.querySelector('.chat-markdown-file-link svg')!.getBoundingClientRect();
      return {sx:start.x+0.2,sy:start.y+start.height/2,ex:icon.x+0.5+col*(icon.width-1)/4,ey:icon.y+0.5+row*(icon.height-1)/4};
    },{row,col});
    await browser.mouse.move(points.sx,points.sy); await browser.mouse.down();
    for(let step=1;step<=20;step++) await browser.mouse.move(points.sx+(points.ex-points.sx)*step/20,points.sy+(points.ey-points.sy)*step/20);
    await browser.mouse.up();
    await browser.evaluate(async()=>{await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));return null;});
    const selected = await browser.evaluate(()=>({text:window.getSelection()?.toString()??'',collapsed:window.getSelection()?.isCollapsed??true, focus:window.getSelection()?.focusNode?.nodeName??''}));
    const cite = screen.getByRole('button','Cite selection in composer');
    const visible = await browser.evaluate(()=>!!document.querySelector('button[aria-label="Cite selection in composer"]'));
    if(row===0&&col===0) await app.screenshot('first-icon-release');
    let cited='';
    if(visible) {
      await cite.tap();
      cited=await browser.evaluate(()=>{ const markdown=document.querySelector('[data-assistant-citation-chip]')?.getAttribute('data-markdown-copy')??''; const address=markdown.match(/\]\((.*)\)$/)?.[1]; return address ? new URL(address).searchParams.get('text')??'' : ''; });
    }
    results.push({row,col,...selected,visible,cited});
    if(row===0&&col===0) await app.screenshot('first-icon-citation');
  }
  await browser.evaluate((results)=>{console.log(JSON.stringify({iconGridResults:results}));return null;},results);
  await app.screenshot('last-icon-citation');
  await writeFile(`.e2e/${APP_DIR.split("/").at(-1)}-icon-grid.json`, JSON.stringify({browser:await browser.evaluate(()=>navigator.userAgent), results},null,2));
  const failures = results.filter(r=>!r.visible || r.collapsed || r.text.trim()!=='I added clamp next to sum in' || r.cited.trim()!=='I added clamp next to sum in');
  await expect(failures).toEqual([]);
});
