"use strict";(()=>{var n=class n extends HTMLElement{constructor(e){super();this.label="";this.button=null;this.href="";this.target="_self";this.styleN="1";this.sizeN="";this.type="dynamic";e&&Object.assign(this,e),Object.assign(this,this.dataset);let a=this.attachShadow({mode:"open"}),i=this.createButton(),s=this.createStyle();this.init(()=>{a.appendChild(s),a.appendChild(i),this.addEventListeners(i)})}static get observedAttributes(){return["data-style-n","data-size-n","data-label","data-href","data-target"]}attributeChangedCallback(e,a,i){if(a!==i)switch(e){case"data-style-n":this.styleN=i||"",this.updateStyleClass();break;case"data-size-n":this.sizeN=i||"",this.updateSizeClass();break;case"data-label":this.label=i||"",this.button&&this.updateButtonText(this.label);break;case"data-href":this.href=i||"",this.button&&(this.button.href=this.href);break;case"data-target":this.target=i||"_self",this.button&&(this.button.target=this.target);break}}init(e){e&&e()}show(){this.button&&(this.button.style.display="")}hide(){this.button&&(this.button.style.display="none")}setDisabled(e){this.button&&(e?this.button.classList.add(`${n.buttonClass}-disabled`):this.button.classList.remove(`${n.buttonClass}-disabled`))}setLoading(e){this.button&&(e?this.button.classList.add(`${n.buttonClass}-loading`):this.button.classList.remove(`${n.buttonClass}-loading`))}updateButtonText(e){this.button&&(this.button.innerHTML=`<span>${e}</span>`)}createButton(){return this.button=document.createElement("a"),this.button.className=n.buttonClass,this.styleN&&this.button.classList.add(`${n.buttonClass}-style-${this.styleN}`),this.sizeN&&this.button.classList.add(`${n.buttonClass}-size-${this.sizeN}`),this.type&&this.button.classList.add(`${n.buttonClass}-type-${this.type}`),this.href&&(this.button.href=this.href),this.target&&(this.button.target=this.target),this.button.innerHTML=`<span>${this.label||this.innerHTML}</span>`,this.button}updateStyleClass(){this.button&&(Array.from(this.button.classList).filter(e=>e.startsWith(`${n.buttonClass}-style-`)).forEach(e=>this.button.classList.remove(e)),this.styleN&&this.button.classList.add(`${n.buttonClass}-style-${this.styleN}`))}updateSizeClass(){this.button&&(Array.from(this.button.classList).filter(e=>e.startsWith(`${n.buttonClass}-size-`)).forEach(e=>this.button.classList.remove(e)),this.sizeN&&this.button.classList.add(`${n.buttonClass}-size-${this.sizeN}`))}createStyle(){let e=document.createElement("style");return e.textContent=`
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300..500&display=swap');
.${n.buttonClass} {
--svg-purple-arrow: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2013.43%2013.42%22%3E%3Cg%20%3E%3Cpath%20d%3D%22M1.5%2C6.71h8.7%22%20fill%3D%22none%22%20stroke%3D%22%23822A85%22%20stroke-linecap%3D%22round%22%20stroke-width%3D%223%22%20stroke-miterlimit%3D%2210%22%2F%3E%3Cpath%20d%3D%22M6.72%2C11.92l5.21-5.21L6.72%2C1.5%22%20fill%3D%22none%22%20stroke%3D%22%23822A85%22%20stroke-linecap%3D%22round%22%20stroke-width%3D%223%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E");
--svg-white-arrow: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2013.43%2013.42%22%3E%3Cg%20%3E%3Cpath%20d%3D%22M1.5%2C6.71h8.7%22%20fill%3D%22none%22%20stroke%3D%22%23fff%22%20stroke-linecap%3D%22round%22%20stroke-width%3D%223%22%20stroke-miterlimit%3D%2210%22%2F%3E%3Cpath%20d%3D%22M6.72%2C11.92l5.21-5.21L6.72%2C1.5%22%20fill%3D%22none%22%20stroke%3D%22%23fff%22%20stroke-linecap%3D%22round%22%20stroke-width%3D%223%22%20stroke-linejoin%3D%22round%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E");
--svg-loader: url("data:image/svg+xml,%3Csvg%20class%3D%22active%20spinner%22%20width%3D%22160%22%20height%3D%22160%22%20viewBox%3D%220%200%20160%20160%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20clip-path%3D%22url(%23clip0_339_22)%22%3E%3Cg%20filter%3D%22url(%23filter0_i_339_22)%22%3E%3Cpath%20fill-rule%3D%22evenodd%22%20clip-rule%3D%22evenodd%22%20d%3D%22M160%2080.0005C160%20124.183%20124.183%20160.001%2080%20160.001C35.8172%20160.001%200%20124.183%200%2080.0005C0%2035.8177%2035.8172%200.00050354%2080%200.00050354C124.183%200.00050354%20160%2035.8177%20160%2080.0005ZM140%2080C140%20113.137%20113.137%20140%2080%20140C46.8629%20140%2020%20113.137%2020%2080C20%2046.8629%2046.8629%2020%2080%2020C113.137%2020%20140%2046.8629%20140%2080Z%22%20fill%3D%22%23DCDCDC%22%3E%3C%2Fpath%3E%3C%2Fg%3E%3Cpath%20d%3D%22M23.5%2023.5005C23.5%2023.5005%2044.5%200.128195%2079.7955%200.000455158C116%20-0.130575%20136.5%2023.5005%20136.5%2023.5005L122.795%2037.7936C122.795%2037.7936%20107.5%2020.0005%2079.7955%2020.0005C53.5%2020.0005%2037.5%2037.5005%2037.5%2037.5005L23.5%2023.5005Z%22%20fill%3D%22url(%23paint0_linear_339_22)%22%3E%3C%2Fpath%3E%3C%2Fg%3E%3Cdefs%3E%3Cfilter%20id%3D%22filter0_i_339_22%22%20x%3D%220%22%20y%3D%220.00050354%22%20width%3D%22160%22%20height%3D%22160%22%20filterUnits%3D%22userSpaceOnUse%22%20color-interpolation-filters%3D%22sRGB%22%3E%3CfeFlood%20flood-opacity%3D%220%22%20result%3D%22BackgroundImageFix%22%3E%3C%2FfeFlood%3E%3CfeBlend%20mode%3D%22normal%22%20in%3D%22SourceGraphic%22%20in2%3D%22BackgroundImageFix%22%20result%3D%22shape%22%3E%3C%2FfeBlend%3E%3CfeColorMatrix%20in%3D%22SourceAlpha%22%20type%3D%22matrix%22%20values%3D%220%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%20127%200%22%20result%3D%22hardAlpha%22%3E%3C%2FfeColorMatrix%3E%3CfeOffset%3E%3C%2FfeOffset%3E%3CfeGaussianBlur%20stdDeviation%3D%222.5%22%3E%3C%2FfeGaussianBlur%3E%3CfeComposite%20in2%3D%22hardAlpha%22%20operator%3D%22arithmetic%22%20k2%3D%22-1%22%20k3%3D%221%22%3E%3C%2FfeComposite%3E%3CfeColorMatrix%20type%3D%22matrix%22%20values%3D%220%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200%200.25%200%22%3E%3C%2FfeColorMatrix%3E%3CfeBlend%20mode%3D%22normal%22%20in2%3D%22shape%22%20result%3D%22effect1_innerShadow_339_22%22%3E%3C%2FfeBlend%3E%3C%2Ffilter%3E%3ClinearGradient%20id%3D%22paint0_linear_339_22%22%20x1%3D%22134.5%22%20y1%3D%2222.5%22%20x2%3D%2224%22%20y2%3D%2223.5004%22%20gradientUnits%3D%22userSpaceOnUse%22%3E%3Cstop%20stop-color%3D%22%23822a85%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23822a85%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3CclipPath%20id%3D%22clip0_339_22%22%3E%3Crect%20width%3D%22160%22%20height%3D%22160%22%20fill%3D%22white%22%3E%3C%2Frect%3E%3C%2FclipPath%3E%3C%2Fdefs%3E%3C%2Fsvg%3E");
font-family: "Open Sans", "Arial", sans-serif;
position: relative;
display: inline-block;
padding: 14px 24px;
text-align: center;
color: #fff;
background: linear-gradient(180deg, #333 0%, #000 100%);
transition: all 0.5s;
text-transform: uppercase;
font-size: 12px;
line-height: 1;
text-decoration: none;
box-sizing: border-box;
cursor: pointer;
margin-bottom: 1em;
margin-top: 1em;
}
.${n.buttonClass}>span{
position:relative;
}
.${n.buttonClass}:hover::before {
left: 0;
width: calc(100% + 32px);
}
.${n.buttonClass}-fixed-width {
width: 247px;
}
.${n.buttonClass}::before,
.${n.buttonClass}::after {
position: absolute;
left: 100%;
top: 0;
bottom: 0;
content: "";
width: 32px;
color: inherit;
transition: all 0.5s;
box-sizing: border-box;
}
.${n.buttonClass}::after {
background-position: center center;
background-repeat: no-repeat;
background-size: 15px auto;
}
.${n.buttonClass}:hover::after {
width: 15px;
animation: arrow 0.5s infinite alternate;
}
@keyframes arrow {
0% {
width: 29px;
}
100% {
width: 18px;
}}
.${n.buttonClass}-size-small {
padding: 12px;
}
.${n.buttonClass}-size-small::before,
.${n.buttonClass}-size-small::after {
width: 29px;
}
.${n.buttonClass}-size-small:hover::before {
width: calc(100% + 29px);
}
.${n.buttonClass}-size-small::after {
background-size: 13px auto;
}
.${n.buttonClass}-size-small:hover::after {
width: 13px;
}
.${n.buttonClass}-size-large {
font-size: 14px;
padding: 16px 28px;
}
.${n.buttonClass}-size-large::before,
.${n.buttonClass}-size-large::after {
width: 38px;
}
.${n.buttonClass}-size-large:hover::before {
width: calc(100% + 38px);
}
.${n.buttonClass}-size-large::after {
background-size: 18px auto;
}
.${n.buttonClass}-size-large:hover::after {
width: 18px;
}
.${n.buttonClass}-style-1 {
color: #fff;
background: linear-gradient(180deg, #333 0%, #000 100%);
}
.${n.buttonClass}-style-1:hover {
color: #000;
}
.${n.buttonClass}-style-1::before {
background: #f0f0f0;
}
.${n.buttonClass}-style-1::after {
background-image: var(--svg-purple-arrow);
}
.${n.buttonClass}-style-2 {
color: #000;
background: none;
box-shadow: inset 0 0 0 1px #c1c1c1;
}
.${n.buttonClass}-style-2:hover {
color: #fff;
}
.${n.buttonClass}-style-2::before {
background: linear-gradient(180deg, #b400bf 0%, #822a85 100%);
}
.${n.buttonClass}-style-2::after {
background-image: var(--svg-white-arrow);
}
.${n.buttonClass}-style-3 {
color: #fff;
background: linear-gradient(180deg, #b400bf 0%, #3f1940 100%, #371738 100%);
}
.${n.buttonClass}-style-3:hover {
color: #000;
}
.${n.buttonClass}-style-3::before {
background: #f0f0f0;
}
.${n.buttonClass}-style-3::after {
background-image: var(--svg-purple-arrow);
}
.${n.buttonClass}-style-4 {
color: #fff;
background: linear-gradient(180deg, #333 0%, #000 100%);
}
.${n.buttonClass}-style-4::before {
background: linear-gradient(180deg, #b400bf 0%, #822a85 100%);
}
.${n.buttonClass}-style-4::after {
background-image: var(--svg-white-arrow);
}
.${n.buttonClass}-disabled {
pointer-events: none;
opacity: 0.5;
}
.${n.buttonClass}-loading {
cursor: wait;
pointer-events: none;
}
.${n.buttonClass}-loading span {
opacity: 0;
}
.${n.buttonClass}-loading::before {
width: 0;
}
.${n.buttonClass}-loading::after {
content: "";
display: block;
position: absolute;
top: 50%;
left: 10px;
width: 30px;
margin-top: -15px;
height: 30px;
background-image: var(--svg-loader);
background-position: center;
background-size: 30px;
background-repeat: no-repeat;
animation: rotate-loading 1s linear infinite;
transform-origin: center;
}
@keyframes rotate-loading { 100% { transform: rotate(360deg); }}
`,e}addEventListeners(e){e.addEventListener("mouseenter",()=>{e.classList.add("mouse-enter"),e.classList.remove("mouse-leave")}),e.addEventListener("mouseleave",()=>{e.classList.add("mouse-leave"),e.classList.remove("mouse-enter")})}};n.buttonClass="leaselink-button";var g=n,m,y;(m=window.customElements)!=null&&m.get("widget-leaselink-button")||(y=window.customElements)==null||y.define("widget-leaselink-button",g);var h=class{constructor(t,e){this.widget=e;this.scriptElementSrc="https://elements.leaselink.pl/leaselinkelements/leaselinkelements.esm.js";this.parentElement=null;this.buildPromise=null;this.disableApplicationProcess=!1;this.disableCartBuilder=!1;this.enableCalculatorOnCheckout=!1;this.styleThemeId="";this.calculatorStyle="";this.buttonLabel="Oblicz rat\u0119 w Leasingu";this.buttonStyle="";this.buttonSize="";this.buttonShowRate=!1;this.apiKey=t.apiKey,this.disableApplicationProcess=!!t.disableApplicationProcess||!!t.isCheckout,this.disableCartBuilder=!!t.disableCartBuilder,this.enableCalculatorOnCheckout=!!t.enableCalculatorOnCheckout,this.renderToSelector=t.renderToSelector,this.styleThemeId=t.styleThemeId||"",this.calculatorStyle=t.calculatorStyle||"",this.buttonLabel=t.buttonLabel||this.buttonLabel,this.buttonStyle=t.buttonStyle||"",this.buttonSize=t.buttonSize||"",this.buttonShowRate=!!t.buttonShowRate,this.buildPromise=this.init();let a=document.createElement("widget-leaselink-button");if(this.buttonStyle){let i=this.buttonStyle.match(/\d+/),s=i?i[0]:this.buttonStyle;a.dataset.styleN=s}this.buttonSize&&(a.dataset.sizeN=this.buttonSize),this.buttonLabel&&(a.dataset.label=this.buttonLabel),this.buttonElement=a}async init(){await this.loadElementsScript(),this.calculatorElement=window.leaselinkElementsBuilder("div").api({apiKey:this.apiKey}).styles({externalId:this.calculatorStyle}).calculator({disableProcess:this.disableApplicationProcess}).build(),this.calculatorElement.getElementsByTagName("leaselink-calculator")[0].setAttribute("disable-process",this.disableApplicationProcess.toString()),this.calculatorStyle=="STYL-WORDPRESS-01"&&this.calculatorElement.getElementsByTagName("leaselink-calculator")[0].setAttribute("white-logo","true"),this.buttonElement&&this.buttonElement.addEventListener("click",()=>this.onClickedButton())}clearCart(){var t,e;(e=(t=window.leaselinkApi)==null?void 0:t.clearCart)==null||e.call(t)}show(){var t,e;(e=(t=window.leaselinkApi)==null?void 0:t.showCalculator)==null||e.call(t)}onClickedButton(){(this.disableCartBuilder||this.widget.isCheckout)&&this.clearCart(),this.widget.products.forEach(t=>this.addItemToCart(t,{componentName:"onsite",componentPlacement:this.widget.isProductPage?"card":"payments",externalApp:"WordPress"})),this.show()}async addItemToCart(t,e){var a,i;(i=(a=window.leaselinkApi)==null?void 0:a.addItemToCart)==null||i.call(a,t,{disableDefault:!0,apiUsageData:e})}updateButtonText(t){let{FinancialProductType:e,NetMonthlyInstallment:a,GrossMonthlyInstallment:i,DeferralPeriodDays:s}=t,o="";switch(e){case"OperationalLeasing":o=this.widget.showRate?`W Leasingu od ${a}`:"We\u017A Leasing teraz";break;case"Loan":o=this.widget.showRate?`Raty dla Firm od ${i}`:"sprawd\u017A Raty dla Firm";break;case"DeferredPayment":this.widget.showRate&&s?o=`Masz firm\u0119? Zap\u0142a\u0107 za ${s} dni`:o="Masz firm\u0119? Zap\u0142a\u0107 p\xF3\u017Aniej";break;case"Subscription":o=this.widget.showRate?`Abonament dla Firm od ${a}`:"Abonament dla Firm";break;default:o="Opcja finansowania"}this.buttonElement&&this.buttonElement.updateButtonText&&this.buttonElement.updateButtonText(o)}async ensureBuilt(){return this.buildPromise||(this.buildPromise=this.init()),await this.buildPromise,this.calculatorElement}async loadElementsScript(){return new Promise((t,e)=>{let a=document.querySelector(`script[src="${this.scriptElementSrc}"]`);if(a)return t(a);let i=document.createElement("script");i.type="module",i.src=this.scriptElementSrc,i.async=!0,i.addEventListener("load",s=>t(s)),i.addEventListener("error",s=>e(new Error("Failed to load LeaseLink elements script"))),document.getElementsByTagName("head")[0].appendChild(i)})}};var d=class f{constructor(){this.Id=0;this.Name="";this.Link="";this.Quantity=1;this.UnitNetPrice=0;this.UnitGrossPrice=0;this.Tax=0;this.UnitTaxValue=0;this.CategoryLevel1="";this.CategoryLevel2="";this.CategoryLevel3="";this.CanBuy=!1;this.HasVariations=!1}static fromJson(t,e=1){let a=new f;return a.Name=String((t==null?void 0:t.Name)||""),a.Link=String((t==null?void 0:t.Link)||""),a.Quantity=Number(e)||1,a.UnitNetPrice=Number((t==null?void 0:t.UnitNetPrice)||0),a.UnitGrossPrice=Number((t==null?void 0:t.UnitGrossPrice)||0),a.Tax=Number((t==null?void 0:t.Tax)||0),a.UnitTaxValue=Number((t==null?void 0:t.UnitTaxValue)||0),a.CategoryLevel1=String((t==null?void 0:t.CategoryLevel1)||""),a.CategoryLevel2=String((t==null?void 0:t.CategoryLevel2)||""),a.CategoryLevel3=String((t==null?void 0:t.CategoryLevel3)||""),a.Id=Number((t==null?void 0:t.Id)||0)||void 0,a.CanBuy=!!(t!=null&&t.CanBuy),a.HasVariations=!!(t!=null&&t.HasVariations),a}static toRequestBody(t){return{Name:t.Name,Quantity:t.Quantity,UnitNetPrice:t.UnitNetPrice,UnitGrossPrice:t.UnitGrossPrice,Tax:t.Tax,UnitTaxValue:t.UnitTaxValue,CategoryLevel1:t.CategoryLevel1,CategoryLevel2:t.CategoryLevel2,CategoryLevel3:t.CategoryLevel3}}};var c=class c{constructor(t){this.token=null;this.isCartReadOnly=!0;this.calculator=null;this.products=[];this.calculateButton=null;this.priceObserver=null;if(!t)throw new Error("LeaseLinkWidget: config is required");this.config=t,this.init()}get apiUrl(){var t;return((t=this.config)==null?void 0:t.apiUrl)||c.BASE_URL}get isSandbox(){var t;return!!((t=this.config)!=null&&t.isSandbox)}get isProductPage(){var t;return!!((t=this.config)!=null&&t.isProductPage)}get isCheckout(){var t;return!!((t=this.config)!=null&&t.isCheckout)}get isCart(){var t;return!!((t=this.config)!=null&&t.isCart)}get showRate(){var t;return!!((t=this.config)!=null&&t.buttonShowRate)}async init(){if(this.config.calculateButtonEnabled&&this.isProductPage){await this.initCalculateButton();return}if(this.calculator=new h(this.config,this),this.isProductPage&&this.config.productId&&this.config.productType!=="variable"){let t=await this.shouldShowCalculator();await this.updateCalculatorVisibility(t)}if(this.isProductPage&&this.config.productId&&this.config.productType==="variable"){let t=await this.shouldShowCalculator({variationId:null});await this.updateCalculatorVisibility(t)}if(this.isCart&&this.config.enableCalculatorOnCart){let t=await this.shouldShowCalculator();await this.updateCalculatorVisibility(t)}if(this.isCheckout){let t=await this.shouldShowCalculator();await this.updateCalculatorVisibility(t);let e=document.querySelector(".wc-block-checkout__payment-method");if(e){let o={childList:!0,subtree:!0},r=()=>{this.shouldShowCalculator().then(u=>{this.updateCalculatorVisibility(u)}),l.disconnect()},l=new MutationObserver(r);l.observe(e,o)}let a=null,i=()=>{a!==null&&clearTimeout(a),a=window.setTimeout(async()=>{let o=await this.shouldShowCalculator();await this.updateCalculatorVisibility(o),a=null},500)},s=window.fetch;window.fetch=async(...o)=>{let r=await s(...o),l="";return typeof o[0]=="string"?l=o[0]:o[0]instanceof Request?l=o[0].url:o[0]instanceof URL&&(l=o[0].href),l.includes("/wc/store/v1/cart/select-shipping-rate")&&i(),r},jQuery(document).ajaxComplete(async(o,r,l)=>{var b;let u=(b=l==null?void 0:l.url)!=null?b:"";typeof u=="string"&&u.includes("wc-ajax=update_order_review")&&i()}),jQuery(document.body).on("updated_checkout",()=>{i()}),jQuery(document.body).on("change","input[name^='shipping_method']",()=>{i()})}jQuery("form.variations_form").on("show_variation",(t,e)=>void this.handleVariationChange(e)),jQuery("form.variations_form").on("hide_variation",()=>void this.handleVariationChange(null)),jQuery(document.body).on("change",this.getPaymentMethodSelector(),async t=>{let a=this.isLeaseLinkPaymentSelected()?await this.shouldShowCalculator():!1;await this.updateCalculatorVisibility(a)})}async handleVariationChange(t){if(t){let e=await this.getProductById(t.variation_id);this.products=e;let a=await this.shouldShowCalculator({variationId:t.variation_id});await this.updateCalculatorVisibility(a)}else{let e=await this.shouldShowCalculator({variationId:null});await this.updateCalculatorVisibility(e)}}async handleCalculateButtonVariationChange(t){if(t){let e=await this.getProductById(t.variation_id);this.products=e}else this.products=[];await this.updateCalculateButtonUrl()}async updateCalculatorVisibility(t){try{let e=this.isLeaseLinkPaymentSelected();t&&e?(await this.renderCalculator(),await this.updateButtonText()):this.removeCalculator()}catch(e){console.warn("[LeaseLink] Failed to update calculator visibility",e)}}async updateButtonText(){if(this.calculator&&this.showRate&&this.products.length>0){let t=await this.createCalculation(this.products,{"Component-Name":"dynamic button","Component-Placement":this.isProductPage?"card":"payments","External-App":"WordPress"});this.calculator.updateButtonText(t.Offers[0])}}async renderCalculator(){if(!this.calculator)return;let t=await this.calculator.ensureBuilt();if(t&&t.parentElement)return;let e=null;if(this.config.isProductPage){let a=this.config.renderToSelector||this.calculator.renderToSelector;a&&(e=document.querySelector(a))}else if(this.config.isCart&&this.config.enableCalculatorOnCart){let a=this.config.buttonCartSelector||".leaselink-calculator-cart-container";e=document.querySelector(a)}else this.config.isCheckout&&this.config.enableCalculatorOnCheckout&&(e=document.querySelector(".leaselink-calculator-checkout-container"));e&&(e.appendChild(t),e.appendChild(this.calculator.buttonElement),this.calculator.parentElement=e)}removeCalculator(){if(this.calculator)try{let t=this.calculator.calculatorElement;t&&t.parentElement&&t.parentElement.removeChild(t),this.calculator.parentElement=null;let e=this.calculator.buttonElement;e&&e.parentElement&&e.parentElement.removeChild(e)}catch(t){}}async getProductById(t){let e=await fetch(`/wp-json/leaselink/v1/product/${t}`,{credentials:"same-origin"});if(!e.ok)throw new Error("Failed to fetch product");let a=await e.json();if(!Array.isArray(a))throw new Error("Invalid product data");return a.map(i=>d.fromJson(i))}async getCartProducts(){let t=await fetch("/wp-json/leaselink/v1/checkout",{credentials:"same-origin"});if(!t.ok)throw new Error("Failed to fetch checkout");let e=await t.json();if(!Array.isArray(e))throw new Error("Invalid checkout data");return e.map(i=>d.fromJson(i,i.Quantity||1))}isPriceInRange(t){let e=Number((t==null?void 0:t.UnitNetPrice)||0),i=this.config.enableCalculatorOnProduct&&this.config.allowCartBuilding&&this.isProductPage?0:c.MIN_VALUE;return e>=i&&e<=c.MAX_VALUE}async shouldShowCalculator(t){if(console.log("[LeaseLink] shouldShowCalculator called",{isCheckout:this.isCheckout,isCart:this.isCart,isProductPage:this.isProductPage,productId:this.config.productId,productType:this.config.productType,options:t}),this.isCart&&this.config.enableCalculatorOnCart)try{let e=await this.getCartProducts();this.products=e;let a=e.every(i=>!!i.CanBuy);return console.log("[LeaseLink] Cart check: canBuy=",a),a}catch(e){return console.warn("[LeaseLink] Failed to fetch cart for cart check",e),!1}if(this.isCheckout)try{let e=await this.getCartProducts();this.products=e;let a=e.every(i=>!!i.CanBuy);return console.log("[LeaseLink] Checkout check: canBuy=",a),a}catch(e){return console.warn("[LeaseLink] Failed to fetch cart for checkout check",e),!1}if(this.isProductPage&&this.config.productId){if(this.config.productType==="variable"){let e=t==null?void 0:t.variationId;if(!e)return console.log("[LeaseLink] Variable product but no variation selected"),!1;try{let a=await this.getProductById(e);this.products=a;let i=a.every(s=>!!s.CanBuy&&this.isPriceInRange(s));return console.log("[LeaseLink] Variable product check:",i,a),i}catch(a){return console.warn("LeaseLink: failed to fetch variation product",a),!1}}if(this.config.productType==="grouped")try{let e=await this.getProductById(this.config.productId);if(this.products=e,e.length===0)return console.log("[LeaseLink] Grouped product: no products found"),!1;let a=e.reduce((r,l)=>r+(Number(l.UnitNetPrice)||0)*(l.Quantity||1),0),i=e.map(r=>r.Name).join(" + "),s=d.fromJson({Name:i,UnitNetPrice:a,CanBuy:e.every(r=>!!r.CanBuy)}),o=e.every(r=>!!r.CanBuy)&&this.isPriceInRange(s);return console.log("[LeaseLink] Grouped product check:",o,{productPrice:a,products:e}),o}catch(e){return console.warn("LeaseLink: failed to fetch product",e),!1}try{let e=await this.getProductById(this.config.productId);this.products=e;let a=e.every(i=>!!i.CanBuy&&this.isPriceInRange(i));return console.log("[LeaseLink] Simple product check:",a,e),a}catch(e){return console.warn("LeaseLink: failed to fetch product",e),!1}}return console.log("[LeaseLink] shouldShowCalculator: no matching condition"),!1}async getToken(){if(this.token===null){let e=await(await fetch(`${this.apiUrl}/api/GetToken`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ApiKey:this.config.apiKey})})).json();this.token=e.Token}return this.token}async createCalculation(t=[],e){try{let a=await this.getToken(),i={MultiOffer:0,isCartReadOnly:Number(this.isCartReadOnly),Items:t.map(o=>d.toRequestBody(o))},s=await fetch(`${this.apiUrl}/api/CreateCalculation`,{method:"POST",headers:Object.assign({"Content-Type":"application/json",Authorization:`Bearer ${a}`},e||{}),body:JSON.stringify(i)});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}catch(a){throw console.error("Error creating calculation:",a),a}}isLeaseLinkPaymentSelected(){if(!this.isCheckout)return!0;try{let t=this.getPaymentMethodSelector();return Array.from(document.querySelectorAll(t)).some(a=>a.value==="leaselink_payment"&&a.checked)}catch(t){return!1}}getPaymentMethodInputNames(){var e;let t=(e=this.config)==null?void 0:e.paymentMethodInputNames;return Array.isArray(t)&&t.length>0?t:["radio-control-wc-payment-method-options","payment_method"]}getPaymentMethodSelector(){return this.getPaymentMethodInputNames().map(t=>`input[name="${t}"]`).join(", ")}async initCalculateButton(){var l,u;if(!this.config.calculateButtonEnabled||!this.isProductPage)return;let t=this.config.renderToSelector;if(!t){console.warn("[LeaseLink] Calculate button rendering selector not configured");return}let e=await this.waitForElement(t);if(!e){console.warn(`[LeaseLink] Target element not found: ${t}`);return}let i=(this.config.calculateButtonStyle||this.config.buttonStyle||"style_1").match(/\d+/),s=i?i[0]:"1",r={small:"small",standard:"",large:"large"}[this.config.buttonSize||"standard"]||"";this.calculateButton=document.createElement("widget-leaselink-button"),this.calculateButton.setAttribute("data-label","We\u017A w Leasing"),this.calculateButton.setAttribute("data-style-n",s),r&&this.calculateButton.setAttribute("data-size-n",r),this.calculateButton.setAttribute("data-href","#"),this.calculateButton.setAttribute("data-target","_blank"),this.calculateButton.dataset.type=this.config.calculateButtonType||"dynamic",this.calculateButton.setDisabled(!0),e.nextSibling?(l=e.parentNode)==null||l.insertBefore(this.calculateButton,e.nextSibling):(u=e.parentNode)==null||u.appendChild(this.calculateButton),this.config.productType==="variable"&&(jQuery("form.variations_form").on("show_variation",(b,C)=>void this.handleCalculateButtonVariationChange(C)),jQuery("form.variations_form").on("hide_variation",()=>void this.handleCalculateButtonVariationChange(null))),this.config.calculateButtonPriceSelector&&this.setupPriceObserver(),await this.updateCalculateButtonUrl()}waitForElement(t,e=5e3){return new Promise(a=>{let i=document.querySelector(t);if(i){a(i);return}let s=new MutationObserver(()=>{let o=document.querySelector(t);o&&(s.disconnect(),a(o))});s.observe(document.body,{childList:!0,subtree:!0}),setTimeout(()=>{s.disconnect(),a(null)},e)})}setupPriceObserver(){if(!this.config.calculateButtonPriceSelector)return;let t=document.querySelector(this.config.calculateButtonPriceSelector);if(!t){console.warn(`[LeaseLink] Price element not found: ${this.config.calculateButtonPriceSelector}`);return}this.priceObserver=new MutationObserver(async()=>{await this.updateCalculateButtonUrl()}),this.priceObserver.observe(t,{childList:!0,subtree:!0,characterData:!0});let e=t.parentElement;e&&this.priceObserver.observe(e,{childList:!0,subtree:!0,characterData:!0})}buildStaticCalculatorUrl(t){let e="https://online.leaselink.pl/RateCalculator/calculate",a=new URLSearchParams;a.append("rate","999"),a.append("externalID",this.config.externalId||""),a.append("productName",t.Name),t.CategoryLevel1&&a.append("categoryLevel",t.CategoryLevel1),t.CategoryLevel2&&a.append("categoryLevel2",t.CategoryLevel2),t.CategoryLevel3&&a.append("categoryLevel3",t.CategoryLevel3),t.Tax&&a.append("tax",String(t.Tax));let i=!1,s=i?t.UnitNetPrice:t.UnitGrossPrice;return a.append("value",String(s)),a.append("isNet",String(i)),t.Quantity&&t.Quantity>1&&a.append("quantity",String(t.Quantity)),`${e}?${a.toString()}`}async fetchCalculation(t,e){try{let a={productId:t};e&&(a.variationId=e);let i=await fetch("/wp-json/leaselink/v1/calculate",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){let o=await i.json().catch(()=>null);return console.warn("[LeaseLink] Calculate endpoint error:",i.status,o),null}let s=await i.json();return s.eligible===!1?(console.log("[LeaseLink] Product not eligible for leasing:",s.reason,s.message),null):{url:s.url,label:s.label||"We\u017A w Leasing"}}catch(a){return console.warn("[LeaseLink] Failed to fetch calculation",a),null}}async updateCalculateButtonUrl(){var t;if(this.calculateButton){this.calculateButton.setDisabled(!0),this.calculateButton.setLoading(!0);try{let e=null,a=null;if(this.products.length>0)a=(t=this.products[0].Id)!=null?t:null;else if(this.config.productId){if(this.config.productType==="variable"){this.calculateButton.setLoading(!1),this.calculateButton.hide(),this.calculateButton.setDisabled(!0);return}e=parseInt(this.config.productId,10)}if(!e&&!a){this.calculateButton.setLoading(!1),this.calculateButton.hide(),this.calculateButton.setDisabled(!0);return}if(this.config.calculateButtonType==="static"){let s=null;if(this.products.length>0)s=this.products[0];else{let r=await this.getProductById(e);r.length>0&&(s=r[0])}if(!s){this.calculateButton.setLoading(!1),this.calculateButton.hide(),this.calculateButton.setDisabled(!0);return}let o=this.buildStaticCalculatorUrl(s);this.calculateButton.setAttribute("data-href",o),this.calculateButton.updateButtonText("We\u017A w Leasing"),this.calculateButton.setLoading(!1),this.calculateButton.setDisabled(!1),this.calculateButton.show()}else{let s=await this.fetchCalculation(e||a,this.config.productType==="variable"&&a?a:null);if(!s||!s.url){this.calculateButton.setLoading(!1),this.calculateButton.hide(),this.calculateButton.setDisabled(!0);return}this.calculateButton.setAttribute("data-href",s.url),this.calculateButton.updateButtonText(s.label),this.calculateButton.setLoading(!1),this.calculateButton.setDisabled(!1),this.calculateButton.show()}}catch(e){console.warn("[LeaseLink] Failed to update calculate button URL",e),this.calculateButton.setLoading(!1),this.calculateButton.setDisabled(!0),this.calculateButton.hide()}}}};c.MIN_VALUE=300,c.MAX_VALUE=15e4,c.BASE_URL="https://online.leaselink.pl";var p=c;window.leaseLinkWidget=new p(window.leaseLinkWidgetConfig);})();