import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

test('Citation dictation keeps Cancel and Save on one row', WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({width:1400,height:900});
  await browser.addInitScript((audio) => {
    navigator.mediaDevices.getUserMedia = async () => {
      const context = new AudioContext();
      await context.resume();
      const bytes = Uint8Array.from(atob(audio), c => c.charCodeAt(0));
      const buffer = await context.decodeAudioData(bytes.buffer);
      const source = context.createBufferSource();
      source.buffer = buffer;
      source.loop = true;
      const destination = context.createMediaStreamDestination();
      source.connect(destination);
      source.start();
      return destination.stream;
    };
  }, Buffer.from(await (await fetch('https://gh-file-drop-api-prod-mi5fy3sowv63ufte.pinglabs.workers.dev/f/62fd16974aa497c3/dictation.wav')).arrayBuffer()).toString('base64'));
  const project = await t3.project('Citation demo');
  const thread = await t3.thread({project,title:'Citation dictation',model:'showcase',messages:['Show the replay example']});
  await t3.open('/settings/voice');
  await screen.getByRole('combobox','Transcribe with').tap();
  await browser.keyboard.press('ArrowDown');
  await browser.keyboard.press('Enter');
  await screen.getByPlaceholder('Search models').fill('moonshine streaming small');
  await app.screenshot('voice-setup');
  const download = screen.getByRole('button','Download',{exact:true});
  await download.tap();
  await screen.getByRole('button','Use model',{exact:true}).tap({timeout:180000});
  await t3.open(thread);
  await screen.getByText('This turn is a replay', {exact:false}).first().tap();
  const box = await browser.evaluate(() => {
    const p = [...document.querySelectorAll('p')].find(p=>p.textContent?.startsWith('This turn is a replay'))!;
    const r=p.getBoundingClientRect();return {x:r.x,y:r.y,h:r.height};
  });
  await browser.mouse.move(box.x+2,box.y+box.h/2);
  await browser.mouse.down();
  await browser.mouse.move(box.x+200,box.y+box.h/2);
  await browser.mouse.up();
  await screen.getByRole('button',/^Cite/).tap();
  await app.screenshot('idle');
  await browser.locator('[data-citation-comment-editor] button').first().tap();
  const samples=[];
  for(let i=0;i<16;i++) {
    await new Promise(r=>setTimeout(r,1000));
    samples.push(await browser.evaluate(()=>{
      const editor=document.querySelector('[data-citation-comment-editor]')!;
      const rect=(name:string)=>{const b=[...editor.querySelectorAll('button')].find(b=>b.textContent?.trim()===name)!;const r=b.getBoundingClientRect();return {x:r.x,y:r.y,w:r.width,h:r.height};};
      return {cancel:rect('Cancel'),save:rect('Save'),transcript:editor.querySelector('[role=status]')?.textContent??''};
    }));
    if([0,3,9,15].includes(i)) await app.screenshot(`dictating-${i+1}s`);
  }
  console.log('LAYOUT',JSON.stringify(samples));
  expect(samples.every((sample,index)=>samples.slice(0,index).every(previous=> {
    const a=sample.cancel,b=previous.save;
    return !(a.x < b.x+b.w && a.x+a.w > b.x && a.y < b.y+b.h && a.y+a.h > b.y);
  }))).toBe(true);
  expect(samples.every(s=>Math.abs(s.cancel.y-s.save.y)<2)).toBe(true);
});
