import{g as B,r as N}from"./api-DZ3cXm1m.js";document.addEventListener("DOMContentLoaded",()=>{const e=window.marginBadgeConfig;if(!e||!e.endpoint)return;const l=document.getElementById(e.entitySelect),g=document.getElementById(e.currencySelect),r=e.costInput?document.getElementById(e.costInput):null,m=document.getElementById(e.badgeTarget);if(!l||!g||!m)return;const t=e.labels||{},T=e.period||1;let p=0;function y(c,o){return`${Number(o||0).toFixed(2)} ${c||""}`.trim()}function a(c,o){m.innerHTML=`<span class="badge ${o} fs-6 py-2 px-3">${c}</span>`}async function i(){const c=l.value,o=g.value;if(!c||!o){m.innerHTML="";return}const f=++p;a(t.loading||"Loading…","bg-secondary");const w=new URLSearchParams({entity_type:e.entityType,entity_id:c,currency_id:o,period:String(T)}),E=n=>fetch(`${e.endpoint}?${w.toString()}`,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${n}`}});try{let n=await E(B());if(n.status===401){const I=await N();I&&(n=await E(I))}if(f!==p)return;if(!n.ok){a(t.error||"Error","bg-danger");return}const d=await n.json();if(!d.success||!d.found||!d.data){a(t.noSale||"No catalog price","bg-warning text-dark");return}const s=d.data;let b=s.cost;r&&r.value!==""&&!Number.isNaN(parseFloat(r.value))&&(b=parseFloat(r.value));const u=Number(s.sale||0),$=u-b,L=u>0?$/u*100:0,S=$<0?"bg-danger":"bg-success",F=[`${t.cost||"Cost"}: ${y(s.currency,b)}`,`${t.sale||"Sale"}: ${y(s.currency,u)}`,`${t.margin||"Margin"}: ${y(s.currency,$)} (${L.toFixed(1)}%)`];a(F.join(" · "),S)}catch{f===p&&a(t.error||"Error","bg-danger")}}let h=null;function v(){clearTimeout(h),h=setTimeout(i,300)}l.addEventListener("change",i),g.addEventListener("change",i),r&&r.addEventListener("input",v),i()});
