(function(){"use strict";const dt="aftership-widget-returns-banner-root",ft="aftership-widget-returns-banner",mt="aftership-widget-returns-banner-toast",gt="Lato",yt=".aftership-widgets_returns-back_btn",$e="#credit .main";var E=(e=>(e.HIDDEN="hidden",e.SHOW="show",e))(E||{}),W=(e=>(e.CONTENT="aftership-widgets_returns-banner",e.THUMBNAIL="aftership-widgets_returns-thumbnail",e))(W||{}),A=(e=>(e.EXCHANGE_ON_STORE_BANNER_CREDIT_EXCHANGE="exchangeOnStore.banner.creditExchange",e.EXCHANGE_ON_STORE_BANNER_CREDIT_USE="exchangeOnStore.banner.creditUse",e.EXCHANGE_ON_STORE_BANNER_GO_BACK="exchangeOnStore.banner.goBack",e))(A||{});const Ue={["exchangeOnStore.banner.creditExchange"]:"You need to pay ${RemainingCredit} for the exchange.",["exchangeOnStore.banner.creditUse"]:"You have ${RemainingCredit} credit to use.",["exchangeOnStore.banner.goBack"]:"Go back"},bt="rc_sn",Le="currency",Ct="rc_banner_fold",_t="rc_session_token";var u=(e=>(e.GET_CART_TOTAL="getCartTotal",e.ADD_TO_CART="addToCart",e.UPDATE_TO_CART="updateToCart",e.REMOVE_FROM_CART="removeFromCart",e.CHECKOUT="checkout",e.BUY_NOW="buyNow",e.ON_CONTEXT_CHANGE="onContextChange",e.ERROR="error",e))(u||{}),B=(e=>(e.ERROR="error",e.INFO="info",e))(B||{});const qe=[".checkout-btn"],Me=['a[href="/checkout"]'],Fe={checkout:qe,buy_now:[],quick_payment:[],shadow_root:[],shadow_checkout:[],shadow_buy_now:[]},je={checkout:Me,buy_now:[],quick_payment:[],shadow_root:[],shadow_checkout:[],shadow_buy_now:[]};class He{computedBannerClass(t){const r=t?W.THUMBNAIL:W.CONTENT,n=t?E.HIDDEN:E.SHOW,o=t?E.SHOW:E.HIDDEN;return{closeClass:t?E.HIDDEN:E.SHOW,contentClass:r,thumbnailClass:o,creditClass:n}}}const ze=`#aftership-widget-returns-banner-root{z-index:60;bottom:0;left:0;right:0;position:fixed}.aftership-widgets_returns-thumbnail{position:fixed;left:32px;bottom:32px;width:72px;height:72px;border-radius:100%;background:rgba(0,0,0,.9);padding:20px 28px;box-sizing:border-box}.aftership-widgets_returns-banner{display:flex;justify-content:space-between;align-items:center;padding:26px 40px;background:rgba(0,0,0,.9);color:#fff;opacity:0}.aftership-widgets_returns-back_btn{color:#fff;text-decoration:underline;cursor:pointer}@media screen and (max-width: 500px){.aftership-widgets_returns-banner{padding:12px 16px}.aftership-widgets_returns-back_btn{padding:10px 5.5px;min-width:64px}}.aftership-widgets_returns-text{font-size:20px;font-weight:500}.aftership-widgets_returns-icon{cursor:pointer}.hidden{display:none}.show{display:""}
`,Ge=`.toastWrapper{text-align:center}.toast{margin:16px auto;padding:16px;display:inline-flex;background:#d82c0d;border-radius:46px;color:#fff;font-size:14px;text-align:unset}.toast_info{background:#000}.icon{margin-right:16px}
`,Xe=`
`,Ve=`
`,We=`${Ve}${Xe}
`;class Z extends He{constructor(){super()}createRootTemplate(t){if(!t)return;const r=document.createElement("style");r.innerHTML=ze+Ge;const n=document.createElement("template");n.innerHTML=We.trim(),t.appendChild(r),t.appendChild(n.content)}createBannerTemplate(t,r){if(!r)return;const n="https://widgets.automizely.com/returns",{closeClass:o,contentClass:s,thumbnailClass:a,creditClass:i}=this.computedBannerClass(t),l=`
Go back
`;r.innerHTML=l.trim()}updateBannerTemplate(t,r){const{contentClass:n}=this.computedBannerClass(t);r?.querySelector("div")?.setAttribute("class",n);const o=r?.querySelector("#credit"),s=r?.querySelector("#img-thumbnail"),a=r?.querySelector("#img-close");[o,s,a].forEach(i=>{i?.classList.toggle(E.SHOW),i?.classList.toggle(E.HIDDEN)})}createToastTemplate(t,r){if(!t)return;const n=`
${r?.message??""}
`;t.innerHTML=n.trim()}}const Et=e=>sessionStorage.getItem(e)||"",J=(e,t)=>{const n=new URLSearchParams(location.search).get(e)||Et(e);if(n)return sessionStorage.setItem(e,n),t?.(()=>n),n};function Ze(e,t){if(typeof t=="string"){const r=e[t];e[t]=function(n){sessionStorage.setItem(Ct,n.toString()),r.call(this,n)}}return e}class Y extends Error{returnsError;constructor(t,r){super(t),this.returnsError={...r,error:t},window.postMessage({type:"returnsError",data:this.returnsError},window.location.origin)}}const Q="https://api.automizely.com/rc/v4/shopper",Je=40300,q=async(e,t)=>{const r=Et(_t);return fetch(Q+e,{...t,headers:{"returns-authorization":`Bearer ${r}`,"Content-Type":"application/json"}}).then(n=>n.json()).then(n=>{if(n.meta.code===Je)throw new Error(JSON.stringify(n.meta));return n}).catch(n=>{const o=n instanceof Error?n.message:"Something went wrong",s=n instanceof Error?JSON.parse(n.message):{},{code:a,errors:i=[]}=s;throw new Y(n,{baseUrl:Q,input:e,requertUrl:Q+e,method:t?.method,message:o,returnsAPIException:!0,errorCode:a,errors:i})})};async function K(e,t){if(!e.intentionId||!t)return null;const r=(await wt({intentionId:e.intentionId}))?.data,o=(await tr({orderId:r?.order_id??"",items:r?.items??[],exchangeItems:r?.exchange_items??[],giftReturn:{is_gift_return:r?.is_gift_return||!1,gift_return_creator_account_id:r?.gift_return_creator_account_id||null},resolutionGranularity:r?.resolution_granularity||"item",returnShippingAddress:r?.return_shipping_address,returnContact:r?.recipient_contact}))?.data?.summary?.credit_remain_set.presentment_money;return o?{credit:Number(o.amount),currency:o.currency,intention:r}:{credit:void 0,currency:void 0,intention:r}}const Ye=async({orgId:e})=>{const t="https://api.returnscenter.com/shopper/v1/shops",r=`?organization_id=${e}`,n="GET",o=t+r;return fetch(o,{method:n}).then(s=>s.json()).then(s=>({background:s?.data?.exchange_for_anything_in_store_banner_background,font:s?.data?.exchange_for_anything_in_store_banner_font})).catch(s=>{const a=s instanceof Error?s.message:"Something went wrong";throw new Y(s,{baseUrl:t,input:r,requertUrl:t+r,method:"GET",message:a,returnsAPIException:!1})})},Qe=async({orgId:e,language:t})=>{const r="https://api.automizely.com/meerkat/v2/public/projects/returns-center-returns-page/production/business",n=`/${e}/translations/${t}/data.json`,o="GET",s=r+n;return fetch(s,{method:o}).then(a=>a.json()).catch(a=>{const i=a instanceof Error?a.message:"Something went wrong";throw new Y(a,{baseUrl:r,input:n,requertUrl:r+n,method:"GET",message:i,returnsAPIException:!1})})},wt=async({intentionId:e})=>q(`/return-intentions/${e}`),Ke=async({intentionId:e,exchangeItems:t,intentionData:r})=>{if(!(!e||!r))return await q(`/return-intentions/${e}`,{method:"PUT",body:JSON.stringify(Object.assign(r,{exchange_items:t}))})},tr=async({orderId:e,items:t,exchangeItems:r,giftReturn:n,resolutionGranularity:o,returnShippingAddress:s,returnContact:a})=>q("/return-previews",{method:"POST",body:JSON.stringify({order:{id:e},return_items:t?.map(i=>({item_id:i.item_id,quantity:i.quantity,resolution:i.resolution,replacement:i.replacement,reason:i.reason,subreason:i.subReason})),exchange_items:r,gift_return:n,resolution_granularity:o,resolution:"exchange_for_anything",return_shipping_address:s,contact_recipient:a})}),M=async()=>q("/setting/efa-on-store-config").then(e=>(e?.data?.efa_on_store_configs||[]).reduce((n,o)=>{if(!o?.key||!o?.value)return n;try{return{...n,[o.key]:JSON.parse(o.value)}}catch(s){return console.error(s),n}},{}));class er{shopInfo;constructor(t){this.shopInfo=t}getShopInfo(){return this.shopInfo}getCurrency(){}getIntention(){return wt({intentionId:this.shopInfo.intentionId})}}function rr(e){if(!e)return!1;try{return typeof JSON.parse(e)=="object"}catch{}return!1}class vt{interceptors;constructor(){this.interceptors=[]}addInterceptor(t){this.interceptors.push(t)}removeInterceptor(t){const r=this.interceptors.indexOf(t);r!==-1&&this.interceptors.splice(r,1)}}class nr extends vt{constructor(){super()}async intercept(...t){const r=window.originalFetch(...t);for(const n of this.interceptors){const[o,s]=t;if(o instanceof Request)n(o,r);else{const a=new Request(o,s);n(a,r)}}return r}}const tt=new nr;class or extends vt{constructor(){super()}intercept(t){this.interceptors.forEach(r=>{r(t)})}}const et=new or,St=e=>rr(e)?JSON.parse(e):e;class sr{interceptors=[];constructor(t){this.interceptors=t}run(){const t=this.interceptors;for(let r of t){const n=s=>{s.addEventListener("readystatechange",function(){if(this.readyState===4&&this.status===200){const a=this.responseURL.replace(window.location.origin,""),i=St(this.response);r(a,i)}})},o=async(s,a)=>{try{const l=await(await a).clone().text(),c=St(l);(Boolean(c)||typeof c=="string")&&r(s.url,c)}catch(i){console.log(i)}};et.addInterceptor(n),tt.addInterceptor(o)}}}class rt{custom;interceptors=[];constructor(t,r){this.custom=r??{},this.interceptors=t}run(){const t=this.interceptors;t?.length&&(this.applyXhr(),this.applyFetch(),new sr(t).run());const{xhr:r,fetch:n}=this.custom??{};r?.enable&&(this.applyXhr(),et.addInterceptor(r.interceptor)),n?.enable&&(this.applyFetch(),tt.addInterceptor(n.interceptor))}applyXhr(){XMLHttpRequest.prototype.originalSend=XMLHttpRequest.prototype.send,XMLHttpRequest.prototype.send=function(t){et.intercept(this),this.originalSend(t)}}applyFetch(){window.originalFetch=window.fetch,window.fetch=function(...t){return tt.intercept(...t)}}}class F{targetButtonSelector;observer;eventCallback;constructor(t,r){t&&(this.targetButtonSelector=t,this.observer=null,this.attachInterceptorAll(),this.observeChanges(),this.eventCallback=r)}attachInterceptorAll(){["click","mousedown"].forEach(t=>{document.addEventListener(t,this.interceptButtonClick.bind(this),{capture:!0})})}interceptButtonClick(t){if(!this.targetButtonSelector)return;document.querySelectorAll(this.targetButtonSelector)?.forEach(n=>{t.target&&n.contains(t.target)&&(t.stopImmediatePropagation(),t.preventDefault(),t.stopPropagation(),this.eventCallback?.(t))})}observeChanges(){this.observer=new MutationObserver(()=>{this.attachInterceptorAll()}),this.observer.observe(document.body,{childList:!0,subtree:!0})}detachInterceptorAll(){document.querySelectorAll(this.targetButtonSelector).forEach(r=>{r.removeEventListener("click",this.interceptButtonClick.bind(this),{capture:!0})})}destroy(){this.observer&&(this.observer.disconnect(),this.observer=null),this.detachInterceptorAll()}}class It{static messageError(t,r){console.error(t,r)}}class N{static formatCartArrayData(t,r){return t?.length===void 0?(It.messageError("cartData is exception",t),[]):t?.map(o=>this.formatCartObjectData(o,r))?.filter(Boolean)??[]}static transformNumberAsString=t=>typeof t=="number"?t+"":t;static formatCartObjectData(t,r){return Object.keys(r??{}).length?{quantity:t[r.quantity],external_variant_id:this.transformNumberAsString(t[r.external_variant_id]),external_product_id:this.transformNumberAsString(t[r.external_product_id])}:(It.messageError("keyMap is empty",r),null)}}const ar=()=>fetch(window.AftershipReturns.GetCartUrl,{credentials:"include",method:"GET"}).then(e=>e.json());var v=(e=>(e.CommonRule="common_rule",e.EFASelectors="efa_selectors",e.CartMapping="cart_mapping",e))(v||{});const kt=(e,t=300)=>{let r=null;return async(...n)=>(r&&clearTimeout(r),new Promise((s,a)=>{r=setTimeout(async()=>{try{const i=await e(...n);s(i)}catch(i){a(i)}finally{r=null}},t)}))},w=e=>[...new Set(e)],ir={updateToCart:{"/Cart-AddProduct":{data:{path:["cart","items"],formatType:"array",formatMap:{quantity:"quantity",external_variant_id:"id",external_product_id:"id"},default:[]}},"/Cart-UpdateQuantity":{data:{path:["items"],formatType:"array",formatMap:{quantity:"quantity",external_variant_id:"id",external_product_id:"id"},default:[]}},"/Cart-RemoveProductLineItem":{data:{path:["basket","items"],formatType:"array",formatMap:{quantity:"quantity",external_variant_id:"id",external_product_id:"id"},default:[]}}}};class C{static cartMapping={};static cacheMappingKeys=[];static processMapping(t){const r={};return Object.keys(t).forEach(n=>{const o=t[n];Object.keys(o??{}).forEach(s=>{r[s]={...o[s],action:n}})}),r}static setCartMapping(t){C.cartMapping=t}static getProcessMapingTable(){const t=Object.keys(C.cartMapping)?.length?C.cartMapping:ir;return C.processMapping(t)}static setMappingKeys(t){C.cacheMappingKeys=t}}const cr=({path:e,data:t,publish:r})=>{let n=C.cacheMappingKeys;if(n){const o=C.getProcessMapingTable();n=Object.keys(o)}n.forEach(o=>{if(e.includes(o)){const a=C.getProcessMapingTable()[o],i=a?.data?.default,l=a?.data?.path?.reduce((c,f)=>c?.[f],t)??i;if(a.data.formatType==="array"){const c=N.formatCartArrayData(l,a.data.formatMap);r(a.action,c)}else{const c=N.formatCartObjectData(l,a.data.formatMap);r(a.action,c)}}})},ur=async e=>{const t=(await ar())?.cart?.items??[],r=N.formatCartArrayData(t,{quantity:"quantity",external_variant_id:"id",external_product_id:"id"});r&&r?.length!==void 0&&e("updateToCart",r)},lr=async()=>{const{[v.CartMapping]:e}=await M();e&&Object.keys(e)?.length&&C.setCartMapping(e)},hr=async()=>{const{[v.CommonRule]:e,[v.EFASelectors]:t}=await M();return w([...Fe.checkout,...e?.checkout||[],...t?.checkout||[]]).join()};class pr{checkoutButtonInterceptor=null;checkoutSelector=null;provider;publish;constructor(t,r){this.publish=t,this.provider=r}create(){}async mount(){await lr(),this.checkoutSelector=await hr(),await ur(this.publish),new rt([this.interceptor.bind(this)]).run(),this.checkoutButtonInterceptor=new F(this.checkoutSelector,()=>{this.publish("checkout")})}interceptor(t,r){cr({path:t,data:r,publish:this.publish})}unmount(){this.checkoutButtonInterceptor?.destroy()}}const dr=[".paypal-buttons",".GooglePayContainer",".AmazonPayContainer",".BraintreeVenmoContainer",".or-use-label"],fr=async()=>fetch("/api/storefront/carts",{credentials:"include",method:"GET"}).then(e=>e.json()),Tt=async()=>{const e=await fr();return{cartItems:[...e?.[0]?.lineItems?.physicalItems??[],...e?.[0]?.lineItems?.digitalItems??[]].filter(t=>Boolean(t.variantId)),cartId:e?.[0]?.id}},mr=async({cartId:e,itemId:t,...r})=>fetch(`/api/storefront/carts/${e}/items/${t}`,{credentials:"include",method:"PUT",body:JSON.stringify(r)}).then(n=>n.json()),gr=async({cartId:e,itemId:t})=>fetch(`/api/storefront/carts/${e}/items/${t}`,{credentials:"include",method:"DELETE"}).then(r=>r.json()),yr=async({path:e,publish:t})=>{(e.includes("/remote/v1/cart/add")||e.includes("/remote/v1/cart/update"))&&await xt(t)},xt=kt(async e=>{const t=(await Tt())?.cartItems,r=N.formatCartArrayData(t,{quantity:"quantity",external_variant_id:"variantId",external_product_id:"productId"});r&&r?.length!==void 0&&e("updateToCart",r)}),br=async()=>{const{[v.CommonRule]:e,[v.EFASelectors]:t}=await M();return{checkoutButtonSelectors:w([...je.checkout,...e?.checkout||[],...t?.checkout||[]]).join(),quickPaymentSelectors:w([...dr,...e?.quick_payment||[],...t?.quick_payment||[]]).join()}},Cr=async e=>{const{cartId:t,cartItems:r}=await Tt();if(t)for(const n of r){const o=e.find(s=>{const a=Number(s.external_product_id),i=Number(s.external_variant_id);return a===n.productId&&i===n.variantId});if(!o&&t&&n.id)try{await gr({cartId:t,itemId:n.id})}catch(s){console.error("delete item error...",s)}if(o&&o.quantity!==n.quantity)try{await mr({cartId:t,itemId:n.id,lineItem:{variantId:n.variantId,productId:n.productId,quantity:o.quantity}})}catch(s){console.error("update item error...",s)}}};class _r{checkoutButtonInterceptor=null;checkoutSelector=null;quickPaymentObserver;provider;publish;constructor(t,r){this.publish=t,this.provider=r}create(){console.log("widget created")}async mount(){const t=await br();this.checkoutSelector=t?.checkoutButtonSelectors;const r=(await this.provider.getIntention())?.data?.exchange_items??[];await Cr(r),await xt(this.publish),new rt([this.interceptor.bind(this)]).run(),this.checkoutButtonInterceptor=new F(this.checkoutSelector,()=>{this.publish("checkout")}),this.observeQuickPaymentSelectors(t?.quickPaymentSelectors)}observeQuickPaymentSelectors(t){if(!t)return;const r=()=>{(document.querySelectorAll(t)??[]).forEach(o=>{o.remove()})};this.quickPaymentObserver=new MutationObserver(r),this.quickPaymentObserver.observe(document.body,{childList:!0,subtree:!0}),r()}interceptor(t,r){yr({path:t,publish:this.publish})}unmount(){this.checkoutButtonInterceptor?.destroy(),this.quickPaymentObserver&&(this.quickPaymentObserver.disconnect(),this.quickPaymentObserver=null)}}const T={checkout:['button[name="checkout"]','input[name="checkout"]','a[href="/checkout"]',".rebuy-cart__checkout-button",'button[id="mu-checkout-button"]',".mu-checkout-btn",".button-checkout",".rebuy-button",'input[value="Checkout"]',".cart-checkout__button",".btn-checkout",".checkout-buttons",".cart-button",'button[class="publicHover"]',".Cart__Checkout",".cart__checkout","shopify-accelerated-checkout","redo-shopify-toggle"],buy_now:["button.shopify-payment-button__button","input.shopify-payment-button__button","div.shopify-payment-button__button","just-pay-button",".shopify-payment-button__more-options",".shopify-payment-button__button",'button[id="mu-checkout-button"]','div[data-testid="PayPalInContext-button"]'],quick_payment:["shop-pay-wallet-button","shopify-amazon-pay-button","shopify-apple-pay-button","shopify-google-pay-button","shopify-paypal-button","shopify-accelerated-checkout"],shadow_root:["#upCart"],shadow_checkout:[],shadow_buy_now:[]},Er=/^.*\/cart(\/)?$/,wr=/^.*\/cart\/add(\.js)?$/,vr=/^.*\/cart\/change(\.js)?/,Sr=async()=>fetch(`/cart.js?rc=${Date.now()}`,{credentials:"include",method:"GET"}).then(e=>e.json()),Ir=async()=>({cartItems:(await Sr()).items.map(t=>({id:t.id,key:t.key,productId:t.product_id,variantId:t.variant_id,quantity:t.quantity}))}),kr=e=>[Er,wr,vr].some(r=>r.test(e)),Tr=async({path:e,publish:t})=>{kr(e)&&await Dt(t)},Dt=kt(async e=>{const t=(await Ir())?.cartItems,r=N.formatCartArrayData(t,{quantity:"quantity",external_variant_id:"variantId",external_product_id:"productId"});r&&r?.length!==void 0&&e("updateToCart",r)}),xr=async()=>{const{[v.CommonRule]:e,[v.EFASelectors]:t}=await M();return{checkoutSelectors:w([...T.checkout,...e?.checkout||[],...t?.checkout||[]]).join(),buyNowSelectors:w([...T.buy_now,...e?.buy_now||[],...t?.buy_now||[]]).join(),quickPaymentSelectors:w([...T.quick_payment,...e?.quick_payment||[],...t?.quick_payment||[]]).join(),shadowRootSelectors:w([...T.shadow_root,...e?.shadow_root||[],...t?.shadow_root||[]]).join(),shadowCheckoutSelectors:w([...T.shadow_checkout,...e?.shadow_checkout||[],...t?.shadow_checkout||[]]).join(),shadowBuyNowSelectors:w([...T.shadow_buy_now,...e?.shadow_buy_now||[],...t?.shadow_buy_now||[]]).join()}},Dr=(e,t,r)=>{try{document.querySelectorAll(e)?.forEach(o=>{const s=o?.shadowRoot?.querySelectorAll(t);s&&Array.from(s).forEach(a=>{a?.addEventListener?.("click",i=>{i.target&&a.contains(i.target)&&(i.stopPropagation(),i.preventDefault(),i.stopImmediatePropagation(),r())},{capture:!0})})})}catch(n){console.error("Bind shadow checkout buttons error:",n)}},Or=async()=>{const e=new URLSearchParams(location.search).get("variant"),t=document.querySelector('[name="quantity"]')?.value??1,r=location.pathname;return fetch(`${r}.js?rc_time=${Date.now()}`).then(n=>n.json()).then(n=>({external_product_id:String(n.id),external_variant_id:String(e||n.variants[0].id),quantity:Number(t)})).catch(()=>{console.error("Please make an exchange on the product details page")})};class Rr{checkoutButtonInterceptor=null;buyNowButtonInterceptor=null;checkoutSelector=null;shadowRootSelectors=null;shadowCheckoutSelector=null;buyNowButtonSelector=null;quickPaymentObserver;provider;publish;constructor(t,r){this.publish=t,this.provider=r}create(){}async mount(){const t=await xr();this.checkoutSelector=t?.checkoutSelectors,this.shadowRootSelectors=t?.shadowRootSelectors,this.shadowCheckoutSelector=t?.shadowCheckoutSelectors,this.buyNowButtonSelector=t?.buyNowSelectors,await Dt(this.publish),new rt([this.interceptor.bind(this)]).run(),this.checkoutSelector&&(this.checkoutButtonInterceptor=new F(this.checkoutSelector,()=>this.publish("checkout"))),this.shadowRootSelectors&&this.shadowCheckoutSelector&&Dr(this.shadowRootSelectors,this.shadowCheckoutSelector,()=>this.publish("checkout")),this.buyNowButtonSelector&&(this.buyNowButtonInterceptor=new F(this.buyNowButtonSelector,async()=>{const n=await Or();n&&(this.publish("updateToCart",[n]),this.publish("buyNow"))})),this.observeQuickPaymentSelectors(t?.quickPaymentSelectors)}observeQuickPaymentSelectors(t){if(!t)return;const r=()=>{(document.querySelectorAll(t)??[]).forEach(o=>{o.remove()})};this.quickPaymentObserver=new MutationObserver(r),this.quickPaymentObserver.observe(document.body,{childList:!0,subtree:!0}),r()}interceptor(t){Tr({path:t,publish:this.publish})}unmount(){this.checkoutButtonInterceptor?.destroy(),this.buyNowButtonInterceptor?.destroy(),this.quickPaymentObserver&&(this.quickPaymentObserver.disconnect(),this.quickPaymentObserver=null)}}const Ar={SFCC:"sfcc",bigCommerce:"bigCommerce",shopify:"shopify"};function Br(e,t){const o={SFCC:pr,bigCommerce:_r,shopify:Rr}?.["shopify"],s=new er(t);return o?new o(e,s):null}function nt(){return Ar["shopify"]}class I{get shopInfo(){const t=J(bt)||"",r=new URLSearchParams(window.atob(t));return sessionStorage.setItem(_t,r.get("sessionToken")||""),{appKey:r.get("appKey")||"",orgId:r.get("orgId")||"",language:r.get("language")||"en-US",intentionId:r.get("intensionId")||"",sessionToken:r.get("sessionToken")||"",currency:this.currency,platform:nt(),goBackUrl:r.get("goBackUrl")||"",shopperContinueUrl:r.get("shopperContinueUrl")||"",shopperHomeUrl:r.get("shopperHomeUrl")||""}}get providerShopInfo(){return{currency:this.shopInfo.currency,language:this.shopInfo.language,redirectUrl:this.shopInfo.goBackUrl,rc_origin:this.shopInfo.shopperHomeUrl,rc_navigate_from_path:this.shopInfo.shopperContinueUrl}}get currency(){return J(Le)||""}}var Nr=Object.defineProperty,Pr=Object.getOwnPropertyDescriptor,$r=(e,t,r,n)=>{for(var o=n>1?void 0:n?Pr(t,r):t,s=e.length-1,a;s>=0;s--)(a=e[s])&&(o=(n?a(t,r,o):a(o))||o);return n&&o&&Nr(t,r,o),o};const Ot=[],ot={}.VITE_PREVIEW==="true";function Rt(e){if(e&&!Ot.includes(e)){const t=` `;document.head.insertAdjacentHTML("beforeend",t),Ot.push(e)}}class At{root=null;banner;isFold;customElementTemplate;constructor(t){this.root=t,this.isFold=!ot&&sessionStorage.getItem(Ct)==="true",this.banner=this.root?.querySelector(`#${ft}`),this.customElementTemplate=new Z,this.init()}init(){Rt(gt),this.customElementTemplate.createBannerTemplate(this.isFold,this.banner),ot||this.registBannerEvent(),ot&&this.initPreviewEvent()}parseJson(t){return typeof t=="string"?JSON.parse(t?.replace("undefined","")):void 0}initPreviewEvent(){const t=sessionStorage.getItem("EFA_ON_STORE_BANNER_CONFIG");if(t){const r=this.parseJson(t);r&&r?.is_efa_on_store_banner_preview===!0&&(this.updateCredit(r?.text??""),this.setStyleConifg({background:r?.background??"",font:r?.font??""}))}window.addEventListener("message",r=>{if(r.origin!==window.location.origin)return;const n=this.parseJson(r.data);n&&n?.is_efa_on_store_banner_preview===!0&&(this.updateCredit(n?.text??""),this.setStyleConifg({background:n?.background??"",font:n?.font??""}))})}registBannerEvent(){const t=this.banner;t&&(t.onclick=r=>{if(!this.isFold&&r.target.className===yt.replace(".","")){const n=new I().shopInfo;window.location.href=n.goBackUrl;return}!this.isFold&&r.target.tagName==="IMG"?this.setFold(!0):this.setFold(!1)})}setFold(t){this.isFold!==t&&(this.isFold=t,this.renderBanner())}get creditText(){return this.banner?.querySelector($e)}get goBack(){return this.banner?.querySelector(yt)}renderBanner(){this.customElementTemplate.updateBannerTemplate(this.isFold,this.banner)}updateGoback(t){this.goBack&&(this.goBack.textContent=t)}updateCredit(t){this.creditText&&(this.creditText.textContent=t)}setStyleConifg(t){let r="";const n={"background-color":t?.background??"","font-family":t?.font??gt,opacity:t?.opacity??1};t?.font&&Rt(t.font);for(let o in n)r+=o+": "+n[o]+"; ";this.banner?.firstElementChild?.setAttribute("style",r)}}$r([Ze],At.prototype,"setFold",1);class _{static items=[];addToCart(t){const r=_.items.find(n=>n.external_variant_id===t.external_variant_id&&n.external_product_id===t.external_product_id);r?r.quantity+=t.quantity:_.items.push(t)}updateToCart(t){_.items=t}removeFromCart(t){_.items=_.items.filter(r=>!(r.external_variant_id===t.external_variant_id&&r.external_product_id===t.external_product_id))}static getCartTotal(){return _.items}}class Ur{subscriptions=new Map;constructor(){this.clear()}on=(t,r)=>{function n(...s){r&&r(...s)}const o=this.subscriptions?.get(t)??[];o.push(n),this.subscriptions.set(t,o)};publish=(t,...r)=>{if(typeof t=="string")this.subscriptions.get(t)?.forEach(o=>{o.apply(this,r)});else throw new TypeError("event must be string !")};removeListener=t=>{this.subscriptions.delete(t)};clear=()=>{this.subscriptions.clear()}}class Bt{emitter=null;onChange=null;constructor(t,r){this.emitter=t,this.onChange=r}}class Lr extends Bt{cart;constructor(t,r){super(t,r),this.cart=new _}register(){this.emitter?.on(u.ADD_TO_CART,t=>{this.cart.addToCart(t),this.onChange?.(u.ADD_TO_CART,t)}),this.emitter?.on(u.REMOVE_FROM_CART,t=>{this.cart.removeFromCart(t),this.onChange?.(u.REMOVE_FROM_CART,t)}),this.emitter?.on(u.UPDATE_TO_CART,t=>{this.cart.updateToCart(t),this.onChange?.(u.UPDATE_TO_CART,t)})}}class qr extends Bt{constructor(t,r){super(t,r)}register(){this.emitter?.on(u.CHECKOUT,()=>{this.onChange?.(u.CHECKOUT)}),this.emitter?.on(u.BUY_NOW,()=>{this.onChange?.(u.BUY_NOW)})}}class Mr{emitter;onChange;constructor(t){this.onChange=t,this.emitter=new Ur,this.init()}init(){this.register()}register(){[Lr,qr].forEach(t=>{new t(this.emitter,this.onChange).register()})}exportPublish(){return this.emitter.publish}}function Fr(){try{const e=J(bt);return new URLSearchParams(window.atob(e))}catch{return!1}}const jr=Boolean(Fr()),Hr=()=>{try{return!!window?.__NEXT_DATA__?.props?.initialProps?.shopHostName}catch{return!1}},zr=(e,t)=>{const r=/\${(.*?)}/g;return e?.replace?.(r,(o,s)=>t.hasOwnProperty(s)?t[s]:o)},Nt=(e,t="USD",r=!1)=>{let n="";try{n=`${new Intl.NumberFormat("en-US",{style:"currency",currency:t,currencyDisplay:"narrowSymbol"}).format(Number(e))}${r?" "+t:""}`}catch{n=`${t} ${Number(e).toFixed(2)}`}return n};class Gr{shopInfo;options;translationsData;constructor(t,r){this.shopInfo=t,this.options=r,this.init(),queueMicrotask(()=>{this.options?.onBeforeLoad?.()})}async init(){try{const t=(await Qe({orgId:this.shopInfo.orgId,language:this.shopInfo.language})).translation;this.translationsData=t,this.options?.onLoad()}catch{this.translationsData=null,this.options?.onLoad()}}run(t,r){return zr(this.translationsData?.[t]??Ue[t],r??{})??"--"}getCreditTranslation(t,r){return!t&&t!==0?this.run(A.EXCHANGE_ON_STORE_BANNER_CREDIT_USE,{RemainingCredit:"--"}):t<0?this.run(A.EXCHANGE_ON_STORE_BANNER_CREDIT_EXCHANGE,{RemainingCredit:` ${Nt(Math.abs(t),r,!0)} `}):this.run(A.EXCHANGE_ON_STORE_BANNER_CREDIT_USE,{RemainingCredit:` ${Nt(t,r,!0)} `})}getGobackTranslation(){return this.run(A.EXCHANGE_ON_STORE_BANNER_GO_BACK)}}const Xr="modulepreload",Vr=function(e){return"/"+e},Pt={},$t=function(t,r,n){return t()};var y=(e=>(e.pageEnter="page_enter",e.pageLeave="page_leave",e.UpdateProduct="click:update_product",e.ClickCheckout="click:checkout",e.ClickBuynow="click:buynow",e.APIcalculateAmount="api:calculate_amount",e.APIintention="api:intention",e))(y||{});const Wr=10;class Zr{reporter;breadcrumbCollector;initStatus="idle";retryCount=0;basicExtraData={trace_id:"",org_id:"",store:"",page_type:"shopper:efa_on_store"};pendingQueue=[];constructor(t){this.basicExtraData.trace_id=t}async init(){if(!(this.initStatus==="initialized"||this.initStatus=="preparing"))try{const{BreadcrumbCollector:t}=await $t(()=>Promise.resolve().then(()=>qn),void 0),{Reporter:r}=await $t(()=>Promise.resolve().then(()=>ws),void 0);this.reporter=new r({pageData:{appName:"returns",pageId:"EFA_ON_STORE"}}),this.breadcrumbCollector=new t({reporter:this.reporter,networkSources:["automizely"],hooks:{onCollectBreadcrumb:n=>n.extraData&&n.extraData.eventName?n:!1,onCollectNetwork:()=>!1}}),this.initStatus="initialized",this.tryReportPendingQueue()}catch{this.initStatus="failed"}}prepareClickData(t,r){const n={...this.basicExtraData,...t};return{type:"click",reportTime:this.getISODateWithTimeZone(),data:this.formatClickData(r),extraData:n}}prepareEnterData(t){const r={...this.basicExtraData,eventName:y.pageEnter,payload:t};return{type:"pageEnter",reportTime:this.getISODateWithTimeZone(),data:{},extraData:r}}preparePageLeave(t){const r={...this.basicExtraData,eventName:y.pageLeave,payload:t};return{type:"pageLeave",reportTime:this.getISODateWithTimeZone(),data:{},extraData:r}}prepareAPIData(t,r){const n={...this.basicExtraData,eventName:t,payload:r};return{type:"api",reportTime:this.getISODateWithTimeZone(),data:{},extraData:n}}tryReportPendingQueue(){this.initStatus==="initialized"&&this.pendingQueue.length>0&&(this.pendingQueue.forEach(t=>this.breadcrumbCollector.collect({...t,extraData:{...this.basicExtraData,eventName:t.extraData.eventName,...t.extraData.payload&&{payload:t.extraData.payload}}})),this.pendingQueue=[])}async reportPageEnterEvent(t){this.collect(this.prepareEnterData(t))}async reportPageLeaveEvent(t){this.collect(this.preparePageLeave(t))}async reportAPIEvent(t,r){this.collect(this.prepareAPIData(t,r))}async reportClickEvent(t,r){this.collect(this.prepareClickData(t,r))}async collect(t){this.initStatus==="idle"?this.pendingQueue.push(t):this.initStatus==="failed"?this.retryCount<=Wr&&(this.retryCount+=1,this.pendingQueue.push(t),await this.init()):this.initStatus==="preparing"?this.pendingQueue.push(t):this.initStatus==="initialized"&&this.breadcrumbCollector.collect(t)}updateExtraDataByDeviceMode(t){this.basicExtraData={...this.basicExtraData,device:t}}updateExtraDataByShopInfo(t){this.basicExtraData={...this.basicExtraData,platform:t?.platform,store:t?.appKey,org_id:t.orgId,from:t.goBackUrl}}formatClickData(t){return{path:this.formatPath(t),text:this.formatText(t)}}formatText(t){return t?.target?.innerText??""}formatPath(t){return(t?.nativeEvent?.path??[]).map(n=>`${n.tagName}${n.id?`#${n.id}`:""}${n.className?`.${n.className.split(" ").join(".")}`:""}`).filter(n=>n!=="undefined")}getISODateWithTimeZone(){const t=new Date,r=t.toISOString(),n=t.getTimezoneOffset();if(n===0)return r;const o=Math.round(Math.abs(n/60)),s=Math.round(Math.abs(n%60)),a=o<10?"0"+o:String(o),i=s<10?"0"+s:String(s),l=`${n<0?"+":"-"}${a}:${i}`;return`${r.replace("Z","")}${l}`}}function Jr(e){let r=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),n;return typeof window<"u"&&window.atob?n=decodeURIComponent(window.atob(r).split("").map(function(o){return"%"+("00"+o.charCodeAt(0).toString(16)).slice(-2)}).join("")):n=Buffer.from(r,"base64").toString(),JSON.parse(n)}let st;const Ut=()=>{const{shopInfo:e}=new I;if(e?.sessionToken)return Jr(e.sessionToken)?.trace_id};function b(){const e=Ut();return!st&&e&&(st=new Zr(Ut())),st}class Yr{toastContainer=null;customElementTemplate;constructor(){this.customElementTemplate=new Z}setToast(t){this.toastContainer=t}open(t){this.customElementTemplate.createToastTemplate(this.toastContainer,t),t?.duration&&typeof t.duration=="number"&&setTimeout(()=>{this.close()},t.duration)}close(){this.toastContainer.innerHTML=""}}const j=new Yr;class Lt{shopInfoDTO;constructor(){this.shopInfoDTO=new I}openShopperPath=()=>{location.href=this.shopInfo.shopperContinueUrl};validCurrency(){return new Promise((t,r)=>{if(this.shopInfoDTO.currency)t("");else{j.open({type:B.INFO,message:"We are processing your checkout···",duration:2e3});const n=nt?.();K(this.shopInfoDTO.shopInfo,n).then(o=>{if(n==="shopify"&&o?.currency!==(window?.Shopify?.currency?.active??"")){j.open({type:B.ERROR,message:`Switch back to ${o?.currency} before the checkout`,duration:2e3}),r("invalid currency");return}t("")}).catch(()=>{r("unknwon error")})}})}checkoutAction(){this.validCurrency().then(()=>{this.openShopperPath()})}buyNowAction(){this.validCurrency().then(()=>{this.openShopperPath()})}get shopInfo(){return this.shopInfoDTO.shopInfo}}const qt={SESSION_EXPIRED:"Session expired",API_ERROR:"API error, please contact the customer service"},Qr=e=>e.errorCode===40300?{type:"SESSION_EXPIRED",message:qt.SESSION_EXPIRED}:{type:"API_ERROR",message:qt.API_ERROR};class Kr{intention;translation=null;businessEvent;shopInfoDTO;context;returnsRecordError;platform;checkout;onEventChangeCallback;wait=null;constructor({platform:t}){this.platform=t,this.shopInfoDTO=new I,this.businessEvent=new Mr(this.onEventChange.bind(this)),this.context={isLoading:!1,isMounted:!1},this.returnsRecordError=null,this.checkout=new Lt,this.wait=this.init()}get shopInfo(){return this.shopInfoDTO.shopInfo}get providerShopInfo(){return this.shopInfoDTO.providerShopInfo}async init(){this.onErrorListener(),this.setContext({shopInfo:this.providerShopInfo,isLoading:!0});try{await K(this.shopInfo,this.platform).then(t=>{t&&(this.intention=t.intention,this.setContext({price:{amount:t.credit,currency:t.currency},cart:t.intention?.exchange_items??[],isLoading:!1}))})}catch(t){b?.()?.reportAPIEvent(y.APIcalculateAmount,{status:"fail",error:t}),this.setContext({isLoading:!1})}this.setContext({isLoading:!1,isMounted:!0}),Ye({orgId:this.shopInfo.orgId}).then(t=>{this.setContext({style:t})})}initTranslation(t){this.translation=new Gr(this.shopInfo,{onBeforeLoad:()=>{t?.onTranslationBeforeLoad?.()},onLoad:()=>{t?.onTranslationLoad?.()}})}getCreditTranslationText(t,r){return this.translation?.getCreditTranslation(t,r)??"--"}getGoBackTranslationText(){return this.translation?.getGobackTranslation()??"Go back"}async onCartChange(){if(await this.wait,this.intention?.id){const t=_.getCartTotal();this.setContext({isLoading:!0});try{await Ke({intentionId:this.intention.id,exchangeItems:t,intentionData:this.intention}),b?.()?.reportAPIEvent?.(y.APIintention,{status:"success"})}catch(r){b?.()?.reportAPIEvent?.(y.APIintention,{status:"fail",error:r}),this.setContext({isLoading:!1})}try{await K(this.shopInfo,this.platform).then(r=>{const{credit:n,currency:o,intention:s}=r??{},{exchange_items:a=[]}=s??{};this.setContext({price:{amount:n,currency:o},cart:a})}).finally(()=>{this.setContext({isLoading:!1})}),b?.()?.reportAPIEvent(y.APIcalculateAmount,{status:"success"})}catch(r){this.setContext({isLoading:!1}),b?.()?.reportAPIEvent(y.APIcalculateAmount,{status:"fail",error:r})}}}onEventChange(t,r){switch(queueMicrotask(()=>{this.onEventChangeCallback?.(t,r)}),t){case u.ADD_TO_CART:case u.REMOVE_FROM_CART:case u.UPDATE_TO_CART:this.onCartChange();break;case u.CHECKOUT:this.checkout.checkoutAction();break;case u.BUY_NOW:this.checkout.buyNowAction();break}}onErrorListener(){window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const{type:r,data:n}=t.data,o=n?.returnsAPIException;r==="returnsError"&&o&&this.setReturnsError(Qr(n))})}setReturnsError(t){this.returnsRecordError=t,this.onEventChange(u.ERROR)}setContext(t){this.context={...this.context,...t},this.onEventChange(u.ON_CONTEXT_CHANGE,this.context)}Provider(){const t=this.businessEvent.exportPublish().bind(this.businessEvent),r=h=>{this.initTranslation({onTranslationLoad:h?.onTranslationLoad})},n=h=>{t(u.ADD_TO_CART,h)},o=h=>{t(u.UPDATE_TO_CART,h)},s=h=>{t(u.REMOVE_FROM_CART,h)},a=()=>_.getCartTotal(),i=()=>{t(u.CHECKOUT)},l=h=>{t(u.UPDATE_TO_CART,[h]),i()},c=()=>{const h=new I().shopInfo;window.location.href=h.goBackUrl},f=(h,ht)=>this.getCreditTranslationText(h,ht),g=()=>this.returnsRecordError,$=()=>{const h=JSON.parse(JSON.stringify(this.context));return Object.freeze(h),h},U=h=>{this.onEventChangeCallback=h};return{publishEvent:t,addToCart:n,updateCart:o,removeFromCart:s,getContext:$,initTranslation:r.bind(this),setContext:this.setContext.bind(this),getGoBackTranslationText:this.getGoBackTranslationText.bind(this),getCreditTranslationText:f,getCart:a,goBack:c,getError:g,checkout:i,buyNow:l,setOnEventChangeCallback:U}}}const tn={}.VITE_PREVIEW==="true";class en{creditBanner=null;platform=null;shopInfoDTO;EFAController;checkout;constructor(){this.shopInfoDTO=new I,this.EFAController=new Kr({platform:nt()}),this.checkout=new Lt,this.platform=Br(this.EFAControllerProvider().publishEvent,this.shopInfo)}create(){this.platform?.create?.()}mount(){tn||(this.creditBanner?.setStyleConifg({opacity:0}),this.EFAControllerProvider().setOnEventChangeCallback(this.onEventChangeCallback.bind(this)),this.EFAController.initTranslation({onTranslationBeforeLoad:()=>{this.setDefaultCredit()},onTranslationLoad:()=>{this.setDefaultCredit(),this.creditBanner?.updateGoback(this.EFAControllerProvider().getGoBackTranslationText()),this.EFAControllerProvider().getContext()?.style||this.creditBanner?.setStyleConifg({opacity:1})}}),this.platform?.mount())}unmount(){this.platform?.unmount?.()}EFAControllerProvider(){return this.EFAController.Provider()}onEventChangeCallback(t,r){switch(t){case u.BUY_NOW:{this.checkout.buyNowAction(),b?.()?.reportClickEvent({eventName:y.ClickBuynow});break}case u.CHECKOUT:{this.checkout.checkoutAction(),b?.()?.reportClickEvent({eventName:y.ClickCheckout});break}case u.ADD_TO_CART:case u.REMOVE_FROM_CART:case u.UPDATE_TO_CART:b?.()?.reportClickEvent({eventName:y.UpdateProduct});break;case u.ON_CONTEXT_CHANGE:{this.creditBanner?.updateCredit(this.EFAControllerProvider().getCreditTranslationText(r?.price?.amount,r?.price?.currency)),r?.style&&this.creditBanner?.setStyleConifg({...r?.style??{},opacity:1});break}case u.ERROR:{const n=this.EFAControllerProvider().getError();n&&(j.open({message:"Your session expired. Please refresh and try again",type:B.ERROR,duration:2e3}),setTimeout(()=>{location.href=this.shopInfo?.shopperHomeUrl},2e3)),n||this.creditBanner?.setStyleConifg({opacity:1});break}}}get shopInfo(){return this.shopInfoDTO.shopInfo}setDefaultCredit(){this.updateCredit(this.EFAControllerProvider().getCreditTranslationText())}updateCredit(t){this.creditBanner?.updateCredit(t)}setCreditBanner(t){this.creditBanner=t}}class rn extends HTMLElement{creditBanner;container;constructor(){super(),this.attachShadow({mode:"open"}),this.container=new en,window.addEventListener("unload",()=>{this.container?.unmount()}),this?.create?.()}create(){this.container?.create()}mount(){this.container?.mount()}unmount(){this.container?.unmount()}connectedCallback(){this.shadowRoot&&(new Z().createRootTemplate(this.shadowRoot),this.creditBanner=new At(this.shadowRoot.getElementById(dt)),this.container?.setCreditBanner(this.creditBanner),j.setToast(this.shadowRoot.getElementById(mt)),this?.mount?.())}appendShadowRootChild(t){this.shadowRoot?.appendChild(t)}disconnectedCallback(){this?.unmount?.()}}const nn={}.VITE_PREVIEW==="true",on=999;class sn{init(){const t=Hr();if(document.getElementsByTagName("credit-banner").length===0&&jr&&!t||nn){const r=document.createElement("credit-banner");r.setAttribute("style",`z-index: ${on}; position: fixed; display: unset;`),document.body.appendChild(r),customElements.define("credit-banner",rn)}}}let Mt;function an(){b?.()?.updateExtraDataByShopInfo(new I().shopInfo),b?.()?.init(),b?.()?.reportPageEnterEvent({origin:location.origin}),Mt=new sn,Mt.init()}try{an()}catch(e){console.log(e)}var H=(e=>(e.errors="errors",e.breadcrumbs="breadcrumbs",e.performances="performances",e))(H||{});const Ft=()=>({reportURL:"https://www.automizely-analytics.com"}),jt=3*1e3,Ht=100*300,zt=10*1e3,Gt=30*1e3,Xt=`${Ft().reportURL}/perf-reports`,Vt=`${Ft().reportURL}/perf-report-settings`,at={reportBreadcrumbs:!1,reportErrors:!1,reportPerformances:!1,reportWebVitals:!1,samplingRatio:0,maxSamples:0},k=e=>{const t=e.toISOString(),r=e.getTimezoneOffset();if(r===0)return t;const n=Math.round(Math.abs(r/60)),o=Math.round(Math.abs(r%60)),s=n<10?"0"+n:String(n),a=o<10?"0"+o:String(o),i=`${r<0?"+":"-"}${s}:${a}`;return`${t.replace("Z","")}${i}`};var cn=typeof global=="object"&&global&&global.Object===Object&&global;const un=cn;var ln=typeof self=="object"&&self&&self.Object===Object&&self,hn=un||ln||Function("return this")();const Wt=hn;var pn=Wt.Symbol;const x=pn;var Zt=Object.prototype,dn=Zt.hasOwnProperty,fn=Zt.toString,P=x?x.toStringTag:void 0;function mn(e){var t=dn.call(e,P),r=e[P];try{e[P]=void 0;var n=!0}catch{}var o=fn.call(e);return n&&(t?e[P]=r:delete e[P]),o}var gn=Object.prototype,yn=gn.toString;function bn(e){return yn.call(e)}var Cn="[object Null]",_n="[object Undefined]",Jt=x?x.toStringTag:void 0;function En(e){return e==null?e===void 0?_n:Cn:Jt&&Jt in Object(e)?mn(e):bn(e)}function wn(e){return e!=null&&typeof e=="object"}var vn="[object Symbol]";function Yt(e){return typeof e=="symbol"||wn(e)&&En(e)==vn}var Sn=Object.defineProperty,In=(e,t,r)=>t in e?Sn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,D=(e,t,r)=>(In(e,typeof t!="symbol"?t+"":t,r),r),O=(e=>(e.Click="click",e.Scroll="scroll",e.Network="network",e.Input="input",e))(O||{});const Qt=1e3,Kt=1e3;var kn=/\s/;function Tn(e){for(var t=e.length;t--&&kn.test(e.charAt(t)););return t}var xn=/^\s+/;function Dn(e){return e&&e.slice(0,Tn(e)+1).replace(xn,"")}function it(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var te=0/0,On=/^[-+]0x[0-9a-f]+$/i,Rn=/^0b[01]+$/i,An=/^0o[0-7]+$/i,Bn=parseInt;function ee(e){if(typeof e=="number")return e;if(Yt(e))return te;if(it(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=it(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=Dn(e);var r=Rn.test(e);return r||An.test(e)?Bn(e.slice(2),r?2:8):On.test(e)?te:+e}var Nn=function(){return Wt.Date.now()};const ct=Nn;var Pn="Expected a function",$n=Math.max,Un=Math.min;function re(e,t,r){var n,o,s,a,i,l,c=0,f=!1,g=!1,$=!0;if(typeof e!="function")throw new TypeError(Pn);t=ee(t)||0,it(r)&&(f=!!r.leading,g="maxWait"in r,s=g?$n(ee(r.maxWait)||0,t):s,$="trailing"in r?!!r.trailing:$);function U(p){var S=n,L=o;return n=o=void 0,c=p,a=e.apply(L,S),a}function h(p){return c=p,i=setTimeout(V,t),f?U(p):a}function ht(p){var S=p-l,L=p-c,Pe=t-S;return g?Un(Pe,s-L):Pe}function Be(p){var S=p-l,L=p-c;return l===void 0||S>=t||S<0||g&&L>=s}function V(){var p=ct();if(Be(p))return Ne(p);i=setTimeout(V,ht(p))}function Ne(p){return i=void 0,$&&n?U(p):(n=o=void 0,a)}function vs(){i!==void 0&&clearTimeout(i),c=0,n=l=o=i=void 0}function Ss(){return i===void 0?a:Ne(ct())}function pt(){var p=ct(),S=Be(p);if(n=arguments,o=this,l=p,S){if(i===void 0)return h(l);if(g)return clearTimeout(i),i=setTimeout(V,t),U(l)}return i===void 0&&(i=setTimeout(V,t)),a}return pt.cancel=vs,pt.flush=Ss,pt}const z={data:[],push(e){this.data.push(e)}};(()=>{const e=window.fetch,t=async(r,n)=>{var o,s;const a=new Date;let i;try{i=await e(r,n)}catch{i={status:0}}const l=new Date,c=k(l),{status:f}=i;return z.push({type:O.Network,data:{status:f,url:(o=r?.url)!=null?o:r.toString(),startTime:k(a),endTime:c,duration:l.getTime()-a.getTime(),method:(s=n?.method)!=null?s:"GET"},reportTime:c,extraData:{}}),i.status,i};window.fetch=t})();const ne=e=>e.map(t=>`${t.tagName}${t.id?`#${t.id}`:""}${t.className?`.${t.className.split(" ").join(".")}`:""}`).filter(t=>t!=="undefined");class Ln{constructor({hooks:t,reporter:r,networkSources:n,excludeNetworkSources:o,scrollDebounce:s=Qt,inputDebounce:a=Kt}){D(this,"reporter"),D(this,"hooks"),D(this,"scrollDebounce"),D(this,"inputDebounce"),D(this,"networkSources"),D(this,"excludeNetworkSources"),this.networkSources=n,this.excludeNetworkSources=[...o??[],"https://www.automizely-analytics.io"],this.scrollDebounce=s,this.inputDebounce=a,this.reporter=r,this.hooks=t,this.collectNetwork(),this.collectClick(),this.collectScroll(),this.collectInput()}collectNetwork(){const t=r=>{var n;if(!(this.excludeNetworkSources.some(o=>r.data.url.match(o))||!this.networkSources.some(o=>r.data.url.match(o)))){if((n=this.hooks)!=null&&n.onCollectNetwork){const o=this.hooks.onCollectNetwork(r);if(!o)return;r=o}this.collect(r)}};z.push=t,z.data.forEach(t),z.data=[]}collectInput(){const t=re(r=>{this.collect({type:O.Input,data:r,extraData:{},reportTime:k(new Date)})},this.inputDebounce);document.addEventListener("input",r=>{var n,o;t({path:r.path?ne(r.path):[],value:(o=(n=r.target)==null?void 0:n.value)!=null?o:""})})}collectClick(){document.addEventListener("click",t=>{var r;this.collect({type:O.Click,data:{path:t.path?ne(t.path):[],text:(r=t.target)==null?void 0:r.innerText},extraData:{},reportTime:k(new Date)})})}collectScroll(){const t={deltaX:0,deltaY:0,deltaZ:0},r=re(n=>{this.collect({type:O.Scroll,data:n,extraData:{},reportTime:k(new Date)}),t.deltaX=0,t.deltaY=0,t.deltaZ=0},this.scrollDebounce);document.addEventListener("touchstart",n=>{var o,s;const{pageX:a,pageY:i}=(s=(o=n.changedTouches)==null?void 0:o[0])!=null?s:{};a===void 0||i===void 0||(t.deltaX=a,t.deltaY=i)}),document.addEventListener("touchend",n=>{var o,s;const{pageX:a,pageY:i}=(s=(o=n.changedTouches)==null?void 0:o[0])!=null?s:{};if(a===void 0||i===void 0)return;const l=t.deltaX-a,c=t.deltaY-i;l===0&&c===0||r({deltaX:l,deltaY:c,deltaZ:0})}),document.addEventListener("wheel",n=>{r({deltaX:n.deltaX,deltaY:n.deltaY,deltaZ:n.deltaZ})})}collect(t){var r,n,o;if(t.reportTime||(t.reportTime=k(new Date)),(r=this.hooks)!=null&&r.onCollectBreadcrumb){const s=(o=(n=this.hooks)==null?void 0:n.onCollectBreadcrumb)==null?void 0:o.call(n,t);if(!s)return;t=s}this.reporter.push(H.breadcrumbs,t)}}const qn=Object.freeze(Object.defineProperty({__proto__:null,BreadcrumbCollector:Ln,BreadcrumbType:O,InputDebounceDefaultValue:Kt,ScrollDebounceDefaultValue:Qt},Symbol.toStringTag,{value:"Module"}));var Mn=Object.defineProperty,Fn=(e,t,r)=>t in e?Mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,m=(e,t,r)=>(Fn(e,typeof t!="symbol"?t+"":t,r),r);function jn(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++ro?0:o+t),r=r>o?o:r,r<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var s=Array(o);++n=n?e:Xn(e,t,r)}var Wn="\\ud800-\\udfff",Zn="\\u0300-\\u036f",Jn="\\ufe20-\\ufe2f",Yn="\\u20d0-\\u20ff",Qn=Zn+Jn+Yn,Kn="\\ufe0e\\ufe0f",to="\\u200d",eo=RegExp("["+to+Wn+Qn+Kn+"]");function ie(e){return eo.test(e)}function ro(e){return e.split("")}var ce="\\ud800-\\udfff",no="\\u0300-\\u036f",oo="\\ufe20-\\ufe2f",so="\\u20d0-\\u20ff",ao=no+oo+so,io="\\ufe0e\\ufe0f",co="["+ce+"]",ut="["+ao+"]",lt="\\ud83c[\\udffb-\\udfff]",uo="(?:"+ut+"|"+lt+")",ue="[^"+ce+"]",le="(?:\\ud83c[\\udde6-\\uddff]){2}",he="[\\ud800-\\udbff][\\udc00-\\udfff]",lo="\\u200d",pe=uo+"?",de="["+io+"]?",ho="(?:"+lo+"(?:"+[ue,le,he].join("|")+")"+de+pe+")*",po=de+pe+ho,fo="(?:"+[ue+ut+"?",ut,le,he,co].join("|")+")",mo=RegExp(lt+"(?="+lt+")|"+fo+po,"g");function go(e){return e.match(mo)||[]}function yo(e){return ie(e)?go(e):ro(e)}function bo(e){return function(t){t=G(t);var r=ie(t)?yo(t):void 0,n=r?r[0]:t.charAt(0),o=r?Vn(r,1).join(""):t.slice(1);return n[e]()+o}}var Co=bo("toUpperCase");const _o=Co;function Eo(e){return _o(G(e).toLowerCase())}function wo(e,t,r,n){var o=-1,s=e==null?0:e.length;for(n&&s&&(r=e[++o]);++o{try{const t=await fetch(`${Vt}?app-name=${e}`).then(r=>r.json());if(!(t!=null&&t.data))throw"Failed to get online setting";return{reportBreadcrumbs:t.data.report_breadcrumbs,reportErrors:t.data.report_errors,reportPerformances:t.data.report_performances,reportWebVitals:t.data.report_web_vitals,samplingRatio:t.data.sampling_ratio,maxSamples:t.data.max_samples}}catch(t){return console.error(t),at}};let X;const ms=new Uint8Array(16);function gs(){if(!X&&(X=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!X))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return X(ms)}const d=[];for(let e=0;e<256;++e)d.push((e+256).toString(16).slice(1));function ys(e,t=0){return(d[e[t+0]]+d[e[t+1]]+d[e[t+2]]+d[e[t+3]]+"-"+d[e[t+4]]+d[e[t+5]]+"-"+d[e[t+6]]+d[e[t+7]]+"-"+d[e[t+8]]+d[e[t+9]]+"-"+d[e[t+10]]+d[e[t+11]]+d[e[t+12]]+d[e[t+13]]+d[e[t+14]]+d[e[t+15]]).toLowerCase()}const bs=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Re={randomUUID:bs};function Cs(e,t,r){if(Re.randomUUID&&!t&&!e)return Re.randomUUID();e=e||{};const n=e.random||(e.rng||gs)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){r=r||0;for(let o=0;o<16;++o)t[r+o]=n[o];return t}return ys(n)}const _s=e=>{var t,r;return{url:window.location.href,enterTime:k(new Date),shopifyStore:(r=(t=window.Shopify)==null?void 0:t.shop)!=null?r:null,sessionId:Cs(),...e}},Ae=e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[ds(t),r]));class Es{constructor({reportInterval:t=jt,reportSize:r=Ht,checkReportInterval:n=zt,reportURL:o=Xt,pageData:s,hooks:a}){m(this,"queue",[]),m(this,"queueSize",0),m(this,"reportInterval"),m(this,"reportURL"),m(this,"pageData"),m(this,"reportSize"),m(this,"checkReportInterval"),m(this,"onlineSetting",at),m(this,"hooks"),m(this,"isInSample",!1),m(this,"hasSetInSample",!1),m(this,"sentEventCount",0),this.checkReportInterval=Math.max(n,Gt),this.reportInterval=t,this.reportSize=r,this.reportURL=o,this.pageData=_s(s),this.reportInIntervals(),this.hooks=a??{},this.checkReport(),this.reportInIntervals()}checkReport(){fs(this.pageData.appName).then(t=>{this.onlineSetting=t,!this.hasSetInSample&&(this.hasSetInSample=!0,this.isInSample=Math.random()<=this.onlineSetting.samplingRatio)}),setTimeout(()=>{!this.isInSample||this.checkReport()},this.checkReportInterval)}reportInIntervals(){setTimeout(()=>{this.report(),this.reportInIntervals()},this.reportInterval)}push(t,r){var n,o,s;const a=((s=(o=(n=this.hooks).onPush)==null?void 0:o.call(n,t,r))!=null?s:[{type:t,data:r}]).map(i=>{const l=JSON.stringify(Ae(i.data));return this.queueSize+=l.length,{...i,data:l}});this.queue.push(...a),this.queueSize>this.reportSize&&this.report()}getDataToReport(){const t=Object.fromEntries(Object.keys(H).map(r=>[r,[]]));return this.queue.forEach(({type:r,data:n})=>{!this.onlineSetting[`report${Eo(r)}`]||t[r].push(n)}),t}checkAndClearQueueSize(){for(;this.queueSize>this.reportSize;){const t=this.queue.shift();if(!t)break;this.queueSize-=t.data.length}}sendReport(t){return t.breadcrumbs||(t.breadcrumbs=[]),t.errors||(t.errors=[]),t.performances||(t.performances=[]),navigator.sendBeacon(this.reportURL,`{"page":${JSON.stringify(Ae(this.pageData))},${Object.entries(t).map(([r,n])=>`"${r}":[${n.join(",")}]`).join(",")}}`)}report(){var t,r;if(!this.isInSample||this.queue.length===0)return;const n=this.getDataToReport(),o=Object.values(n).flat();if(o.length===0)return this.checkAndClearQueueSize();this.sentEventCount+=o.length,!(this.sentEventCount>=this.onlineSetting.maxSamples)&&((r=(t=this.hooks).onReport)==null||r.call(t,n),this.queue=[],this.queueSize=0,this.sendReport(n))}}const ws=Object.freeze(Object.defineProperty({__proto__:null,DefaultCheckReportInterval:zt,DefaultOnlineSettings:at,DefaultReportInterval:jt,DefaultReportSize:Ht,DefaultReportURL:Xt,MaxCheckReportInterval:Gt,ReportType:H,Reporter:Es,getSettingURL:Vt},Symbol.toStringTag,{value:"Module"}))})();