const $=id=>document.getElementById(id),emit=(n,d)=>window.dispatchEvent(new CustomEvent(n,{detail:d}));let state=null,request=200000,pending=null,pendingAction=null,analysisCandidate=null;const edit=(type,extra={})=>{pending=++request;pendingAction=type;emit('cad:edit',{id:pending,type,...extra});};const parse=s=>{const a=s.replace(/[\s,;]+/g,'').split('').map(v=>Number(v)-1);if(a.length<2||a.length>64||a.some(v=>v!==0&&v!==1)||!a.includes(0)||!a.includes(1))throw Error('Use both1and2in a repeating layout (up to64positions).');return a;};function density(){if(!state?.construction)return;const {epi,ppi}=state.construction;try{const w=parse($('clothWarp').value),f=parse($('clothWeft').value),ratio=a=>a.filter(v=>v===0).length/a.length;$('clothDensity').textContent=`Total: ${epi} EPI × ${ppi} PPI · Face: ${(epi*ratio(w)).toFixed(2)} × ${(ppi*ratio(f)).toFixed(2)} · Back: ${(epi*(1-ratio(w))).toFixed(2)} × ${(ppi*(1-ratio(f))).toFixed(2)}`;}catch{$('clothDensity').textContent=`Total construction: ${epi} EPI × ${ppi} PPI`;}}function refresh(){if(!state)return;const c=state.cloth;$('clothSide').hidden=!c;$('clothSide').value=c?.side||'face';$('clothBadge').textContent=c?'Two layers · '+(c.side==='back'?'Back':'Face'):'';for(const id of ['applyCloth','doublePlain','detectCloth'])$(id).disabled=$('count').disabled;}window.addEventListener('cad:document',e=>{state=e.detail;refresh();});document.addEventListener('click',e=>{if(!e.target.closest('[data-action="cloth-editor"]'))return;analysisCandidate=null;$('clothMode').value=state?.cloth?'double':'single';$('clothWarp').value=(state?.cloth?.warpLayers||[0,1]).map(v=>v+1).join(' ');$('clothWeft').value=(state?.cloth?.weftLayers||[0,1]).map(v=>v+1).join(' ');$('clothEvidence').textContent=state?.cloth?'Layer assignment: '+state.cloth.provenance:'No layer settings applied. Detect a separated weave or set the layout manually.';$('clothError').textContent='';density();$('clothDialog').showModal();});$('clothWarp').oninput=$('clothWeft').oninput=()=>{analysisCandidate=null;density();};$('applyCloth').onclick=()=>{try{$('clothError').textContent='';if($('clothMode').value==='single'){edit('set-cloth',{mode:'single'});return;}edit('set-cloth',{mode:$('clothMode').value,cloth:{warpLayers:parse($('clothWarp').value),weftLayers:parse($('clothWeft').value),side:state?.cloth?.side||'face',provenance:analysisCandidate?'weave-analysis':'manual'}});}catch(e){$('clothError').textContent=e.message;}};$('doublePlain').onclick=()=>edit('double-plain');$('detectCloth').onclick=()=>edit('analyse-cloth');$('clothSide').onchange=()=>{if(state?.cloth)edit('set-cloth',{mode:'double',cloth:{...state.cloth,side:$('clothSide').value}});};window.addEventListener('cad:cloth-analysis',e=>{const r=e.detail;if(r.status==='detected'){analysisCandidate=r.cloth;$('clothMode').value='double';$('clothWarp').value=r.cloth.warpLayers.map(v=>v+1).join(' ');$('clothWeft').value=r.cloth.weftLayers.map(v=>v+1).join(' ');$('clothEvidence').textContent='Separated face/back systems found in the full weave. Apply to view them.';density();}else $('clothEvidence').textContent=r.status==='ambiguous'?'More than one layer arrangement fits. Check the original and enter the correct layout.':'No unambiguous separated double weave found. Binding points or another layout may need manual assignment.';});window.addEventListener('cad:edit-result',e=>{if(e.detail.id!==pending)return;if(!e.detail.ok)$('clothError').textContent=e.detail.error;else if(pendingAction!=='analyse-cloth'&&$('clothDialog').open&&state?.cloth)$('clothEvidence').textContent='Layer settings applied. Close to inspect Face / Back.';emit('cad:request-state');pending=null;});new MutationObserver(refresh).observe($('count'),{attributes:true,attributeFilter:['disabled']});emit('cad:request-state');