(function(d,c){typeof exports=="object"&&typeof module<"u"?module.exports=c():typeof define=="function"&&define.amd?define(c):(d=typeof globalThis<"u"?globalThis:d||self,d.AltapayPaymentWidget=c())})(this,function(){"use strict";var H=Object.defineProperty;var $=(d,c,m)=>c in d?H(d,c,{enumerable:!0,configurable:!0,writable:!0,value:m}):d[c]=m;var a=(d,c,m)=>($(d,typeof c!="symbol"?c+"":c,m),m);class d{constructor(){a(this,"_cachedData",{})}setCache(e,n){e=this._prepareKey(e),this._cachedData[e]=n}getCache(e){return e=this._prepareKey(e),Object.hasOwnProperty.call(this._cachedData,e)?this._cachedData[e]:!1}flush(){this._cachedData={}}_prepareKey(e){if(typeof e=="string")return e;if(typeof e=="number")return e.toString();if(typeof e=="object")return Object.keys(e).reduce((t,i)=>(t+=`${e[i]}::`,t),"");throw new Error("Data is not cacheable")}}class c{constructor(e){a(this,"successTemplate","#altapay-success-template");a(this,"errorTemplate","#altapay-error-template");a(this,"infoBlockTemplate","#altapay-info-template");a(this,"container","#altapay-container");a(this,"activeTerminal");a(this,"root");a(this,"content");a(this,"cache",null);a(this,"onSuccess",null);a(this,"onFail",null);a(this,"onClose",null);a(this,"beforeRegisterIntent",null);a(this,"afterRegisterIntent",null);a(this,"paymentCompleted",!1);const{container:n,template:t,api:i,terminals:o,css:s,onSuccess:l,onFail:h,onClose:u,beforeRegisterIntent:f,afterRegisterIntent:y}=e;if(this.container=n,this.template=t,this.api=i,this.terminals=o,this.css=s||[],typeof l=="function"&&(this.onSuccess=l),typeof h=="function"&&(this.onFail=h),typeof u=="function"&&(this.onClose=u),typeof f=="function"&&(this.beforeRegisterIntent=f),typeof y=="function"&&(this.afterRegisterIntent=y),!this.template)throw new Error("Template is not set");if(!this.api)throw new Error("Api is not set");if(!Array.isArray(this.terminals)||!this.terminals.length)throw new Error("Terminals is not set");this.init()}open(e,n,t,i=null,o={},s=null){if(this.content.innerHTML="",this.amount=e,this.currency=n,this.orderId=t,this.tid=i,this.description=o,this.renderAmount(),s){const l=this.root.querySelector(`#support-terminals [data-terminal=${s}]`);this.setActiveTab(l)}else this.setActiveTab()}close(){this.amount=void 0,this.currency=void 0,this.orderId=void 0,this.tid=null,this.description={},this.content.innerHTML="",this.showTabs(),this.cache&&this.cache.flush(),window.removeEventListener("message",this.onMessage,!1)}isCompleted(){return this.paymentCompleted}setActiveTerminal(e){if(!e)return;const n=this.root.querySelector(`#support-terminals [data-terminal=${e}]`);n&&(console.log(n),this.setActiveTab(n))}setCache(e=null){(e instanceof d||e===null)&&(this.cache=e)}init(){this.render(),window.addEventListener("message",this.onMessage.bind(this),!1)}render(){const e=document.querySelector(this.container);if(!e)throw new Error("Container is not set.");e.attachShadow({mode:"open"}),this.css.forEach(t=>{const i=document.createElement("link");i.rel="stylesheet",i.href=t,e.shadowRoot.appendChild(i)});const n=this.getNodeFromTemplate(this.template);if(e.shadowRoot.appendChild(n),this.root=e.shadowRoot.querySelector("#altapay-payment-widget"),this.content=this.root.querySelector("#payment-data"),!this.content)throw new Error("Content not found");this.renderTabs()}renderAmount(){const e=new Intl.NumberFormat(navigator.language,{style:"currency",currency:this.currency}).format(this.amount/100);this.root.querySelectorAll(".amount").forEach(t=>{t.innerText=e})}renderTabs(){const e=this.root.querySelector("#support-terminals");if(!e)throw new Error("Payment types list is not set.");this.terminals.forEach(n=>{const t=document.createElement("button");t.classList.add("tabs__item"),t.dataset.terminal=n.id;const i=document.createElement("span");i.classList.add("custom-icon"),i.classList.add(n.icon),t.appendChild(i),t.appendChild(document.createTextNode(n.name)),e.appendChild(t)}),setTimeout(()=>{e.style.overflowX="auto"},300),e.addEventListener("click",this.onTabClick.bind(this))}onTabClick(e){let n;e&&e.target&&!e.target.classList.contains("tabs__item")?n=e.target.closest(".tabs__item"):n=e.target,this.setActiveTab(n)}setActiveTab(e=null){const n=this.root.querySelectorAll("#support-terminals .tabs__item");n.forEach(t=>{t.classList.remove("active")}),e||(e=n[0]),e.classList.add("active"),this.activeTerminal=this.terminals.find(t=>t.id===e.dataset.terminal),this.root.setAttribute("data-gateway",this.activeTerminal.id),e.scrollIntoView({behavior:"smooth",block:"end",inline:"nearest"}),this.renderContent()}renderContent(e=!1){this.content.innerHTML="",!e&&Object.prototype.hasOwnProperty.call(this.activeTerminal,"infoBlock")?this.showInfoBlock(this.content):this.renderIFrame(this.content)}renderIFrame(e){this.showLoader(),this.fetchPaymentData().then(({url:n})=>{this.createIFrame(e,n).finally(()=>{this.hideLoader()})}).catch(()=>{this.hideLoader()})}createIFrame(e,n){return new Promise(t=>{const i=this.root.querySelector("#altapay-iframe");if(i===null){const o=document.createElement("iframe");o.className="PensioEmbeddedPaymentWindow",o.src=`${n}&embeddedPaymentWindow=true&handleRedirectInsideIFrame=false`,o.setAttribute("id","altapay-iframe"),o.setAttribute("allowTransparency","true"),o.setAttribute("frameBorder","0"),e.appendChild(o),o.addEventListener("load",()=>t(o))}else return i.src=n,t(i)})}onPayButtonClick(){Object.prototype.hasOwnProperty.call(this.activeTerminal,"callback")&&typeof this.activeTerminal.callback=="function"?this.activeTerminal.callback(this.tid).then(e=>{this.hideTabs(),this.showSuccessMessage(e),this.paymentCompleted=!0,this.onSuccess&&this.onSuccess({terminal:{...this.activeTerminal}})}).catch(()=>{this.showErrorMessage()}):this.renderContent(!0)}fetchPaymentData(){let e={amount:this.amount,currency:this.currency,orderId:this.orderId,tid:this.tid,description:this.description,terminal:this.activeTerminal.id};typeof this.beforeRegisterIntent=="function"&&(e=this.beforeRegisterIntent(e));const n=this.cache.getCache(e);return n?Promise.resolve(n):fetch(this.api,{method:"POST",mode:"cors",cache:"no-cache",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).then(t=>{if(t.status>=200&&t.status<=299)return t.json();throw Error(t.statusText)}).then(t=>(typeof this.afterRegisterIntent=="function"&&(t=this.afterRegisterIntent(t)),t)).then(t=>(this.cache&&this.cache.setCache(e,t),t)).catch(t=>(this.showErrorMessage(),Promise.reject(t)))}blockInactiveTabs(){this.root.querySelectorAll("#support-terminals .tabs__item").forEach(n=>{if(!(n instanceof HTMLElement))return;n.classList.contains("active")||(n.hasAttribute("disabled")?n.removeAttribute("disabled"):n.setAttribute("disabled","disabled"))})}showLoader(){this.root.querySelector(".loader").classList.add("show"),this.blockInactiveTabs()}hideLoader(){this.root.querySelector(".loader").classList.remove("show"),this.blockInactiveTabs()}showInfoBlock(e){const n=this.getNodeFromTemplate(this.infoBlockTemplate),t=n.querySelector(".text");t&&(t.innerHTML=this.activeTerminal.infoBlock),e.appendChild(n);const i=e.querySelector(".actions__button");i&&i.addEventListener("click",this.onPayButtonClick.bind(this))}showErrorMessage(){const e=this.getNodeFromTemplate(this.errorTemplate),n=this.root.querySelector("#payment-data");n.innerHTML="",n.appendChild(e);const t=n.querySelector("input[type=button]");t&&t.addEventListener("click",()=>{this.renderContent()})}showSuccessMessage(e=""){const n=this.getNodeFromTemplate(this.successTemplate),t=this.root.querySelector("#payment-data");t.innerHTML=e,t.appendChild(n),t.querySelector("input[type=button]").addEventListener("click",this.tryToClose.bind(this))}onMessage({data:e}){let n={};const t=s=>s!=null&&s.constructor===String,i=s=>t(s)&&(s.includes("payment_completed")||s.includes("payment_failed")),o=s=>t(s)&&s==="close";i(e)?(n=JSON.parse(e),this.paymentResult(n)):o(e)&&this.tryToClose()}paymentResult(e){const{id:n,...t}=e;this.hideTabs(),n==="payment_completed"?(this.paymentCompleted=!0,this.onSuccess&&this.onSuccess(t)):n==="payment_failed"&&this.onFail&&this.onFail(t)}tryToClose(){this.paymentCompleted?typeof this.onClose=="function"&&this.onClose({isCompleted:this.paymentCompleted}):(this.showTabs(),this.renderContent())}hideTabs(){const e=this.root.querySelector("header.collapsible");e.classList.contains("collapsed")||e.classList.add("collapsed")}showTabs(){this.root.querySelector("header.collapsible").classList.remove("collapsed")}getNodeFromTemplate(e){const n=document.querySelector(e)||this.root.querySelector(e);if(!n)throw new Error(`Template with selector '${e}' is not found.`);return n.content.cloneNode(!0)}}function m(r,e){for(var n=0;nr.length)&&(e=r.length);for(var n=0,t=new Array(e);n0&&this.registerTriggers.apply(this,g(s)),this.onClick=this.onClick.bind(this),this.onKeydown=this.onKeydown.bind(this)}var e,n;return e=r,(n=[{key:"registerTriggers",value:function(){for(var t=this,i=arguments.length,o=new Array(i),s=0;s0&&arguments[0]!==void 0?arguments[0]:null;if(this.activeElement=document.activeElement,this.modal.setAttribute("aria-hidden","false"),this.modal.classList.add(this.config.openClass),this.scrollBehaviour("disable"),this.addEventListeners(),this.config.awaitOpenAnimation){var o=function s(){t.modal.removeEventListener("animationend",s,!1),t.setFocusToFirstNode()};this.modal.addEventListener("animationend",o,!1)}else this.setFocusToFirstNode();this.config.onShow(this.modal,this.activeElement,i)}},{key:"closeModal",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,i=this.modal;if(this.modal.setAttribute("aria-hidden","true"),this.removeEventListeners(),this.scrollBehaviour("enable"),this.activeElement&&this.activeElement.focus&&this.activeElement.focus(),this.config.onClose(this.modal,this.activeElement,t),this.config.awaitCloseAnimation){var o=this.config.openClass;this.modal.addEventListener("animationend",function s(){i.classList.remove(o),i.removeEventListener("animationend",s,!1)},!1)}else i.classList.remove(this.config.openClass)}},{key:"closeModalById",value:function(t){this.modal=document.getElementById(t),this.modal&&this.closeModal()}},{key:"scrollBehaviour",value:function(t){if(this.config.disableScroll){var i=document.querySelector("body");switch(t){case"enable":Object.assign(i.style,{overflow:""});break;case"disable":Object.assign(i.style,{overflow:"hidden"})}}}},{key:"addEventListeners",value:function(){this.modal.addEventListener("touchstart",this.onClick),this.modal.addEventListener("click",this.onClick),document.addEventListener("keydown",this.onKeydown)}},{key:"removeEventListeners",value:function(){this.modal.removeEventListener("touchstart",this.onClick),this.modal.removeEventListener("click",this.onClick),document.removeEventListener("keydown",this.onKeydown)}},{key:"onClick",value:function(t){(t.target.hasAttribute(this.config.closeTrigger)||t.target.parentNode.hasAttribute(this.config.closeTrigger))&&(t.preventDefault(),t.stopPropagation(),this.closeModal(t))}},{key:"onKeydown",value:function(t){t.keyCode===27&&this.closeModal(t),t.keyCode===9&&this.retainFocus(t)}},{key:"getFocusableNodes",value:function(){var t=this.modal.querySelectorAll(C);return Array.apply(void 0,g(t))}},{key:"setFocusToFirstNode",value:function(){var t=this;if(!this.config.disableFocus){var i=this.getFocusableNodes();if(i.length!==0){var o=i.filter(function(s){return!s.hasAttribute(t.config.closeTrigger)});o.length>0&&o[0].focus(),o.length===0&&i[0].focus()}}}},{key:"retainFocus",value:function(t){var i=this.getFocusableNodes();if(i.length!==0)if(i=i.filter(function(s){return s.offsetParent!==null}),this.modal.contains(document.activeElement)){var o=i.indexOf(document.activeElement);t.shiftKey&&o===0&&(i[i.length-1].focus(),t.preventDefault()),!t.shiftKey&&i.length>0&&o===i.length-1&&(i[0].focus(),t.preventDefault())}else i[0].focus()}}])&&m(e.prototype,n),r}(),p=null,T=function(r){if(!document.getElementById(r))return console.warn("MicroModal: ❗Seems like you have missed %c'".concat(r,"'"),"background-color: #f8f9fa;color: #50596c;font-weight: bold;","ID somewhere in your code. Refer example below to resolve it."),console.warn("%cExample:","background-color: #f8f9fa;color: #50596c;font-weight: bold;",'')),!1},E=function(r,e){if(function(t){t.length<=0&&(console.warn("MicroModal: ❗Please specify at least one %c'micromodal-trigger'","background-color: #f8f9fa;color: #50596c;font-weight: bold;","data attribute."),console.warn("%cExample:","background-color: #f8f9fa;color: #50596c;font-weight: bold;",''))}(r),!e)return!0;for(var n in e)T(n);return!0},{init:function(r){var e=Object.assign({},{openTrigger:"data-micromodal-trigger"},r),n=g(document.querySelectorAll("[".concat(e.openTrigger,"]"))),t=function(s,l){var h=[];return s.forEach(function(u){var f=u.attributes[l].value;h[f]===void 0&&(h[f]=[]),h[f].push(u)}),h}(n,e.openTrigger);if(e.debugMode!==!0||E(n,t)!==!1)for(var i in t){var o=t[i];e.targetModal=i,e.triggers=g(o),p=new w(e)}},show:function(r,e){var n=e||{};n.targetModal=r,n.debugMode===!0&&T(r)===!1||(p&&p.removeEventListeners(),(p=new w(n)).showModal())},close:function(r){r?p.closeModalById(r):p.closeModal()}});typeof window<"u"&&(window.MicroModal=v);class q{constructor(e,n="altapay-widget-modal",t=!0){a(this,"modalId","altapay-widget-modal");const i=o=>{typeof e.onClose=="function"&&e.onClose(o),v.close()};if(this.widget=new c({...e,onClose:i}),t){const o=new d;this.widget.setCache(o)}v.init()}open(e,n,t,i=null,o={},s=null){v.show(this.modalId,{onShow:()=>{const l=document.querySelector("body");l.style.overflow="hidden",this.widget.open(e,n,t,i,o,s)},onClose:()=>{const l=document.querySelector("body");l.style.overflow="auto",this.widget.close()}})}}return q});