if("undefined"==typeof MantleAppTrackClass){function getMantleAppTrackScriptParams(){var e;for(e of document.getElementsByTagName("script")){var t=e.getAttribute("src");if(t&&t.includes("mantle_apptrack.js"))return t=new URLSearchParams(t.split("?")[1]),Object.fromEntries(t)}return{}}function generateEventId(){return Date.now()+"_"+Math.random().toString(36).substr(2,9)}let n=e=>new Blob([e]).size;function generatePageViewId(e){var t=Math.floor(Date.now()/1e3),e=new URL(e),e=(e.pathname+e.search).split("").reduce((e,t)=>(e<<5)-e+t.charCodeAt(0)&4294967295,0);return`pv_${t}_`+Math.abs(e)}function loadWebVitalsLibrary(t){try{if(window.webVitals)t(window.webVitals);else if(document.querySelector('script[src*="web-vitals.attribution"]')){let e=setInterval(()=>{window.webVitals&&(clearInterval(e),t(window.webVitals))},100);void setTimeout(()=>{clearInterval(e),window.webVitals||(console.warn("Web vitals library loading timeout"),t(null))},5e3)}else{var a=document.createElement("script");a.src="https://unpkg.com/web-vitals@5/dist/web-vitals.attribution.iife.js",a.async=!0,a.setAttribute("data-mantle-webvitals","true");let e=setTimeout(()=>{console.warn("Web vitals library loading timeout"),t(null)},1e4);a.onload=function(){clearTimeout(e);try{window.webVitals?t(window.webVitals):(console.warn("Web vitals library loaded but webVitals global not found"),t(null))}catch(e){console.warn("Error initializing web vitals library:",e),t(null)}},a.onerror=function(){clearTimeout(e),console.warn("Failed to load web vitals library from CDN"),t(null)},document.head.appendChild(a)}}catch(e){console.warn("Error loading web vitals library:",e),t(null)}}function measureWebVitals(i){loadWebVitalsLibrary(e=>{if(e)try{e.onLCP(t=>{try{let e=(t.attribution?.lcpEntry?.element)?.outerHTML;var a=102400;e&&n(e)>a&&(e=e.slice(0,a)),i("lcp",{value:Math.round(t.value),attributionTarget:t.attribution?.target,url:t.attribution?.url,attributionTargetHtml:e})}catch(e){console.warn("LCP callback failed:",e)}}),e.onINP(e=>{try{i("inp",{value:Math.round(e.value),attributionTarget:e.attribution?.interactionTarget,interactionType:e.attribution?.interactionType})}catch(e){console.warn("INP callback failed:",e)}}),e.onCLS(e=>{try{i("cls",{value:Math.round(1e3*e.value)/1e3,attributionTarget:e.attribution?.largestShiftTarget})}catch(e){console.warn("CLS callback failed:",e)}}),e.onFCP(e=>{try{i("fcp",{value:Math.round(e.value)})}catch(e){console.warn("FCP callback failed:",e)}}),e.onTTFB(e=>{try{i("ttfb",{value:Math.round(e.value)})}catch(e){console.warn("TTFB callback failed:",e)}})}catch(e){console.warn("Error setting up web vitals measurements:",e)}else console.warn("Web vitals library not available, skipping measurements")})}class MantleAppTrackClass{constructor(){this.TRACK_URL="https://appapi.heymantle.com/track",this.SESSION_CONTACT_URL="https://appapi.heymantle.com/shopify/session",this.SESSION_KEY="mantle_user_session",this.TIMEOUT_MINUTES=30,this.currentPageViewId=null,this.webVitalsCollected={},this.webVitalsUpdateTimeout=null,this.webVitalsSent=!1,this.webVitalsSentMetrics={},this.webVitalsMinMetrics=2,this.webVitalsMaxWaitTime=15e3,this.webVitalsDebounceTime=3e3,this.webVitalsAllowFinalUpdate=!0,this.webVitalsFailureCount=0,this.webVitalsMaxFailures=3,this.webVitalsDisabled=!1,this.webVitalsMaxWaitTimer=null,this.webVitalsFinalUpdateTimeout=null,this.lastPageViewUrl=null,this.cxWidgetId=null}startTracking({appToken:e,customerId:t,properties:a,beforeSend:i,identifyUserContact:n,collectWebVitals:r=!0,cxWidgetId:s}){try{var o;if(e&&"undefined"!==e&&"null"!==e||(e=(o=getMantleAppTrackScriptParams()).appToken,t=t||o.customerId),e&&"undefined"!==e&&"null"!==e){if(!(t=t||new URL(window.location).searchParams.get("shop")))try{t=localStorage.getItem("mantle_shop_domain")}catch(e){console.error("Failed to check localStorage for previous shop domain",e)}if(t){try{localStorage.setItem("mantle_shop_domain",t)}catch(e){console.error("Failed to set localStorage for current shop domain",e)}this.appToken=e,this.customerId=t,this.properties=a||{},this.beforeSend=i,this.identifyUserContact=null==n||n,this.collectWebVitals=r,this.lastTrackTime=0,this.cxWidgetId=s,(async()=>{this.identifyUserContact&&await this.execIdentifyUserContact(),window.addEventListener("load",this.initializeSession),window.addEventListener("beforeunload",this.initializeSession),this.track("page_view",{url:window.location.href,debounceTime:3e3}),this.observeRouteChanges()})()}else console.error("customerId is missing or could not be determined.")}else console.error("appToken is missing in the tracking script URL.")}catch(e){console.error("Failed to start tracking",e)}}configureWebVitals({minMetrics:e=2,maxWaitTime:t=15e3,debounceTime:a=3e3,enabled:i=!0,maxFailures:n=3,resetFailures:r=!1}={}){this.webVitalsMinMetrics=e,this.webVitalsMaxWaitTime=t,this.webVitalsDebounceTime=a,this.collectWebVitals=i,this.webVitalsMaxFailures=n,r&&(this.webVitalsFailureCount=0,this.webVitalsDisabled=!1),i||(this.webVitalsDisabled=!0)}isSessionExpired(e){var t=MantleAppTrack.getInstance();return((new Date).getTime()-new Date(e).getTime())/6e4>t.TIMEOUT_MINUTES}findOrCreateSession(){try{var t=MantleAppTrack.getInstance();let e=JSON.parse(localStorage.getItem(t.SESSION_KEY));return!e||t.isSessionExpired(e.timestamp)?t.initializeSession():(e?.customerId!==t.customerId&&(console.log(`Customer ID changed from ${e.customerId} to ${t.customerId}. Creating a new session.`),localStorage.removeItem(t.SESSION_KEY),e=t.initializeSession()),e)}catch(e){console.error("Failed to find or create session",e)}}initializeSession(){try{let t=MantleAppTrack.getInstance(),e=JSON.parse(localStorage.getItem(t.SESSION_KEY));var a=(new Date).getTime();if(!e||t.isSessionExpired(e.timestamp)){var i="session:"+t.customerId+":"+Math.random().toString(36).substr(2,9);if(e={id:i,timestamp:a,customerId:t.customerId},localStorage.setItem(t.SESSION_KEY,JSON.stringify(e)),t.beforeSend)if(!1===t.beforeSend({type:"user_session_start"}))return console.log("beforeSend returned false, not sending the session data."),e;fetch(t.TRACK_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"user_session_start",appToken:t.appToken,customerId:t.customerId,url:window.location.href,pageTitle:document.title,timestamp:Date.now(),userAgent:navigator.userAgent,sessionId:i,user:t.shopify?.user,properties:t.properties||{}})}).catch(e=>{console.error("Failed to send session data",e),localStorage.removeItem(t.SESSION_KEY)})}else e.timestamp=a,localStorage.setItem(t.SESSION_KEY,JSON.stringify(e));return e}catch(e){console.error("Failed to initialize session",e)}}async track(a,{timestamp:i,properties:n,debounceTime:r,url:s,id:o}={}){try{let e=MantleAppTrack.getInstance();var l,c,d,u="undefined"!=typeof window;"page_view"!==a||o||(c=generatePageViewId(l=s||window.location.href),e.currentPageViewId&&e.lastPageViewUrl===l&&(d=parseInt(e.currentPageViewId.split("_")[1]),parseInt(c.split("_")[1])-d<30)?o=e.currentPageViewId:(o=c,e.currentPageViewId=o,e.lastPageViewUrl=l),e.collectWebVitals&&setTimeout(()=>{try{e.webVitalsCollected={},e.webVitalsSent=!1,e.webVitalsSentMetrics={},e.webVitalsUpdateTimeout&&(clearTimeout(e.webVitalsUpdateTimeout),e.webVitalsUpdateTimeout=null),e.webVitalsFinalUpdateTimeout&&(clearTimeout(e.webVitalsFinalUpdateTimeout),e.webVitalsFinalUpdateTimeout=null),e.webVitalsAllowFinalUpdate=!0,e.startWebVitalsCollection()}catch(e){console.warn("Failed to initialize web vitals collection:",e)}},0));let t={type:a,appToken:e.appToken,customerId:e.customerId,timestamp:i||Date.now(),properties:Object.assign({},n||{},e.properties||{})};if(o&&(t.id=o),u){if("page_view"===a&&r&&Date.now()-e.lastTrackTime=c.webVitalsMaxFailures)){c.webVitalsMaxWaitTimer&&clearTimeout(c.webVitalsMaxWaitTimer),c.webVitalsMaxWaitTimer=setTimeout(()=>{try{!c.webVitalsSent&&0{try{var a,i,n,r,s,o,l=e.value;t&&"number"==typeof l&&isFinite(l)?(c.webVitalsCollected[t]={value:l,timestamp:Date.now(),...e.attributionTarget?{attributionTarget:e.attributionTarget}:{},...e.attributionTargetHtml?{attributionTargetHtml:e.attributionTargetHtml}:{},...e.attributionUrl?{attributionUrl:e.attributionUrl}:{},...e.interactionType&&{interactionType:e.interactionType}},a=["lcp","cls","inp"].includes(t),i=!c.webVitalsSentMetrics[t],n=c.webVitalsSent&&c.webVitalsAllowFinalUpdate&&a&&i,c.webVitalsUpdateTimeout&&(clearTimeout(c.webVitalsUpdateTimeout),c.webVitalsUpdateTimeout=null),n?(c.webVitalsAllowFinalUpdate=!1,c.webVitalsFinalUpdateTimeout&&clearTimeout(c.webVitalsFinalUpdateTimeout),c.webVitalsFinalUpdateTimeout=setTimeout(()=>{try{c.sendWebVitalsUpdate(!1,!0)}catch(e){console.warn("Error in final update timeout:",e)}},1e3)):c.webVitalsSent||(r=Object.keys(c.webVitalsCollected).length,s=c.webVitalsCollected.lcp||c.webVitalsCollected.cls||c.webVitalsCollected.inp,o=r>=c.webVitalsMinMetrics,c.webVitalsUpdateTimeout=s&&o?setTimeout(()=>{c.sendWebVitalsUpdate(),clearTimeout(c.webVitalsMaxWaitTimer)},1e3):setTimeout(()=>{c.sendWebVitalsUpdate(),clearTimeout(c.webVitalsMaxWaitTimer)},c.webVitalsDebounceTime))):console.warn(`Invalid web vital data: ${t} = `+l)}catch(e){console.warn(`Failed to process web vital ${t}:`,e),c.webVitalsFailureCount++}});let e=()=>{try{var e;0c.webVitalsCollected[e]&&!c.webVitalsSentMetrics[e]),!c.webVitalsSent||0{try{"hidden"===document.visibilityState&&e()}catch(e){console.warn("Error in web vitals visibilitychange handler:",e)}})}catch(e){console.warn("Failed to add unload listeners for web vitals:",e)}}}catch(e){console.warn("Failed to start web vitals collection:",e),this.webVitalsFailureCount++,this.webVitalsFailureCount>=this.webVitalsMaxFailures&&(console.warn("Web vitals collection disabled due to repeated failures"),this.webVitalsDisabled=!0)}}async sendWebVitalsUpdate(e=!1,t=!1){var a=MantleAppTrack.getInstance();if(!a.webVitalsDisabled&&a.currentPageViewId&&0!==Object.keys(a.webVitalsCollected).length&&(!a.webVitalsSent||t))try{var i,n,r,s={},o={};for([i,n]of Object.entries(a.webVitalsCollected))n&&"number"==typeof n.value&&isFinite(n.value)&&(s[i]=n.value,n.attributionTarget&&(s[i+"_attribution_target"]=n.attributionTarget),n.attributionTargetHtml&&(s[i+"_attribution_target_html"]=n.attributionTargetHtml),n.attributionUrl&&(s[i+"_attribution_url"]=n.attributionUrl),n.interactionType&&(s[i+"_interaction_type"]=n.interactionType),a.webVitalsSentMetrics[i]||(o[i]=n.value));if(0!==Object.keys(s).length){if(t)if(!Object.keys(o).some(e=>["lcp","cls","inp"].includes(e)))return;t||(a.webVitalsSent=!0);for(r of Object.keys(s))a.webVitalsSentMetrics[r]=!0;var l={type:"page_view",appToken:a.appToken,customerId:a.customerId,timestamp:Date.now(),id:a.currentPageViewId,url:window.location.href,pageTitle:document.title,userAgent:navigator.userAgent,sessionId:a.findOrCreateSession()?.id,user:a.shopify?.user,properties:{...a.properties,webVitals:{...s,collectedAt:(new Date).toISOString(),updateType:t?"final":"initial"}}};if(e&&navigator.sendBeacon)try{navigator.sendBeacon(a.TRACK_URL,JSON.stringify(l))||(console.warn("Failed to send web vitals via beacon"),a.webVitalsFailureCount++)}catch(e){console.warn("Error using sendBeacon for web vitals:",e),a.webVitalsFailureCount++}else try{let e=new AbortController;var c=setTimeout(()=>e.abort(),5e3);await fetch(a.TRACK_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l),signal:e.signal}),clearTimeout(c)}catch(e){"AbortError"===e.name?console.warn("Web vitals update request timed out"):console.warn("Error sending web vitals update:",e),a.webVitalsFailureCount++}}}catch(e){console.warn("Failed to update web vitals:",e),a.webVitalsFailureCount++,a.webVitalsFailureCount>=a.webVitalsMaxFailures&&(console.warn("Web vitals updates disabled due to repeated failures"),a.webVitalsDisabled=!0),t||(a.webVitalsSent=!1)}}observeRouteChanges(){try{let t=MantleAppTrack.getInstance(),e=history.pushState,a=history.replaceState;history.pushState=function(){try{e.apply(history,arguments),t.track("page_view",{url:window.location.href,debounceTime:3e3})}catch(e){console.error("Failed to observe route changes",e)}},history.replaceState=function(){try{a.apply(history,arguments),t.track("page_view",{url:window.location.href,debounceTime:3e3})}catch(e){console.error("Failed to observe route changes",e)}},window.addEventListener("popstate",function(){t.track("page_view",{url:window.location.href,debounceTime:3e3})}),"undefined"!=typeof navigation&&navigation.addEventListener("navigate",function(e){t.track("page_view",{url:e.destination.url,debounceTime:3e3})})}catch(e){console.error("Failed to observe route changes",e)}}async execIdentifyUserContact(){if("undefined"!=typeof shopify){var e=await shopify.idToken(),t=MantleAppTrack.getInstance(),e=await fetch(t.SESSION_CONTACT_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:e,appToken:t.appToken,customerId:t.customerId,...t.cxWidgetId?{cxWidgetId:t.cxWidgetId}:{}})});try{var a=await e.json();this.shopify={user:a?.shopify?.user||null},a?.widget&&(this.widget=a?.widget)}catch(e){console.error("Failed to parse session contact response",e)}}else console.warn("No shopify global detected, unable to identify user contact. Verify App Bridge v4 is being used and is loaded before this script.")}}var MantleAppTrack=(()=>{let e;function t(){return new MantleAppTrackClass}return{getInstance:function(){return e=e||t()}}})();(()=>{try{var e=getMantleAppTrackScriptParams();e.skipStart||MantleAppTrack.getInstance().startTracking({appToken:e.appToken,customerId:e.customerId,identifyUserContact:"true"===e.identifyUserContact||"false"!==e.identifyUserContact,collectWebVitals:"false"!==e.collectWebVitals,cxWidgetId:e.cxWidgetId}),window.mantleTrack=MantleAppTrack.getInstance()}catch(e){console.error("Failed to initialize MantleAppTrack:",e);try{window.mantleTrack=MantleAppTrack.getInstance()}catch(e){console.error("Failed to create fallback MantleAppTrack instance:",e)}}})()}else console.log("MantleAppTrack already loaded");