(()=>{"use strict";const e={API_BASE:"https://webhooks.myperfit.net/track",API_REGISTER_DOMAIN:"https://webhooks.myperfit.net/events/domains/generic/all/3a2e8954/3e2a1161",API_PUSH_SUBSCRIPTION:"https://webhooks.myperfit.net/events/push/generic/subscription/4rt3tmrgre/f5518f90",OPTIN_RULES_API:"https://optinrules.myperfit.net/optinrules/public",app:"",source:"",trackCartUpdates:!1,loadOptinRules:!0},t="PerfitDebugMode";let n=!1;function r(e){if(n){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i1&&(s.privateKey=a[1]),s}async function c(e,t){const n=[],r=await crypto.subtle.exportKey("jwk",e),i=o(r.x),a=o(r.y),s=new Uint8Array(65);if(s.set([4],0),s.set(i,1),s.set(a,33),n.push(s),t){const e=await crypto.subtle.exportKey("jwk",t);n.push(o(e.d))}const c=await Promise.all(n),d={publicKey:c[0]};return c.length>1&&(d.privateKey=c[1]),d}function d(){return crypto.getRandomValues(new Uint8Array(16))}const l={publicKey:"BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXKpNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo",privateKey:"xKZKYRNdFFn8iQIF2MH54KTfUHwH105zBdzMR7SI3xI"};new URLSearchParams(window.location.search).get("backend");class u{static async createVapidAuthHeader(e,t,n,r){if(!t)return Promise.reject(new Error("Audience must be the origin of the server"));if(!n)return Promise.reject(new Error("Subject must be either a mailto or http link"));"number"!=typeof r&&(r=Math.floor(Date.now()/1e3+43200));const a=o(e.publicKey),s=o(e.privateKey),c={aud:t=new URL(t).origin,exp:r,sub:n},d=new TextEncoder("utf-8"),l=i(d.encode(JSON.stringify({typ:"JWT",alg:"ES256"})))+"."+i(d.encode(JSON.stringify(c))),u={kty:"EC",crv:"P-256",x:i(a.subarray(1,33)),y:i(a.subarray(33,65)),d:i(s)},p=await crypto.subtle.importKey("jwk",u,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),y=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},p,d.encode(l));return{Authorization:"WebPush "+(l+"."+i(new Uint8Array(y))),"Crypto-Key":`p256ecdsa=${i(a)}`}}}class p{constructor(e){this._ikm=e}async sign(e){const t=await crypto.subtle.importKey("raw",this._ikm,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return crypto.subtle.sign("HMAC",t,e)}}class y{constructor(e,t){this._ikm=e,this._salt=t,this._hmac=new p(t)}async generate(e,t){const n=new Uint8Array(e.byteLength+1);n.set(e,0),n.set(new Uint8Array(1).fill(1),e.byteLength);const r=await this._hmac.sign(this._ikm),i=new p(r);return(await i.sign(n)).slice(0,t)}}class h{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._b64ServerKeys=e.serverKeys,this._b64Salt=e.salt,this._b4VapidKeys=e.vapidKeys}getServerKeys(){return this._b64ServerKeys?s(o(this._b64ServerKeys.publicKey),o(this._b64ServerKeys.privateKey)):h.generateServerKeys()}getSalt(){return this._b64Salt?o(this._b64Salt):d()}getVapidKeys(){return this._b4VapidKeys?this._b4VapidKeys:l}async getRequestDetails(e,t){const n=await u.createVapidAuthHeader(this.getVapidKeys(),e.endpoint,"mailto:simple-push-demo@gauntface.co.uk"),r=await this.encryptPayload(e,t);let i=null;const o={TTL:60};r?(i=r.cipherText,o.Encryption=`salt=${r.salt}`,o["Crypto-Key"]=`dh=${r.publicServerKey}`,o["Content-Encoding"]="aesgcm"):o["Content-Length"]=0,n&&Object.keys(n).forEach((e=>{o[e]?o[e]=`${o[e]}; ${n[e]}`:o[e]=n[e]}));const a={headers:o,endpoint:e.endpoint};return i&&(a.body=i),a}async encryptPayload(e,t){if(!t||0===t.trim().length)return Promise.resolve(null);const n=this.getSalt(),r=await this.getServerKeys(),o=await c(r.publicKey),a=await this._generateEncryptionKeys(e,n,r),s=await crypto.subtle.importKey("raw",a.contentEncryptionKey,"AES-GCM",!0,["decrypt","encrypt"]);a.contentEncryptionCryptoKey=s;const d=new Uint8Array(2),l=new TextEncoder("utf-8").encode(t),u=new Uint8Array(d.byteLength+l.byteLength);u.set(d,0),u.set(l,d.byteLength);const p={name:"AES-GCM",tagLength:128,iv:a.nonce};return{cipherText:await crypto.subtle.encrypt(p,a.contentEncryptionCryptoKey,u),salt:i(n),publicServerKey:i(o.publicKey)}}static generateServerKeys(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"])}async _generateEncryptionKeys(e,t,n){const r=await Promise.all([this._generatePRK(e,n),this._generateCEKInfo(e,n),this._generateNonceInfo(e,n)]),i=r[0],o=r[1],a=r[2],s=new y(i,t),c=new y(i,t),d=await Promise.all([s.generate(o,16),c.generate(a,12)]);return{contentEncryptionKey:d[0],nonce:d[1]}}async _generateContext(e,t){const n={clientPublicKey:(await s(e.getKey("p256dh"))).publicKey,serverPublicKey:t.publicKey},r=await Promise.all([c(n.clientPublicKey),c(n.serverPublicKey)]),i={clientPublicKey:r[0].publicKey,serverPublicKey:r[1].publicKey},o=new TextEncoder("utf-8").encode("P-256"),d=new Uint8Array(1).fill(0),l=new Uint8Array(2);l[0]=0,l[1]=i.clientPublicKey.byteLength;const u=new Uint8Array(2);return u[0]=0,u[1]=i.serverPublicKey.byteLength,a([o,d,l,i.clientPublicKey,u,i.serverPublicKey])}async _generateCEKInfo(e,t){return a([new TextEncoder("utf-8").encode("Content-Encoding: aesgcm"),new Uint8Array(1).fill(0),await this._generateContext(e,t)])}async _generateNonceInfo(e,t){return a([new TextEncoder("utf-8").encode("Content-Encoding: nonce"),new Uint8Array(1).fill(0),await this._generateContext(e,t)])}async _generatePRK(e,t){const n=await this._getSharedSecret(e,t),r=new TextEncoder("utf-8").encode("Content-Encoding: auth\0");return new y(n,e.getKey("auth")).generate(r,32)}async _getSharedSecret(e,t){const n=await s(e.getKey("p256dh"));if(!(n.publicKey instanceof CryptoKey))throw new Error("The publicKey must be a CryptoKey.");const r={name:"ECDH",namedCurve:"P-256",public:n.publicKey};return crypto.subtle.deriveBits(r,t.privateKey,256)}}class g{static async createVapidAuthHeader(e,t,n,r){if(!t)return Promise.reject(new Error("Audience must be the origin of the server"));if(!n)return Promise.reject(new Error("Subject must be either a mailto or http link"));"number"!=typeof r&&(r=Math.floor(Date.now()/1e3+43200));const a=o(e.publicKey),s=o(e.privateKey),c={aud:t=new URL(t).origin,exp:r,sub:n},d=new TextEncoder("utf-8"),l=i(d.encode(JSON.stringify({typ:"JWT",alg:"ES256"})))+"."+i(d.encode(JSON.stringify(c))),u={kty:"EC",crv:"P-256",x:i(a.subarray(1,33)),y:i(a.subarray(33,65)),d:i(s)},p=await crypto.subtle.importKey("jwk",u,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]),y=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},p,d.encode(l));return{Authorization:`vapid t=${l+"."+i(new Uint8Array(y))}, k=${i(a)}`}}}class f{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._b64ServerKeys=e.serverKeys,this._b64Salt=e.salt,this._b4VapidKeys=e.vapidKeys}getServerKeys(){return this._b64ServerKeys?s(o(this._b64ServerKeys.publicKey),o(this._b64ServerKeys.privateKey)):f.generateServerKeys()}getSalt(){return this._b64Salt?o(this._b64Salt):d()}getVapidKeys(){return this._b4VapidKeys?this._b4VapidKeys:l}async getRequestDetails(e,t){const n=g,r=e.endpoint,i=await n.createVapidAuthHeader(this.getVapidKeys(),e.endpoint,"mailto:simple-push-demo@gauntface.co.uk"),o=await this.encryptPayload(e,t);let a=null;const s={TTL:60};o?(a=o.cipherText,s["Content-Encoding"]="aes128gcm"):s["Content-Length"]=0,i&&Object.keys(i).forEach((e=>{s[e]=i[e]}));const c={headers:s,endpoint:r};return a&&(c.body=a),c}async encryptPayload(e,t){if(!t||0===t.trim().length)return Promise.resolve(null);const n=this.getSalt(),r=await this.getServerKeys(),o=await c(r.publicKey),s=await this._generateEncryptionKeys(e,n,r),d=await crypto.subtle.importKey("raw",s.contentEncryptionKey,"AES-GCM",!0,["decrypt","encrypt"]);s.contentEncryptionCryptoKey=d;const l=new TextEncoder("utf-8").encode(t),u=new Uint8Array(1);u.fill(0),u[0]=2;const p=a([l,u]),y={name:"AES-GCM",tagLength:128,iv:s.nonce},h=await crypto.subtle.encrypt(y,s.contentEncryptionCryptoKey,p);return{cipherText:await this._addEncryptionContentCodingHeader(h,r,n),salt:i(n),publicServerKey:i(o.publicKey)}}static generateServerKeys(){return crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"])}async _addEncryptionContentCodingHeader(e,t,n){const r=await c(t.publicKey),i=new Uint8Array([0,0,16,0]),o=new Uint8Array(1);return o[0]=r.publicKey.byteLength,a([n,i,o,r.publicKey,new Uint8Array(e)]).buffer}async _generateEncryptionKeys(e,t,n){const r=await Promise.all([this._generatePRK(e,n),this._generateCEKInfo(e,n),this._generateNonceInfo(e,n)]),i=r[0],o=r[1],a=r[2],s=new y(i,t),c=new y(i,t),d=await Promise.all([s.generate(o,16),c.generate(a,12)]);return{contentEncryptionKey:d[0],nonce:d[1]}}_generateCEKInfo(){return a([new TextEncoder("utf-8").encode("Content-Encoding: aes128gcm"),new Uint8Array(1).fill(0)])}_generateNonceInfo(){return a([new TextEncoder("utf-8").encode("Content-Encoding: nonce"),new Uint8Array(1).fill(0)])}async _generatePRK(e,t){const n=await this._getSharedSecret(e,t),r=await this._getKeyInfo(e,t);return new y(n,e.getKey("auth")).generate(r,32)}async _getSharedSecret(e,t){const n=await s(e.getKey("p256dh"));if(!(n.publicKey instanceof CryptoKey))throw new Error("The publicKey must be a CryptoKey.");const r={name:"ECDH",namedCurve:"P-256",public:n.publicKey};return crypto.subtle.deriveBits(r,t.privateKey,256)}async _getKeyInfo(e,t){const n=new TextEncoder("utf-8"),r=await c(t.publicKey);return a([n.encode("WebPush: info"),new Uint8Array(1).fill(0),new Uint8Array(e.getKey("p256dh")),r.publicKey])}}class m{static supportedEncodings(){return PushManager.supportedContentEncodings?PushManager.supportedContentEncodings:["aes128gcm"]}static generateHelper(){const e=this.supportedEncodings();for(const t of e)switch(t){case"aes128gcm":return new f;case"aesgcm":return new h;default:console.warn(`Unknown content encoding: ${t}`)}throw console.error("Failed to find a known encoding: ",e),new Error("Unable to find a known encoding")}}class w{constructor(e,t,n){this._stateChangeCb=e,this._subscriptionUpdate=t,this._publicApplicationKey=o(n),this._state={UNSUPPORTED:{id:"UNSUPPORTED",interactive:!1,pushEnabled:!1},INITIALISING:{id:"INITIALISING",interactive:!1,pushEnabled:!1},PERMISSION_DENIED:{id:"PERMISSION_DENIED",interactive:!1,pushEnabled:!1},PERMISSION_GRANTED:{id:"PERMISSION_GRANTED",interactive:!0},PERMISSION_PROMPT:{id:"PERMISSION_PROMPT",interactive:!0,pushEnabled:!1},ERROR:{id:"ERROR",interactive:!1,pushEnabled:!1},STARTING_SUBSCRIBE:{id:"STARTING_SUBSCRIBE",interactive:!1,pushEnabled:!0},SUBSCRIBED:{id:"SUBSCRIBED",interactive:!0,pushEnabled:!0},STARTING_UNSUBSCRIBE:{id:"STARTING_UNSUBSCRIBE",interactive:!1,pushEnabled:!1},UNSUBSCRIBED:{id:"UNSUBSCRIBED",interactive:!0,pushEnabled:!1}},"serviceWorker"in navigator?"PushManager"in window?"showNotification"in ServiceWorkerRegistration.prototype?this.init():this._stateChangeCb(this._state.UNSUPPORTED,"Showing Notifications from a service worker is not available on this browser"):this._stateChangeCb(this._state.UNSUPPORTED,"PushManager not available on this browser"):this._stateChangeCb(this._state.UNSUPPORTED,"Service worker not available on this browser")}async init(){await navigator.serviceWorker.ready,this._stateChangeCb(this._state.INITIALISING),this.setUpPushPermission()}_permissionStateChange(e){switch(e){case"denied":this._stateChangeCb(this._state.PERMISSION_DENIED);break;case"granted":this._stateChangeCb(this._state.PERMISSION_GRANTED);break;case"default":this._stateChangeCb(this._state.PERMISSION_PROMPT);break;default:console.error("Unexpected permission state: ",e)}}async setUpPushPermission(){try{this._permissionStateChange(Notification.permission);const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();if(this._subscriptionUpdate(t),!t)return;this._stateChangeCb(this._state.SUBSCRIBED)}catch(e){console.error("setUpPushPermission() ",e),this._stateChangeCb(this._state.ERROR,e)}}async subscribeDevice(){this._stateChangeCb(this._state.STARTING_SUBSCRIBE);try{switch(Notification.permission){case"denied":throw new Error("Push messages are blocked.");case"granted":break;default:await new Promise(((e,t)=>{Notification.requestPermission((n=>{"granted"!==n&&t(new Error("Bad permission result")),e()}))}))}try{const e=await navigator.serviceWorker.ready,t=await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this._publicApplicationKey});this._stateChangeCb(this._state.SUBSCRIBED),this._subscriptionUpdate(t)}catch(e){console.error("subscribeDevice() ",e),this._stateChangeCb(this._state.ERROR,e)}}catch(e){console.error("subscribeDevice() ",e),this._permissionStateChange(Notification.permission)}}async unsubscribeDevice(){this._stateChangeCb(this._state.STARTING_UNSUBSCRIBE);try{const e=await navigator.serviceWorker.ready,t=await e.pushManager.getSubscription();if(!t)return this._stateChangeCb(this._state.UNSUBSCRIBED),void this._subscriptionUpdate(null);await t.unsubscribe()||console.warn("We were unable to unregister from push"),this._stateChangeCb(this._state.UNSUBSCRIBED),this._subscriptionUpdate(null)}catch(e){console.error("Error thrown while revoking push notifications. Most likely because push was never registered",e)}}}function b(e,t){let n=t;return window.location.href.indexOf(e)>-1&&(n=function(){const e={};return window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,(function(t,n,r){return e[n]=r,r})),e}()[e]),n}function _(e){return`app-738-${e}`}function v(e){try{const t=_(e),n=localStorage.getItem(t);if(!n)return null;const r=JSON.parse(n);return r.ttl&&Date.now()>r.ttl?(localStorage.removeItem(t),null):r.value}catch(t){return console.error(`[getLocalStorageItem] Error reading ${e}:`,t),null}}function S(e,t,n){try{const r=_(e),i={value:t,ttl:n?Date.now()+24*n*60*60*1e3:0};localStorage.setItem(r,JSON.stringify(i))}catch(t){console.error(`[setLocalStorageItem] Error writing ${e}:`,t)}}const I=[{cookieName:"perfit-cart",localStorageKey:"p-cart",ttlDays:7},{cookieName:"p-customer",localStorageKey:"p-customer",ttlDays:365},{cookieName:"p-contact",localStorageKey:"p-contact",ttlDays:365},{cookieName:"p-last-cart",localStorageKey:"p-last-cart",ttlDays:7},{cookieName:"p-visitor-anon",localStorageKey:"p-visitor-anon",ttlDays:365},{cookieName:"p-visitor-id",localStorageKey:"p-visitor-id",ttlDays:365}];function E(e){let t=v(e);if(null!==t)return t;const n=I.find((t=>t.localStorageKey===e));if(n){const t=function(e){for(var t=e+"=",n=document.cookie.split(";"),r=0;r0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];"vtex"===e.source&&(t.product_id=t.product_id||k.getPageProductId(),t.category_id=t.category_id||k.getPageCategoryId()),(t.product_id||t.category_id)&&(n&&(C=!1),C&&t.product_id===C.product_id&&t.category_id===C.category_id||function(e){P&&clearInterval(P),C={product_id:e.product_id||void 0,category_id:e.category_id||void 0},K=0,N(),T()&&(P=setInterval(N,5e3))}(t))}function N(){A("visit",{...C,customer_id:O.customerId||void 0,contact_id:O.contactId||void 0,email:O.email||void 0,visitor_id:O.visitorId,secs_lapsed:5*K,timestamp:(new Date).toISOString()}),K++,K>5&&(clearInterval(P),C=null)}const k={getPageProductId:function(){if(dataLayer)return dataLayer.find((e=>"Product"===e.pageCategory))?.productId||dataLayer.find((e=>"productDetail"==e.event))?.ecommerce.detail?.products[0]?.id},getPageCategoryId:function(){if(dataLayer)return dataLayer.find((e=>"Product"===e.pageCategory))?.productCategoryId||dataLayer.find((e=>"categoryView"==e.event))?.categoryId},getUserEmail:function(){if(dataLayer)return dataLayer.find((e=>e.visitorLoginState))?.visitorContactInfo?.[0]||dataLayer.find((e=>"userData"==e.event))?.userId},listenUrlChanges:function(){try{const e=()=>{setTimeout((()=>{R(),U({},!1)}),2e3)};window.addEventListener("pushstate",e),window.addEventListener("popstate",e)}catch(e){console.error("Perfit: could not attach to listen url changes")}}},O={contactId:null,customerId:null,email:null,visitorId:null};function R(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};"vtex"===e.source&&(t.email=t.email||k.getUserEmail()),t.customer_id&&(O.customerId=t.customer_id),t.email&&(O.email=t.email),L(),O.customerId&&S("p-customer",O.customerId,365)}function T(){return O.contactId||O.customerId||O.email}function L(){localStorage.setItem("perfit-session",JSON.stringify(O))}function A(t,n){const r=`${e.API_BASE}/${e.source}/${e.app}/${t}`;fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:t,data:n})})}function D(){fetch(e.API_REGISTER_DOMAIN,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:e.app,domain:window.location.origin})})}class x{constructor(){this._encryptionHelper=m.generateHelper(),this._stateChangeListener=this._stateChangeListener.bind(this),this._subscriptionUpdate=this._subscriptionUpdate.bind(this),this._pushClient=new w(this._stateChangeListener,this._subscriptionUpdate,l.publicKey)}async subscribe(){await this._pushClient.subscribeDevice()}registerServiceWorker(){"serviceWorker"in navigator?navigator.serviceWorker.register("/sw.js").then((e=>{console.debug("serviceWorker registered")})).catch((e=>{console.error(e),this.showErrorMessage("Unable to Register SW","Sorry this demo requires a service worker to work and it failed to install - sorry :(")})):this.showErrorMessage("Service Worker Not Supported","Sorry this demo requires service worker support in your browser. Please try this demo in Chrome or Firefox Nightly.")}_stateChangeListener(e,t){switch(console.log("_stateChangeListener",e),e.id){case"UNSUPPORTED":this.showErrorMessage("Push Not Supported",t);break;case"ERROR":this.showErrorMessage("Ooops a Problem Occurred",t)}}_subscriptionUpdate(t){if(this._currentSubscription=t,!t)return;const n=JSON.parse(JSON.stringify(t));console.log("subscriptionUpdate",n),function(t){fetch(e.API_PUSH_SUBSCRIPTION,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:e.app,subscription:t,contact:{email:O.email||void 0,contact_id:O.contactId||void 0},topic:"transactional",device:"desktop"})})}({endpoint:n.endpoint,p256dh:n.keys.p256dh,auth:n.keys.auth})}toHex(e){return[...new Uint8Array(e)].map((e=>e.toString(16).padStart(2,"0"))).join(" ")}showErrorMessage(e,t){console.error(e,t)}}const M="PerfitOptinRulesExecInfo";let B=[];let H=!1,J={};const j={last_triggered:void 0,success:!1,trigger_count:0};async function $(t){B=t||await async function(){try{let t=`${e.OPTIN_RULES_API}?account=${e.app}`;n&&(t+=`&ts=${(new Date).getTime()}`);const r=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json","X-Account":e.app}});if(!r.ok)throw new Error("fetch error: "+t);return(await r.json()).data}catch(e){return console.error("Perfit: could not load optin configuration",e),[]}}(),W(),window.addEventListener("pushstate",W),window.addEventListener("popstate",W)}function W(){B.sort(((e,t)=>e.priority-t.priority)).filter(G).map(V)}function G(e){if(!e.enabled)return!1;const t=new RegExp(e.trigger_options.url,"i");if(!window.location.href.match(t))return!1;const n=(r=e.id,F(),J[r]||{...j});var r;return!(e.trigger_options.stop_on_success&&n.success||e.trigger_options.max_displays>0&&n.trigger_count>=e.trigger_options.max_displays||n.last_triggered&&e.trigger_options.interval_days>0&&(new Date).getTime(){Y(e)}));const t=n=>{!H&&n.clientY<0&&(Q(e),z(e.id,"triggered"),document.removeEventListener("mouseleave",t,!1))};document.addEventListener("mouseleave",t,!1)}(e);break;case"scroll":!function(e){Z(e.optin_id).then((()=>{Y(e)}));const t=n=>{let r=window.scrollY/(document.body.offsetHeight-window.innerHeight),i=Math.round(100*r);!H&&i>=e.trigger_mode_options.scroll&&(Q(e),z(e.id,"triggered"),document.removeEventListener("scroll",t,!1))};document.addEventListener("scroll",t,!1)}(e)}}function q(e){e.trigger_mode_options.delay>0&&Z(e.optin_id).then((()=>{Y(e)})),setTimeout((()=>{H?q(e):(Q(e),z(e.id,"triggered"))}),1e3*e.trigger_mode_options.delay)}function F(){try{J=JSON.parse(localStorage.getItem(M)||"{}")}catch(e){J={}}}function z(e,t){F(),J[e]||(J[e]={...j}),"triggered"===t?(J[e].trigger_count++,J[e].last_triggered=(new Date).getTime()):"submitted"===t&&(J[e].success=!0),localStorage.setItem(M,JSON.stringify(J))}async function Z(t){if(window.PerfitOptIn&&window.PerfitOptIn[t])return;if(t.startsWith("push"))return void function(e){window.PerfitOptIn||(window.PerfitOptIn=[]),window.PerfitOptIn[e]={open:()=>{if(!T())return;const e=function(){if(console.debug("Setting up push."),!navigator.serviceWorker)return void console.warn("Service workers are not supported in this browser.");if(!("PushManager"in window))return void console.warn("Push is not supported in this browser.");const e=new x;return e.registerServiceWorker(),e}();e&&setTimeout((()=>{e.subscribe()}),1e3)},close:()=>{},setCallbacks:()=>{},form:void 0,config:void 0}}(t);const n=window.document,r=n.createElement("div");r.id=`optin-${t}`,r.dataset.type="popup",r.dataset.mode="manual",n.body.appendChild(r);const i=new Promise((r=>{const i=n.createElement("link");i.rel="stylesheet",i.type="text/css",i.href=`https://optin.myperfit.com/res/css/${e.app}/${t}.css`,i.onload=r,n.body.appendChild(i)})),o=new Promise((r=>{const i=n.createElement("script");i.type="text/javascript",i.charset="utf-8",i.src=`https://optin.myperfit.com/res/js/${e.app}/${t}.js`,i.onload=r,n.body.appendChild(i)}));return Promise.all([i,o])}function X(e){H||window.PerfitOptIn[e].open()}function Y(e){window.PerfitOptIn[e.optin_id].setCallbacks({submitted:()=>{r("submitted "+e.optin_id),z(e.id,"submitted")},closed:()=>{r("closed "+e.optin_id),H=!1},opened:()=>{r("opened "+e.optin_id),H=!0}})}function Q(e){window.PerfitOptIn&&window.PerfitOptIn[e.optin_id]?X(e.optin_id):Z(e.optin_id).then((()=>{Y(e),X(e.optin_id)}))}const ee="p-cart";function te(){!function(e){try{const t=_(e);localStorage.removeItem(t)}catch(t){console.error(`[removeLocalStorageItem] Error removing ${e}:`,t)}}(ee)}const ne={};let re;const ie={identify:R,visit:U,cart:function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1?arguments[1]:void 0;if(!t||!t.length)return void te();const r=E(ee);let i={cart:[]};try{r&&(i="string"==typeof r?JSON.parse(r):r)}catch(e){console.error("Perfit: invalid cart data"),te()}n&&i?.cartId!=n&&(te(),i={cart:[]}),S(ee,{cart:t,cartId:n},7),!i?.cart?.length&&t.length>0?T()&&A("cart-init",{cart:t,cart_id:n,customer_id:O.customerId||void 0,contact_id:O.contactId||void 0,email:O.email||void 0,visitor_id:O.visitorId,timestamp:(new Date).toISOString()}):i?.cart?.length&&i?.cart?.length!=t.length&&e.trackCartUpdates&&T()&&A("cart-update",{cart:t,cart_id:n,customer_id:O.customerId||void 0,contact_id:O.contactId||void 0,email:O.email||void 0,visitor_id:O.visitorId,timestamp:(new Date).toISOString()})},showPopup:function(e){const t=e.id;if(!t)return;const n=e.options?.timeout||0;Z(t).then((()=>{e.options?.callbacks&&window.PerfitOptIn[t].setCallbacks(e.options?.callbacks),setTimeout((()=>{X(t)}),n)}))},initRules:function(e){e&&$(e)},setDebug:function(e){n=e,localStorage.setItem(t,JSON.stringify(n)),r("Debug mode enabled")},registerOrigin:D,loadOnsites:async()=>{const t={...e};window.addEventListener("message",(function(e){const t=e.data;if(!t.eventId)return;const n=ne[t.onsiteId];if(n){if("perfit_onsite_set_styles"===t.eventId)return(r=n.reference).style.height="initial",r.style.width="initial",r.style.display="initial",r.style.position="initial",r.style.inset="initial",r.style.zIndex="initial",void Object.entries(t.styles).forEach((e=>{let[t,r]=e;n.reference.style[t]=r}));var r;if("perfit_onsite_mounted"!==t.eventId)"perfit_onsite_close"!==t.eventId||n.reference.remove();else{const e=n.rule.trigger_options?.element_id;if(e){const t=document.getElementById(e);if(!t)return;const r=n.reference.parentNode?.isEqualNode(t);if(r)return void n.reference.contentWindow?.postMessage({eventId:"perfit_onsite_set_rule",data:n.rule},"*");t?.appendChild(n.reference)}else n.reference.contentWindow?.postMessage({eventId:"perfit_onsite_set_rule",data:n.rule},"*")}}})),(await(async e=>{let{account:t}=e;return[{onsite_id:"onsite_cldvoehor00060d24ziwulk3y",account:"test20220128",name:"Multiple steps",enabled:!0,priority:1,trigger_options:{url:".*",interval_days:1,max_displays:3,stop_on_success:!1},trigger_mode:"delayed",trigger_mode_options:{delay:1},created:"2024-03-13T00:00:00Z"},{onsite_id:"onsite_cldvoehor00060d24ziwul123",account:"test20220128",name:"Modal Fijo",enabled:!0,priority:1,trigger_options:{element_id:"montar-aqui",url:".*",interval_days:1,max_displays:3,stop_on_success:!1},trigger_mode:"delayed",trigger_mode_options:{delay:1},created:"2024-03-13T00:00:00Z"}]})({account:t.app})).forEach((e=>{(e=>{const t=document.createElement("iframe");t.src=`https://onsite.myperfit.net?perfitOnsiteId=${e.onsite_id}`,t.id=e.onsite_id,t.style.height="0px",t.style.width="0px",t.style.display="none",ne[e.onsite_id]={reference:t,rule:e},document.body.appendChild(t)})(e)}))}};function oe(){if(!window.Perfit?.q?.length)return;const e=window.Perfit.q.shift();if(!e)return;const t=e[0],n=e[1];ie[t]?ie[t](n):console.warn(`Perfit: invalid command '${t}'`)}!function(){var i,o,a,s,c,d,l,u,p,y,h=["https://apps-scripts.tiendanube.com/perfit/perfit-js/","https://apps-scripts.tiendanube.com/perfit-email-marketing/perfit-js/"],g="p-customer",f="p-contact",m="p-last-cart",w="p-visitor-anon",_=0,I="not_detected";function C(e){var t,n=!1,i=!1;let c=LS?.cart?.id,d=LS?.cart?.subtotal;r("[CheckCartUpdated] - LS.cart.id",c),r("[CheckCartUpdated] - LS.cart.subtotal",d),e&&e.detail&&(i=!0,c=e.detail?.cart_item?.cart_id?e.detail.cart_item.cart_id:LS?.cart?.id,d=e.detail?.cart_item?.subtotal?e.detail.cart_item.cart_id:LS?.cart?.subtotal,I="product_added_to_cart",r("[CheckCartUpdated] - addedToCartEvent",e),r("[CheckCartUpdated] - cartId updated: ",c),r("[CheckCartUpdated] - cartSubtotal updated: ",d));var l=E(m);l&&(n=l,r("[CheckCartUpdated] - last cart stored: "+JSON.stringify(n))),"undefined"!=typeof LS&&c&&(o||a||s)&&(i||d>0)&&(n&&n.id==c?n.subtotal!=d&&(t={id:c,subtotal:d,stage:n.stage},r("[CheckCartUpdated] - cart subtotal updated: "+JSON.stringify(t)),S(m,t,7)):("not_detected"===I&&(I="store_load"),t={id:c,subtotal:d,stage:I},r("[CheckCartUpdated] - new cart stored: "+JSON.stringify(t)),S(m,t,7),P({event_type:"cart.created",cart_id:t.id,customer_id:o||void 0,contact_id:a||void 0,email:s||void 0,stage:I}),I="not_detected"))}function P(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];var n=new XMLHttpRequest,r="https://webhooks.myperfit.net/events/tiendanube/"+i.a+"/js/"+i.r+"/"+i.h;n.open("POST",r,t),n.send(JSON.stringify(e))}function K(){var e=new XMLHttpRequest,t="https://webhooks.myperfit.net/events/tiendanube-trk/"+i.a+"/js/"+i.r+"/"+i.h,n={store_id:i.store,account:i.a,category_id:LS.category?LS.category.id:void 0,product_id:LS.product?LS.product.id:void 0,customer_id:o||void 0,contact_id:a||void 0,email:s||void 0,secs_lapsed:5*_,visitor_id:d,timestamp:(new Date).toISOString()};o||a||s?(e.open("POST",t,!0),e.send(JSON.stringify(n))):E(w)||(e.open("POST",t,!0),e.send(JSON.stringify(n)),clearInterval(c),S(w,"1",1))}!function(){try{n=JSON.parse(localStorage.getItem(t)||"false")}catch(e){n=!1}}(),r("Debug mode enabled"),i=function(){for(var e=document.getElementsByTagName("script"),t=0;t-1}))){var r=n.split("?").pop();if(!r||r===n)continue;for(var i=r.split("&"),o={},a=0;a{let{app:n,source:r,trackCartUpdates:i,loadOptinRules:o}=t;n&&(e.app=n),r&&(e.source=r),void 0!==i&&(e.trackCartUpdates=i),void 0!==o&&(e.loadOptinRules=o)})({app:i.a,source:"tiendanube"}),function(){!function(){try{const e=JSON.parse(localStorage.getItem("perfit-session"));O.contactId=e.contactId,O.customerId=e.customerId,O.email=e.email,O.visitorId=e.visitorId}catch(e){}if(!O.customerId){const e=E("p-customer");e&&(O.customerId=e)}if(!O.contactId){const e=E("p-contact");e&&(O.contactId=e)}if(!O.visitorId){const e=E("p-visitor-id");e&&(O.visitorId=e)}}(),O.visitorId||(O.visitorId=crypto.randomUUID(),O.visitorId.endsWith("0")&&D());const e=b("pc",!1)||b("pcid",!1);e&&(O.contactId=e),L(),S("p-visitor-id",O.visitorId,365)}(),function(){if(window.Perfit&&window.Perfit.q)return;const e=function(){e.c(arguments)};e.q=[],e.c=function(t){e.q.push(t)},window.Perfit=e}(),re=setInterval(oe,300),$(),O?.email&&(s=O.email),O?.customerId&&(o=O.customerId),d=O.visitorId,function(){if("undefined"!=typeof LS&&LS.customer)o=LS.customer,S(g,o,365);else{var e=v(g);o=e||!1}}(),LS?.cart?.contact?.email&&r("Cart contact email detected",s=LS.cart.contact.email),p=v(f),u=!1,window.location.href.indexOf("pc")>-1&&(u=(l={},window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,(function(e,t,n){l[t]=n.split("#")[0]})),l).pc),(y=u)?S(f,a=y,365):a=!!p&&p.split("#")[0],o&&R({customer_id:o}),s&&R({email:s}),LS&&LS.on&&"subscribedToNewsletter"in LS.events?LS.on("subscribedToNewsletter",(e=>{const t=e.detail.email;t&&R({email:t}),P({event_type:"newsletter.subscribed",email:t})})):function(){var e=document.getElementsByTagName("form");for(var t of e)t.action.includes("winnie-pooh")&&t.addEventListener("submit",(function(e){var t,n;for(var r of e.target)"email"===r.name?t=r.value:"name"===r.name&&(n=r.value);t&&R({email:t}),P({event_type:"newsletter.subscribed",email:t,name:"Sin nombre"!==n?n:void 0},!1)}))}(),LS&&LS.on&&LS.on("productAddedToCart",C),window.location.pathname.startsWith("/checkout")||C(),r("[init] customer",o),r("[init] contact",a),r("[init] email",s),LS&&(LS.product||LS.category)&&(c=setInterval((function(){_++>=5&&clearInterval(c),K()}),5e3),K())):r("no url params")}()})();