import {dimensions,ledPlan,timeline,ledKey} from './engines.mjs'; const $=id=>document.getElementById(id),form=$('calculator'),status=$('result-status'),out=$('results'),mode=document.body.dataset.tool; const el=(tag,text)=>{const x=document.createElement(tag);x.textContent=text;return x};const n=(v,k)=>{const s=v.get(k);if(typeof s!=='string'||!s.trim())throw Error('Complete every number field.');return Number(s)};const fmt=x=>Number(x.toFixed(3)).toLocaleString('en-US'); let last=null;function render(pairs){out.replaceChildren();for(const [k,v] of pairs){out.append(el('dt',k),el('dd',v));}} function calculate(){last=null;out.replaceChildren();if($('transfer'))$('transfer').disabled=true;try{const v=new FormData(form);if(mode==='aspect'){const x=dimensions(...['width','height','targetWidth','targetHeight'].map(k=>n(v,k)));render([['Source ratio',x.ratio],['Fit inside target (px)',`${fmt(x.fit.width)} × ${fmt(x.fit.height)}`],['Fill target before crop (px)',`${fmt(x.fill.width)} × ${fmt(x.fill.height)}`],['Fit scaling',`${fmt(x.fitScale*100)}%`],['Fill scaling',`${fmt(x.fillScale*100)}%`]]);} else if(mode==='led'){const values=['wmm','hmm','px','py','cols','rows'].map(k=>n(v,k));const x=ledPlan(...values);render([['Cabinets',fmt(x.cabinets)],['Active width × height (m)',`${fmt(x.widthM)} × ${fmt(x.heightM)}`],['Native raster (px)',`${fmt(x.widthPx)} × ${fmt(x.heightPx)}`],['Total pixels',fmt(x.pixels)]]);last=values;$('transfer').disabled=false;} else{const rows=String(v.get('items')).split(/\r?\n/).filter(s=>s.trim()).map(line=>{const i=line.indexOf('|');if(i<1||!line.slice(0,i).trim())throw Error('Use days before event | milestone on each line.');return {days:Number(line.slice(0,i)),label:line.slice(i+1).trim()};});render(timeline(String(v.get('event')),rows).map(x=>[x.date,x.label]));}status.textContent='Calculated from the current inputs.';}catch(e){status.textContent=e.message;}} form.addEventListener('submit',e=>{e.preventDefault();calculate()});form.addEventListener('input',()=>{last=null;out.replaceChildren();status.textContent='Inputs changed. Calculate again.';if($('transfer'))$('transfer').disabled=true;}); if($('transfer'))$('transfer').addEventListener('click',()=>{if(!last)return;try{if(sessionStorage.getItem(ledKey)&&!confirm('Replace the pending unsaved LED transfer?'))return;sessionStorage.setItem(ledKey,JSON.stringify({version:1,kind:'led',createdAt:Date.now(),values:last}));location.assign('/project/');}catch(e){status.textContent='Local transfer unavailable. Record the values manually.';}}); calculate();