import {defaults,calculate} from './rate-model.mjs';
const form=document.querySelector('#rate-form'),usd=n=>'$'+Math.round(n).toLocaleString('en-US'),pct=n=>(n*100).toFixed(1)+'%';
let result;
const initial=new URLSearchParams(location.hash.slice(1));for(const key of Object.keys(defaults)){if(!initial.has(key))continue;const input=form.elements[key];if(key==='zone')input.checked=initial.get(key)==='1';else input.value=initial.get(key);}
function read(){const v=Object.fromEntries(new FormData(form));v.zone=form.elements.zone.checked;return v;}
function update(){result=calculate(read());const r=result,s=r.inputs;document.querySelector('#out-ups').textContent=`UPS ${s.ups}% · FedEx ${100-s.ups}%`;for(const k of ['surch','resi','hand','exp'])document.querySelector('#out-'+k).textContent=s[k]+'%';document.querySelector('#rate-mix-note').textContent=r.scaled?`Your choices exceed 100%. For this estimate we scaled them to ${r.resi}% residential, ${r.hand}% handling and 0% other.`:`Other surcharges: ${r.other}%.`;document.querySelector('#rate-error').textContent=form.elements.spend.validity.valid?'':'Enter a spend from $0 to $1 billion. The displayed estimate uses a value within this range.';document.querySelector('#rate-total').textContent=usd(r.total);document.querySelector('#rate-context').textContent=`${pct(r.percent)} on ${usd(s.spend)} · about ${usd(r.monthly)} per month`;document.querySelector('#rate-breakdown').innerHTML=r.parts.map(([label,rate,n])=>`
${label}${pct(rate)} scenario${usd(n)}
`).join('');document.querySelector('#rate-refunds').textContent=usd(r.low)+'–'+usd(r.high);document.querySelector('#rate-recovery-breakdown').innerHTML=`Potentially eligible late delivery${usd(r.lateLow)}–${usd(r.lateHigh)}
Possible billing discrepancies${usd(r.errorLow)}–${usd(r.errorHigh)}
`;document.querySelector('#rate-offset').textContent=r.total?`Illustrative gross offset: ${Math.round(r.low/r.total*100)}–${Math.round(r.high/r.total*100)}% of the estimated increase, if those amounts were eligible and recovered.`:'No cost increase is modeled. A percentage offset is not applicable.';document.querySelector('#rate-net').textContent=`At an illustrative 25% parcel recovery fee, estimated net retained would be ${usd(r.low*.75)}–${usd(r.high*.75)} if that range were fully recovered. Actual recovery may be $0.`;}
function summary(){const r=result;return `FreightCashBack — 2027 planning estimate\nSources checked October 24, 2026\n\nAnnual spend: ${usd(r.inputs.spend)}\nUPS share: ${r.inputs.ups}%\nUPS base assumption: ${r.inputs.upsRate}%\nSurcharge share: ${r.inputs.surch}%\nResidential share: ${r.resi}%\nHandling share: ${r.hand}%\nEligible express share: ${r.inputs.exp}%\nZone allowance: ${r.inputs.zone?'On':'Off'}\n\nEstimated annual cost increase: ${usd(r.total)} (${pct(r.percent)})\n${r.parts.map(p=>p[0]+': '+usd(p[2])).join('\n')}\n\nIllustrative amounts you may be owed: ${usd(r.low)}–${usd(r.high)} before fees. Actual recovery may be $0. These are model assumptions, not audit findings or a refund promise.\n\nEligibility: https://www.ups.com/us/en/support/shipping-support/legal-terms-conditions/ups-service-guarantee\nhttps://www.fedex.com/en-us/service-guide/money-back-guarantee.html\nRates: https://www.ups.com/us/en/support/shipping-support/shipping-costs-rates\nhttps://www.fedex.com/en-us/shipping/rate-changes.html\nRecheck carrier terms each season and for the shipment date.\n`;}
function download(name,blob){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
form.addEventListener('input',update);form.addEventListener('change',update);form.addEventListener('submit',e=>e.preventDefault());document.querySelector('#rate-reset').addEventListener('click',()=>{form.reset();update();});
document.querySelector('#rate-copy').addEventListener('click',async()=>{const p=new URLSearchParams(Object.entries(result.inputs).map(([k,v])=>[k,k==='zone'?(v?'1':'0'):String(v)])),url=location.origin+location.pathname+'#'+p;try{await navigator.clipboard.writeText(url);document.querySelector('#rate-share-status').textContent='Estimate link copied. It includes your inputs.';}catch{const status=document.querySelector('#rate-share-status');status.textContent='Copy this estimate link: ';const input=document.createElement('input');input.readOnly=true;input.setAttribute('aria-label','Estimate sharing link');input.value=url;status.append(input);input.select();}});
document.querySelector('#rate-download').addEventListener('click',()=>download('FreightCashBack-2027-estimate.txt',new Blob([summary()],{type:'text/plain'})));
document.querySelector('#rate-image').addEventListener('click',()=>{const r=result,c=document.createElement('canvas');c.width=1200;c.height=900;const x=c.getContext('2d');x.fillStyle='#f2f8fc';x.fillRect(0,0,1200,900);x.fillStyle='#082f59';x.font='bold 32px Arial';x.fillText('FreightCashBack · 2027 planning estimate',65,85);x.font='22px Arial';x.fillText('Estimated annual shipping-cost increase',65,145);x.font='bold 72px Arial';x.fillText(usd(r.total),65,235);x.font='24px Arial';x.fillText(`${pct(r.percent)} on annual spend of ${usd(r.inputs.spend)}`,65,283);x.fillStyle='#087149';x.font='bold 30px Arial';x.fillText(`Illustrative amounts you may be owed: ${usd(r.low)}–${usd(r.high)}`,65,360);x.fillStyle='#082f59';x.font='22px Arial';const lines=[`UPS ${r.inputs.ups}% / FedEx ${100-r.inputs.ups}% · UPS scenario ${r.inputs.upsRate}%`,`Surcharge share ${r.inputs.surch}% · residential ${r.resi}% · handling ${r.hand}%`,`Potentially eligible express ${r.inputs.exp}% · zone allowance ${r.inputs.zone?'on':'off'}`,'Assumptions: base FedEx 5.9%; surcharge scenarios 6.0% / 7.7%.','Recovery scenarios: 1–3% of eligible express; 0.2–0.6% of total spend.','Ranges are before fees. Actual eligible recovery may be $0.','No refund promised. Carrier terms, exclusions and suspensions apply.','Sources checked October 24, 2026 · Full method and carrier links on website.'];lines.forEach((l,i)=>x.fillText(l,65,425+i*45));c.toBlob(blob=>{if(blob){download('FreightCashBack-2027-estimate.png',blob);document.querySelector('#rate-share-status').textContent='Estimate image saved with assumptions and eligibility notice.';}else document.querySelector('#rate-share-status').textContent='Image could not be saved. Download the text summary instead.';},'image/png');});
update();