import { afterEach, expect, test } from 'vitest'
import { page } from 'vitest/browser'
afterEach(() => document.body.replaceChildren())
function select(label){const element=document.createElement('select');element.setAttribute('aria-label',label);for(const [text,value]of[['One','one'],['Two','two']]){const option=document.createElement('option');option.textContent=text;option.value=value;element.append(option)}document.body.append(element);return element}
function trace(element){const events=[];for(const type of ['input','change'])element.addEventListener(type,event=>events.push({type:event.type,constructor:event.constructor.name,target:event.target===element,currentTarget:event.currentTarget===element,trusted:event.isTrusted,bubbles:event.bubbles,composed:event.composed,value:element.value,selectedIndex:element.selectedIndex}));return events}
function settled(operation){return operation.then(value=>({returnedUndefined:value===undefined}),error=>({error:{name:error.name,message:error.message,stack:error.stack}}))}
for(const mode of ['missing-target','late-duplicates','missing-option'])test('delayed selection '+mode+' retains following native work',async()=>{
 const query=page.getByLabelText('Pending choices'),missingAtCall=query.elements().length===0,pending=settled(query.selectOptions(mode==='missing-option'?'absent':'two',{timeout:60}));await Promise.resolve();const missingBeforeMount=query.elements().length===0,failedEvents=[];if(mode!=='missing-target'){failedEvents.push(trace(select('Pending choices')));if(mode==='late-duplicates')failedEvents.push(trace(select('Pending choices')))}
 const outcome=await pending,healthy=select('Healthy choices'),nodes=[...healthy.options],events=trace(healthy),following=await settled(page.getByLabelText('Healthy choices').selectOptions('two',{timeout:500}));if(outcome.error)console.log('SELECT_DELAYED_NATIVE_DIAGNOSTIC '+JSON.stringify({mode,error:outcome.error}));const error=outcome.error
 console.log('SELECT_DELAYED_CONTROL_RAW '+JSON.stringify({mode,missingAtCall,missingBeforeMount,outcome:error?{error:{name:error.name,timeout:error.message.includes('Timeout 60ms exceeded'),strict:error.message.includes('strict mode violation')}}:outcome,failedEvents,following,events,value:healthy.value,selectedIndex:healthy.selectedIndex,originalNodes:[...healthy.options].every((option,index)=>option===nodes[index]),selectedIdentity:healthy.selectedOptions[0]===nodes[1]}))
 expect(error).toBeDefined();expect(error.message).toContain(mode==='late-duplicates'?'strict mode violation':'Timeout 60ms exceeded');expect(following).toEqual({returnedUndefined:true});expect(events.map(event=>event.type)).toEqual(['input','change']);expect(failedEvents.every(events=>events.length===0)).toBe(true);expect(healthy.value).toBe('two')
})
