import {exportWIF,planWarping,estimateCost} from './advanced-utilities.mjs'; let state=null,target=null,result=null; const dialog=document.createElement('dialog');dialog.id='advancedUtilitiesDialog';dialog.style.cssText='max-width:820px;width:92vw;max-height:88vh;overflow:auto;color:#e6eaf1;background:#182132;border:1px solid #6c7d94;border-radius:12px;padding:22px'; const title=document.createElement('h2'),intro=document.createElement('p'),form=document.createElement('form'),fields=document.createElement('div'),prices=document.createElement('div'),actions=document.createElement('div'),output=document.createElement('pre'),error=document.createElement('p');output.style.cssText='white-space:pre-wrap;max-height:36vh;overflow:auto;background:#0e1520;padding:12px';error.setAttribute('role','alert');error.style.color='#ffb5a6';fields.style.cssText='display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px';prices.style.cssText='display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:12px';actions.style.cssText='display:flex;gap:10px;margin-top:16px'; function button(text,type='button'){const b=document.createElement('button');b.textContent=text;b.type=type;return b;} const run=button('Calculate estimate','submit'),download=button('Download result'),close=button('Close');download.disabled=true;close.onclick=()=>dialog.close();actions.append(run,download,close);form.append(fields,prices,actions);dialog.append(title,intro,form,error,output);document.body.append(dialog); function field(parent,key,label,{text=false}={}){const l=document.createElement('label');l.textContent=label;const i=document.createElement('input');i.name=key;i.type=text?'text':'number';if(!text){i.min='0';i.step='any';}i.required=true;i.style.cssText='display:block;width:95%;margin-top:4px';l.append(i);parent.append(l);return i;} function read(key){const i=form.elements.namedItem(key);if(!i||!i.value.trim())throw Error('Enter all required inputs; zero is allowed for an unused allowance or charge.');return Number(i.value);} function project(){if(!state?.project)throw Error('Project state unavailable.');return state.project;} function showResult(){error.textContent='';output.textContent='';download.disabled=true;try{if(target==='wif'){result=exportWIF(project());output.textContent=`Full aligned repeat: ${result.ends} ends × ${result.picks} picks; ${result.shafts} shafts.\n\n${result.warnings.join('\n')}\n\n${result.text.slice(0,24000)}${result.text.length>24000?'\n[Preview shortened; download contains full file.]':''}`;}else{const input=Object.fromEntries(['widthCm','lengthM','warpCrimpPct','weftCrimpPct','wastePct','loomWasteM'].map(k=>[k,read(k)]));result=planWarping(project(),input);if(target==='price'){const pp={};for(const i of prices.querySelectorAll('[data-yarn]')){if(!i.value.trim())throw Error('Enter every yarn price per kg.');pp[i.dataset.yarn]=Number(i.value);}result=estimateCost(result,{prices:pp,conversionPerM:read('conversionPerM'),otherTotal:read('otherTotal'),currency:form.elements.namedItem('currency').value});}output.textContent=`${result.kind}\n${result.ends} warp ends; ${result.picks} picks\nWarp length/end: ${result.warpLengthPerEndM.toFixed(3)} m\nWarp ${result.warpKg.toFixed(4)} kg; weft ${result.weftKg.toFixed(4)} kg; total ${result.totalKg.toFixed(4)} kg\n\n${result.yarns.map(y=>`${y.axis===0?'Warp':'Weft'} ${y.id}: ${y.threads} threads, ${y.metres.toFixed(2)} m, ${y.kg.toFixed(4)} kg${y.cost!==undefined?`, cost ${y.cost.toFixed(2)}`:''}`).join('\n')}${target==='price'?`\n\nTotal: ${result.total.toFixed(2)} ${result.currency}\nPer metre: ${result.perMetre.toFixed(3)} ${result.currency}`:''}\n\n${result.warnings.join('\n')}`;}download.disabled=false;}catch(e){result=null;error.textContent=e.message;}} form.onsubmit=e=>{e.preventDefault();showResult();};download.onclick=()=>{if(!result)return;const blob=new Blob([target==='wif'?result.text:JSON.stringify(result,null,2)],{type:target==='wif'?'text/plain':'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=`independent-${target==='wif'?'draft.wif':target+'-estimate.json'}`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}; function open(t){target=t;result=null;fields.replaceChildren();prices.replaceChildren();output.textContent='';error.textContent='';download.disabled=true;title.textContent=t==='wif'?'Independent WIF 1.1 export':t==='warping'?'Warping and yarn consumption estimate':'Fabric cost estimate';intro.textContent=t==='wif'?'Exports the full aligned yarn plan and draft/liftplan, RGB colours and uniform EPI/PPI spacing. This is interchange, subject to target software/loom verification.':'Local estimate using the current yarn plans, density and current model count/ply. Enter woven dimensions and your own crimp, extra allowance and prices. No mill, material or price values are inferred.';run.textContent=t==='wif'?'Prepare WIF':'Calculate estimate';if(t!=='wif'){for(const [key,label]of [['widthCm','Woven width (cm)'],['lengthM','Woven length (m)'],['warpCrimpPct','Warp crimp (%)'],['weftCrimpPct','Weft crimp (%)'],['wastePct','Extra yarn allowance (%)'],['loomWasteM','Additional loom waste per warp end (m)']])field(fields,key,label);if(t==='price'){field(fields,'currency','Currency label',{text:true});field(fields,'conversionPerM','Conversion cost per metre');field(fields,'otherTotal','Other costs total');const d=state?.project;for(const id of new Set([...(d?.warp||[]),...(d?.weft||[])])){const i=field(prices,'price-'+id,'Yarn '+id+' price per kg');i.dataset.yarn=id;}}}if(!dialog.open)dialog.showModal();if(t==='wif')showResult();} window.addEventListener('cad:document',e=>{state=e.detail;if(dialog.open){result=null;download.disabled=true;output.textContent='Project changed. Calculate again to use the latest document.';}});window.addEventListener('cad:advanced-tool',e=>{if(['wif','warping','price'].includes(e.detail?.target)){window.dispatchEvent(new CustomEvent('cad:request-state'));open(e.detail.target);}});window.dispatchEvent(new CustomEvent('cad:request-state'));