﻿window.runOutlinePrototypeChecks=async()=>{
let checks=0;const errors=[],check=(ok,name)=>{checks++;if(!ok)errors.push(name)};
const closed=(dlg,action)=>new Promise(resolve=>{dlg.addEventListener('close',resolve,{once:true});action();});
ed.leaveIsolation(); ed.setTool('select'); ed.doc=newDoc(); ed.history=new History(); ed.doc.layers[0]=defaultLayer(0);
const ring=(x,y,w,h)=>({closed:true,nodes:[{x,y},{x:x+w,y},{x:x+w,y:y+h},{x,y:y+h}]});
const source={id:newId(),m:[1,0,0,1,0,0],layer:0,shape:{kind:'path',subs:[ring(10,10,100,60),ring(30,20,20,20)]}};
ed.doc.objs=[source];ed.setSel([source]);ed.render();const before=ed.state();
const listeners=ed.listeners.size;
await openOutlineDialog(ed);let dlg=document.querySelector('.outline-dialog');
check(!!dlg,'outline opens'); check(dlg.querySelector('#outline-keep').checked,'keep originals default');
check([...dlg.querySelectorAll('p.note:not([role=status])')].reduce((n,p)=>n+p.textContent.length,0)<180,'outline dialog keeps instructional copy compact');
check(dlg.querySelector('#outline-tolerance').title.includes('zurück')&&dlg.textContent.includes('doppelt'),'short interface retains tolerance-reset and duplicate-cut warnings');
const outputMode=dlg.querySelector('#outline-mode');
check(outputMode.options.length===3&&outputMode.value==='outer','three extraction modes default to outer contour only');
check(dlg.querySelector('.outline-choices input').disabled,'outer-only mode does not silently accept island picks');
outputMode.value='combined';outputMode.dispatchEvent(new Event('change'));
check(!dlg.matches(':modal')&&!dlg.querySelector('canvas'),'small nonmodal window uses workspace instead of second canvas');
check(ed.state()===before&&ed.history.position===0,'opening only stages a preview');
check(dlg.querySelectorAll('.outline-choices input').length===1,'one clickable hole');
const canvas=ed.canvas,r=canvas.getBoundingClientRect(),capture=canvas.setPointerCapture;
canvas.setPointerCapture=()=>{};
const click=(x,y)=>{const p=ed.toScreen({x,y});canvas.dispatchEvent(new PointerEvent('pointerdown',{button:0,pointerId:7,clientX:r.left+p.x,clientY:r.top+p.y,bubbles:true}));};
const dashes=[],setDash=ed.ctx.setLineDash;ed.ctx.setLineDash=function(a){dashes.push([...a]);return setDash.call(this,a);};
ed.render();ed.ctx.setLineDash=setDash;
check(dashes.some(a=>a.length===2&&Math.abs(a[0]/a[1]-1.5)<.01),'workspace preview renders dashed contour');
click(40,30);check(dlg.querySelector('.outline-choices input').checked,'workspace click selects hole');
check(dlg.querySelector('[data-island-index="0"]').classList.contains('outline-choice-active'),'workspace pointer click highlights the matching island list entry');
check(ed.outlinePreview.subs.length===2&&ed.sel[0]===source,'selected hole changes staged geometry, not object selection');
outputMode.value='islands';outputMode.dispatchEvent(new Event('change'));
check(ed.outlinePreview.subs.length===1&&ed.outlinePreview.subs[0].nodes.every(n=>n.x>=30&&n.x<=50),'islands-only preview excludes the exterior');
outputMode.value='outer';outputMode.dispatchEvent(new Event('change'));
check(ed.outlinePreview.subs.length===1&&dlg.querySelector('.outline-choices input').checked,'mode change preserves staged island selection without outputting it in outer mode');
outputMode.value='combined';outputMode.dispatchEvent(new Event('change'));
click(40,30);check(!dlg.querySelector('.outline-choices input').checked&&ed.outlinePreview.subs.length===1,'second click removes hole');
click(40,30);
canvas.dispatchEvent(new KeyboardEvent('keydown',{key:'Delete',bubbles:true,cancelable:true}));
check(ed.state()===before,'workspace editing shortcuts are reserved during preview');
const oldView={...ed.view};
canvas.dispatchEvent(new PointerEvent('pointerdown',{button:1,pointerId:7,clientX:r.left+200,clientY:r.top+200,bubbles:true}));
canvas.dispatchEvent(new PointerEvent('pointermove',{pointerId:7,clientX:r.left+240,clientY:r.top+220,bubbles:true}));
canvas.dispatchEvent(new PointerEvent('pointerup',{button:1,pointerId:7,clientX:r.left+240,clientY:r.top+220,bubbles:true}));
check(ed.view.ox!==oldView.ox&&!!ed.outlinePreview&&dlg.open,'workspace panning remains available');
canvas.setPointerCapture=capture;
check(ed.state()===before&&ed.history.position===0,'hole toggles never edit document');
const win=dlg.getBoundingClientRect();dlg.querySelector('h3').dispatchEvent(new PointerEvent('pointerdown',{button:0,clientX:win.left+30,clientY:win.top+20,bubbles:true}));
window.dispatchEvent(new PointerEvent('pointermove',{clientX:win.left-40,clientY:win.top+40}));window.dispatchEvent(new PointerEvent('pointerup'));
check(Math.abs(dlg.getBoundingClientRect().left-win.left)>10,'tool window can be moved');
await closed(dlg,()=>dlg.querySelector('.primary').click());check(!document.querySelector('.outline-dialog'),'apply closes');
check(ed.doc.objs.length===2 && ed.doc.objs[0]===source && !source.noLaser,'keep leaves source unchanged');
check(ed.sel[0].shape.subs.length===2 && ed.history.position===1,'chosen hole in new geometry, one undo');
ed.doUndo();check(ed.state()===before,'keep undo exact');
await openOutlineDialog(ed);dlg=document.querySelector('.outline-dialog');
const islandMode=dlg.querySelector('#outline-mode');islandMode.value='islands';islandMode.dispatchEvent(new Event('change'));
check(dlg.querySelector('.primary').disabled&&ed.outlinePreview.subs.length===0,'islands-only mode requires an explicit nonempty selection');
dlg.querySelector('.outline-choices input').click();
check(!dlg.querySelector('.primary').disabled&&ed.state()===before,'selecting an island enables Apply without editing the source');
await closed(dlg,()=>dlg.querySelector('.primary').click());
check(ed.doc.objs.length===2&&ed.sel[0].name==='Inselkonturen'&&ed.sel[0].shape.subs.length===1,'islands-only Apply creates no outer contour');
ed.doUndo();check(ed.state()===before,'islands-only Apply Undo restores exact document');
await openOutlineDialog(ed);dlg=document.querySelector('.outline-dialog');await closed(dlg,()=>dlg.close());
check(ed.state()===before && ed.history.position===0&&!ed.outlinePreview,'cancel clears workspace preview without edits');
await openOutlineDialog(ed);dlg=document.querySelector('.outline-dialog');
await closed(dlg,()=>canvas.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true})));
check(ed.state()===before&&!ed.outlinePreview,'Escape on workspace cancels without document edits');
await openOutlineDialog(ed);dlg=document.querySelector('.outline-dialog');dlg.querySelector('#outline-keep').checked=false;
const confirm=window.confirm;window.confirm=()=>false;dlg.querySelector('.primary').click();
check(ed.state()===before && dlg.open,'replacement cancellation leaves originals');
window.confirm=()=>true;await closed(dlg,()=>dlg.querySelector('.primary').click());window.confirm=confirm;
check(ed.doc.objs.length===1 && ed.sel[0].shape.subs.length===1,'replace defaults to solid outer geometry');
ed.doUndo();check(ed.state()===before,'replacement undo exact');
await openOutlineDialog(ed);dlg=document.querySelector('.outline-dialog');ed.doc.objs[0].m[4]+=1;
await closed(dlg,()=>ed.emit('doc'));check(!ed.outlinePreview,'source edits invalidate and clear preview');
const after=ed.state();await openOutlineDialog(ed);check(!!document.querySelector('.outline-dialog'),'reopen after cleanup');
dlg=document.querySelector('.outline-dialog');await closed(dlg,()=>dlg.close());check(ed.state()===after,'reopen/cancel no edit');
check(ed.listeners.size===listeners,'dialog listeners cleaned up');
const openSource={id:newId(),m:[1,0,0,1,0,0],layer:0,shape:{kind:'path',subs:[{closed:false,nodes:[{x:10,y:10},{x:110,y:10},{x:110,y:70},{x:10,y:70},{x:10,y:10.04}]}]}};
ed.doc.objs=[openSource];ed.setSel([openSource]);const openBefore=ed.state();
await openOutlineDialog(ed);dlg=document.querySelector('.outline-tool-window');
check(dlg.open&&dlg.querySelector('.primary').disabled,'window stays usable when initial tolerance yields no closed face');
const tol=dlg.querySelector('#outline-tolerance');tol.value='.05';tol.dispatchEvent(new Event('input',{bubbles:true}));
check(dlg.querySelector('.primary').disabled,'pending tolerance rebuild disables stale Apply immediately');
await new Promise(resolve=>setTimeout(resolve,160));
check(!dlg.querySelector('.primary').disabled&&ed.outlinePreview.subs.length===1,'tolerance change rebuilds workspace preview');
tol.value='';tol.dispatchEvent(new Event('input',{bubbles:true}));
check(dlg.querySelector('.primary').disabled&&ed.outlinePreview.subs.length===0,'invalid tolerance cannot apply last valid geometry');
tol.value='.05';tol.dispatchEvent(new Event('input',{bubbles:true}));
await new Promise(resolve=>setTimeout(resolve,160));
check(!dlg.querySelector('.primary').disabled,'valid tolerance recovers');
const updateOutline=ed.updateOutline;let rebuilds=0;
ed.updateOutline=function(...args){rebuilds++;return updateOutline.apply(this,args)};
for(const value of ['.01','.02','.05']){tol.value=value;tol.dispatchEvent(new Event('input',{bubbles:true}));}
check(dlg.querySelector('.primary').disabled,'rapid tolerance typing cannot apply a stale preview');
await new Promise(resolve=>setTimeout(resolve,160));
check(rebuilds===1&&!dlg.querySelector('.primary').disabled,'rapid tolerance edits coalesce into one validated rebuild');
tol.value='.06';tol.dispatchEvent(new Event('input',{bubbles:true}));
await closed(dlg,()=>tol.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true})));
await new Promise(resolve=>setTimeout(resolve,160));
check(rebuilds===1,'closing the window cancels its pending tolerance rebuild');ed.updateOutline=updateOutline;
check(ed.state()===openBefore&&!ed.outlinePreview&&ed.listeners.size===listeners,'Escape from input discards preview and listeners');
return {errors,checks,objects:ed.doc.objs.length,undo:ed.history.position};
};
