var e;e=()=>(()=>{function e(t){var n,i=Dn[t];return void 0!==i?i.exports:(n=Dn[t]={exports:{}},Nn[t](n,n.exports,e),n.exports)}function t(e,t,i=576e3,r){var o;try{const a=new Date;a.setTime(a.getTime()+60*i*1e3);const s=[`${e}=${encodeURIComponent(t)}`,`expires=${a.toUTCString()}`,`path=${(null==r?void 0:r.path)||"/"}`,`SameSite=${(null==r?void 0:r.sameSite)||"Lax"}`];(null==r?void 0:r.domain)&&s.push(`domain=${r.domain}`);const c="undefined"!=typeof window&&"https:"===(null===(o=window.location)||void 0===o?void 0:o.protocol);(!0===(null==r?void 0:r.secure)||!1!==(null==r?void 0:r.secure)&&c)&&s.push("Secure");const l=s.join("; ");document.cookie=l,i<=0||""===String(t)||"__cst_domain_test__"===e||null===n(e)&&(0,Pn.AO)(`Failed to set cookie: ${e}`)}catch(e){(0,Pn.AO)("Error setting cookie:",e)}}function n(e){try{const t=e+"=",n=document.cookie.split(";");for(let e of n)if(e=e.trim(),e.startsWith(t))return decodeURIComponent(e.substring(t.length))}catch(t){(0,Pn.AO)(`Error getting cookie: ${e}`,t)}return null}function i(e,t){const n={},i={};return e?(e.split(";").forEach(e=>{const r=e.indexOf("=");if(-1===r)return;const o=e.substring(0,r).trim(),a=e.substring(r+1).trim();if(o)try{const e=decodeURIComponent(o),r=decodeURIComponent(a);let s=r;if(e===ai)try{s=JSON.parse(r)}catch(e){(0,Pn.AO)(`Error parsing location cookie JSON: ${r}`,e),s=r}n[e]?n[e].includes(s)||n[e].push(s):n[e]=[s],function(e,t){if(ci.exact.includes(e))return!0;for(const t of ci.prefix)if(e.startsWith(t))return!0;return!(!t||!t.includes(e))}(e,t)&&"string"==typeof s&&(i[e]?i[e].includes(s)||i[e].push(s):i[e]=[s])}catch(e){(0,Pn.AO)(`Error decoding cookie: ${o}=${a}`,e)}}),{allCookies:n,marketingTrackers:i}):{allCookies:n,marketingTrackers:i}}function r(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>{try{if(Array.isArray(t)&&1===t.length){const n=t[0];return e===ai&&"object"==typeof n&&null!==n?[e,JSON.stringify(n)]:[e,String(n)]}return[e,Array.isArray(t)?JSON.stringify(t):String(t)]}catch(t){return(0,Pn.AO)(`Error converting value for key: ${e}`,t),[e,""]}}))}function o(e){return r(e)}function a(){try{if("undefined"==typeof window)return;if(mi)return ui;const i=window;if(i.CST_COOKIE_DOMAIN&&"string"==typeof i.CST_COOKIE_DOMAIN)return i.CST_COOKIE_DOMAIN.trim();const r=document.querySelector('meta[name="cst:cookieDomain"], meta[name="cst-cookie-domain"]');if(null==r?void 0:r.content)return r.content.trim();const o=window.location.hostname;if(!(e=o)||"localhost"===e||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)||e.includes(":"))return mi=!0,ui=void 0,ui;const a=o.split(".");if(a.length<2)return mi=!0,ui=void 0,ui;const s=[];for(let e=a.length-2;e>=0;e--){const t="."+a.slice(e).join(".");s.push(t)}const c="__cst_domain_test__";for(const e of s)try{t(c,"1",1,{domain:e,path:"/",sameSite:"Lax"});const i="1"===n(c);if(t(c,"",-1,{domain:e,path:"/",sameSite:"Lax"}),i)return(0,Pn.cY)("Selected cookie domain",e),mi=!0,ui=e,ui}catch(e){}}catch(e){}var e;return mi=!0,ui=void 0,ui}function s(){try{return navigator.userAgent||""}catch(e){return""}}function c(e=s()){const t=e.match(/Version\/(\d+).*Safari/);return!!t&&parseInt(t[1],10)>=17}function l(e=s()){const t=e.match(/SamsungBrowser\/(\d+)/);return!!t&&parseInt(t[1],10)>=26}function d(e=s()){return c(e)||l(e)}async function u(){try{if(d())return"canvas-antifingerprint";await new Promise(e=>requestAnimationFrame(e));const e=navigator.maxTouchPoints>0||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),t=(await Promise.all([m(),...e?[]:[f()]])).join("|||");return await async function(e){const t=(new TextEncoder).encode(e);try{const e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,"0")).join("").slice(0,12)}catch(t){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n&=n;return Math.abs(n).toString(36).padStart(12,"0")}}(t)}catch(e){return"canvas-error"}}async function m(){try{const e=document.createElement("canvas"),t=e.getContext("2d");return t?(e.width=200,e.height=100,t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(100,1,50,15),t.fillStyle="#069",t.font="12pt Arial",t.fillText("Canvas test 🔒",2,15),t.fillStyle="rgba(102, 204, 0, 0.8)",t.font="16pt Arial",t.fillText("Font Test",4,40),t.fillStyle="#ff0000",t.font="11pt Times",t.fillText("©®™€",2,65),t.fillStyle="#0000ff",t.font="14pt Arial",t.fillText("😀🌍",2,85),e.toDataURL()):"text-canvas-unsupported"}catch(e){return"text-canvas-error"}}async function f(){try{const e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return"geometry-canvas-unsupported";e.width=150,e.height=150;const n=t.createLinearGradient(0,0,150,150);return n.addColorStop(0,"#ff0000"),n.addColorStop(.5,"#00ff00"),n.addColorStop(1,"#0000ff"),t.fillStyle=n,t.fillRect(10,10,130,50),t.strokeStyle="#ff00ff",t.lineWidth=2,t.beginPath(),t.arc(75,100,30,0,2*Math.PI),t.stroke(),t.strokeStyle="#00ffff",t.lineWidth=1.5,t.beginPath(),t.moveTo(30,80),t.quadraticCurveTo(75,50,120,80),t.stroke(),t.globalAlpha=.6,t.fillStyle="#ffff00",t.fillRect(40,70,70,40),e.toDataURL()}catch(e){return"geometry-canvas-error"}}function h(e,t){return!Number.isFinite(e)||t<=0?0:Math.round(e/t)*t}function p(e){return Number.isFinite(e)?Math.max(.5,.5*Math.round(e/.5)):1}function g(){try{if("function"!=typeof matchMedia)return"unknown";if(matchMedia("(color-gamut: rec2020)").matches)return"rec2020";if(matchMedia("(color-gamut: p3)").matches)return"p3";if(matchMedia("(color-gamut: srgb)").matches)return"srgb"}catch(e){}return"unknown"}function v(){const e=navigator.userAgent;return/Edg\//.test(e)?"edge":/OPR\//.test(e)?"opera":/Chrome\//.test(e)?"chromium":/Firefox\//.test(e)?"gecko":/Safari\//.test(e)&&/Version\//.test(e)?"webkit":"unknown"}function y(){return d()}function w(){try{const e=navigator.userAgent||"",t=/Edg\//.test(e),n=/OPR\//.test(e),i=/Firefox\//.test(e),r=/SamsungBrowser\//.test(e),o=/Safari\//.test(e)&&/Version\//.test(e)&&!/Chrome\//.test(e)&&!t&&!n,a=/Chrome\//.test(e)&&!t&&!n&&!r,s=function(){try{const e=navigator;return!(!(null==e?void 0:e.brave)||"function"!=typeof e.brave.isBrave)||Boolean(null==e?void 0:e.brave)}catch(e){return!1}}();return{engine:v(),isSafari:o,isBrave:s,isSamsungInternet:r,isFirefox:i,isChromium:a,isEdge:t,isOpera:n}}catch(e){return{engine:"unknown",isSafari:!1,isBrave:!1,isSamsungInternet:!1,isFirefox:!1,isChromium:!1,isEdge:!1,isOpera:!1}}}function S(){try{const e=null===Intl||void 0===Intl?void 0:Intl.DateTimeFormat;if(e){const t=(new e).resolvedOptions().timeZone;if(t)return t}}catch(e){}return"UTC"+-(new Date).getTimezoneOffset()/60}async function b(){if(y())return"audio-antifingerprint";try{const e=window.OfflineAudioContext||window.webkitOfflineAudioContext;if(!e)return"audio-unsupported";const t=new e(1,5e3,44100),n=t.createOscillator();n.type="triangle",n.frequency.value=1e4;const i=t.createDynamicsCompressor();i.threshold.value=-50,i.knee.value=40,i.ratio.value=12,i.attack.value=0,i.release.value=.25,n.connect(i),i.connect(t.destination),n.start(0);const r=(await Promise.race([new Promise((e,n)=>{t.oncomplete=t=>e(t.renderedBuffer),t.startRendering().catch(n)}),new Promise((e,t)=>setTimeout(()=>t(new Error("Audio timeout")),1e3))])).getChannelData(0).subarray(4500,5e3);let o=0;for(let e=0;e<r.length;e++)o=(o<<5)-o+Math.round(1e6*r[e])>>>0;return o.toString(36)}catch(e){return"audio-error"}}function T(e){return!e.includes("error")&&!e.includes("unsupported")&&"canvas-antifingerprint"!==e}function _(e){return!e.includes("error")&&"audio-unsupported"!==e&&"audio-antifingerprint"!==e}async function I(e,t,n){const i=await e();if(!n||!t(i))return{value:i,stable:null};const r=await e();return t(r)?{value:i,stable:i===r}:{value:i,stable:!1}}function k(){var e;try{const t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.brands;return Array.isArray(t)?t.map(e=>(null==e?void 0:e.brand)||"").filter(Boolean).sort().join(","):""}catch(e){return""}}function A(){var e;try{return(null===(e=navigator.userAgentData)||void 0===e?void 0:e.platform)||""}catch(e){return""}}function E(){var e;try{return(null===(e=navigator.userAgentData)||void 0===e?void 0:e.architecture)||""}catch(e){return""}}function O(e){return e.map(e=>"string"==typeof e?e:String(e)).join("|||")}async function L(){return await async function(){var e,t,n,i,r,o;if(fi)return fi.raw;try{const r=(new Date).toISOString(),o=w(),a=k(),s=A(),d=E(),m=h(screen.width,64),f=h(screen.height,64),v=p(window.devicePixelRatio),L=S(),M=(new Date).getTimezoneOffset(),P=Array.isArray(navigator.languages)?navigator.languages.slice().sort().join(","):navigator.language||"",x=[`screen:${m}x${f}`,`depth:${screen.colorDepth}`,`dpr:${v}`,`hw:${navigator.hardwareConcurrency||"unknown"}`,`mem:${null!==(e=navigator.deviceMemory)&&void 0!==e?e:"unknown"}`,`touch:${null!==(t=navigator.maxTouchPoints)&&void 0!==t?t:0}`,`touchEvt:${"ontouchstart"in window}`,`platform:${navigator.platform||"unknown"}`,`uaPlatform:${s}`,`arch:${d||"unknown"}`,`engine:${o.engine}`,`brands:${a}`,`lang:${P}`,`tz:${L}`,`gamut:${g()}`],R=function(){try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(!t)return"no-webgl";const n=t,i=n.getExtension("WEBGL_debug_renderer_info"),r=i?n.getParameter(i.UNMASKED_VENDOR_WEBGL):null,o=i?n.getParameter(i.UNMASKED_RENDERER_WEBGL):null;return[n.getParameter(n.RENDERER),n.getParameter(n.VENDOR),n.getParameter(n.VERSION),n.getParameter(n.SHADING_LANGUAGE_VERSION),r,o,n.getParameter(n.MAX_TEXTURE_SIZE),n.getParameter(n.MAX_RENDERBUFFER_SIZE),n.getParameter(n.MAX_VERTEX_ATTRIBS)].filter(Boolean).join("|||")}catch(e){return"webgl-error"}}();await async function(){try{const e=null===document||void 0===document?void 0:document.fonts;if(!e||!e.ready||"function"!=typeof e.ready.then)return;await Promise.race([e.ready,new Promise(e=>setTimeout(e,300))])}catch(e){}}();const N=function(){try{const e=["Arial","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","Comic Sans MS","Impact","Calibri","Cambria","Consolas","Helvetica Neue","Helvetica","SF Pro Display","SF Pro Text","Menlo","Monaco","Apple Symbols","Lucida Grande","Palatino","Ubuntu","Liberation Sans","DejaVu Sans","Droid Sans","Roboto","Open Sans","Noto Sans","Source Sans Pro","Microsoft YaHei","SimSun","Hiragino Sans","Meiryo","Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji"],t=document.createElement("canvas"),n=t.getContext("2d");if(!n)return"canvas-unsupported";t.width=50,t.height=20;const i=["monospace","sans-serif","serif"],r="mmmmmmmmmmlli",o={};for(const e of i)n.font=`12px ${e}`,o[e]=n.measureText(r).width;const a=[];for(const t of e){let e=!1;for(const a of i)if(n.font=`12px '${t}', ${a}`,n.measureText(r).width!==o[a]){e=!0;break}e&&a.push(t)}return a.sort().join(",")||"none"}catch(e){return"font-detection-error"}}(),D=function(){try{const e=Math;return[e.acos(.12312423423423424),e.acosh(1e308),e.asin(.12312423423423424),e.asinh(1),e.atanh(.5),e.atan(2),e.sin(.5),e.sinh(1),e.cos(.5),e.cosh(1),e.tan(.5),e.tanh(1),e.exp(1),e.expm1(1),e.log1p(10),e.pow(e.PI,-100)].map(e=>e.toString().slice(0,15)).join(",")}catch(e){return"math-unsupported"}}(),$=function(){try{const e=document.createElement("video"),t=['video/mp4; codecs="avc1.42E01E"','video/mp4; codecs="avc1.4D401E"','video/mp4; codecs="avc1.64001E"','video/webm; codecs="vp8"','video/webm; codecs="vp9"','video/webm; codecs="av1"','audio/mp4; codecs="mp4a.40.2"','audio/webm; codecs="opus"'].filter(t=>""!==e.canPlayType(t));return t.length>0?t.join(","):"no-media"}catch(e){return"media-error"}}(),W=y(),F=o.isBrave,H={canvasStable:null,audioStable:null};let j="canvas-antifingerprint",U="audio-antifingerprint";if(!W){const e=await I(u,T,F);j=e.value,H.canvasStable=e.stable;const t=await I(b,_,F);U=t.value,H.audioStable=t.stable}const z={canvas:T(j)&&!1!==H.canvasStable,webgl:"no-webgl"!==R&&"webgl-error"!==R,fonts:"fonts-unsupported"!==N&&"font-detection-error"!==N&&"none"!==N,audio:_(U)&&!1!==H.audioStable,math:"math-unsupported"!==D,media:"media-error"!==$&&"no-media"!==$},V=[R,N,z.canvas?j:"canvas-unstable",z.audio?U:"audio-unstable",D,$],q=O(x),B=O(V),[K,G]=await Promise.all([C(q),C(B)]),X=Y(K.slice(0,40)).slice(0,12),J=Y(G.slice(0,40)).slice(0,12),Q=function(e){const t=[e.canvas,e.webgl,e.fonts,e.audio,e.math].filter(Boolean).length;return 5===t?"high":t>=3?"medium":"low"}(z),Z=`fp_${X}${"high"===Q?"h":"medium"===Q?"m":"l"}${J}`,ee=function(e){const t=[];return c()&&t.push("safari17_noise"),l()&&t.push("samsung_antifp"),!1===e.canvasStable&&t.push("canvas_inconsistent"),!1===e.audioStable&&t.push("audio_inconsistent"),{detected:t.length>0,reasons:t}}(H),te={screen:{width:m,height:f,colorDepth:screen.colorDepth||0,dpr:v},hardware:{cores:navigator.hardwareConcurrency||"unknown",memory:null!==(n=navigator.deviceMemory)&&void 0!==n?n:"unknown",touchPoints:null!==(i=navigator.maxTouchPoints)&&void 0!==i?i:0,touchEvent:"ontouchstart"in window},platform:{platform:navigator.platform||"unknown",uaPlatform:s,arch:d||"unknown",brands:a,engine:o.engine},timezone:{id:L,offset:M},colorGamut:g(),mediaCapabilities:$,webgl:R,fonts:N,math:D,canvas:j,audio:U};return fi={raw:Z,stable:X,entropy:J,confidence:Q,signals:z,stability:H,browser:o,antiFingerprinting:ee,rawSignals:te,collectedAt:r},Z}catch(e){(0,Pn.AO)("Error generating browser fingerprint:",e);const t=function(){const e=[`${screen.width}x${screen.height}`,screen.colorDepth,navigator.hardwareConcurrency||"unknown",Math.round(window.devicePixelRatio),navigator.platform||"unknown"].join("|");let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t>>>=0;return t.toString(36).padStart(24,"0")}(),n=t.slice(0,12),i=t.slice(12),a=`fp_${n}l${i}`,s=w(),c=(new Date).toISOString(),l={canvasStable:null,audioStable:null},d={screen:{width:h(screen.width,64),height:h(screen.height,64),colorDepth:screen.colorDepth||0,dpr:p(window.devicePixelRatio)},hardware:{cores:navigator.hardwareConcurrency||"unknown",memory:null!==(r=navigator.deviceMemory)&&void 0!==r?r:"unknown",touchPoints:null!==(o=navigator.maxTouchPoints)&&void 0!==o?o:0,touchEvent:"ontouchstart"in window},platform:{platform:navigator.platform||"unknown",uaPlatform:A(),arch:E()||"unknown",brands:k(),engine:s.engine},timezone:{id:S(),offset:(new Date).getTimezoneOffset()},colorGamut:g(),mediaCapabilities:"media-error",webgl:"webgl-error",fonts:"font-detection-error",math:"math-unsupported",canvas:"canvas-error",audio:"audio-error"};return fi={raw:a,stable:n,entropy:i,confidence:"low",signals:{canvas:!1,webgl:!1,fonts:!1,audio:!1,math:!1,media:!1},stability:l,browser:s,antiFingerprinting:{detected:!1,reasons:[]},rawSignals:d,collectedAt:c},a}}(),fi}async function C(e){try{const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}catch(t){return(0,Pn.AO)("Error generating SHA-256 hash:",t),function(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t>>>=0;return t.toString(36).padStart(24,"0")}(e)}}function Y(e){let t=BigInt("0x"+e),n="";for(;t>0;)n="0123456789abcdefghijklmnopqrstuvwxyz"[Number(t%BigInt(36))]+n,t/=BigInt(36);return n.padStart(24,"0")}function M(e){if(!e)return null;const t=e.trim();if(0===t.length)return null;try{const e="undefined"!=typeof document&&document.baseURI||"undefined"!=typeof location&&location.href||void 0,n=t.length>2048?t.slice(0,2048):t,i=e?new URL(n,e):new URL(n),r=i.protocol.toLowerCase();return"http:"!==r&&"https:"!==r&&"mailto:"!==r&&"tel:"!==r?null:(i.username="",i.password="",i.toString())}catch(e){return null}}function P(e){const t=e.split(".");if(t.length<=2)return e;const n=t.slice(-2).join(".");if(["co.uk","com.au","gov.bd","edu.sg"].includes(n)){if(3===t.length)return t.slice(-3).join(".");if(t.length>=4)return t.slice(-3).join(".")}return n}function x(e,t,n={}){const{maxRequestsPerSecond:i=10,leading:r=!0,trailing:o=!0}=n;let a=0,s=null,c=t;return function(...n){const l=Date.now(),d=l-a;c=d<1e3/i?Math.min(1.5*c,1e3):Math.max(t,.75*c),(r||0===a)&&d>=c?(s&&(clearTimeout(s),s=null),a=l,e.apply(this,n)):o&&!s&&(s=setTimeout(()=>{a=Date.now(),s=null,e.apply(this,n)},c))}}function R(e,t){let n=null;return function(...i){n&&clearTimeout(n),n=setTimeout(()=>{n=null,e(...i)},t)}}function N(){return(new Date).toISOString()}function D(){return Date.now()}function $(e){if("number"==typeof e)return e;if("string"==typeof e){const t=Number(e);if(!isNaN(t))return t;const n=Date.parse(e);if(!isNaN(n))return n}throw new Error(`Invalid time value: ${e}`)}function W(e,t){return new Promise((n,i)=>{const r=setTimeout(()=>{i(new Error(`Operation timed out after ${t} ms`))},t);e.then(e=>{clearTimeout(r),n(e)}).catch(e=>{clearTimeout(r),i(e)})})}function F(e){const t=e.trim();if(!t)return"";if(/^https?:\/\//i.test(t))return t;try{if("undefined"!=typeof window&&window.location){const e=window.location.origin||"";if(e)return t.startsWith("/")?`${e}${t}`:`${e}/${t}`}}catch(e){}return t}function H(e){var t,n;const i=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.url;if(i&&i.trim())return i;try{if("undefined"!=typeof window&&window.location){const e=window.location.href||"";if(e.trim())return e;const t=F(window.location.pathname||"");if(t)return t}}catch(e){}const r=null===(n=null==e?void 0:e.page)||void 0===n?void 0:n.pathname;return r&&r.trim()?F(r):""}function j(e){var t,n;const i=(null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.url)||"",r=(null===(n=null==e?void 0:e.page)||void 0===n?void 0:n.pathname)||"";return!i.trim()&&!r.trim()}function U(e){var t,n;return null!==(n=null!==(t=null==e?void 0:e[gi.session])&&void 0!==t?t:null==e?void 0:e.session)&&void 0!==n?n:{}}function z(e){var t,n;const i=U(e);return null!==(n=null!==(t=null==i?void 0:i[gi.pageView])&&void 0!==t?t:null==i?void 0:i.pageView)&&void 0!==n?n:{}}function V(e){try{const t=function(e){var t,n;try{const i=z(e),r=null!==(n=null!==(t=null==i?void 0:i[gi.url])&&void 0!==t?t:null==i?void 0:i.url)&&void 0!==n?n:"";return"string"==typeof r?r:String(r||"")}catch(e){return""}}(e);if(!B(t))return;const n=function(){try{if("undefined"!=typeof window&&window.location){if(window.location.href&&window.location.href.trim())return window.location.href;const e=window.location.pathname||"",t=window.location.origin||"";if(t&&e)return e.startsWith("/")?`${t}${e}`:`${t}/${e}`;if(e)return e}}catch(e){}return"about:blank"}();if(B(n))return;const i=U(e),r=z(e);r[gi.url]=n,r.url=n,e[gi.session]&&!e[gi.session][gi.pageView]&&(e[gi.session][gi.pageView]=r),e.session&&!e.session.pageView&&(e.session.pageView=r),i[gi.pageView]=r,i.pageView=r}catch(e){}}async function q(e,t,n){const{signal:i,cleanup:r}=function(e){try{const t="undefined"!=typeof AbortSignal?AbortSignal:null;if(t&&"function"==typeof t.timeout)return{signal:t.timeout(e),cleanup:()=>{}}}catch(e){}if("undefined"!=typeof AbortController){const t=new AbortController,n=setTimeout(()=>{try{t.abort()}catch(e){}},e);return{signal:t.signal,cleanup:()=>clearTimeout(n)}}return{cleanup:()=>{}}}(n);try{const n=i?Object.assign(Object.assign({},t),{signal:i}):t;return await fetch(e,n)}finally{r()}}function B(e){const t=(e||"").trim().toLowerCase();return!t||"unknown - state"===t||"undefined"===t||"null"===t}function K(e){const t=[];return B(function(e){var t,n,i;try{const r=U(e),o=null!==(i=null!==(n=null!==(t=null==r?void 0:r[gi.sessionId])&&void 0!==t?t:null==r?void 0:r.sessionId)&&void 0!==n?n:null==r?void 0:r.id)&&void 0!==i?i:"";return"string"==typeof o?o:String(o||"")}catch(e){return""}}(e))&&t.push("sessionId"),B(function(e){var t,n,i;try{const r=z(e),o=null!==(i=null!==(n=null!==(t=null==r?void 0:r[gi.pageViewId])&&void 0!==t?t:null==r?void 0:r.pageViewId)&&void 0!==n?n:null==r?void 0:r.id)&&void 0!==i?i:"";return"string"==typeof o?o:String(o||"")}catch(e){return""}}(e))&&t.push("pageViewId"),t}function G(e){null==Si&&(Si=setTimeout(()=>{Si=null,J()},Math.max(100,e)))}function X(e,t){const n=gi.session,i=gi.pageView,r=gi.events,o=gi.sessionId,a=gi.pageViewId,s=gi.clientId,c=new Map;for(const t of e){const e=t[n],r=null==e?void 0:e[i],l=`${t[s]||"unknown"}|${(null==e?void 0:e[o])||(null==e?void 0:e.id)||"unknown"}|${(null==r?void 0:r[a])||(null==r?void 0:r.id)||"unknown"}`,d=c.get(l);d?d.push(t):c.set(l,[t])}const l=[];return c.forEach(e=>{var o;e.sort((e,t)=>e.queuedAt-t.queuedAt);let a=0;for(;a<e.length;){const s=e[a],c=Object.assign(Object.assign({},s),{id:`${Date.now()}_${Math.random().toString(36).slice(2)}`,queuedAt:[s.queuedAt]}),d=s[n],u=null==d?void 0:d[i],m=Array.isArray(null==u?void 0:u[r])?[...u[r]]:[];(null===(o=c[n])||void 0===o?void 0:o[i])||(c[n]=c[n]||{},c[n][i]=c[n][i]||{[r]:[]}),c[n][i][r]=m;const f=[s.id];let h=c[n][i][r].length;for(a++;a<e.length&&h<t;){const o=e[a],s=o[n],l=null==s?void 0:s[i],d=Array.isArray(null==l?void 0:l[r])?l[r]:[];c[n][i][r]=[...c[n][i][r],...d].slice(0,t),f.push(o.id),c.queuedAt.push(o.queuedAt),h=c[n][i][r].length,a++}l.push({merged:c,sourceIds:f})}}),l}async function J(e={}){var t;if(_i)return(0,Pn.cY)("Already sending, scheduling pending flush"),void(Ii=!0);_i=!0,Ii=!1;try{do{Ii=!1;const n=Boolean(e.force);if(!yi.isAllowed())return void(0,Pn.cY)("Circuit breaker preventing send");const i=oe();if(!i.length)break;const r=Date.now();if(!(n||i.length>=Ti||r-bi>=1e4)){const e=Math.max(100,1e4-(r-bi));(0,Pn.cY)("Delaying send: thresholds not met",{remaining:e,queued:i.length}),G(e);break}n&&Si&&(clearTimeout(Si),Si=null);const o=X(i,Ti);for(const{merged:e,sourceIds:n}of o){V(e);const i=K(e);if(i.length>0){(0,Pn.AO)("Dropping queued batch with missing required context",{eventType:null!==(t=null==e?void 0:e[gi.eventType])&&void 0!==t?t:null==e?void 0:e.eventType,sourceBatchCount:n.length,missingFields:i});for(const e of n)ae(e)}else{if(!await se(e)){yi.recordFailure();break}for(const e of n)ae(e);yi.recordSuccess(),bi=Date.now()}}}while(Ii)}catch(e){(0,Pn.AO)("Error in sendQueuedBatches",e),yi.recordFailure()}finally{_i=!1}}async function Q(){try{(0,Pn.cY)("sendInitialData called");const e=await vi(null,"initial");V(e);const t=K(e);if(t.length>0)return(0,Pn.AO)("Refusing to send initial batch with missing required context",{missingFields:t}),!1;try{let t;try{t=JSON.stringify(e)}catch(e){throw(0,Pn.AO)("JSON serialization failed for initial data",e),e}const n=await q(CST_LAMBDA_ENDPOINT,{method:"POST",headers:{"Content-Type":"text/plain"},body:t,credentials:"omit",cache:"no-store"},1e4);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return(0,Pn.cY)("sendInitialData sent successfully"),!0}catch(t){return(0,Pn.AO)("Error in immediate initial data send",t),await se(e,!1)?((0,Pn.cY)("sendInitialData retry succeeded"),!0):((0,Pn.cY)("sendInitialData saving to storage after failed attempts"),re(e)?ki():(0,Pn.AO)("Failed to queue initial batch after send failure"),!1)}}catch(e){return(0,Pn.AO)("Error sending initial data",e),!1}}async function Z(e){var t;try{V(e);const n=K(e);return n.length>0?((0,Pn.AO)("Refusing to queue batch with missing required context",{eventType:null!==(t=null==e?void 0:e[gi.eventType])&&void 0!==t?t:null==e?void 0:e.eventType,missingFields:n}),!1):re(e)?(ki(),!0):((0,Pn.AO)("Failed to queue batch - storage persistence failed"),!1)}catch(e){return(0,Pn.AO)("Error queueing data",e),!1}}async function ee(e){return Z(await vi(e))}function te(e,t={}){const n=re(e);return n&&t.triggerSend&&ki(),n}function ne(e){e&&ae(e)}function ie(e){if(null==e?void 0:e.force)return J({force:!0});ki()}function re(e){try{const t=oe(),n=Object.assign(Object.assign({},e),{id:`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,queuedAt:Date.now()});return t.push(n),t.length>10&&t.splice(0,t.length-10),localStorage.setItem(si,JSON.stringify(t)),(0,Pn.cY)(`Saved batch to storage. Total batches: ${t.length}`),n.id}catch(e){return(0,Pn.AO)("Error saving batch to storage",e),null}}function oe(){try{const e=localStorage.getItem(si);return e?JSON.parse(e):[]}catch(e){return(0,Pn.AO)("Error loading pending batches",e),[]}}function ae(e){try{const t=oe().filter(t=>t.id!==e);try{localStorage.setItem(si,JSON.stringify(t))}catch(e){(0,Pn.AO)("JSON serialization failed for batch removal",e)}}catch(e){(0,Pn.AO)("Error removing batch from storage",e)}}async function se(e,t=!1){var n;try{V(e);const i=K(e);if(i.length>0)return(0,Pn.AO)("Dropping outbound batch with missing required context",{eventType:null!==(n=null==e?void 0:e[gi.eventType])&&void 0!==n?n:null==e?void 0:e.eventType,missingFields:i}),!1;(0,Pn.cY)("sendDataWithRetry called",e.eventType);const r=Object.assign({},e);let o;delete r.id,delete r.queuedAt;try{o=JSON.stringify(r)}catch(e){throw(0,Pn.AO)("JSON serialization failed",e),e}const a=("hidden"===document.visibilityState||t)&&"function"==typeof navigator.sendBeacon;let s=!1;if(a){(0,Pn.cY)("sendDataWithRetry using beacon");try{const t=new Blob([o],{type:"application/json"});if(s=navigator.sendBeacon(CST_LAMBDA_ENDPOINT,t),s)return(0,Pn.cY)("sendDataWithRetry beacon accepted for delivery"),"heartbeat"!==e.eventType&&(wi=Date.now()),!0;(0,Pn.cY)("sendDataWithRetry beacon not accepted; falling back to fetch")}catch(e){(0,Pn.AO)("Beacon threw error, falling back to fetch",e)}}(0,Pn.cY)("sendDataWithRetry trying primary endpoint:",CST_LAMBDA_ENDPOINT);try{const t=await q(CST_LAMBDA_ENDPOINT,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",cache:"no-store",keepalive:!0},1e4);if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);try{await t.text()}catch(e){(0,Pn.cY)("Could not read success response body, but request succeeded")}return"heartbeat"!==e.eventType&&(wi=Date.now()),(0,Pn.cY)("sendDataWithRetry primary endpoint success"),!0}catch(t){(0,Pn.AO)("Primary endpoint failed, trying fallback:",t);const n=(()=>{const e=$n;return(0,Pn.cY)("Using fallback endpoint:",e),e})();(0,Pn.cY)("sendDataWithRetry trying fallback endpoint:",n);try{const t=await q(n,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",cache:"no-store",keepalive:!0},1e4);if(!t.ok)throw new Error(`Fallback HTTP error! status: ${t.status}`);try{await t.text()}catch(e){(0,Pn.cY)("Could not read fallback success response body, but request succeeded")}return"heartbeat"!==e.eventType&&(wi=Date.now()),(0,Pn.cY)("sendDataWithRetry fallback endpoint success"),!0}catch(e){return(0,Pn.AO)("Both primary and fallback endpoints failed:",e),!1}}}catch(e){return(0,Pn.AO)("Error sending data",e),!1}}function ce(e){try{const t=localStorage.getItem(Ei);if(!t)return;const n=JSON.parse(t).filter(t=>t.id!==e);0===n.length?localStorage.removeItem(Ei):localStorage.setItem(Ei,JSON.stringify(n)),(0,Pn.cY)(`Removed batch ${e} from storage. Remaining: ${n.length}`)}catch(e){(0,Pn.AO)("Error removing batch from storage",e)}}async function le(){if(Oi)(0,Pn.cY)("Already retrying events, skipping");else try{Oi=!0;const e=localStorage.getItem(Ei);if(!e)return;const t=JSON.parse(e);if(0===t.length)return;(0,Pn.cY)(`Retrying ${t.length} stored batches`);for(const e of t){try{await se(e)?ce(e.id):(0,Pn.cY)(`Failed to send batch ${e.id}, keeping in storage`)}catch(t){(0,Pn.AO)(`Error processing batch ${e.id}`,t)}await new Promise(e=>setTimeout(e,Ai))}}catch(e){(0,Pn.AO)("Error in retryFailedEvents",e)}finally{Oi=!1}}function de(e){if(!Ci)return Ci={x:e.clientX,y:e.clientY},void Mi();Math.hypot(e.clientX-Ci.x,e.clientY-Ci.y)>100&&(Ci={x:e.clientX,y:e.clientY},Mi())}function ue(){me(),document.addEventListener("mousemove",de,{passive:!0}),["touchmove","scroll","keypress","click"].forEach(e=>{document.addEventListener(e,Mi,{passive:!0})}),Mi(),(0,Pn.cY)("Activity tracking initialized")}function me(){Li&&(clearTimeout(Li),Li=null),document.removeEventListener("mousemove",de),["touchmove","scroll","keypress","click"].forEach(e=>{document.removeEventListener(e,Mi)})}function fe(e=Date.now()){var t,n,i;try{const r=localStorage.getItem(ei)||localStorage.getItem(ti);if(!r)return null;const o=JSON.parse(r);if(!o||"object"!=typeof o)return he(),null;const a=o.createdAt||o.timestamp,s=a?$(a):NaN;if(!Number.isFinite(s))return he(),null;if(e-s>7776e6)return he(),null;const c=String(o.sessionId||""),l=o.entryUrl||o.originalEntryUrl||o.original_entry_url||"",d=null!==(i=null!==(n=null!==(t=o.entryReferrer)&&void 0!==t?t:o.originalReferrer)&&void 0!==n?n:o.original_referrer)&&void 0!==i?i:null,u="string"==typeof d?d:null;return c&&l?{sessionId:c,entryUrl:String(l),entryReferrer:u,createdAt:"string"==typeof o.createdAt?o.createdAt:new Date(s).toISOString(),version:"string"==typeof o.version?o.version:"v1"}:(he(),null)}catch(e){return(0,Pn.AO)("Error loading acquisition context",e),null}}function he(){try{localStorage.removeItem(ei),localStorage.removeItem(ti)}catch(e){(0,Pn.AO)("Error clearing acquisition context",e)}}function pe(){return crypto.randomUUID().replace(/-/g,"")}function ge(e){return"string"!=typeof e?null:e.trim()||null}function ve(e){if("string"!=typeof e)return"";const t=e.trim();return t&&(n=t)?encodeURIComponent(n).replace(/'/g,"%27").replace(/"/g,"%22"):"";var n}function ye(e){return/^cid_[a-z0-9]{8,}$/i.test(e)}function we(e,t){if(!e)return!0;const n=e.toLowerCase();return"unknown"===n||"undefined"===n||t.has(e)}function Se(e){const n=ge(e);if(n){try{localStorage.setItem(Wi,n)}catch(e){}try{const e=a();t(Wi,n,576e3,{domain:e,path:"/",sameSite:"Lax"})}catch(e){}}}function be(e){if(e){try{const n=a();t(zn,e,qn,{domain:n,path:"/",sameSite:"Lax"})}catch(e){}try{"undefined"!=typeof localStorage&&localStorage.setItem(zn,e)}catch(e){}}}async function Te(e){var t;const n=await L(),i=n.raw;return be(i),e&&Se(e),stateManager.setFingerprintConfidence(null!==(t=n.confidence)&&void 0!==t?t:null),(0,Pn.cY)("Generated new visitor ID:",i,{confidence:n.confidence}),i}function _e(){var e;const i=e=>{if(e){try{t("_cst_clientId",e,576e3,{domain:a(),path:"/",sameSite:"Lax"})}catch(e){}try{localStorage.setItem("_cst_clientId",e)}catch(e){}try{("undefined"!=typeof window?window:{}).CST_CLIENT_ID=e}catch(e){}}},r=function(){const e=new Set;try{const t=ve(n(Di)),i=ve(n($i));t&&e.add(t),i&&e.add(i)}catch(e){}return e}();try{const e="undefined"!=typeof window?window:{},t=ve("string"==typeof e.CST_CLIENT_ID?e.CST_CLIENT_ID:"");if(t){if(!we(t,r)&&ye(t))return i(t),t;(0,Pn.AO)("Rejected non-canonical or blocked CST_CLIENT_ID",{candidate:t})}}catch(e){}try{const t="undefined"!=typeof document&&"string"==typeof document.cookie&&((null===(e=document.cookie.match(/(?:^|; )_cst_clientId=([^;]*)/))||void 0===e?void 0:e[1])?decodeURIComponent(document.cookie.match(/(?:^|; )_cst_clientId=([^;]*)/)[1]):void 0)||void 0,n="undefined"!=typeof localStorage&&(localStorage.getItem("_cst_clientId")||localStorage.getItem("cst_client_id")||void 0)||void 0,o=ve(t||n||"");if(o){if(!we(o,r)&&ye(o))return i(o),o;(0,Pn.AO)("Rejected non-canonical or blocked stored clientId",{candidate:o})}}catch(e){}let o="UNKNOWN";try{const e=document.getElementsByTagName("script");(0,Pn.cY)("Searching for clientId in scripts:",e.length);for(const t of Array.from(e)){if(!t)continue;let e=null;try{if(t.src){const n=new URL(t.src,document.baseURI);e=n.searchParams.get("cid")||n.searchParams.get("clientId")||n.searchParams.get("client_id")}}catch(e){}e||(e=t.getAttribute("data-cid")||t.getAttribute("data-client-id")||null);const n=t.src||"",i=[Hn,"cst.js","cst-local.js"].some(e=>n.includes(e)),a=n.includes("https://ti-cs.s3.amazonaws.com/dev")||n.includes("https://ti-cs.s3.amazonaws.com")||n.includes("https://dev-cdn.klrr.org")||n.includes("https://cdn.klrr.org")||n.includes("klrr.org");if((0,Pn.cY)("Checking script for clientId",{src:n,rawClientId:e,matchesKnownScriptName:i,matchesKnownDomain:a}),(i||a)&&e){const t=ve(e);if(we(t,r))continue;o=t,(0,Pn.cY)("Found clientId:",o);break}}}catch(e){(0,Pn.AO)("Error during clientId discovery",e)}if("UNKNOWN"===o)try{const e=document.querySelector('meta[name="cst:clientId"], meta[name="cst-client-id"]');if(e&&e.content){const t=ve(e.content);we(t,r)||(o=t,(0,Pn.cY)("Found clientId via meta tag:",o))}}catch(e){}return(0,Pn.cY)("Final clientId:",o),o&&"UNKNOWN"!==o&&i(o),o}function Ie(){let e=n(Vn)||localStorage.getItem(Vn)||"";if(e){try{const n=a();t(Vn,e,qn,{domain:n,path:"/",sameSite:"Lax"}),localStorage.setItem(Vn,e)}catch(e){(0,Pn.AO)("Error re-persisting existing userId:",e)}return e}const i="cst_uid_lock",r=Date.now(),o=`${r}:${Math.random().toString(36).slice(2)}`,s=()=>localStorage.getItem(i)||"",c=e=>{const t=Number(e.split(":")[0]||0);return t&&r-t<5e3};let l=s();if(l&&c(l)){const i=Date.now();for(;Date.now()-i<250&&(e=n(Vn)||localStorage.getItem(Vn)||"",!e)&&(l=s(),l&&c(l));){const e=Date.now()+25;for(;Date.now()<e;);}if(e){try{const n=a();t(Vn,e,qn,{domain:n,path:"/",sameSite:"Lax"})}catch(e){}return e}}try{const e=s();e&&c(e)||localStorage.setItem(i,o)}catch(e){}const d=s()===o;e=`u_${pe()}`,(0,Pn.cY)("Generated new userId",e);try{const n=a();t(Vn,e,qn,{domain:n,path:"/",sameSite:"Lax"})}catch(e){(0,Pn.AO)("Error persisting userId cookie:",e)}try{localStorage.setItem(Vn,e)}catch(e){(0,Pn.AO)("Error persisting userId to localStorage:",e)}try{d&&localStorage.removeItem(i)}catch(e){}return e}function ke(e){let t;t="target"in e&&"function"==typeof e.target.getIframe?e.target.getIframe():e;let n=t.tagName.toLowerCase();return t.id&&(n+=`#${t.id}`),t.className&&(n+=`.${t.className.split(/\s+/).join(".")}`),n}function Ae(e){let t;t="target"in e&&"function"==typeof e.target.getIframe?e.target.getIframe():e;const n=(e,t)=>e?n(e.previousElementSibling,t||e.nodeName)+(e.nodeName===t?1:0):1,i=e=>e&&1===e.nodeType?e.id&&document.getElementById(e.id)===e?[`id("${e.id}")`]:[...i(e.parentNode),`${e.nodeName.toLowerCase()}[${n(e.previousElementSibling,e.nodeName)}]`]:[];return i(t).join("/")}function Ee(e,t,n=3e5){if(e.forEach((i,r)=>{t-i>n&&e.delete(r)}),e.size>500){const t=[];e.forEach((e,n)=>t.push([n,e])),t.sort((e,t)=>e[1]-t[1]);const n=e.size-500;for(let i=0;i<n;i++)e.delete(t[i][0])}}function Oe(e){Ee(Ui,e),Ee(zi,e),Ee(qi,e)}function Le(e){const t=D(),n=Ui.get(e);return void 0!==n&&t-n<3e3}function Ce(e){const t=D();Ui.set(e,t),Oe(t)}function Ye(e,t=3e3){const n=D(),i=Ui.get(e);return void 0!==i&&n-i<t}function Me(e){const t=D();return t-(qi.get(e)||0)<Vi||(qi.set(e,t),Oe(t),!1)}function Pe(e){const t=Fi.get(e);return!!t&&D()-t.timestamp<Hi.DEDUPLICATION_WINDOW}function xe(e){try{return`form:${e.id||e.getAttribute("data-form-id")||ke(e)}`}catch(e){return"form:unknown"}}function Re(e){return`form:${e}`}function Ne(e,t,n=1e3){e.forEach((i,r)=>{t-i>n&&e.delete(r)})}function De(e){if(!e)return"";try{const t=new URL(e,location.href);return`${t.hostname}${t.pathname}`}catch(t){return String(e||"")}}function $e(e){if(!e)return"";const t={};try{Object.keys(e).forEach(n=>{const i=n.toLowerCase();i.startsWith("hs_")||i.startsWith("utm")||"hs_context"===i||Gi.has(i)&&(t[i]=e[n])})}catch(e){}return function(e){if(!e)return"";try{const t=Object.keys(e).sort().map(t=>`${t}:${String(e[t])}`);return t.join("|")}catch(t){try{return JSON.stringify(e)}catch(t){return String(e)}}}(t)}function We(e){const t=De(e||"");return t?`action:${t}`:""}function Fe(e){try{return new URL(e,location.href).hostname}catch(e){return""}}function He(e){if(null==e)return"";if("string"==typeof e)return e.toLowerCase();try{const t=e;if("string"==typeof t.value)return t.value.toLowerCase();if("string"==typeof t.baseVal)return t.baseVal.toLowerCase()}catch(e){}return String(e||"").toLowerCase()}function je(e){try{let t=!0;try{const n=window.getComputedStyle(e);t=null!==e.offsetParent||"none"!==n.display}catch(e){t=!0}if(!t)return!1;const n=Array.from(e.elements||[]);for(const e of n)if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)if(e instanceof HTMLInputElement){const t=(e.type||"").toLowerCase();if("hidden"===t)continue;if("password"===t)continue;if(("checkbox"===t||"radio"===t)&&e.checked)return!0;if("text"===t||"email"===t||"tel"===t||"url"===t||"search"===t||"number"===t){const t=(e.value||"").trim();if(t&&"0"!==t)return!0}}else if(e instanceof HTMLTextAreaElement){if((e.value||"").trim())return!0}else if(e instanceof HTMLSelectElement){const t=(e.value||"").trim();if(t&&"0"!==t&&"select"!==t.toLowerCase())return!0}}catch(e){}return!1}function Ue(e){const t=Zi.get(e);return t?D()-t.timestamp>5e3?(Zi.delete(e),null):t.data:null}function ze(){const e=D();return er>0&&e-er<2e3}function Ve(e,t){if(Pe(e))return ji.duplicatesBlocked++,(0,Pn.cY)("Duplicate submission blocked",e),"";const n=pe(),i={elementId:e.id||ke(e),timestamp:D(),submissionId:n,method:t};return Fi.set(e,i),n}function qe(e){return li.some(t=>"string"==typeof t?e.toLowerCase().includes(t.toLowerCase()):t.test(e))}function Be(e){var t,n;const i={};let r=0;if(e.elements.length>Hi.MAX_FORM_FIELDS)return(0,Pn.AO)("Form has too many fields, skipping",e.id),{};if(null===(t=e.action)||void 0===t?void 0:t.includes("facebook.com/tr/"))return{};if(e.classList.contains("hs-form")||(null===(n=e.id)||void 0===n?void 0:n.includes("hsForm_"))||e.closest("[data-reactroot]"))try{const t=new FormData(e);if(Array.from(t.entries()).forEach(([e,t])=>{"hs_context"!==e&&t&&"string"==typeof t&&(i[e]=t.slice(0,Hi.MAX_FIELD_LENGTH))}),0===Object.keys(i).length){const t=Ue(e);if(t)return(0,Pn.cY)("Using snapshot data for empty HubSpot form",e.id),t}return i}catch(e){(0,Pn.AO)("Error processing HubSpot form data",e)}for(let t=0;t<e.elements.length;t++){const n=e.elements[t];if(n instanceof HTMLInputElement||n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement){if(n instanceof HTMLInputElement&&Hi.DISALLOWED_FIELD_TYPES.includes(n.type))continue;if(n.name&&"submit"!==n.type){if(r++,r>Hi.MAX_FORM_FIELDS){(0,Pn.AO)("Too many form fields, truncating",e.id);break}const t=n.value.slice(0,Hi.MAX_FIELD_LENGTH);i[n.name]=qe(n.name)?"[REDACTED]":t}}}if(0===Object.keys(i).length||!Object.values(i).some(e=>e.length>0)){const t=Ue(e);if(t&&Object.keys(t).length>0)return(0,Pn.cY)("Using snapshot data for empty form",{formId:e.id,snapshotFields:Object.keys(t).length}),t}return i}async function Ke(e,t,n={}){var i,r;try{if(e.element&&null==e.element.captureSource){let n;n="submit"===t?"native":"xhr"===t?"network:xhr":"provider"===t?"provider":"click"===t?"button-only":t,e.element.captureSource=n}const n=function(e){var t,n;return[e.eventType||"",De((null===(t=e.element)||void 0===t?void 0:t.action)||""),$e(null===(n=e.element)||void 0===n?void 0:n.formData)].join("#")}(e);if(function(e,t=1e3){if(function(){var e;try{return"undefined"!=typeof process&&"test"===(null===(e=process.env)||void 0===e?void 0:"production")}catch(e){return!1}}())return!1;const n=D();return Ne(Bi,n,t),n-(Bi.get(e)||0)<t||(Bi.set(e,n),!1)}(n))return ji.duplicatesBlocked++,void(0,Pn.cY)("Duplicate form event fingerprint blocked",{label:e.label,action:null===(i=e.element)||void 0===i?void 0:i.action,method:t});const o=(null===(r=e.element)||void 0===r?void 0:r.action)||"";if(o)try{!function(e,t=1e3){const n=We(e);if(!n)return!1;const i=D();Ne(Ki,i,t),i-(Ki.get(n)||0)<t||Ki.set(n,i)}(o)}catch(e){}}catch(e){return void(0,Pn.AO)("Error preparing form event",e)}let o,a=null;const s=`form_submit_${e.eventId}`;try{o=await vi(e),localStorage.setItem(s,JSON.stringify(o)),a=te(o,{triggerSend:!1})}catch(e){return(0,Pn.AO)("Error building form batch",e),ji.formsMissed++,void ji.errors.push(`Batch error: ${e}`)}try{const i="submit"===t||"click"===t;let r=!1;try{r=await se(o,i)}catch(e){(0,Pn.AO)("Error sending form data",e),ji.errors.push(`Send error: ${e}`),r=!1}if(r)return a&&ne(a),localStorage.removeItem(s),(Array.isArray(n.throttleKeys)?n.throttleKeys:n.throttleKeys?[n.throttleKeys]:[]).forEach(e=>Ce(e)),ji.formsSubmitted++,"submit"===t||"xhr"===t?ji.universalSuccess++:"provider"===t&&ji.providerSuccess++,void(0,Pn.cY)("Form data sent successfully",e.eventId);(0,Pn.cY)("Form send failed, scheduling queued retry",e.eventId),a?ie():te(o,{triggerSend:!0}),ji.formsMissed++,!ji.errors.some(e=>e.includes("Send error"))&&ji.errors.length<50&&ji.errors.push("Send error: queued for retry")}catch(e){(0,Pn.AO)("Critical error in form submission recovery",e),ji.formsMissed++,ji.errors.length<50&&ji.errors.push(`Recovery error: ${e}`)}}async function Ge(e,t={}){const n={eventId:pe(),eventType:"formSubmit",time:(new Date).toISOString(),label:e.formId||`${e.provider}-form-signal`,value:e.action||e.provider,element:{tag:"form",id:e.formId||null,class:null,action:e.action||null,method:"post",formData:{},customSelector:e.formId?`#${e.formId}`:"",xpath:"",captureSource:"iframe-signal",signalMetadata:Object.assign({provider:e.provider,signalType:e.signalType,confidence:e.confidence,dataAvailable:!1},e.metadata||{})}};(0,Pn.cY)("📡 Sending form signal (no field data)",{provider:e.provider,formId:e.formId,signalType:e.signalType,confidence:e.confidence}),await Ke(n,"provider",t),ji.providerTriggers[`signal:${e.provider}`]=(ji.providerTriggers[`signal:${e.provider}`]||0)+1}async function Xe(e,t,n={}){try{if(n.throttleKeys&&(Array.isArray(n.throttleKeys)?n.throttleKeys:[n.throttleKeys]).forEach(e=>Ce(e)),(e.className||"").toLowerCase().includes("fusion-form")&&!je(e))return void(0,Pn.cY)("Skipping Fusion form without user input",e.className);const i=await async function(e,t){try{const n=Ve(e,t);if(!n)return null;const i=Be(e);return{eventId:n,eventType:"formSubmit",time:(new Date).toISOString(),label:e.id||e.className||"unnamed-form",value:M(e.action)||e.action||"",element:{tag:"form",id:e.id,class:e.className,action:M(e.action)||e.action,method:e.method,formData:i,customSelector:ke(e),xpath:Ae(e)}}}catch(e){return(0,Pn.AO)("Error creating form event",e),ji.errors.push(`Error creating form event: ${e}`),null}}(e,t);i&&await Ke(i,t,n)}catch(e){(0,Pn.AO)("Error handling form submission",e),ji.formsMissed++}}function Je(e){const t=e.target;if(!t||"FORM"!==t.tagName)return;const n=je(t),i=function(e){const t=Zi.get(e);return!!t&&(D()-t.timestamp>5e3?(Zi.delete(e),!1):t.hadUserInput)}(t);if(!n&&!i)return void(0,Pn.cY)("Skipping form submit without likely user input (checked current and snapshot)",t.id||t.className);const r=xe(t);if(Le(r))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled native form submit",r);try{if(t.classList.contains("hs-form")||t.id&&t.id.startsWith("hsForm_")||t.querySelector("input[name='hs_context']")){const e=D();zi.set(r,e)}}catch(e){}(0,Pn.cY)("Universal form submit detected",t.id||t.className),Xe(t,"submit",{throttleKeys:r})}function Qe(e){var t,n;const i=e.target.closest("button, input[type=submit], input[type=button]");if(!i)return;const r=i.matches("[type=submit]")||(null===(t=i.textContent)||void 0===t?void 0:t.toLowerCase().includes("submit"))||(null===(n=i.textContent)||void 0===n?void 0:n.toLowerCase().includes("send"))||i.classList.contains("submit")||"submit"===i.getAttribute("data-action");r&&ji.buttonSubmissions++;const o=i.closest("form");if(o&&r){const e=je(o),t=function(e){const t=je(e),n=Be(e),i=Object.keys(n).length>0&&Object.values(n).some(e=>e.length>0);return!(!t&&!i||(Zi.set(e,{data:n,timestamp:D(),hadUserInput:t}),(0,Pn.cY)("📸 Form data snapshot captured",{formId:e.id,fieldCount:Object.keys(n).length,hadUserInput:t}),0))}(o);if(!e&&!t)return;const n=xe(o);return void setTimeout(()=>{try{Pe(o)||Ye(n)||((0,Pn.cY)("Fallback form submission via button click (no native submit detected)",o.id||o.className),Xe(o,"submit",{throttleKeys:n}))}catch(e){(0,Pn.AO)("Fallback form submission error",e)}},400)}ze()||r&&((0,Pn.cY)("Button-only form submission detected",i),async function(e){var t,n;try{const i=`button:${e.id||(null===(t=e.textContent)||void 0===t?void 0:t.trim())||ke(e)}`;if(Le(i))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled button-only submission",i);Ce(i);const r=Ve(e,"click");if(!r)return;let o=e.closest("[data-form], .ghl-form-wrap, .form-builder--wrap, #_builder-form, .hl_form-builder--main, .c-form, .form, .contact-form, .newsletter")||document.getElementById("_builder-form")||e.closest(".ghl-form-wrap, .form-builder--wrap");if(!o){let t=e.parentElement,n=0;const i=5;for(;t&&n<i&&t!==document.body;){if(t.querySelectorAll("input:not([type=hidden]):not([type=submit]), textarea, select").length>=1){o=t;break}t=t.parentElement,n++}}o||(o=e.parentElement);const a=(null==o?void 0:o.querySelectorAll("input, textarea, select"))||[],s={};a.forEach(e=>{(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.name&&!qe(e.name)&&(s[e.name]=e.value.slice(0,Hi.MAX_FIELD_LENGTH).trim())});const c={eventId:r,eventType:"formSubmit",time:(new Date).toISOString(),label:(null===(n=e.textContent)||void 0===n?void 0:n.slice(0,Hi.MAX_FIELD_LENGTH).trim())||e.id||"unnamed-button",value:e.getAttribute("data-action")||"",element:{tag:e.tagName.toLowerCase(),id:e.id,class:e.className,formData:s,customSelector:ke(e),xpath:Ae(e)}};await Ke(c,"provider",{throttleKeys:i})}catch(e){(0,Pn.AO)("Error capturing button submission",e),ji.errors.push(`Button capture error: ${e}`)}}(i))}function Ze(e){if(ze())return void(0,Pn.cY)("Startup debounce active; skipping XHR form scan");const t=D();if(t-tr<1e3){if(!nr){const n=1e3-(t-tr)+50;(0,Pn.cY)(`XHR scan rate limited, queuing scan in ${n}ms`),nr=setTimeout(()=>{nr=null,Ze(e)},n)}return}tr=t;const n=document.querySelectorAll("form");let i=!1;n.forEach(t=>{if(t instanceof HTMLFormElement&&!Pe(t)){const n=Be(t),r=Object.keys(n).length>0&&Object.values(n).some(e=>e.length>0),o=je(t),a=null!==t.offsetParent||"none"!==window.getComputedStyle(t).display;if(r&&o&&a){(0,Pn.cY)("Potential XHR form submission detected",t.id||t.className);const n=xe(t);Ye(n)||function(e,t=1e3){const n=We(e);return!!n&&D()-(Ki.get(n)||0)<t}(t.action)?(0,Pn.cY)("Skipping XHR capture due to recent native/provider send",n):Xe(t,e,{throttleKeys:n}),i=!0}}}),i||(0,Pn.cY)("XHR detected but no valid form submissions found")}function et(e,t=0){if(!e||t>3)return[];const n=[];if(Array.isArray(e)){for(const i of e)n.push(...et(i,t+1));return n}if("object"==typeof e)for(const[i,r]of Object.entries(e)){const e=i.toLowerCase();"string"==typeof r&&["event","eventname","event_type","type","status","action","name"].includes(e)&&n.push(r.toLowerCase()),n.push(...et(r,t+1))}return n}function tt(e,t=0){if(!e||t>3)return!1;if(Array.isArray(e))return e.some(e=>tt(e,t+1));if("object"==typeof e)for(const[n,i]of Object.entries(e)){const e=n.toLowerCase();if(or.includes(e))return!0;if(tt(i,t+1))return!0}return!1}function nt(e,t,n){var i;if("leadconnector"!==e)return!0;const r=function(e){if(!(null==e?void 0:e.text))return null;try{return JSON.parse(e.text)}catch(e){return null}}(n),o=et(r);if(o.some(e=>rr.has(e)))return!1;if(o.some(e=>ir.has(e)))return!0;if(tt(r))return!0;const a=(null===(i=null==n?void 0:n.text)||void 0===i?void 0:i.toLowerCase())||"";return!!a&&!/"event"\s*:\s*"calendar\.view"/i.test(a)&&(!!/email=|phone=|first_name=|last_name=|contact=/i.test(a)||/booking\.scheduled|appointment\.scheduled|meeting\.scheduled|\bbooked\b|\bconfirmed\b/i.test(a))}function it(){function e(e){try{return new URL(e).hostname}catch(e){return""}}const t="cst_calendar_listener";if(window[t])return;window[t]=!0;const n=["calendly.com","www.calendly.com","cal.com","app.cal.com","tidycal.com","app.tidycal.com","acuityscheduling.com","app.acuityscheduling.com","oncehub.com","scheduleonce.com","savvycal.com","meetings.hubspot.com","leadconnectorhq.com","backend.leadconnectorhq.com","meetings.leadconnectorhq.com","app.leadconnectorhq.com","gohighlevel.com","msgsndr.com"];window.addEventListener("message",t=>{try{const i=e(t.origin);if(!i)return;if(!n.some(e=>i.endsWith(e)))return;const r=function(e){const t=e.toLowerCase();return t.includes("calendly")?"calendly":t.endsWith("cal.com")?"cal.com":t.includes("tidycal")?"tidycal":t.includes("acuity")?"acuity":t.includes("oncehub")||t.includes("scheduleonce")?"oncehub":t.includes("savvycal")?"savvycal":t.includes("hubspot")?"hubspot-meetings":t.includes("leadconnectorhq")||t.includes("leadconnector")||t.includes("gohighlevel")||t.includes("msgsndr")?"leadconnector":null}(i);if(!r)return;const o=t.data;let a="";"string"==typeof o?a=o.toLowerCase():o&&"object"==typeof o&&(a=String(o.type||o.event||"").toLowerCase());let s=a.includes("scheduled")||a.includes("booking")||a.includes("meeting")||a.includes("booked")||a.includes("event_scheduled");if(!s&&o&&"object"==typeof o)try{const e=JSON.stringify(o).toLowerCase(),t=["event_scheduled","appointment","scheduled","booking","booked","meeting"].find(t=>e.includes(t));t&&(s=!0,a||(a=`payload:${t}`))}catch(e){}if(!s)return;const c=`calendar:${r}:${a}`;if(!(()=>{var e;try{return"undefined"!=typeof process&&"test"===(null===(e=process.env)||void 0===e?void 0:"production")}catch(e){return!1}})()&&Le(c))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled calendar event",{provider:r,signal:a});if(Me(c))return;const l=pe();let d=null;try{const n=Array.from(document.querySelectorAll("iframe")),i=e(t.origin);d=n.find(e=>{try{const t=new URL(e.src).hostname;return t===i||t.endsWith(i)}catch(e){return!1}})||null}catch(e){}const u={eventId:l,eventType:"formSubmit",time:(new Date).toISOString(),label:`calendar-${r}`,value:`message:${a}`,element:{tag:"iframe",id:(null==d?void 0:d.id)||"",class:(null==d?void 0:d.className)||"",action:(null==d?void 0:d.src)||t.origin,method:"postMessage",formData:{},customSelector:d?ke(d):r,xpath:d?Ae(d):"",captureSource:`calendar:${r}`}};(0,Pn.cY)("Calendar/iframe scheduled event detected",{provider:r,origin:t.origin,signal:a}),Ke(u,"provider",{throttleKeys:c}).catch(e=>(0,Pn.AO)("Error sending calendar event",e))}catch(e){(0,Pn.AO)("Calendar listener error",e)}})}function rt(e){const t=[],n=e||window.location.href;return Object.entries(sr).forEach(([e,i])=>{!i.active&&i.trigger(n)&&(t.push(e),i.active=!0,(0,Pn.cY)(`Form provider activated: ${i.name}`))}),t}function ot(){return Object.values(sr).filter(e=>e.active)}function at(e){if(null==e)return null;if("string"==typeof e){const t=e.trim();if(!t)return null;const n=t.toLowerCase();if(n.includes("hsformcallback")||n.includes("hubspot"))return{type:"hsFormCallback"};try{return JSON.parse(t)}catch(e){return null}}return"object"==typeof e?e:null}function st(e){return["password","credit_card","cc_number","cvv","ssn","social_security"].some(t=>e.toLowerCase().includes(t))}function ct(){if(cr.completed||cr.inProgress)return;const e=D();if(cr.lastAttemptAt&&e-cr.lastAttemptAt<3e4)return;if("undefined"==typeof window||"undefined"==typeof document||!((null===(n=null===(t=window.hbspt)||void 0===t?void 0:t.forms)||void 0===n?void 0:n.create)||document.querySelector(".hs-form, form[data-hs-cf-bound], .hbspt-form, script[src*='hsforms'], script[src*='hubspot'], iframe[src*='hsforms']")||ot().some(e=>"HubSpot"===e.name)))return;var t,n;cr.inProgress=!0,cr.lastAttemptAt=e;let i=0;const r=()=>{var e,t,n,o;if(i++,1!==i&&i%5!=0||(0,Pn.cY)(`🔧 HubSpot patch attempt ${i}:`,{hasWindow:"undefined"!=typeof window,hasHbspt:!!window.hbspt,hasForms:!!(null===(e=window.hbspt)||void 0===e?void 0:e.forms),hasCreate:"function"==typeof(null===(n=null===(t=window.hbspt)||void 0===t?void 0:t.forms)||void 0===n?void 0:n.create),hbsptKeys:window.hbspt?Object.keys(window.hbspt):[]}),"undefined"!=typeof window&&(null===(o=window.hbspt)||void 0===o?void 0:o.forms)&&"function"==typeof window.hbspt.forms.create){const e=window.hbspt.forms.create;return window.hbspt.forms.create=t=>{(0,Pn.cY)("🎯 HubSpot form created, patching callbacks:",t.formId);const n=t.onFormSubmit;return t.onFormSubmit=e=>{try{const n={};e.serializeArray().forEach(({name:e,value:t})=>{"hs_context"!==e&&(n[e]=t)}),(0,Pn.cY)("✅ HubSpot form submit intercepted:",{formId:t.formId,formData:n}),window.postMessage({type:"hsFormCallback",fields:n,id:t.formId,action:"hubspot"},"*")}catch(e){(0,Pn.AO)("Error in HubSpot form callback patch",e)}return n&&n(e)},e(t)},cr.completed=!0,cr.inProgress=!1,void(0,Pn.cY)("✅ HubSpot forms.create successfully patched!")}i<50?setTimeout(r,100):(cr.inProgress=!1,(0,Pn.cY)("⚠️ HubSpot patching failed after maximum attempts"))};r()}function lt(e,t,n,i){var r,o,a;try{if(!e)return void(0,Pn.cY)(`${i}: target missing, skipping wrap`);const s=Object.getOwnPropertyDescriptor(e,t),c=null!==(r=null==s?void 0:s.value)&&void 0!==r?r:e[t];if("function"!=typeof c)return void(0,Pn.cY)(`${i}: original is not a function, skipping wrap`);if(c[dr])return void(0,Pn.cY)(`${i}: already wrapped, skipping wrap`);if(/\[native code\]/.test(c.toString())||(0,Pn.cY)(`${i}: existing non-native implementation detected, chaining wrap`,{originalName:c.name}),s&&!1===s.configurable)return void(0,Pn.cY)(`${i}: descriptor not configurable, skipping wrap`);const l=n(c);l[dr]=!0,l[ur]=c;try{const e=c.toString.bind(c);Object.defineProperty(l,"toString",{value:function(){return e()},configurable:!0,writable:!0})}catch(e){}s?Object.defineProperty(e,t,{configurable:!0,enumerable:null!==(o=s.enumerable)&&void 0!==o&&o,writable:null===(a=s.writable)||void 0===a||a,value:l}):e[t]=l,(0,Pn.cY)(`${i}: successfully wrapped ${t}`)}catch(e){(0,Pn.AO)(`${i}: error wrapping ${t}`,e)}}function dt(e){if(!e)return null;if("string"==typeof e)return e;if("undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams)return e.toString();if("undefined"!=typeof FormData&&e instanceof FormData){const t=[];return e.forEach((e,n)=>{"string"==typeof e&&t.push(`${n}=${encodeURIComponent(e)}`)}),t.length?t.join("&"):null}if("object"==typeof e)try{return JSON.stringify(e)}catch(e){return null}return null}function ut(e,t){if(!e)return null;const n=function(e,t){if(!e)return null;try{if((null==t?void 0:t.includes("application/json"))||e.trim().startsWith("{"))return JSON.parse(e);if((null==t?void 0:t.includes("application/x-www-form-urlencoded"))||e.includes("=")){const t=new URLSearchParams(e),n={};if(t.forEach((e,t)=>{"hs_context"!==t&&(n[t]=e)}),Object.keys(n).length>0)return n}return null}catch(e){return null}}(e,t);return{text:e,parsed:n||void 0,contentType:t}}function mt(){var e;e={onProviderTrigger:e=>{rt(e)},onCalendarMatch:(e,t,n)=>{const i=function(e){for(const t of ar)if(t.re.test(e))return{provider:t.provider,signal:t.signal};return null}(e);i&&setTimeout(()=>{!async function(e,t,n,i){try{if(!nt(e,0,i))return void(0,Pn.cY)("Skipping calendar network event due to non-booking payload",{provider:e,signal:n});const r=`calendar:${e}:network:${n}`;if(Le(r)||Me(r))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled calendar network event",{provider:e,signal:n});const o={eventId:pe(),eventType:"formSubmit",time:(new Date).toISOString(),label:`calendar-${e}`,value:`network:${n}`,element:{tag:"network",id:"",class:"calendar-network",action:t,method:"POST",formData:{},customSelector:e,xpath:"",captureSource:`calendar:${e}`}};(0,Pn.cY)("Calendar booking detected via network",{provider:e,url:t,signal:n}),await Ke(o,"provider",{throttleKeys:r})}catch(e){(0,Pn.AO)("Error emitting calendar network event",e)}}(i.provider,e,i.signal,n)},50)},onFormSubmissionMatch:(e,t,n)=>{"POST"===t.toUpperCase()&&(function(e,t){const n=hr.find(t=>t.test(e));n&&((0,Pn.cY)("🔍 POTENTIAL HUBSPOT SUBMISSION DETECTED (lenient):",{url:e,matchedPattern:n.toString(),method:"POST",timestamp:(new Date).toISOString(),hasBody:!!(null==t?void 0:t.text),hasParsedData:!!(null==t?void 0:t.parsed)}),(e.includes("hsforms.com")||e.includes("hubspot.com/submissions"))&&function(e,t){const n=ft(e)||"hubspot-network",i=`form:${n}`;Ye(i)?(0,Pn.cY)("Skipping network HubSpot signal - recent postMessage capture exists"):setTimeout(()=>{Ye(i)?(0,Pn.cY)("Skipping network HubSpot signal - postMessage captured during delay"):Ge({provider:"hubspot",formId:n,action:e,signalType:"networkIntercept",confidence:(null==t?void 0:t.parsed)?.7:.5,metadata:{source:"network-fallback",hasBody:String(!!(null==t?void 0:t.text)),hasParsedData:String(!!(null==t?void 0:t.parsed))}},{throttleKeys:i})},500)}(e,t))}(e,n),function(e){if(mr.some(t=>t.test(e)))return(0,Pn.cY)("Excluded analytics endpoint from form detection:",e),!1;const t=fr.find(t=>t.test(e));return!!t&&((0,Pn.cY)("Form submission endpoint detected:",{url:e,matchedPattern:t.toString()}),!0)}(e)&&((0,Pn.cY)("Likely form submission detected via network",e),(null==n?void 0:n.parsed)&&Object.keys(n.parsed).length>0?function(e,t){const n=ft(e)||"network-form",i=xe({id:n});if(Le(i)||Ye(i))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled network form capture",{url:e,formId:n});const r=function(e){const t=document.querySelectorAll("form");for(const n of Array.from(t)){const t=n;if(t.action&&e.includes(t.action))return t}const n=Fe(e);if(n)for(const e of Array.from(t)){const t=e;if(t.action&&Fe(t.action)===n)return t}return null}(e);r?Xe(r,"xhr",{throttleKeys:i}):((0,Pn.cY)("📡 Network form capture (no DOM form found):",{url:e,formId:n,parsedFields:t.parsed?Object.keys(t.parsed):[]}),Ge({provider:ht(e)||"unknown",formId:n,action:e,signalType:"networkIntercept",confidence:t.parsed?.7:.5,metadata:{capturedFields:t.parsed?String(Object.keys(t.parsed).length):"0",contentType:t.contentType||"unknown"}},{throttleKeys:i}))}(e,n):setTimeout(()=>Ze("xhr"),100)))}},"undefined"!=typeof XMLHttpRequest&&(lt(XMLHttpRequest.prototype,"send",e=>function(t){try{this.__cstRequestBodyText=dt(t)}catch(e){(0,Pn.cY)("Unable to capture XHR request body",e)}return e.call(this,t)},"XMLHttpRequest.send"),lt(XMLHttpRequest.prototype,"setRequestHeader",e=>function(t,n){try{"content-type"===t.toLowerCase()&&(this.__cstContentType=n)}catch(e){}return e.call(this,t,n)},"XMLHttpRequest.setRequestHeader"),lt(XMLHttpRequest.prototype,"open",t=>function(n,i,r=!0,o,a){const s="string"==typeof i?i:i.toString();try{e.onProviderTrigger(s)}catch(e){(0,Pn.AO)("Error in onProviderTrigger callback",e)}if("POST"===n.toUpperCase()){const t=this;this.addEventListener("load",()=>{try{const i=ut(t.__cstRequestBodyText,t.__cstContentType);e.onCalendarMatch(s,n,i),e.onFormSubmissionMatch(s,n,i)}catch(e){(0,Pn.AO)("Error in XHR load callbacks",e)}})}return t.call(this,n,i,r,o,a)},"XMLHttpRequest.open")),"undefined"!=typeof window&&"function"==typeof window.fetch&&lt(window,"fetch",t=>async function(n,i){const{url:r,method:o,bodyInfo:a}=function(e,t){var n,i,r;let o,a="",s="GET",c=null!==(n=null==t?void 0:t.body)&&void 0!==n?n:null;if("string"==typeof e)a=e;else if(e instanceof URL)a=e.toString();else if("undefined"!=typeof Request&&e instanceof Request){if(a=e.url,s=e.method||s,null==c&&"function"==typeof e.clone)try{c="function"==typeof e.clone().text?void 0:null}catch(e){}try{o=(null===(r=null===(i=e.headers)||void 0===i?void 0:i.get)||void 0===r?void 0:r.call(i,"content-type"))||void 0}catch(e){}}else a=String(e);if((null==t?void 0:t.method)&&(s=t.method),!o&&(null==t?void 0:t.headers))try{if(t.headers instanceof Headers)o=t.headers.get("content-type")||void 0;else if(Array.isArray(t.headers)){const e=t.headers.find(([e])=>"content-type"===e.toLowerCase());o=null==e?void 0:e[1]}else"object"==typeof t.headers&&(o=t.headers["content-type"]||t.headers["Content-Type"])}catch(e){}const l=dt(c);return{url:a,method:(s||"GET").toUpperCase(),bodyInfo:ut(l,o)}}(n,i);if(r)try{e.onProviderTrigger(r)}catch(e){(0,Pn.AO)("Error in onProviderTrigger callback (fetch)",e)}const s=await t.call(this,n,i);if("POST"===o&&r)try{e.onCalendarMatch(r,o,a),e.onFormSubmissionMatch(r,o,a)}catch(e){(0,Pn.AO)("Error in fetch callbacks",e)}return s},"window.fetch")}function ft(e){try{const t=new URL(e,location.href),n=e.match(/\/([a-f0-9-]{36})\//)||t.searchParams.get("formGuid")||t.searchParams.get("formId");return n?"string"==typeof n?n:n[1]:t.searchParams.get("form_id")||t.searchParams.get("formId")||t.searchParams.get("id")||null}catch(e){return null}}function ht(e){const t=[[/hubspot|hsforms/i,"hubspot"],[/pardot/i,"pardot"],[/eloqua/i,"eloqua"],[/marketo/i,"marketo"],[/mailchimp/i,"mailchimp"],[/typeform/i,"typeform"],[/gravityforms|gf_/i,"gravity"],[/wpforms/i,"wpforms"],[/ninja/i,"ninjaforms"],[/formidable/i,"formidable"]];for(const[n,i]of t)if(n.test(e))return i;return null}function pt(){ot().forEach(e=>{var t;ji.providerTriggers[e.name]=(ji.providerTriggers[e.name]||0)+1,null===(t=e.events)||void 0===t||t.forEach(t=>{const n=`${e.name}:${t}`;if(pr.has(n))return;if("HubSpot"===e.name&&"message"===t)return(0,Pn.cY)("Skipping HubSpot message handler - using dedicated listener"),void pr.add(n);const i=n=>{(0,Pn.cY)(`Provider event detected: ${t} for ${e.name}`),setTimeout(()=>function(e){e.selectors.forEach(t=>{document.querySelectorAll(t).forEach(n=>{var i;if(n instanceof HTMLFormElement){if("HubSpot"===e.name&&!n.classList.contains("hs-form")&&!(null===(i=n.id)||void 0===i?void 0:i.startsWith("hsForm_"))&&null===n.querySelector("input[name='hs_context']"))return void(0,Pn.cY)("Skipping non-HubSpot form with hs-cf-bound",{id:n.id,className:n.className});if(!je(n))return void(0,Pn.cY)("Skipping provider capture without user input",{provider:e.name,selector:t,id:n.id});const r=`provider:${e.name}:${n.id||ke(n)}`;if(Le(r))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled provider form submit",r);const o=xe(n);if(Ye(o))return ji.duplicatesBlocked++,void(0,Pn.cY)("Suppressed provider capture due to recent send",{provider:e.name,idPart:o});(0,Pn.cY)(`Provider form found: ${e.name}`,n.id),Xe(n,"provider",{throttleKeys:[r,o]})}})})}(e),50)};window.addEventListener(t,i),document.addEventListener(t,i,!0),pr.add(n)})})}function gt(){var e,t;if(vr)return;vr=!0,(0,Pn.cY)("Initializing enhanced form tracking");const n="__cstEnhancedFormTrackingInit";if(("undefined"==typeof process||"test"!==(null===(e=process.env)||void 0===e?void 0:"production"))&&window[n])return void(0,Pn.cY)("Enhanced form tracking already initialized, skipping");window[n]=!0,t=D(),er=t,function(){try{const e=JSON.parse(localStorage.getItem("cst_learned_patterns")||"[]");e.forEach(e=>{Xi.add(e),Ji.set(e,.8)}),(0,Pn.cY)(`Loaded ${e.length} learned patterns from storage`)}catch(e){(0,Pn.AO)("Error loading learned patterns",e)}}();const i=function(){const e=new Set,t=document.querySelectorAll("form");Array.from(t).forEach(t=>{if(t.action)try{const n=new URL(t.action,location.href).hostname;n&&n!==location.hostname&&(e.add(n),Qi.add(n))}catch(e){}const n=t,i=He(n.className),r=He(n.id||n.getAttribute("id"));(i.includes("hubspot")||i.includes("hs-form")||r.includes("hsform"))&&(Qi.add("hsforms.com"),e.add("hubspot")),(i.includes("gravity")||i.includes("gform"))&&e.add("gravity-forms"),(i.includes("contact")||i.includes("mailchimp"))&&e.add("contact-form"),i.includes("typeform")&&(Qi.add("typeform.com"),e.add("typeform"))});const n=document.querySelectorAll("iframe");return Array.from(n).forEach(t=>{const n=t.src;if(n)try{const t=new URL(n).hostname;(t.includes("hubspot")||t.includes("hsforms"))&&(Qi.add(t),e.add("hubspot-iframe")),t.includes("typeform")&&(Qi.add(t),e.add("typeform-iframe"))}catch(e){}}),(0,Pn.cY)("Discovered providers:",Array.from(e)),e}();(0,Pn.cY)("Discovered form providers:",Array.from(i));try{rt()}catch(e){(0,Pn.AO)("Error activating form providers via triggers",e)}pt(),document.addEventListener("gform_confirmation_loaded",e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t[0];(0,Pn.cY)("Gravity Forms confirmation loaded:",n);const i=document.querySelector(`#gform_${n}`);i&&!Pe(i)&&((0,Pn.cY)("Gravity Forms submission detected via confirmation:",n),Xe(i,"provider"))}),document.addEventListener("gform_post_render",e=>{var t;const n=null===(t=e.detail)||void 0===t?void 0:t.formId;(0,Pn.cY)("Gravity Forms post render:",n)}),"undefined"!=typeof HTMLFormElement&&lt(HTMLFormElement.prototype,"submit",e=>function(...t){var n;return(null===(n=null==this?void 0:this.id)||void 0===n?void 0:n.startsWith("gform_"))&&!Pe(this)&&((0,Pn.cY)("Gravity Forms iframe submission detected:",this.id),Xe(this,"provider")),e.apply(this,t)},"HTMLFormElement.submit"),document.addEventListener("click",e=>{var t;const n=e.target;if((null===(t=null==n?void 0:n.id)||void 0===t?void 0:t.startsWith("gform_submit_button_"))&&!Pe(n)){const e=n.id.replace("gform_submit_button_",""),t=document.querySelector(`#gform_${e}`);t&&((0,Pn.cY)("Gravity Forms button submission detected:",e),Xe(t,"provider"))}}),function(){const e="__cstHubSpotListener";window[e]||(window[e]=!0,window.addEventListener("message",e=>{var t,n;try{if(!function(e){if(/hubspot|hsforms/i.test(e.origin||""))return!0;const t=at(e.data);if(!t)return!1;const n="string"==typeof t.origin?t.origin:"";if(n&&/hubspot|hsforms/i.test(n))return!0;const i="string"==typeof t.type?t.type.toLowerCase():"";if("hsformcallback"===i)return!0;if(i.startsWith("hs.form.")||i.startsWith("hsform"))return!0;const r="string"==typeof t.eventName?t.eventName.toLowerCase():"";if(r.includes("hubspot")||r.includes("hsform"))return!0;if(lr.submitted.some(e=>r.includes(e))&&(t.formGuid||t.portalId||t.formId))return!0;const o="string"==typeof t.id?t.id.toLowerCase():"";return!!(o.startsWith("hsform")||o.includes("hubspot")||t.formGuid||t.portalId)}(e))return;const i=at(e.data);if(!i)return;(0,Pn.cY)("🔔 HubSpot PostMessage received:",{origin:e.origin,data:e.data,type:typeof e.data,hasType:null==i?void 0:i.type,isHubSpot:(null===(t=e.origin)||void 0===t?void 0:t.includes("hubspot"))||(null===(n=e.origin)||void 0===n?void 0:n.includes("hsforms"))});const r=function(e){if(!e)return null;const t="string"==typeof e.type?e.type.toLowerCase():"",n="string"==typeof e.eventName?e.eventName.toLowerCase():"",i=lr.submitted.some(e=>n.includes(e)),r=!!(e.fields||e.data||e.submissionData);if(!(i||"hsformcallback"===t&&i||"hsformcallback"===t&&r||"hs.form.submitted"===t||t.includes("submitted")||"onformsubmitted"===n||r&&(e.portalId||e.formGuid)))return null;const o=e.id||e.formId||e.formGuid||e.guid||("object"==typeof e.form?e.form.id:null)||"hubspot-form",a=e.fields||e.data||e.submissionData;let s=.5;return r&&a&&Object.keys(a).length>0&&(s+=.3),(e.formGuid||e.portalId)&&(s+=.1),"onformsubmitted"===n&&(s+=.1),{isSubmission:!0,formId:String(o),hasFields:r,fields:a,confidence:Math.min(s,1)}}(i);if(!r||!r.isSubmission)return;const o=r.formId||"hubspot-form",a=Re(o),s=D();if(Le(a)||Ye(a))return ji.duplicatesBlocked++,void(0,Pn.cY)("Throttled HubSpot callback",{formId:o});if(s-(zi.get(a)||0)<Hi.DEDUPLICATION_WINDOW)return ji.duplicatesBlocked++,void(0,Pn.cY)("Duplicate HubSpot submission blocked (unified)",{formId:o});zi.set(a,s);let c=i.action||i.url||"hubspot";try{const e=document.querySelector(`form#${CSS.escape(o)}, form[id*='${o}'], form.hs-form`);e&&e.action&&(c=e.action)}catch(e){}r.hasFields&&r.fields?((0,Pn.cY)("✅ HubSpot form callback processed with field data:",{formId:o,hasFields:!0,confidence:r.confidence}),async function(e,t,n){try{const i=pe(),r={};return Array.isArray(n)?n.forEach(({name:e,value:t})=>{const n="string"==typeof t?t:String(null!=t?t:"");e&&(r[e]=st(e)?"[REDACTED]":n.slice(0,Hi.MAX_FIELD_LENGTH))}):Object.entries(n).forEach(([e,t])=>{t&&"string"==typeof t&&(r[e]=st(e)?"[REDACTED]":t.slice(0,Hi.MAX_FIELD_LENGTH))}),{eventId:i,eventType:"formSubmit",time:(new Date).toISOString(),label:e||"hubspot-form",value:t,element:{tag:"form",id:e,class:"hs-form",action:t,method:"post",formData:r,customSelector:`#hsForm_${e}`,xpath:"",captureSource:"provider:hubspot"}}}catch(e){return(0,Pn.AO)("Error creating HubSpot form event",e),ji.errors.push(`Error creating HubSpot form event: ${e}`),null}}(o,c,r.fields).then(e=>{e&&Ke(e,"provider",{throttleKeys:a})}).catch(e=>{(0,Pn.AO)("Error processing HubSpot form callback",e)})):((0,Pn.cY)("📡 HubSpot form submission detected (signal-only, no field data):",{formId:o,confidence:r.confidence,origin:e.origin}),Ge({provider:"hubspot",formId:o,action:c,signalType:"postMessage",confidence:r.confidence,metadata:{origin:e.origin||"unknown",hasPortalId:String(!!i.portalId),hasFormGuid:String(!!i.formGuid)}},{throttleKeys:a}).catch(e=>{(0,Pn.AO)("Error sending HubSpot signal-only capture",e)}))}catch(e){(0,Pn.AO)("Error processing HubSpot postMessage",e)}}),function(){const e="__cstHubSpotBroadListener";window[e]||(window[e]=!0,window.addEventListener("message",e=>{try{if(!/hsforms\.net|hubspot\.com/i.test(e.origin||""))return;const t=at(e.data);if(!t)return;const n="string"==typeof t.type?t.type.toLowerCase():"",i="string"==typeof t.eventName?t.eventName.toLowerCase():"";if((lr.complete.some(e=>n.includes(e)||i.includes(e))||t.redirectUrl||t.thankYouMessage)&&!lr.submitted.some(e=>i.includes(e))){const e=t.formGuid||t.formId||"hubspot-unknown",r=Re(e);Ye(r)||((0,Pn.cY)("📡 HubSpot completion signal detected via broad listener:",{formId:e,type:n,eventName:i,hasRedirect:!!t.redirectUrl}),Ge({provider:"hubspot",formId:e,signalType:"postMessage",confidence:.6,metadata:{detectedVia:"broad-listener",hasRedirect:String(!!t.redirectUrl),hasThankYou:String(!!t.thankYouMessage)}},{throttleKeys:r}).catch(e=>{(0,Pn.AO)("Error in broad HubSpot listener",e)}))}}catch(e){}}))}())}(),it(),ct();try{mt()}catch(e){(0,Pn.AO)("Failed installing form network interceptors",e)}if(document.addEventListener("submit",Je,!0),document.addEventListener("click",Qe,!0),yr){try{yr.disconnect()}catch(e){}yr=null}yr=new MutationObserver(e=>{let t=!1;e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&("FORM"===e.tagName||e.querySelector&&e.querySelector("form"))&&(t=!0)})}),t&&((0,Pn.cY)("New forms detected via MutationObserver"),setTimeout(()=>{document.querySelectorAll("form").forEach(e=>{e instanceof HTMLFormElement&&!gr.has(e)&&((0,Pn.cY)("Setting up tracking for late-rendered form:",e.id||e.className||"unnamed"),gr.add(e))}),rt(),ct()},500))}),yr.observe(document.body,{childList:!0,subtree:!0}),Sr&&clearTimeout(Sr),Sr=setTimeout(()=>{const e=document.querySelectorAll("form");(0,Pn.cY)(`Found ${e.length} forms on page load`),e.forEach(e=>{e instanceof HTMLFormElement&&!gr.has(e)&&((0,Pn.cY)("Setting up tracking for form:",e.id||e.className||"unnamed"),gr.add(e))})},1e3),wr&&clearInterval(wr),wr=setInterval(()=>{pt(),ct()},2e3),(0,Pn.cY)("Enhanced form tracking initialized")}function vt(){(0,Pn.cY)("Rescanning all forms");const e=document.querySelectorAll("form");ji.formsFound=e.length,ct(),rt(),pt(),it(),(0,Pn.cY)(`Rescan complete: ${e.length} forms found`)}function yt(){br?(0,Pn.cY)("Heartbeat already running"):"visible"===document.visibilityState?((0,Pn.cY)("Starting heartbeat"),br=setInterval(()=>{(async function(e=!1){var t;try{(0,Pn.cY)("sendHeartbeat called");const n=stateManager.getState();if("UNKNOWN - STATE"===n.clientId||!(null===(t=n.session)||void 0===t?void 0:t.id))return void(0,Pn.cY)("heartbeat - invalid state. not sending");if("visible"!==document.visibilityState)return void(0,Pn.cY)("heartbeat - tab not visible");const i=wi;if(i>0&&Date.now()-i<Tr)return void(0,Pn.cY)("heartbeat - recent non-heartbeat event sent; skipping keepalive");const r=Object.assign({},ji),o={eventId:pe(),eventType:"heartbeat",time:(new Date).toISOString(),activeTime:n.session.activeTimeInSeconds,timeout:e,formMetrics:r};await ee(o)}catch(e){(0,Pn.AO)("Error sending heartbeat",e),wt()}})().catch(e=>(0,Pn.AO)("Error sending heartbeat",e))},Tr)):(0,Pn.cY)("Heartbeat not started - page hidden")}function wt(){br&&(clearInterval(br),br=null,(0,Pn.cY)("Heartbeat stopped"))}function St(){const e=window.scrollY||document.documentElement.scrollTop||0,t=(document.documentElement.scrollHeight||0)-(window.innerHeight||0);return t<=0?0:Math.min(100,Math.max(0,Math.round(e/t*100)))}function bt(){(0,Pn.cY)("Resetting scroll tracking"),Lr&&(clearTimeout(Lr),Lr=null),kr=Object.assign({},di),Er=0,Cr=0,Yr=!1,Mr=!1,Ar&&(window.removeEventListener("scroll",Ar),Ar=null),Or=!1}function Tt(){const e=St();e>Cr&&(Cr=e),(0,Rn.AE)()}function _t(){Lr&&clearTimeout(Lr),Lr=setTimeout(()=>{Lr=null,function(){if(Mr)(0,Pn.cY)("Already processing scroll milestones, skipping");else if(!(Cr<=Er)){Mr=!0;try{Er=Cr;let e=null;if(Object.keys(kr).forEach(t=>{const n=parseInt(t,10);Cr>=n&&!kr[n]&&(kr[n]=!0,(!e||n>e)&&(e=n))}),null!==e){const t={eventId:pe(),eventType:"scroll",time:(new Date).toISOString(),value:e};(0,Pn.cY)(`Sending scroll event for milestone: ${e}%`),ee(t)}}finally{Mr=!1}}}()},500)}function It(){if(Or&&Ar)(0,Pn.cY)("Scroll tracking already initialized, skipping");else try{(0,Pn.cY)("Initializing scroll tracking"),bt(),Ar=()=>{Yr||(Yr=!0,requestAnimationFrame(()=>{Yr=!1,Tt()})),_t()},window.addEventListener("scroll",Ar,{passive:!0}),Or=!0,setTimeout(()=>{Tt(),Cr>0&&_t()},0),(0,Pn.cY)("Scroll tracking initialized")}catch(e){(0,Pn.AO)("Error tracking scroll",e),Or=!1}}function kt(){const{clickTrackingMode:e,customClickSelector:t,alwaysIncludeClasses:n,includeDataAnlInStandard:i}=Pr,r='button, a, input, select, textarea, [role="button"], [data-track-click]',o=['[class*="btn"]','[class*="button"]','[class*="cta"]'],a=["[data-anl-event]","[data-anl-event_action]"];if("standard"===e){const e=[];return n&&e.push(...o),i&&e.push(...a),At(r+(e.length?", "+e.join(", "):""),t)}const s=a.concat('[tabindex]:not([tabindex="-1"])',o);return At("enhanced"===e?r+", "+s.join(", "):r+", "+[].concat(s).concat(["[onclick]","div[role]","span[role]","[data-action]","[data-anl-element_order]","[data-anl-event_action_result]"]).join(", "),t)}function At(e,t){return t?e+", "+t:e}function Et(){try{(0,Pn.cY)("Reinitializing click tracking (manual trigger)"),Yt(),xr="",Ct()}catch(e){(0,Pn.AO)("Failed to reinitialize click tracking",e)}}function Ot(e){const t=Object.assign({},Pr);if(t.customClickSelector)try{if(e.matches(t.customClickSelector))return{mode:"forced",source:"custom"}}catch(e){}return"BUTTON"===e.tagName||"A"===e.tagName||["INPUT","SELECT","TEXTAREA"].includes(e.tagName)||"button"===e.getAttribute("role")||e.hasAttribute("data-track-click")?{mode:"semantic",source:"native"}:e.hasAttribute("data-anl-event")||e.hasAttribute("data-anl-event_action")?{mode:"heuristic",source:"data-anl"}:/btn|button|cta/i.test(e.className||"")?{mode:"heuristic",source:"class"}:e.hasAttribute("onclick")?{mode:"heuristic",source:"onclick"}:{mode:"heuristic",source:"other"}}function Lt(e,t){const n=kt(),i=null==e?void 0:e.closest(n);if(!i)return;if($r.has(i))return;const r=x(async()=>{var e,t,n,r,o;try{(0,Pn.cY)("Click event triggered for element:",i.tagName,i.id||i.className);let a="",s="";const c=e=>{if(e instanceof HTMLImageElement)return e;const t=e.querySelector("img");return t instanceof HTMLImageElement?t:null};i instanceof HTMLAnchorElement&&(a=i.href),(i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement)&&(s=i.value);const l=i.getBoundingClientRect(),d={top:l.top,left:l.left},u=Ot(i),m=c(i),f=(null===(e=i.innerText)||void 0===e?void 0:e.slice(0,1e3).trim())||"",h=i.getAttribute("aria-label")||"",p=i.getAttribute("title")||"",g=(null==m?void 0:m.alt)||"",v=(null==m?void 0:m.src)?M(m.src)||m.src:"",y=f||h||p||g||v||null,w={eventId:pe(),eventType:"click",time:(new Date).toISOString(),label:i.tagName.toLowerCase(),value:s||i.tagName.toLowerCase(),element:{tag:i.tagName.toLowerCase(),text:y,id:null!==(t=i.id)&&void 0!==t?t:null,class:null!==(n=i.className)&&void 0!==n?n:null,ariaLabel:null!==(r=i.getAttribute("aria-label"))&&void 0!==r?r:null,role:null!==(o=i.getAttribute("role"))&&void 0!==o?o:null,viewportPosition:null!=d?d:null,scrollDepth:St(),selector:ke(i),href:M(a)||a||null,src:v||null,value:null!=s?s:null,checked:i instanceof HTMLInputElement?i.checked:null,customSelector:ke(i),xpath:Ae(i),captureMode:u.mode,captureSource:u.source}};(0,Pn.cY)("Queueing click event:",w),await ee(w),(0,Pn.cY)("Click event queued for batched send")}catch(e){(0,Pn.AO)("Error in throttled click handler",e)}},500,{maxRequestsPerSecond:2,leading:!0,trailing:!1}),o=async function(e){var t,n,o,a,s,c;try{if(e.__cstClickHandled)return;(0,Rn.WI)();const i=e.currentTarget instanceof HTMLElement?e.currentTarget:this instanceof HTMLElement?this:null;if(!i)return;if((0,Pn.cY)("Click event detected on:",i.tagName,i.id||i.className),!(e instanceof MouseEvent))return;try{const t=e.target;if(t&&t instanceof HTMLElement){const e=t.closest(kt());if(e&&e!==i)return}}catch(e){}e.__cstClickHandled=!0;const l=i instanceof HTMLAnchorElement?i.getAttribute("target"):null,d=!l||""===l||"_self"===l,u=(()=>{if(!(i instanceof HTMLAnchorElement))return!1;if((i.getAttribute("href")||"").startsWith("#"))return!0;try{const e=new URL(i.href,document.baseURI);return e.origin===location.origin&&e.pathname===location.pathname&&e.search===location.search&&e.hash!==location.hash&&""!==e.hash}catch(e){return!1}})();if(i instanceof HTMLAnchorElement&&i.href&&!u&&d&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&!e.altKey&&i instanceof HTMLAnchorElement){const e=i.getAttribute("href")||i.href,r=Ot(i),l=(e=>{if(e instanceof HTMLImageElement)return e;const t=e.querySelector("img");return t instanceof HTMLImageElement?t:null})(i),d=(null===(t=i.innerText)||void 0===t?void 0:t.slice(0,1e3).trim())||"",u=i.getAttribute("aria-label")||"",m=i.getAttribute("title")||"",f=(null==l?void 0:l.alt)||"",h=(null==l?void 0:l.src)?M(l.src)||l.src:"",p=d||u||m||f||h||null,g={eventId:pe(),eventType:"click",time:(new Date).toISOString(),label:i.tagName.toLowerCase(),value:i.tagName.toLowerCase(),element:{tag:i.tagName.toLowerCase(),text:p,id:null!==(n=i.id)&&void 0!==n?n:null,class:null!==(o=i.className)&&void 0!==o?o:null,ariaLabel:null!==(a=i.getAttribute("aria-label"))&&void 0!==a?a:null,role:null!==(s=i.getAttribute("role"))&&void 0!==s?s:null,viewportPosition:null!==(c=i.getBoundingClientRect())&&void 0!==c?c:null,scrollDepth:St(),selector:ke(i),href:M(e)||e||null,src:h||null,value:null,checked:null,customSelector:ke(i),xpath:Ae(i),captureMode:r.mode,captureSource:r.source}},v=await vi(g);(0,Pn.cY)("Navigation click batch",v);const y=te(v,{triggerSend:!1});try{await se(v,!0)?ne(y):((0,Pn.cY)("Navigation click send failed, scheduling queued retry",v.eventType),y?ie():te(v,{triggerSend:!0}))}catch(e){(0,Pn.AO)("Navigation click send threw error, scheduling queued retry",e),y?ie():te(v,{triggerSend:!0})}}else r()}catch(e){(0,Pn.AO)("Error in click handler",e),i instanceof HTMLAnchorElement&&window.location.assign(i.href)}};i.addEventListener("click",o,{capture:!0,passive:!1}),$r.add(i),(0,Pn.cY)("Click listener added to:",i.tagName,i.id||i.className),t instanceof MouseEvent&&o.call(i,t)}function Ct(){try{if(Rr)return void(0,Pn.cY)("Click tracking already initialized");Rr=!0,(0,Pn.cY)("Initializing click tracking system"),function(){try{(function(e=document){if(!Pr.autoEnhanceClicks)return!1;try{const t=e.querySelectorAll('button, a, [role="button"], [data-track-click]').length,n=e.querySelectorAll('[class*="btn"], [class*="button"], [class*="cta"], [data-anl-event], [data-anl-event_action]').length;return 0!==n&&(0===t||n/(t+1)>.5)}catch(e){return!1}})(document)&&"standard"===Pr.clickTrackingMode&&(Pr=Object.assign(Object.assign({},Pr),{clickTrackingMode:"enhanced"}),1)&&(0,Pn.cY)("Auto-enhanced click tracking mode → enhanced");const e=kt();xr=e;const t=document.querySelectorAll(e);if((0,Pn.cY)(`Initializing click listeners for ${t.length} elements`),t.forEach(e=>{Lt(e)}),Nr)try{Nr.disconnect()}catch(e){}Nr=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&(e.matches(kt())&&Lt(e),e.querySelectorAll(kt()).forEach(e=>{Lt(e)}))})})}),Nr.observe(document.body,{childList:!0,subtree:!0})}catch(e){(0,Pn.AO)("Error initializing clickable elements",e)}}();const e=x(e=>{const t=kt();if(e.target instanceof HTMLElement){const n=e.target.closest(t);n&&!$r.has(n)&&((0,Pn.cY)("Adding click listener to dynamically detected element:",n.tagName),Lt(n,e))}},200,{maxRequestsPerSecond:2,leading:!0,trailing:!1});Dr=e,document.addEventListener("click",Dr),(0,Pn.cY)("Click tracking system initialized")}catch(e){(0,Pn.AO)("Error in initial click listener",e)}}function Yt(){try{Nr&&(Nr.disconnect(),Nr=null),Dr&&(document.removeEventListener("click",Dr),Dr=null)}catch(e){(0,Pn.AO)("cleanupClickTracking error",e)}finally{Rr=!1}}function Mt({element:e,eventType:t,platform:n,videoId:i,src:r,label:o,value:a,watchPercentage:s,furthestWatchPercentage:c,watchTime:l,furthestWatchTime:d}){try{ee({eventId:pe(),eventType:t,time:(new Date).toISOString(),label:o||i,value:null!=a?a:String(s),element:{tag:e.tagName.toLowerCase(),id:e.id,class:e.className,videoId:i,watchPercentage:s,furthestWatchPercentage:c,watchTime:l,furthestWatchTime:d,videoPlatform:n,customSelector:ke(e),xpath:Ae(e),src:null!=r?r:e instanceof HTMLMediaElement?e.currentSrc:e.src||null}})}catch(e){(0,Pn.AO)("Error emitting video event",e)}}function Pt(){document.querySelectorAll("video").forEach(e=>{(e=>{try{if(Fr.has(e))return;Fr.add(e);const t=Hr.get(e)||pe();Hr.set(e,t),(0,Pn.cY)("Initializing HTML video tracking",{videoId:t,src:e.currentSrc||e.src,duration:e.duration}),Wr.has(t)||Wr.set(t,{lastPlayTime:e.currentTime,furthestWatchTime:0,watchTime:0,intervalsReported:new Set,lastRealTimestamp:void 0}),e.addEventListener("play",()=>{const n=Wr.get(t);if(!n)return;const i=Date.now();n.lastPlayTime=e.currentTime,n.lastRealTimestamp=i;const r=Math.floor(n.watchTime/e.duration*100),o=Math.floor(n.furthestWatchTime/e.duration*100);(0,Pn.cY)("HTML Video play event",{videoId:t,currentTime:e.currentTime,watchTime:n.watchTime,watchPercentage:r,furthestWatchTime:n.furthestWatchTime,furthestWatchPercentage:o}),Mt({element:e,eventType:"videoPlay",platform:"HTML5",videoId:Hr.get(e)||t,watchPercentage:r,furthestWatchPercentage:o,watchTime:Math.floor(n.watchTime),furthestWatchTime:Math.floor(n.furthestWatchTime),src:e.currentSrc||e.src}),n.intervalId&&clearInterval(n.intervalId),n.intervalId=setInterval(()=>{if(e.paused||e.ended)return void(n.intervalId&&(clearInterval(n.intervalId),n.intervalId=void 0));const i=Date.now();n.lastRealTimestamp&&(n.watchTime+=(i-n.lastRealTimestamp)/1e3),n.lastRealTimestamp=i,e.currentTime>n.furthestWatchTime&&(n.furthestWatchTime=e.currentTime);const r=Math.floor(n.watchTime/e.duration*100),o=Math.floor(n.furthestWatchTime/e.duration*100),a=10*Math.floor(o/10);a>0&&!n.intervalsReported.has(a)&&(n.intervalsReported.add(a),(0,Pn.cY)(`HTML Video ${t}: ${a}% position reached. Actually watched: ${r}%`),Mt({element:e,eventType:"videoProgress",platform:"HTML5",videoId:Hr.get(e)||t,watchPercentage:r,furthestWatchPercentage:o,watchTime:Math.floor(n.watchTime),furthestWatchTime:Math.floor(n.furthestWatchTime),src:e.currentSrc||e.src}))},1e3)}),e.addEventListener("pause",()=>{const n=Wr.get(t);if(!n)return;if(n.lastRealTimestamp){const e=Date.now();n.watchTime+=(e-n.lastRealTimestamp)/1e3,n.lastRealTimestamp=void 0}e.currentTime>n.furthestWatchTime&&(n.furthestWatchTime=e.currentTime);const i=Math.floor(n.watchTime/e.duration*100),r=Math.floor(n.furthestWatchTime/e.duration*100);(0,Pn.cY)("HTML Video pause event",{videoId:t,currentTime:e.currentTime,watchTime:n.watchTime,watchPercentage:i,furthestWatchTime:n.furthestWatchTime,furthestWatchPercentage:r}),n.intervalId&&(clearInterval(n.intervalId),n.intervalId=void 0),Mt({element:e,eventType:"videoPause",platform:"HTML5",videoId:Hr.get(e)||t,watchPercentage:i,furthestWatchPercentage:r,watchTime:Math.floor(n.watchTime),furthestWatchTime:Math.floor(n.furthestWatchTime),src:e.currentSrc||e.src})}),e.addEventListener("ended",()=>{const n=Wr.get(t);if(!n)return;if(n.lastRealTimestamp){const e=Date.now();n.watchTime+=(e-n.lastRealTimestamp)/1e3,n.lastRealTimestamp=void 0}n.furthestWatchTime=e.duration;const i=Math.floor(n.watchTime/e.duration*100);(0,Pn.cY)("HTML Video ended event",{videoId:t,duration:e.duration,watchTime:n.watchTime,watchPercentage:i}),n.intervalId&&(clearInterval(n.intervalId),n.intervalId=void 0),Mt({element:e,eventType:"videoEnded",platform:"HTML5",videoId:Hr.get(e)||t,watchPercentage:i,furthestWatchPercentage:100,watchTime:Math.floor(n.watchTime),furthestWatchTime:Math.floor(e.duration),src:e.currentSrc||e.src})})}catch(e){(0,Pn.AO)("Error tracking HTML video",e)}})(e)})}function xt(e,t=0){const n=e.duration||0;return{watchPercentage:n?Math.min(100,Math.floor(e.watchTime/n*100)):Math.min(100,Math.floor(100*t)),furthestWatchPercentage:n?Math.min(100,Math.floor(e.furthestWatchTime/n*100)):Math.min(100,Math.floor(100*t))}}async function Rt(e){var t;try{if(await function(){var e;return(null===(e=window.Vimeo)||void 0===e?void 0:e.Player)?Promise.resolve():jr||(jr=new Promise((e,t)=>{const n=document.createElement("script");n.src="https://player.vimeo.com/api/player.js",n.async=!0,n.onload=()=>e(),n.onerror=e=>t(e),document.head.appendChild(n)}).catch(e=>{throw(0,Pn.AO)("Failed to load Vimeo player API",e),jr=null,e}),jr)}(),!(null===(t=window.Vimeo)||void 0===t?void 0:t.Player))return void(0,Pn.AO)("Vimeo Player constructor not available after script load");const n=Vr.get(e)||`vimeo-${pe()}`;Vr.set(e,n),zr.add(e);const i=new window.Vimeo.Player(e),r={player:i,element:e,videoKey:n,duration:0,watchTime:0,furthestWatchTime:0,lastSeconds:0,intervalsReported:new Set,handlers:{play:()=>{i.getCurrentTime().then(e=>{r.lastSeconds=e||0}).catch(()=>{}),i.getDuration().then(e=>{e&&(r.duration=e)}).catch(()=>{});const{watchPercentage:e,furthestWatchPercentage:t}=xt(r);Mt({element:r.element,eventType:"videoPlay",platform:"Vimeo",videoId:r.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(r.watchTime),furthestWatchTime:Math.floor(r.furthestWatchTime),src:r.element.src})},pause:()=>{i.getCurrentTime().then(e=>{if("number"==typeof e){e>r.furthestWatchTime&&(r.furthestWatchTime=e);const t=e-r.lastSeconds;t>0&&(r.watchTime+=t),r.lastSeconds=e}}).catch(()=>{});const{watchPercentage:e,furthestWatchPercentage:t}=xt(r);Mt({element:r.element,eventType:"videoPause",platform:"Vimeo",videoId:r.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(r.watchTime),furthestWatchTime:Math.floor(r.furthestWatchTime),src:r.element.src})},ended:()=>{r.duration>0&&(r.watchTime=r.duration,r.furthestWatchTime=r.duration);const{watchPercentage:e,furthestWatchPercentage:t}=xt(r,1);Mt({element:r.element,eventType:"videoEnded",platform:"Vimeo",videoId:r.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(r.watchTime||r.duration),furthestWatchTime:Math.floor(r.furthestWatchTime||r.duration),src:r.element.src})},timeupdate:e=>function(e,t){try{const n="number"==typeof(null==t?void 0:t.seconds)?t.seconds:e.lastSeconds,i="number"==typeof(null==t?void 0:t.percent)?t.percent:0;if("number"==typeof(null==t?void 0:t.duration)&&t.duration>0&&(e.duration=t.duration),"number"==typeof n){if(e.lastSeconds>=0){const t=n-e.lastSeconds;t>0&&(e.watchTime+=t)}e.lastSeconds=n,n>e.furthestWatchTime&&(e.furthestWatchTime=n)}const{watchPercentage:r,furthestWatchPercentage:o}=xt(e,i),a=10*Math.floor(o/10);a>0&&a<=100&&!e.intervalsReported.has(a)&&(e.intervalsReported.add(a),Mt({element:e.element,eventType:"videoProgress",platform:"Vimeo",videoId:e.element.src,watchPercentage:r,furthestWatchPercentage:o,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime),src:e.element.src}))}catch(e){(0,Pn.AO)("Error handling Vimeo timeupdate",e)}}(r,e)}};i.getDuration().then(e=>{e&&(r.duration=e)}).catch(()=>{}),i.on("play",r.handlers.play),i.on("pause",r.handlers.pause),i.on("ended",r.handlers.ended),i.on("timeupdate",r.handlers.timeupdate),Ur.set(n,r),(0,Pn.cY)("Vimeo tracking initialized",{src:e.src,videoKey:n})}catch(e){(0,Pn.AO)("Error setting up Vimeo tracking",e)}}function Nt(e=document){const t=function(e){const t=e instanceof HTMLElement?e:document;return Array.from(t.querySelectorAll('iframe[src*="player.vimeo.com"]')).filter(e=>!zr.has(e))}(e);t.forEach(e=>Rt(e))}function Dt(e){const t=e.duration||0;return{watchPercentage:t?Math.min(100,Math.floor(e.watchTime/t*100)):0,furthestWatchPercentage:t?Math.min(100,Math.floor(e.furthestWatchTime/t*100)):0}}function $t(e){const t=e.dataset&&(e.dataset.wistiaId||e.dataset.hashedId||e.dataset.videoId)||null;if(t)return t;const n=e.className.match(/wistia_async_([a-zA-Z0-9]+)/);return n&&n[1]?n[1]:e.getAttribute("data-wistia-id")||e.getAttribute("data-hashed-id")||null}function Wt(e,t){t&&!Br.has(t)&&(Br.add(t),Gr.set(e,t),window._wq||(window._wq=[]),window._wq.push({id:t,onReady:n=>{try{!function(e,t,n){var i;try{const r={video:e,element:t,videoKey:n,duration:(null===(i=e.duration)||void 0===i?void 0:i.call(e))||0,watchTime:0,furthestWatchTime:0,lastSeconds:0,intervalsReported:new Set,handlers:{}};r.handlers=function(e){return{play:()=>{e.lastSeconds=e.video.time()||0,e.duration=e.video.duration()||e.duration;const{watchPercentage:t,furthestWatchPercentage:n}=Dt(e);Mt({element:e.element,eventType:"videoPlay",platform:"Wistia",videoId:e.videoKey,label:e.element.getAttribute("title")||e.videoKey,src:e.element instanceof HTMLIFrameElement?e.element.src:null,watchPercentage:t,furthestWatchPercentage:n,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime)})},pause:()=>{const{watchPercentage:t,furthestWatchPercentage:n}=Dt(e);Mt({element:e.element,eventType:"videoPause",platform:"Wistia",videoId:e.videoKey,label:e.element.getAttribute("title")||e.videoKey,src:e.element instanceof HTMLIFrameElement?e.element.src:null,watchPercentage:t,furthestWatchPercentage:n,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime)})},end:()=>{e.duration=e.video.duration()||e.duration,e.watchTime=e.duration,e.furthestWatchTime=e.duration;const{watchPercentage:t,furthestWatchPercentage:n}=Dt(e);Mt({element:e.element,eventType:"videoEnded",platform:"Wistia",videoId:e.videoKey,label:e.element.getAttribute("title")||e.videoKey,src:e.element instanceof HTMLIFrameElement?e.element.src:null,watchPercentage:t,furthestWatchPercentage:n,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime)})},timechange:t=>{if("number"!=typeof t)return;const n=t-e.lastSeconds;n>0&&(e.watchTime+=n),e.lastSeconds=t,e.duration=e.video.duration()||e.duration,t>e.furthestWatchTime&&(e.furthestWatchTime=t);const{watchPercentage:i,furthestWatchPercentage:r}=Dt(e),o=10*Math.floor(r/10);o>0&&o<=100&&!e.intervalsReported.has(o)&&(e.intervalsReported.add(o),Mt({element:e.element,eventType:"videoProgress",platform:"Wistia",videoId:e.videoKey,label:e.element.getAttribute("title")||e.videoKey,src:e.element instanceof HTMLIFrameElement?e.element.src:null,watchPercentage:i,furthestWatchPercentage:r,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime)}))}}}(r),e.bind("play",r.handlers.play),e.bind("pause",r.handlers.pause),e.bind("end",r.handlers.end),e.bind("timechange",r.handlers.timechange),Kr.add(t),Gr.set(t,n),qr.set(n,r),(0,Pn.cY)("Wistia tracking initialized",{videoKey:n})}catch(e){(0,Pn.AO)("Error binding Wistia video",e)}}(n,e,t)}catch(e){(0,Pn.AO)("Error in Wistia onReady handler",e)}}}))}function Ft(e=document){const t=function(e){const t=e instanceof HTMLElement?e:document;return Array.from(t.querySelectorAll('.wistia_embed, [data-wistia-id], [data-hashed-id], iframe[src*="fast.wistia.net"], iframe[src*="wistia.com"]')).filter(e=>!Kr.has(e))}(e);t.forEach(e=>{const t=$t(e);t?Wt(e,t):(0,Pn.cY)("Unable to determine Wistia hashed id",{id:e.id,className:e.className})})}function Ht(e){const t=e.duration||0;return{watchPercentage:t?Math.min(100,Math.floor(e.watchTime/t*100)):0,furthestWatchPercentage:t?Math.min(100,Math.floor(e.furthestWatchTime/t*100)):0}}function jt(e,t,n){if("number"==typeof n&&n>0&&(e.duration=n),"number"==typeof t){const n=t-e.lastSeconds;n>0&&(e.watchTime+=n),e.lastSeconds=t,t>e.furthestWatchTime&&(e.furthestWatchTime=t)}const{watchPercentage:i,furthestWatchPercentage:r}=Ht(e),o=10*Math.floor(r/10);o>0&&o<=100&&!e.intervalsReported.has(o)&&(e.intervalsReported.add(o),Mt({element:e.element,eventType:"videoProgress",platform:"Loom",videoId:e.element.src,src:e.element.src,watchPercentage:i,furthestWatchPercentage:r,watchTime:Math.floor(e.watchTime),furthestWatchTime:Math.floor(e.furthestWatchTime)}))}function Ut(e){try{if(!e.data||"object"!=typeof e.data)return;if(!function(e){try{const t=new URL(e).hostname;return t.endsWith("loom.com")||t.endsWith("loom.com:443")}catch(e){return!1}}(e.origin))return;const t=function(e){if(!e)return null;let t=null;return Jr.forEach(n=>{t||n.contentWindow!==e||(t=n)}),t}(e.source)||(1===Jr.size?Array.from(Jr.values())[0]:null);if(!t)return;const n=Zr.get(t)||t.src;let i=Xr.get(n);i||(i={element:t,videoKey:n,duration:0,watchTime:0,furthestWatchTime:0,lastSeconds:0,intervalsReported:new Set},Xr.set(n,i));const r=function(e){if(!e)return null;const t=e.eventName||e.type||e.name||e.event||e.event_type||e.action;return t?{name:String(t).toUpperCase().startsWith("LOOM_")?String(t).toUpperCase():`LOOM_${String(t).toUpperCase()}`,data:e.data||e.payload||e.details||e.message||e}:null}(e.data);if(!r)return;const o=r.name;if(!o.startsWith("LOOM_"))return;const a=r.data||{},s="number"==typeof a.currentTime?a.currentTime:"number"==typeof a.time?a.time:void 0,c="number"==typeof a.duration?a.duration:void 0;switch(o){case"LOOM_PLAY":{"number"==typeof s&&(i.lastSeconds=s),"number"==typeof c&&(i.duration=c);const{watchPercentage:e,furthestWatchPercentage:t}=Ht(i);Mt({element:i.element,eventType:"videoPlay",platform:"Loom",videoId:i.element.src,src:i.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(i.watchTime),furthestWatchTime:Math.floor(i.furthestWatchTime)});break}case"LOOM_PAUSE":{"number"==typeof s&&jt(i,s,c);const{watchPercentage:e,furthestWatchPercentage:t}=Ht(i);Mt({element:i.element,eventType:"videoPause",platform:"Loom",videoId:i.element.src,src:i.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(i.watchTime),furthestWatchTime:Math.floor(i.furthestWatchTime)});break}case"LOOM_END":case"LOOM_ENDED":{"number"==typeof c&&(i.duration=c),i.watchTime=i.duration,i.furthestWatchTime=i.duration;const{watchPercentage:e,furthestWatchPercentage:t}=Ht(i);Mt({element:i.element,eventType:"videoEnded",platform:"Loom",videoId:i.element.src,src:i.element.src,watchPercentage:e,furthestWatchPercentage:t,watchTime:Math.floor(i.watchTime),furthestWatchTime:Math.floor(i.furthestWatchTime)});break}case"LOOM_SEEK":case"LOOM_PROGRESS":case"LOOM_TIME":"number"==typeof s&&jt(i,s,c)}}catch(e){(0,Pn.AO)("Error handling Loom message",e)}}function zt(e){const t=e instanceof HTMLElement?e:document;return Array.from(t.querySelectorAll('iframe[src*="loom.com/embed"], iframe[src*="loom.com/share"]')).filter(e=>!Qr.has(e))}function Vt(e){if(Qr.has(e))return;eo||(eo=!0,window.addEventListener("message",Ut));let t=Zr.get(e)||`loom-${pe()}`;Zr.set(e,t),Qr.add(e),Jr.add(e),Xr.has(t)||Xr.set(t,{element:e,videoKey:t,duration:0,watchTime:0,furthestWatchTime:0,lastSeconds:0,intervalsReported:new Set}),(0,Pn.cY)("Loom tracking initialized",{src:e.src,videoKey:t})}function qt(e=document){zt(e).forEach(Vt);try{to&&(to.disconnect(),to=null),to=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&zt(e).forEach(Vt)})})}),to.observe(document.body,{childList:!0,subtree:!0})}catch(e){(0,Pn.AO)("Error setting up Loom MutationObserver",e)}}function Bt(e){e&&(async()=>{try{if(await new Promise((e,t)=>{let n=0;const i=()=>{if(window.YT&&window.YT.Player)return(0,Pn.cY)("YouTube API loaded successfully"),void e();if(n>=uo){(0,Pn.cY)("YouTube API not found after retries, attempting to reload"),window.onYouTubeIframeAPIReady=()=>{(0,Pn.cY)("YouTube API reloaded successfully"),e()};const t=document.querySelector('script[src*="youtube.com/iframe_api"]');return t&&t.remove(),void ao()}n++,setTimeout(i,mo)};i()}),(()=>{const e=document.querySelectorAll('iframe[src*="youtube.com/embed/"]');(0,Pn.cY)("Found YouTube iframes:",e.length),e.forEach(e=>{const t=ho(e);t.id&&Kt(t,!0)})})(),fo)try{fo.disconnect()}catch(e){}fo=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&e.querySelectorAll('iframe[src*="youtube.com/embed/"]').forEach(e=>{const t=ho(e);t.id&&Kt(t,!0)})})})}),fo.observe(document.body,{childList:!0,subtree:!0})}catch(e){(0,Pn.AO)("Error initializing YouTube iframes:",e)}})()}function Kt(e,t){try{const n=e;if((0,Pn.cY)("Initializing YouTube Iframe",{id:n.id,src:n.src,apiReady:!!window.YT&&!!window.YT.Player,youTubeApiCalled:t}),n.id||(n.id=`yt-${pe()}`,(0,Pn.cY)("Generated new YouTube iframe ID",{id:n.id})),!t)return void(0,Pn.cY)("YouTube API script not loaded yet, skipping initialization");if(!window.YT||!window.YT.Player){const e=lo.get(n)||0;if(e>=10)return void(0,Pn.AO)("Failed to initialize YouTube iframe after 10 retries",{id:n.id,src:n.src});const i=Math.min(100*Math.pow(2,e),3e3);return lo.set(n,e+1),(0,Pn.cY)("YouTube API not ready, retrying in "+i+"ms",{retryCount:e+1,id:n.id}),void setTimeout(()=>Kt(n,t),i)}if(lo.delete(n),co.has(n.id))return void(0,Pn.cY)("Player already initialized",{id:n.id});(0,Pn.cY)("Creating YouTube player",{iframeId:n.id,src:n.src}),new window.YT.Player(n.id,{events:{onReady:e=>{(0,Pn.cY)("YouTube player ready",{id:n.id,playerInfo:e.target.playerInfo}),co.has(n.id)||co.set(n.id,{lastPlayTime:0,furthestWatchTime:0,watchTime:0,intervalsReported:new Set,lastRealTimestamp:e.data===window.YT.PlayerState.PLAYING?Date.now():void 0})},onStateChange:e=>{const t=e;(0,Pn.cY)("YouTube player state changed",{id:n.id,state:e.data,playerInfo:e.target.playerInfo}),function(e){var t;try{const n=null===(t=e.target.g)||void 0===t?void 0:t.id;if(!n)return void(0,Pn.AO)("Missing player ID in YouTube event",e.target);const i=e.target;co.has(n)||co.set(n,{lastPlayTime:i.playerInfo.currentTime,furthestWatchTime:0,watchTime:0,intervalsReported:new Set,lastRealTimestamp:e.data===window.YT.PlayerState.PLAYING?Date.now():void 0});const r=co.get(n);if(!r)return void(0,Pn.AO)("Failed to get player state",{playerID:n});const o=i.playerInfo.currentTime,a=i.playerInfo.duration,s=Date.now();let c=null;if(e.data===window.YT.PlayerState.PLAYING&&(c="videoPlay",r.lastPlayTime=o,r.lastRealTimestamp=s,function(e,t){try{const n=setInterval(()=>{if(e.data!==window.YT.PlayerState.PLAYING)return void clearInterval(n);const i=co.get(t);if(!i||!i.lastRealTimestamp)return void clearInterval(n);const r=e.target,o=r.playerInfo.currentTime,a=r.playerInfo.duration,s=Date.now();i.watchTime+=(s-i.lastRealTimestamp)/1e3,i.lastRealTimestamp=s,i.furthestWatchTime=Math.max(i.furthestWatchTime,o);const c=Math.floor(o/a*100),l=Math.floor(i.watchTime/a*100),d=10*Math.floor(c/10);!i.intervalsReported.has(d)&&d>0&&(i.intervalsReported.add(d),(0,Pn.cY)(`YouTube video ${t}: ${d}% position reached. Actually watched: ${l}%`),Mt({element:document.getElementById(t),eventType:"videoProgress",platform:"YouTube",videoId:r.playerInfo.videoUrl,label:r.playerInfo.videoUrl,value:d.toString(),watchPercentage:l,furthestWatchPercentage:c,watchTime:Math.floor(i.watchTime),furthestWatchTime:Math.floor(i.furthestWatchTime),src:r.playerInfo.videoUrl}))},1e3),i=co.get(t);i&&(i.intervalId=n)}catch(e){(0,Pn.AO)("Error tracking youtube progress",e)}}(e,n)),(e.data===window.YT.PlayerState.PAUSED||e.data===window.YT.PlayerState.ENDED)&&(c=e.data===window.YT.PlayerState.PAUSED?"videoPause":"videoEnded",r.lastRealTimestamp&&(r.watchTime+=(s-r.lastRealTimestamp)/1e3,r.lastRealTimestamp=void 0),o>r.lastPlayTime&&(r.furthestWatchTime=Math.max(r.furthestWatchTime,o))),!c)return;const l=Math.floor(o/a*100),d=Math.floor(r.watchTime/a*100);(0,Pn.cY)("youtube video update",{playerID:n,eventType:c,watchPercentage:d,watchTime:Math.floor(r.watchTime),furthestWatchTime:Math.floor(r.furthestWatchTime),furthestWatchPercentage:l,formattedWatchTime:Gt(r.watchTime),currentTime:o,duration:a,lastPlayTime:r.lastPlayTime}),Mt({element:document.getElementById(n),eventType:c,platform:"YouTube",videoId:i.playerInfo.videoUrl,label:i.playerInfo.videoUrl,value:d.toString(),watchPercentage:d,furthestWatchPercentage:l,watchTime:Math.floor(r.watchTime),furthestWatchTime:Math.floor(r.furthestWatchTime),src:i.playerInfo.videoUrl})}catch(e){(0,Pn.AO)("Error in onPlayerStateChange",e)}}(t)},onError:e=>{(0,Pn.AO)("YouTube player error",{id:n.id,errorCode:e.data,src:n.src})}},playerVars:{origin:window.location.origin,enablejsapi:1,modestbranding:1,rel:0,controls:1,host:window.location.origin}})}catch(t){(0,Pn.AO)("Error initializing YouTube iframe",{error:t,iframeId:e.id,src:e.src})}}function Gt(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),i=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`:`${n}:${i.toString().padStart(2,"0")}`}function Xt(e){if(po.has(e))return;const t=e instanceof HTMLSelectElement,n=t?"change":"blur",i=t?"select_change":"input_blur",r=async()=>{if((0,Pn.cY)(`${n} event triggered`,e),!e.value.trim()||e instanceof HTMLInputElement&&("password"===e.type||"file"===e.type)||e.name&&(t=e.name,li.some(e=>"string"==typeof e?t.toLowerCase().includes(e.toLowerCase()):e.test(t))))return;var t;const r={eventId:pe(),eventType:"input",time:(new Date).toISOString(),label:i,value:e.value,element:{tag:e.tagName.toLowerCase(),id:e.id,class:e.className,type:e.type||null,name:e.name,value:e.value,customSelector:ke(e),xpath:Ae(e)}};(0,Pn.cY)("Queueing input event:",r);try{await ee(r),(0,Pn.cY)("input event queued for batched send")}catch(e){(0,Pn.AO)("Error queueing input data",e)}};e.addEventListener(n,r),po.add(e);const o=go.get(e)||{};o[n]=r,go.set(e,o)}function Jt(e){e.querySelectorAll("input, textarea, select").forEach(e=>{Xt(e)});const t=new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&Xt(e),e.querySelectorAll("input, textarea, select").forEach(e=>{Xt(e)}))})})});return t.observe(e,{childList:!0,subtree:!0}),t}function Qt(){wo||(wo=!0,(0,Pn.cY)("Starting input and select tracking"),vo=Jt(document),function(){let e=window.location.pathname;if(yo)try{yo.disconnect()}catch(e){}yo=new MutationObserver(()=>{window.location.pathname!==e&&(e=window.location.pathname,(0,Pn.cY)("SPA navigation detected, reinitializing input tracking"),vo&&vo.disconnect(),vo=Jt(document))}),yo.observe(document.body,{childList:!0,subtree:!0});const t=e=>{(0,Pn.cY)("Navigation detected, reinitializing input tracking"),vo&&vo.disconnect(),vo=Jt(document)};So=t,bo=t,To=t,window.addEventListener("popstate",So),window.addEventListener("pushState",bo),window.addEventListener("replaceState",To)}())}function Zt(e){return e.closest(Io)||e.closest("[role='listbox']")}async function en(e){const t=Zt(e),{value:n,label:i}=function(e){var t,n;const i=null!==(n=null===(t=e.textContent)||void 0===t?void 0:t.trim())&&void 0!==n?n:"",r=e.getAttribute("data-value"),o=e.getAttribute("value"),a=(r||o||i).trim();return{value:a,label:i||a}}(e);if(!n&&!i)return;const r=function(e,t){const n=function(e){if(!e)return null;const t=e.id;if(t){const e=document.querySelector(`[aria-controls='${CSS.escape(t)}']`);if(e instanceof HTMLInputElement)return e;const n=null==e?void 0:e.querySelector("input[name]");if(n instanceof HTMLInputElement)return n}const n=e.closest(Io)||e,i=null==n?void 0:n.querySelector("input[name], input[type='hidden'][name]");return i instanceof HTMLInputElement?i:null}(e.closest("[role='listbox']")||t);if(null==n?void 0:n.name)return n.name;if(t){const e=t.getAttribute("name")||t.getAttribute("data-name");return e&&e.trim()?e.trim():t.id&&t.id.trim()?t.id.trim():ke(t)}return ke(document.body)}(e,t),o={eventId:pe(),eventType:"input",time:(new Date).toISOString(),label:"dropdown_select",value:n,element:{tag:e.tagName.toLowerCase(),id:(null==t?void 0:t.id)||e.id||null,class:(null==t?void 0:t.className)||e.className||null,role:(null==t?void 0:t.getAttribute("role"))||null,name:r,text:i,selector:ke(e),customSelector:ke(e),xpath:Ae(e)}};(0,Pn.cY)("Custom dropdown option selected",{name:r,value:n,label:i,optionTag:e.tagName});const a=await vi(o);await se(a),(0,Pn.cY)("Custom dropdown input event sent successfully")}function tn(e){var t,n,i;try{const r=Object.getOwnPropertyDescriptor(history,e),o=null!==(t=null==r?void 0:r.value)&&void 0!==t?t:history[e];if("function"!=typeof o)return void(0,Pn.cY)(`SPA tracking: history.${e} missing or not a function; skipping patch`);if(o[Mo])return void(0,Pn.cY)(`SPA tracking: history.${e} already wrapped by CST`);if(/\[native code\]/.test(o.toString())||(0,Pn.cY)(`SPA tracking: history.${e} appears pre-wrapped; chaining listener`,{originalName:o.name}),r&&!1===r.configurable)return void(0,Pn.cY)(`SPA tracking: history.${e} not configurable; cannot patch`);const a=function(...t){const n=o.apply(this,t);try{window.dispatchEvent(new Event(e))}catch(t){(0,Pn.AO)(`SPA tracking: failed to dispatch ${e} event`,t)}return n};a[Mo]=!0,r?Object.defineProperty(history,e,{configurable:!0,enumerable:null!==(n=r.enumerable)&&void 0!==n&&n,writable:null===(i=r.writable)||void 0===i||i,value:a}):history[e]=a}catch(t){(0,Pn.AO)(`SPA tracking: error patching history.${e}`,t)}}function nn(e,t){try{if(Po.has(e))return;!function(e){var t;try{if(Po.has(e))return;if(e instanceof HTMLFormElement&&xo(),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&Xt(e),e.matches(kt())&&Lt(e),e instanceof HTMLVideoElement&&Lt(e),e instanceof HTMLIFrameElement&&(null===(t=e.src)||void 0===t?void 0:t.includes("youtube.com/embed/"))){const t=ho(e);oo()||ao(),Kt(t,oo())}!function(e){var t;e instanceof HTMLIFrameElement&&(null===(t=e.src)||void 0===t?void 0:t.includes("player.vimeo.com"))&&!zr.has(e)&&Rt(e)}(e),function(e){const t=$t(e);t&&Wt(e,t)}(e),function(e){var t,n;e instanceof HTMLIFrameElement&&((null===(t=e.src)||void 0===t?void 0:t.includes("loom.com/embed"))||(null===(n=e.src)||void 0===n?void 0:n.includes("loom.com/share")))&&Vt(e)}(e),Po.add(e)}catch(e){(0,Pn.AO)("Error processing element",e)}}(e),t.depth<Oo&&Array.from(e.children).forEach(e=>{e instanceof HTMLElement&&!t.processedNodes.has(e)&&(t.processedNodes.add(e),nn(e,Object.assign(Object.assign({},t),{depth:t.depth+1})))})}catch(e){(0,Pn.AO)("Error handling dynamic element",e)}}async function rn(){try{const e=Co,t=location.href;if(t===e)return void(0,Pn.cY)("Route change ignored because URL has not changed");if(function(e,t){try{const n=new URL(e,document.baseURI),i=new URL(t,document.baseURI);return n.origin===i.origin&&n.pathname===i.pathname&&n.search===i.search&&n.hash!==i.hash}catch(n){const i=e=>e.split("#")[0];return i(e)===i(t)&&e!==t}}(e,t))return Co=t,window.__cst_spa_last_url=Co,void(0,Pn.cY)("Hash-only navigation detected; skipping new page view");if(function(e,t){try{const n=new URL(e,document.baseURI),i=new URL(t,document.baseURI);return n.origin===i.origin&&n.pathname===i.pathname&&n.search!==i.search}catch(e){return!1}}(e,t))return Co=t,window.__cst_spa_last_url=Co,void(0,Pn.cY)("Query-only URL change detected; skipping new page view",{previousUrl:e,currentUrl:t});Co=t,window.__cst_spa_last_url=Co,(0,Pn.cY)(`Route change detected: ${e} -> ${t}`,{previousUrl:e,currentUrl:t,documentReferrer:document.referrer,computedReferrer:e||document.referrer});const n=D(),i={id:`pv_${window.location.pathname}_${pe()}`,startTime:n,startTimestamp:N(),lastActivityTime:n,activeTimeInSeconds:0,url:t,pathname:location.pathname,title:document.title,referrer:e||document.referrer,isValid:!0};await stateManager.endCurrentPageViewAndStartNew(i);try{(0,Pn.cY)("Sending initial data for SPA route change"),await Q()}catch(e){(0,Pn.AO)("Error sending initial data during SPA route change",e)}setTimeout(async()=>{try{me(),Yt(),function(){try{vo&&(vo.disconnect(),vo=null),yo&&(yo.disconnect(),yo=null),So&&(window.removeEventListener("popstate",So),So=null),bo&&(window.removeEventListener("pushState",bo),bo=null),To&&(window.removeEventListener("replaceState",To),To=null)}catch(e){(0,Pn.AO)("cleanupInputTracking error",e)}finally{wo=!1}}(),function(){try{Wr.forEach(e=>{e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}),Wr.clear()}catch(e){}}(),Ur.forEach(e=>{try{e.player.off("play",e.handlers.play),e.player.off("pause",e.handlers.pause),e.player.off("ended",e.handlers.ended),e.player.off("timeupdate",e.handlers.timeupdate)}catch(e){(0,Pn.AO)("Error cleaning up Vimeo tracking",e)}}),Ur.clear(),qr.forEach(e=>{try{e.video.unbind("play",e.handlers.play),e.video.unbind("pause",e.handlers.pause),e.video.unbind("end",e.handlers.end),e.video.unbind("timechange",e.handlers.timechange)}catch(e){(0,Pn.AO)("Error cleaning up Wistia tracking",e)}}),qr.clear(),Br.clear(),function(){window.removeEventListener("message",Ut),eo=!1;try{to&&(to.disconnect(),to=null)}catch(e){}Jr.clear(),Xr.clear()}();try{!function(){try{Ao&&(document.removeEventListener("click",Ao,!0),Ao=null),Eo&&(document.removeEventListener("keydown",Eo,!0),Eo=null)}catch(e){(0,Pn.AO)("cleanupCustomDropdownTracking error",e)}finally{ko=!1}}()}catch(e){}bt(),It(),document.querySelectorAll("input, textarea").forEach(e=>{e.removeAttribute("cst-event-active")}),Et(),gt(),vt(),Pt(),Nt(),Ft(),qt(),yt(),document.querySelectorAll("input, textarea").forEach(e=>Xt(e)),oo()&&Bt(!0)}catch(e){(0,Pn.AO)("Error reinitializing tracking after route change",e)}},100)}catch(e){(0,Pn.AO)("Error handling route change",e)}}async function on(e,t,n){const i=stateManager.getState().cookieConsent,r=function(e,t,n){if(!n)return`${e}|${t}`;try{return`${e}|${t}|${i=n,JSON.stringify(sn(i))}`}catch(n){return`${e}|${t}|[details-unserializable]`}var i}(e,t,n);if(i!==e||r!==Fo){stateManager.setCookieConsent(e),Fo=r,(0,Pn.cY)(`Cookie consent set to ${e} from ${t}`);try{const i={eventId:pe(),eventType:"cookieConsent",time:(new Date).toISOString(),label:"Cookie consent "+(e?"granted":"denied"),value:Object.assign({consentGiven:e,consentSource:t},n?{details:n}:{})};await ee(i)}catch(e){(0,Pn.AO)("Error sending cookie consent event",e)}}}function an(e){$o.push(e)}function sn(e,t=new WeakSet){if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[circular]";if(t.add(e),Array.isArray(e))return e.map(e=>sn(e,t));const n=e,i={},r=Object.keys(n).sort((e,t)=>e<t?-1:e>t?1:0);for(const e of r)i[e]=sn(n[e],t);return i}function cn(){try{const e=document.cookie||"",t=e.match(/(?:^|; )OptanonConsent=([^;]+)/),n=e.match(/(?:^|; )OptanonActiveGroups=([^;]+)/);if(n){const e=decodeURIComponent(n[1]).split(",").filter(Boolean);return{hasConsent:!!e.some(e=>e&&"C0001"!==e),details:{oneTrust:{activeGroups:e}}}}if(!t)return null;const i=decodeURIComponent(t[1]),r=(Object.fromEntries(i.split("&").map(e=>{const t=e.indexOf("=");return-1===t?[e,""]:[e.slice(0,t),e.slice(t+1)]})).groups||"").split(",").map(e=>e.trim()).filter(Boolean);let o=!1;const a={};for(const e of r){const[t,n]=e.split(":"),i=Number(n);t&&(a[t]=i),t&&"C0001"!==t&&1===i&&(o=!0)}return{hasConsent:o,details:{oneTrust:{groups:a}}}}catch(e){return(0,Pn.AO)("Error parsing OneTrust consent",e),null}}function ln(e=5){const t=window.__tcfapi;if("function"==typeof t){const e=(e,t)=>{var n,i,r,o;if(t&&("useractioncomplete"===e.eventStatus||"tcloaded"===e.eventStatus)){const t=(null===(n=null==e?void 0:e.purpose)||void 0===n?void 0:n.consents)||{},a=(null===(i=null==e?void 0:e.vendor)||void 0===i?void 0:i.consents)||{},s=Object.entries(t).some(([e,t])=>"1"!==e&&!0===t),c=Object.values(a).some(e=>e);on(!(!s&&!c),"tcfapi",{tcf:{purposeConsents:null===(r=e.purpose)||void 0===r?void 0:r.consents,vendorConsents:null===(o=e.vendor)||void 0===o?void 0:o.consents}})}};return t("addEventListener",2,e),an(()=>{try{t("removeEventListener",2,e)}catch(e){}}),void t("getTCData",2,(e,t)=>{var n,i,r,o;if(!t)return;const a=(null===(n=null==e?void 0:e.purpose)||void 0===n?void 0:n.consents)||{},s=(null===(i=null==e?void 0:e.vendor)||void 0===i?void 0:i.consents)||{},c=Object.entries(a).some(([e,t])=>"1"!==e&&!0===t),l=Object.values(s).some(e=>e);on(!(!c&&!l),"tcfapi",{tcf:{purposeConsents:null===(r=e.purpose)||void 0===r?void 0:r.consents,vendorConsents:null===(o=e.vendor)||void 0===o?void 0:o.consents}})})}if(e>0){const t=setTimeout(()=>ln(e-1),1e3);Wo.push(t)}}function dn(){var e;if(!Do&&"undefined"!=typeof window){Do=!0;try{ln(),function(){try{const e=window;let t=null,n=null,i=!1,r=!1;const o=e=>{if(!e||"object"!=typeof e)return null;const t=e.consentParameters||e,n=["analytics_storage","ad_storage","ad_user_data","ad_personalization","personalization_storage","functionality_storage","security_storage"],i={};let r=!1;for(const e of n){const n=null==t?void 0:t[e];"string"==typeof n&&(i[e]=n,r=!0)}return r?i:null},a=(e,t)=>{try{const a=o(e);if(!a)return;const s=Object.values(a),c=s.some(e=>"granted"===e),l=s.length&&s.every(e=>"denied"===e);if(!c&&!l)return;if(!r&&!l)return;const d=JSON.stringify(a,Object.keys(a).sort());if(d===n)return;n=d,i=!0,on(c,t,{gcm:e,gcmState:a})}catch(e){(0,Pn.AO)("Error emitting GCM consent",e)}},s=e=>{try{if(!e)return;const t="object"==typeof e&&!Array.isArray(e)&&"number"==typeof e.length&&"consent"===e[0];if((Array.isArray(e)||t)&&"consent"===e[0])return"update"===e[1]&&(r=!0),void a(e[2]||{},"gcm");if("object"==typeof e){const t=String(e.event||"");(t.includes("consent")||"gtm.init_consent"===t||"gtm.default_consent"===t||"gtm.default_consent_update"===t||"gtm.consentUpdate"===t)&&("gtm.consentUpdate"===t&&(r=!0),a(e,"gcm"))}}catch(e){(0,Pn.AO)("Error processing GCM dataLayer item",e)}},c=e=>{if(!Array.isArray(e)||e.__cstPatched)return;try{e.forEach(s)}catch(e){}const t=e.push.bind(e),n=function(...e){const n=t(...e);try{e.forEach(s)}catch(e){}return n};n.__cstPatched=!0,e.push=n,e.__cstPatched=!0,an(()=>{try{Array.isArray(e)&&e.push===n&&(e.push=t)}catch(e){}})};let l=40;const d=setInterval(()=>{try{Array.isArray(e.dataLayer)&&c(e.dataLayer)}catch(e){}--l<=0&&clearInterval(d)},250);an(()=>clearInterval(d));try{Array.isArray(e.dataLayer)&&c(e.dataLayer)}catch(e){}const u=()=>{const n=e.gtag||function(){e.dataLayer=e.dataLayer||[],e.dataLayer.push(arguments)};if(n.__cstPatched)return;t||(t=n);const i=function(...e){try{"consent"!==e[0]||"update"!==e[1]&&"default"!==e[1]||("update"===e[1]&&(r=!0),a(e[2]||{},"gcm"))}catch(e){(0,Pn.AO)("Error intercepting gtag consent",e)}return n.apply(this,e)};i.__cstPatched=!0,e.gtag=i};u();let m=40;const f=setInterval(()=>{try{"function"!=typeof e.gtag||e.gtag.__cstPatched||u()}catch(e){}--m<=0&&clearInterval(f)},250);an(()=>clearInterval(f)),an(()=>{var n;try{t&&(null===(n=e.gtag)||void 0===n?void 0:n.__cstPatched)&&(e.gtag=t)}catch(e){}})}catch(e){(0,Pn.AO)("Error setting up Google Consent Mode listener",e)}}();const t=e=>{try{const t=function(e){var t,n,i,r;try{if(!e||"object"!=typeof e)return null;const o=e=>{if("boolean"==typeof e)return e;if("string"==typeof e){const t=e.trim().toLowerCase();if("true"===t||"1"===t||"yes"===t||"granted"===t)return!0;if("false"===t||"0"===t||"no"===t||"denied"===t)return!1}},a=o(null!==(n=null!==(t=e.analyticsAllowed)&&void 0!==t?t:e.analytics_allowed)&&void 0!==n?n:e.analytics),s=o(null!==(r=null!==(i=e.marketingAllowed)&&void 0!==i?i:e.marketing_allowed)&&void 0!==r?r:e.marketing);return!0===a||!0===s||(!1!==a||!1!==s)&&null}catch(e){return(0,Pn.AO)("Error parsing Shopify consent payload",e),null}}(null==e?void 0:e.detail);null!==t&&on(t,"shopify")}catch(e){(0,Pn.AO)("Error handling Shopify consent event",e)}};try{document.addEventListener("visitorConsentCollected",t,{passive:!0}),an(()=>{try{document.removeEventListener("visitorConsentCollected",t)}catch(e){}})}catch(e){(0,Pn.AO)("Error registering Shopify consent listener",e)}try{const e=()=>async function(){var e;try{const t=window,n=null===(e=null==t?void 0:t.Shopify)||void 0===e?void 0:e.customerPrivacy;if(!n)return null;const i=async e=>{if("function"==typeof e)try{const t=e();return t&&"function"==typeof t.then?await t:t}catch(e){return}},r=await i(()=>{var e;return null===(e=n.analyticsProcessingAllowed)||void 0===e?void 0:e.call(n)}),o=await i(()=>{var e;return null===(e=n.marketingAllowed)||void 0===e?void 0:e.call(n)});if(!0===r||!0===o)return!0;if(!1===r&&!1===o)return!1}catch(e){(0,Pn.AO)("Error reading Shopify customer privacy",e)}return null}().then(e=>(null!==e&&on(e,"shopify"),e)).catch(()=>null);e().then(t=>{if(null!==t)return;const n=setTimeout(()=>{e()},1e3);Wo.push(n)})}catch(e){(0,Pn.AO)("Error probing Shopify consent",e)}try{let e=null;const t=()=>{const e=document.cookie,t=e.match(/__hs_cookie_cat_pref=([^;]+)/),n=e.match(/hs-privacy-settings=([^;]+)/);let i={},r=null;if(t)try{const e=decodeURIComponent(t[1]),n={};e.split(/[_,]/).map(e=>e.trim()).filter(Boolean).forEach(e=>{const t=e.indexOf(":");t>-1&&(n[e.slice(0,t)]=e.slice(t+1))}),r="true"===n[2]||"true"===n[3]||"true"===n[4],i.cookie_cat_pref=n}catch(e){}if(n)try{const e=JSON.parse(decodeURIComponent(n[1]));null===r&&(r=!!(e.consentAllowed||e.consentAnalytics||e.consentAdvertisement||e.consentFunctionality)),i.legacy=e}catch(e){}return null===r?null:{consent:r,details:{hubspot:i}}},n=()=>{try{const n=t();if(!n)return;const i=JSON.stringify(n);if(i===e)return;e=i,on(n.consent,"hubspot",n.details)}catch(e){}};n();const i=setInterval(n,1e3);an(()=>clearInterval(i))}catch(e){(0,Pn.AO)("Error initializing HubSpot cookie monitor",e)}const n=setInterval(()=>{try{const e=window.hsConsentApi;if(e&&"function"==typeof e.onConsentChange){clearInterval(n);const t=e=>{try{const t={hasConsent:!!((null==e?void 0:e.consentAllowed)||(null==e?void 0:e.consentAnalytics)||(null==e?void 0:e.consentAdvertisement)||(null==e?void 0:e.consentFunctionality)),details:{hubspot:e}};on(t.hasConsent,"hubspot",t.details)}catch(e){(0,Pn.AO)("Error handling HubSpot onConsentChange",e)}};try{e.onConsentChange(t),an(()=>{var n;try{null===(n=e.offConsentChange)||void 0===n||n.call(e,t)}catch(e){}})}catch(e){(0,Pn.AO)("Failed to register HubSpot onConsentChange",e)}}}catch(e){(0,Pn.AO)("Error probing HubSpot consent API",e)}},1e3);an(()=>clearInterval(n));const i=()=>on(!0,"cookiebot"),r=()=>on(!1,"cookiebot"),o=()=>{var e,t,n;const i=window.Cookiebot;on(!!((null===(e=null==i?void 0:i.consent)||void 0===e?void 0:e.marketing)||(null===(t=null==i?void 0:i.consent)||void 0===t?void 0:t.preferences)||(null===(n=null==i?void 0:i.consent)||void 0===n?void 0:n.statistics)),"cookiebot")};window.addEventListener("CookiebotOnAccept",i,{passive:!0}),window.addEventListener("CookiebotOnDecline",r,{passive:!0}),window.addEventListener("CookiebotOnLoad",o,{passive:!0}),an(()=>{window.removeEventListener("CookiebotOnAccept",i),window.removeEventListener("CookiebotOnDecline",r),window.removeEventListener("CookiebotOnLoad",o)}),(null===(e=window.Cookiebot)||void 0===e?void 0:e.consent)&&o();const a=()=>{const e=setTimeout(()=>{const e=cn();e&&on(e.hasConsent,"oneTrust",e.details)},100);Wo.push(e)};window.addEventListener("OneTrustConsentChanged",a,{passive:!0}),an(()=>{window.removeEventListener("OneTrustConsentChanged",a)});const s=cn();s&&on(s.hasConsent,"oneTrust",s.details);const c=()=>on(!0,"generic"),l=()=>on(!1,"generic");window.addEventListener("consentGiven",c,{passive:!0}),window.addEventListener("consentDenied",l,{passive:!0}),an(()=>{window.removeEventListener("consentGiven",c),window.removeEventListener("consentDenied",l)}),(0,Pn.cY)("Cookie consent tracking initialized")}catch(e){(0,Pn.AO)("Error initializing cookie consent tracking",e)}}}function un(e,t){return`${"string"==typeof t&&t.trim().length>0?t.trim().toLowerCase():"unknown"}:${e}`}function mn(e){return"string"==typeof e?e.trim():""}function fn(e,t){return[un(t,e.shop),mn(e.clientId),mn(e.sessionId),mn(e.pageViewId),mn(e.userId),mn(e.visitorId)].join("|")}function hn(){zo||(zo=!0,Promise.resolve().then(async()=>{zo=!1;const e=Uo.shift();if(e){try{await async function(e){const t=await gn(e);if(!t||!t.ok)throw new Error("Pixel context sync failed"+(t?` with status ${t.status}`:""));const n=e.cartToken.trim(),i=fn(e,n);jo.set(i,Date.now())}(e)}catch(e){(0,Pn.AO)("Failed to push pixel context bridge payload",e)}Uo.length>0&&hn()}}))}function pn(e){return new Promise(t=>setTimeout(t,e))}async function gn(e){const t=`${Un}/sync`,n=JSON.stringify(e);return(0,Pn.cY)("Posting pixel context bridge payload",{endpoint:t,shop:e.shop}),W(fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-CST-Bridge":"1"},keepalive:!0,body:n,credentials:"omit"}),2e3).catch(()=>null)}function vn(e){return!e||"UNKNOWN - STATE"===e||!e.trim()}function yn(e){var t,n;const i=null===(t=null==e?void 0:e.session)||void 0===t?void 0:t.id,r=null===(n=null==e?void 0:e.page)||void 0===n?void 0:n.id,o=null==e?void 0:e.clientId;return!vn(i)&&!vn(r)&&!vn(o)}function wn(e){if(Ko)return;Ko={attempts:0,ticks:0,nextTickInterval:1};const t=stateManager.addTickListener(async()=>{if(!Ko)return void t();if(Ko.ticks+=1,Ko.ticks<Ko.nextTickInterval)return;if(Ko.ticks=0,"undefined"!=typeof document&&"visible"!==document.visibilityState)return;if("undefined"!=typeof navigator&&!1===navigator.onLine)return;Ko.attempts+=1;let e=!1;try{e=await En({force:!0})}catch(t){e=!1}return e||Ko.attempts>=4?(t(),void(Ko=null)):void(Ko.nextTickInterval=Math.min(2*Ko.nextTickInterval,12))});Ko.dispose=t;try{console.log("[CST] Scheduled cart token retry",{reason:e,maxAttempts:4,baseTickInterval:1})}catch(e){}}function Sn(e){if("string"==typeof e)return e.trim()||void 0}function bn(e){if("string"==typeof e)return e.trim().toLowerCase()||void 0}function Tn(){var e,t;const n=[],i=new Set,r=e=>{const t=bn(e);t&&!i.has(t)&&(i.add(t),n.push(t))};try{r(null===(e=null===window||void 0===window?void 0:window.Shopify)||void 0===e?void 0:e.shop)}catch(e){}try{r(null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.hostname)}catch(e){}return 0===n.length?{}:{shop:n[0],shopAliases:n.length>1?n:void 0}}function _n(e){if("string"==typeof e)return e.trim()||void 0}function In(e){const t=_n(e);return t&&/^[0-9]{4}-[0-9]{2}$/.test(t)?t:qo}function kn(e){try{if("undefined"==typeof localStorage)return;e.accessToken&&(localStorage.setItem("__kleerr_storefront_access_token",e.accessToken),localStorage.setItem("kleerr_storefront_access_token",e.accessToken)),e.apiVersion&&(localStorage.setItem("__kleerr_storefront_api_version",e.apiVersion),localStorage.setItem("kleerr_storefront_api_version",e.apiVersion))}catch(e){}}function An(e,t){for(const n of t){const t=_n(e[n]);if(t)return t}}async function En(e={}){var t,n;if(ea)return!1;const{force:i=!1}=e,r=Date.now();if(!i&&0!==ta&&r-ta<na)return console.log("[CST] Skipping cart context sync (cooldown active)"),!1;try{ea=!0,await stateManager.ensureInitialized();let e=stateManager.getState();if(!yn(e)&&(await stateManager.refreshStateManually(),await stateManager.ensureInitialized(),e=stateManager.getState(),!yn(e)))return(0,Pn.cY)("Skipping cart context sync: missing required identifiers after refresh.",{sessionId:null===(t=null==e?void 0:e.session)||void 0===t?void 0:t.id,pageViewId:null===(n=null==e?void 0:e.page)||void 0===n?void 0:n.id,clientId:null==e?void 0:e.clientId}),function(e,t){var n,i,r,o,a,s,c,l;const d=Date.now();if(!(d-Go<6e4)){Go=d;try{null===(r=null===(i=null===(n=null==t?void 0:t.session)||void 0===n?void 0:n.id)||void 0===i?void 0:i.slice)||void 0===r||r.call(i,0,12),null===(s=null===(a=null===(o=null==t?void 0:t.page)||void 0===o?void 0:o.id)||void 0===a?void 0:a.slice)||void 0===s||s.call(a,0,12),null===(l=null===(c=null==t?void 0:t.clientId)||void 0===c?void 0:c.slice)||void 0===l||l.call(c,0,12)}catch(e){}}}(0,e),function(){if(Bo)return;Bo={attempts:0,ticks:0};const e=stateManager.addTickListener(async()=>{if(Bo){if(Bo.ticks+=1,!(Bo.ticks<1)){if(Bo.ticks=0,!yn(stateManager.getState()))return Bo.attempts+=1,void(Bo.attempts>=3&&(e(),Bo=null));e(),Bo=null;try{await En({force:!0})}catch(e){}}}else e()});Bo.dispose=e;try{console.log("[CST] Scheduled cart context sync retry",{reason:"missing-identifiers"})}catch(e){}}(),!1;const r=function(){try{const e=localStorage.getItem("cart");if(e)try{const t=JSON.parse(e),n=Sn(null==t?void 0:t.token);if(n)return n}catch(e){(0,Pn.cY)("Failed to parse Shopify cart localStorage payload",e)}const t=Sn(localStorage.getItem("_shopify_cart_token"));if(t)return t}catch(e){(0,Pn.cY)("Failed to read Shopify cart localStorage",e)}return null}();r&&e.parsedMarketingTrackers&&(e.parsedMarketingTrackers.shopify_cart_token=r);let o,a,s=!1,c=0,l=!1,d=null;try{const e=await W(fetch("/cart.js",{credentials:"same-origin"}),2e3).catch(()=>null);if(e&&e.ok){const t=await e.json().catch(()=>null);if(t&&"object"==typeof t){d=t,s=!0,Array.isArray(t.items)&&(c=t.items.length);const e=Sn(t.token);e&&(o=e,l=!0)}}}catch(e){}if(o||(a=Sn(r),o=a,a&&(0,Pn.cY)("Using cart token from Shopify localStorage",{existingToken:a})),o&&e.parsedMarketingTrackers&&(e.parsedMarketingTrackers.shopify_cart_token=o),s&&(0===c||!o))return(0,Pn.cY)("Skipping cart context sync: cart is empty or lacks a token.",{itemsCount:c,hasToken:!!o}),!1;const u=async()=>{if(!o)return!1;try{const t=Tn(),n={cartToken:o,clientId:e.clientId,sessionId:e.session.id,pageViewId:e.page.id,userId:e.userId,visitorId:e.visitorId,shop:t.shop,shopAliases:t.shopAliases},i=await async function(e){var t;if(!e||"string"!=typeof e.cartToken)return!1;const n=e.cartToken.trim();if(!n)return!1;const i=fn(e,n);if(Date.now()-(null!==(t=jo.get(i))&&void 0!==t?t:0)<6e4)return!0;let r=120;for(let t=1;t<=3;t+=1){const o=await gn(Object.assign(Object.assign({},e),{cartToken:n,timestamp:(new Date).toISOString()}));if(o&&o.ok){const e=Date.now();return jo.set(i,e),Ho.set(i,e),!0}t<3&&(await pn(r),r=Math.min(2*r,1200))}return!1}(n);return i||function(e){var t;if(!e||"string"!=typeof e.cartToken)return;const n=e.cartToken.trim();if(!n)return;const i=fn(e,n),r=Date.now();r-(null!==(t=Ho.get(i))&&void 0!==t?t:0)<6e4||(Ho.set(i,r),Uo.length>=25&&Uo.shift(),Uo.push(Object.assign(Object.assign({},e),{cartToken:n,timestamp:(new Date).toISOString()})),hn())}(n),i}catch(e){return(0,Pn.AO)("Failed to enqueue pixel context sync",e),!1}};if(!o)return(0,Pn.cY)("No cart token available after all fallbacks; returning false so polling retries."),wn("missing-token"),!1;if(!l)return(0,Pn.cY)("Skipping cart-linking event: token is not confirmed via cart API.",{storageFallbackToken:a}),wn("unconfirmed-token"),!1;console.log("[CST] Syncing cart tracking context (no cart attribute writes)",{hasToken:!0,itemsCount:c,sessionId:e.session.id,clientId:e.clientId});const m=function(e){const t=(null==e?void 0:e.parsedMarketingTrackers)&&"object"==typeof e.parsedMarketingTrackers?e.parsedMarketingTrackers:{},n=function(){try{return _n(localStorage.getItem("__cst_shopify_checkout_session"))}catch(e){return}}();return{checkoutSessionId:An(t,["checkout_token","checkoutToken","checkout_session","checkoutSessionId"])||n,previousCheckoutSessionId:n,shopifyY:An(t,["_shopify_y","shopify_y","_y"]),shopifyS:An(t,["_shopify_s","shopify_s","_s"])}}(e),f=function(e,t){var n,i,r,o;const a=[null==e?void 0:e.id,null==e?void 0:e.cart_id,null==e?void 0:e.cartId,null==e?void 0:e.admin_graphql_api_id,null===(n=null==e?void 0:e.cart)||void 0===n?void 0:n.id,null===(i=null==e?void 0:e.cart)||void 0===i?void 0:i.cart_id,null===(r=null==e?void 0:e.cart)||void 0===r?void 0:r.cartId,null===(o=null==e?void 0:e.cart)||void 0===o?void 0:o.admin_graphql_api_id];for(const e of a){const t=_n(e);if(null==t?void 0:t.startsWith("gid://shopify/Cart/"))return t}return t.startsWith("gid://shopify/Cart/")?t:`gid://shopify/Cart/${t}`}(d,o);await async function(e){var t,n,i;const r=function(){try{const e="undefined"!=typeof globalThis?globalThis:{},t=_n(e.__KLEERR_STOREFRONT_ACCESS_TOKEN)||_n(e.KLEERR_STOREFRONT_ACCESS_TOKEN);if(t)return kn({accessToken:t}),t}catch(e){}try{if("undefined"!=typeof localStorage){const e=_n(localStorage.getItem("__kleerr_storefront_access_token"))||_n(localStorage.getItem("kleerr_storefront_access_token"));if(e)return e}}catch(e){}}(),o=function(){var e,t;try{return bn(null===(e=null===window||void 0===window?void 0:window.Shopify)||void 0===e?void 0:e.shop)}catch(e){}try{return bn(null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.hostname)}catch(e){}}();if(!r||!o)return!1;const a=[(i={cartId:e.cartId,clientId:e.clientId,sessionId:e.sessionId,pageViewId:e.pageViewId,userId:e.userId,visitorId:e.visitorId,checkoutSessionId:e.checkoutSessionId,shopifyY:e.shopifyY,shopifyS:e.shopifyS}).cartId,i.clientId,i.sessionId,i.pageViewId,i.userId||"",i.visitorId||"",i.checkoutSessionId||"",i.shopifyY||"",i.shopifyS||""].join("|"),s=Date.now();if(!e.force&&a===Xo&&s-Jo<15e3)return!0;const c=`https://${o}/api/${function(){try{const e="undefined"!=typeof globalThis?globalThis:{},t=_n(e.__KLEERR_STOREFRONT_API_VERSION||e.KLEERR_STOREFRONT_API_VERSION);if(t){const e=In(t);return kn({apiVersion:e}),e}}catch(e){}try{if("undefined"!=typeof localStorage){const e=_n(localStorage.getItem("__kleerr_storefront_api_version"))||_n(localStorage.getItem("kleerr_storefront_api_version"));if(e)return In(e)}}catch(e){}return qo}()}/graphql.json`,l=[{namespace:Vo,key:"client_id",type:"single_line_text_field",value:e.clientId},{namespace:Vo,key:"session_id",type:"single_line_text_field",value:e.sessionId},{namespace:Vo,key:"pageview_id",type:"single_line_text_field",value:e.pageViewId},...e.userId?[{namespace:Vo,key:"user_id",type:"single_line_text_field",value:e.userId}]:[],...e.visitorId?[{namespace:Vo,key:"visitor_id",type:"single_line_text_field",value:e.visitorId}]:[],...e.checkoutSessionId?[{namespace:Vo,key:"checkout_session_id",type:"single_line_text_field",value:e.checkoutSessionId}]:[],...e.shopifyY?[{namespace:Vo,key:"shopify_y",type:"single_line_text_field",value:e.shopifyY}]:[],...e.shopifyS?[{namespace:Vo,key:"shopify_s",type:"single_line_text_field",value:e.shopifyS}]:[]];try{const i=await W(fetch(c,{method:"POST",keepalive:!0,credentials:"omit",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":r},body:JSON.stringify({query:"#graphql\n    mutation KleerrCartMetafieldsSet($cartId: ID!, $metafields: [CartMetafieldsSetInput!]!) {\n      cartMetafieldsSet(cartId: $cartId, metafields: $metafields) {\n        cart { id }\n        userErrors { field message code }\n      }\n    }\n  ",variables:{cartId:e.cartId,metafields:l}})}),2500).catch(()=>null);if(!(null==i?void 0:i.ok))return!1;const o=await i.json().catch(()=>null),d=Array.isArray(null==o?void 0:o.errors)?o.errors:[],u=Array.isArray(null===(n=null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.cartMetafieldsSet)||void 0===n?void 0:n.userErrors)?o.data.cartMetafieldsSet.userErrors:[];return d.length>0||u.length>0?((0,Pn.cY)("Storefront cartMetafieldsSet returned errors",{topErrors:d.length,userErrors:u.length}),!1):(Xo=a,Jo=s,!0)}catch(e){return(0,Pn.cY)("Storefront cartMetafieldsSet failed",e),!1}}({cartId:f,clientId:e.clientId,sessionId:e.session.id,pageViewId:e.page.id,userId:e.userId,visitorId:e.visitorId,checkoutSessionId:m.checkoutSessionId,shopifyY:m.shopifyY,shopifyS:m.shopifyS,force:i}).catch(()=>!1),function(){try{const e=function(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"!=typeof e)return;const t=e.trim().toLowerCase();return t?!!["1","true","yes","on","enabled"].includes(t)||!["0","false","no","off","disabled"].includes(t)&&void 0:void 0}(("undefined"!=typeof globalThis?globalThis:{}).CART_ATTRIBUTES_ON);if(void 0!==e)return e}catch(e){}return!1}()&&await async function(e){const t=[(n={clientId:e.clientId,sessionId:e.sessionId,pageViewId:e.pageViewId,cartToken:e.cartToken,userId:e.userId,visitorId:e.visitorId,checkoutSessionId:e.checkoutSessionId,shopifyY:e.shopifyY,shopifyS:e.shopifyS}).clientId,n.sessionId,n.pageViewId,n.cartToken||"",n.userId||"",n.visitorId||"",n.checkoutSessionId||"",n.shopifyY||"",n.shopifyS||""].join("|");var n;const i=Date.now();if(!e.force&&t===Qo&&i-Zo<15e3)return!0;try{const n={_cst_clientId:e.clientId,_cst_sessionId:e.sessionId,_cst_pageViewId:e.pageViewId};e.userId&&(n._cst_userId=e.userId),e.visitorId&&(n._cst_visitorId=e.visitorId),e.checkoutSessionId&&(n._cst_checkoutSessionId=e.checkoutSessionId),e.shopifyY&&(n._cst_shopifyY=e.shopifyY),e.shopifyS&&(n._cst_shopifyS=e.shopifyS);const r=await W(fetch("/cart/update.js",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({attributes:n})}),2e3).catch(()=>null);return(null==r?void 0:r.ok)?(Qo=t,Zo=i,!0):((0,Pn.cY)("Cart attributes sync fallback failed",{status:null==r?void 0:r.status}),!1)}catch(e){return(0,Pn.cY)("Cart attributes sync fallback error",e),!1}}({clientId:e.clientId,sessionId:e.session.id,pageViewId:e.page.id,cartToken:o,userId:e.userId,visitorId:e.visitorId,checkoutSessionId:m.checkoutSessionId,shopifyY:m.shopifyY,shopifyS:m.shopifyS,force:i}).catch(()=>!1);const h=await u();let p=!1;try{const t=N(),n=Tn();p=await async function(e){try{const t=function(){try{const e=_n(("undefined"!=typeof globalThis?globalThis:{}).__KLEERR_PIXEL_ENDPOINT);if(e)return e}catch(e){}return jn}(),n=await W(fetch(t,{method:"POST",keepalive:!0,credentials:"omit",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),2e3).catch(()=>null);return!!n&&n.ok}catch(e){return!1}}({eventId:"crt_"+pe(),eventType:"cartIdsSync",platform:"shopify",source:"shopify_tracker",time:t,timestamp:t,clientId:e.clientId,sessionId:e.session.id,pageViewId:e.page.id,userId:e.userId,visitorId:e.visitorId,cartToken:String(o),storageCartToken:a,tokenConfirmedViaCartApi:!0,trackingMethod:"pixel_context",attributesPresent:!1,shop:n.shop,shopAliases:n.shopAliases,shopifyCheckoutSessionId:m.checkoutSessionId,checkoutSessionId:m.checkoutSessionId,previousCheckoutSessionId:m.previousCheckoutSessionId,shopifyY:m.shopifyY,shopifyS:m.shopifyS,ids:{checkoutSessionId:m.checkoutSessionId,previousCheckoutSessionId:m.previousCheckoutSessionId,shopify_y:m.shopifyY,shopify_s:m.shopifyS}})}catch(e){(0,Pn.AO)("Failed to emit cartIdsSync event",e)}return!(!h&&!p&&((0,Pn.cY)("Cart context sync not yet confirmed (pixel context + event both failed); polling should continue."),1))}catch(e){return(0,Pn.AO)("Failed to sync cart tracking context",e),!1}finally{ta=Date.now(),ea=!1}}function On(e){return!e||"UNKNOWN - STATE"===e||!e.trim()}function Ln(e){var t,n;const i=null===(t=null==e?void 0:e.session)||void 0===t?void 0:t.id,r=null===(n=null==e?void 0:e.page)||void 0===n?void 0:n.id,o=null==e?void 0:e.clientId;return!On(i)&&!On(r)&&!On(o)}function Cn(e){if(ia)return;ia={attempts:0,ticks:0};const t=stateManager.addTickListener(async()=>{if(ia){if(ia.ticks+=1,!(ia.ticks<1)){if(ia.ticks=0,!Ln(stateManager.getState()))return ia.attempts+=1,void(ia.attempts>=12&&(t(),ia=null));t(),ia=null;try{await Yn()}catch(e){}}}else t()});ia.dispose=t;try{console.log("[CST] Scheduled cart context sync retry",{reason:e})}catch(e){}}async function Yn(){var e,t;try{(0,Pn.cY)("Performing initial Shopify cart context sync check"),await stateManager.ensureInitialized();let n=stateManager.getState();if(!Ln(n)&&(await stateManager.refreshStateManually(),await stateManager.ensureInitialized(),n=stateManager.getState(),!Ln(n)))return(0,Pn.cY)("Skipping cart context sync: missing required identifiers after refresh.",{sessionId:null===(e=null==n?void 0:n.session)||void 0===e?void 0:e.id,pageViewId:null===(t=null==n?void 0:n.page)||void 0===t?void 0:t.id,clientId:null==n?void 0:n.clientId}),function(e,t){var n,i,r,o,a,s,c,l;const d=Date.now();if(!(d-ra<6e4)){ra=d;try{null===(r=null===(i=null===(n=null==t?void 0:t.session)||void 0===n?void 0:n.id)||void 0===i?void 0:i.slice)||void 0===r||r.call(i,0,12),null===(s=null===(a=null===(o=null==t?void 0:t.page)||void 0===o?void 0:o.id)||void 0===a?void 0:a.slice)||void 0===s||s.call(a,0,12),null===(l=null===(c=null==t?void 0:t.clientId)||void 0===c?void 0:c.slice)||void 0===l||l.call(c,0,12)}catch(e){}}}(0,n),void Cn("missing-identifiers");let i=null,r=!1;try{const e=await W(fetch("/cart.js",{method:"GET",credentials:"same-origin",headers:{Accept:"application/json"}}),2e3).catch(()=>null);(null==e?void 0:e.ok)?i=await e.json().catch(()=>null):r=!0}catch(e){r=!0,(0,Pn.cY)("Initial cart read threw unexpectedly.",e)}if(r&&!i)return oa+=1,oa>=3?void(0,Pn.cY)("Initial cart read failed; max retries reached, giving up.",{attempts:oa}):((0,Pn.cY)("Initial cart read failed, scheduling retry."),void Cn("cart-read-failed"));if(oa=0,!i)return void(0,Pn.cY)("No cart snapshot available on init, skipping cart context sync.");if(!i.token)return void(0,Pn.cY)("Cart token missing on init, skipping cart context sync.");if(0===(Array.isArray(i.items)?i.items.length:0))return void(0,Pn.cY)("Cart empty on init, skipping cart context sync.");await En({force:!0}),(0,Pn.cY)("Initial Shopify cart context sync complete.")}catch(e){(0,Pn.AO)("Initial cart context sync failed",e)}}function initialize(n={}){if((0,Pn.cY)("KLRR_CST_FX] initialize() called; isInitialized:",aa),aa)return Promise.resolve();if(sa&&ca)return(0,Pn.cY)("KLRR_CST_FX] initialize() already in progress; reusing promise"),ca;try{i=n,Pr=Object.assign(Object.assign({},Pr),i)}catch(e){(0,Pn.AO)("Failed applying runtime config",e)}var i;return(0,Pn.cY)("KLRR_CST_FX] invoking cst() now"),sa=!0,ca=async function(){var n,i;if(aa)(0,Pn.cY)("KLRR_CST_FX] Already initialized, skipping");else try{(0,Pn.cY)("KLRR_CST_FX] Starting initialization"),(0,Pn.cY)("KLRR_CST_FX] calling stateManager.initialize()"),await stateManager.initialize(),(0,Pn.cY)("KLRR_CST_FX] state initialized; session:",stateManager.getSessionId(),"page:",stateManager.getState().page.id);let r=null;try{(0,Pn.cY)("KLRR_CST_FX] running bot detection"),r=await async function(){try{const e=await No.detect(),n=e.isBot;return(0,Pn.cY)("BotDetector result",e),t("cst_bot",String(n)),e}catch(e){return(0,Pn.cY)("detectBot error",e),{isBot:!1,confidence:0,signals:[]}}}(),stateManager.setBotDetection(r);const{checkCanvasUaMismatch:n}=await Promise.resolve().then(e.bind(e,53));n()}catch(e){(0,Pn.AO)("Bot detection failed, proceeding with tracking:",e),r=null}let o=!!(null==r?void 0:r.isBot);if("undefined"!=typeof window&&"true"===window.localStorage.getItem("bypassBotDetection")&&((0,Pn.cY)("Manual bot detection bypass enabled"),o=!1),o){const e=null!==(n=null==r?void 0:r.confidence)&&void 0!==n?n:0;(0,Pn.cY)("Bot detected but kept for tracking",{category:(null==r?void 0:r.botType)||"UNKNOWN",confidence:e})}(0,Pn.cY)("Installing early form network interceptors"),function(){try{mt()}catch(e){(0,Pn.AO)("Failed installing early network interceptors",e)}}(),(0,Pn.cY)("Initializing cookie consent tracking"),dn(),(0,Pn.cY)("Initializing visibility handling"),_r=()=>{(async function(){try{const e="visible"===document.visibilityState;(0,Pn.cY)("Visibility changed to: "+(e?"visible":"hidden")),e?((await stateManager.isSessionValid()).isValid?((0,Pn.cY)("Session valid, resuming tracking"),stateManager.resumeTracking(),yt()):((0,Pn.cY)("Session invalid, creating new session"),await stateManager.handleSessionTimeout()),stateManager.updateActivity()):((0,Pn.cY)("Tab hidden, pausing tracking"),stateManager.pauseTracking(),wt(),await le())}catch(e){(0,Pn.AO)("Error handling visibility change",e)}})().catch(e=>(0,Pn.AO)("Visibility handler error",e))},document.addEventListener("visibilitychange",_r,{passive:!0}),(0,Pn.cY)("Initializing SPA tracking"),function(){try{Lo&&(Lo.disconnect(),Lo=null),Co=location.href,window.__cst_spa_last_url=Co,Lo=new MutationObserver(Ro);const e=R(async()=>{location.href!==Co&&((0,Pn.cY)(`Route change detected: ${Co} -> ${location.href}`),await rn())},100);return Yo=e,window.addEventListener("popstate",e),window.addEventListener("pushState",e),window.addEventListener("replaceState",e),tn("pushState"),tn("replaceState"),Lo.observe(document.body,{childList:!0,subtree:!0,attributes:!1,characterData:!1}),(0,Pn.cY)("SPA tracking initialized",{initialLastUrl:Co}),Lo}catch(e){throw(0,Pn.AO)("Error setting up SPA tracking",e),e}}(),(0,Pn.cY)("Initializing scroll tracking"),It(),(0,Pn.cY)("Initializing click tracking"),Ct(),(0,Pn.cY)("Initializing enhanced form tracking"),gt(),(0,Pn.cY)("Initializing input tracking"),Qt(),(0,Pn.cY)("Initializing custom dropdown tracking"),ko||(ko=!0,Ao=async e=>{try{if(!(e.target instanceof HTMLElement))return;const t=e.target.closest(_o);if(!t)return;if(!Zt(t))return;await en(t)}catch(e){(0,Pn.AO)("Error handling custom dropdown selection",e)}},document.addEventListener("click",Ao,{capture:!0,passive:!0}),Eo=async e=>{try{const t=e.key;if("Enter"!==t&&" "!==t)return;if(!(e.target instanceof HTMLElement))return;const n=e.target.closest(_o);if(!n)return;if(!Zt(n))return;await en(n)}catch(e){(0,Pn.AO)("Error handling keyboard dropdown selection",e)}},document.addEventListener("keydown",Eo,{capture:!0}),(0,Pn.cY)("Initialized custom dropdown tracking")),(0,Pn.cY)("Initializing video tracking (HTML5, Vimeo, Wistia, Loom)"),Pt(),Nt(),Ft(),qt(),(0,Pn.cY)("Loading YouTube API and watcher"),ao(),ro||(ro=setInterval(()=>{document.querySelectorAll('iframe[src*="youtube.com/embed/"]').length>0&&(io||(no||ao(),so()))},2e3)),(0,Pn.cY)("Initializing activity tracking"),ue(),(0,Pn.cY)("KLRR_CST_FX] Initialization complete");const a=()=>{try{(0,Pn.cY)("Ensuring click tracking after DOM ready"),Et()}catch(e){(0,Pn.AO)("Error reinitializing click tracking",e)}try{window.__cstEnhancedFormTrackingInit&&((0,Pn.cY)("Rescanning forms after DOM ready"),vt())}catch(e){(0,Pn.AO)("Error rescanning forms",e)}try{(0,Pn.cY)("Ensuring input tracking after DOM ready"),Qt()}catch(e){(0,Pn.AO)("Error ensuring input tracking",e)}},s=()=>{(0,Pn.cY)("KLRR_CST_FX] scheduleInteractionEnsure()"),a(),setTimeout(a,500),setTimeout(a,2e3)},c=(()=>{let e=!1;return()=>{e||(e=!0,setTimeout(()=>{e=!1,s()},50))}})();"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{(0,Pn.cY)("KLRR_CST_FX] DOMContentLoaded"),s()},{once:!0}):((0,Pn.cY)("KLRR_CST_FX] DOM already ready -> ensuring interactions immediately"),s()),document.addEventListener("readystatechange",()=>{(0,Pn.cY)("KLRR_CST_FX] readystatechange:",document.readyState),"complete"===document.readyState&&c()});try{if("undefined"!=typeof MutationObserver){const e=document.documentElement||document;new MutationObserver(e=>{let t=!1;for(const n of e)n.addedNodes.forEach(e=>{(e instanceof HTMLBodyElement||e instanceof HTMLHtmlElement)&&(t=!0)}),n.removedNodes.forEach(e=>{(e instanceof HTMLBodyElement||e instanceof HTMLHtmlElement)&&(t=!0)});t&&((0,Pn.cY)("DOM root changed, reapplying interaction hooks"),c())}).observe(e,{childList:!0})}}catch(e){(0,Pn.AO)("Error setting up DOM replacement monitor",e)}if(window.addEventListener("online",()=>{(0,Pn.cY)("Network online, retrying failed events"),(0,Pn.cY)("KLRR_CST_FX] online -> retryFailedEvents()"),le()},{passive:!0}),window.addEventListener("load",()=>{(0,Pn.cY)("Page load complete, retrying failed events"),(0,Pn.cY)("KLRR_CST_FX] window load -> retryFailedEvents()"),le()},{passive:!0}),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&((0,Pn.cY)("Document hidden, flushing queued batches"),ie({force:!0}))},{passive:!0}),window.addEventListener("pagehide",()=>{(0,Pn.cY)("Pagehide event, flushing queued batches"),ie({force:!0})},{passive:!0}),Pi.cleanupOldStorage(),await le(),"undefined"!=typeof window&&(null===(i=window.Shopify)||void 0===i?void 0:i.shop)){(0,Pn.cY)("Shopify storefront detected, enabling cart context sync."),await Yn(),"undefined"!=typeof document&&document.addEventListener("mousedown",e=>{const t=e.target;t.closest&&t.closest('[name="checkout"], [name="add"], .shopify-payment-button, [href*="/checkout"]')&&En({force:!0}).catch(()=>{})},{capture:!0,passive:!0}),document.addEventListener("cart:updated",()=>{(0,Pn.cY)("Cart change event detected, resetting context latch and queueing sync.");try{e=!1}catch(e){}En({force:!1})},{passive:!0});let e=!1,t=0;const n=24,i=stateManager.addTickListener(async()=>{try{if(t+=1,t<n)return;if(t=0,e)return;if("visible"!==document.visibilityState)return;if("undefined"!=typeof navigator&&!1===navigator.onLine)return;await En({force:!1})&&(e=!0,(0,Pn.cY)("Cart context sync confirmed; polling dormant"))}catch(e){(0,Pn.AO)("Unified polling tick failed",e)}});try{const e=()=>{try{i&&i()}catch(e){}};window.addEventListener("beforeunload",e,{once:!0}),window.addEventListener("pagehide",e,{once:!0})}catch(e){}}(0,Pn.cY)("CST initialization complete - all handlers initialized");const l=stateManager.getState();(0,Pn.cY)("Final initialization state:",{sessionValid:l.session.isValid,isTracking:l.session.isValid,sessionId:l.session.id,pageId:l.page.id}),aa=!0}catch(e){throw(0,Pn.AO)("CST initialization error:",e),console.error("KLRR_CST_FX] Initialization error",e),aa=!1,e}}().finally(()=>{sa=!1,ca=null}),ca}var Mn,Pn,xn,Rn,Nn={53(e,t,n){function i(){const e=performance.now();d.push(e),d.length>20&&d.shift()}function r(){const e=performance.now(),t=window.scrollY||document.documentElement.scrollTop;if(m>0){const n=e-m;if(n>16){const e=Math.abs(t-f);u.push(e/n),u.length>30&&u.shift()}}m=e,f=t}function o(){if(null!==h)return h;try{const e=navigator.userAgent.toLowerCase(),t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(!n)return h={detected:!1},h;const i=n.getExtension("WEBGL_debug_renderer_info"),r=i&&n.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",o=r.toLowerCase();return o.includes("google swiftshader")?(h={detected:!0,reason:"google_swiftshader_renderer"},(0,l.cY)("Canvas/UA mismatch: Google SwiftShader renderer"),h):o.includes("swiftshader")&&!e.includes("headless")?(h={detected:!0,reason:"swiftshader_without_headless_ua"},(0,l.cY)("Canvas/UA mismatch: SwiftShader detected without headless UA"),h):o.includes("angle")&&e.includes("linux")&&(o.includes("direct3d")||o.includes("d3d"))?(h={detected:!0,reason:"angle_d3d_on_linux"},(0,l.cY)("Canvas/UA mismatch: Direct3D ANGLE on Linux"),h):r&&"unknown"!==r&&(o.includes("llvmpipe")||o.includes("mesa")&&o.includes("software"))&&!e.includes("linux")?(h={detected:!0,reason:"software_renderer_non_linux_ua"},(0,l.cY)("Canvas/UA mismatch: Software renderer with non-Linux UA"),h):(h={detected:!1},h)}catch(e){return(0,l.cY)("Error checking Canvas/UA mismatch",e),h={detected:!1},h}}function a(e){if(e.length<3)return null;const t=e.length,n=e.reduce((e,t)=>e+t,0)/t;return e.map(e=>Math.pow(e-n,2)).reduce((e,t)=>e+t,0)/t}function s(e){if(e.length<5)return!0;let t=0;for(let n=2;n<e.length;n++){const i=e[n-1]-e[n-2],r=e[n]-e[n-1];(Math.sign(i)!==Math.sign(r)||Math.abs(r-i)>.1)&&t++}return t>.2*e.length}function c(){const e={};if(d.length>=3){const t=[];for(let e=1;e<d.length;e++)t.push(d[e]-d[e-1]);const n=a(t);null!==n&&(e.clickTiming={intervalVariance:Math.round(100*n)/100,sampleCount:d.length})}if(u.length>=3){const t=a(u);null!==t&&(e.scrollVelocity={velocityVariance:Math.round(1e4*t)/1e4,hasAcceleration:s(u),sampleCount:u.length})}const t=o();return t&&(e.canvasUaMismatch=t),e}n.d(t,{AE:()=>r,WI:()=>i,checkCanvasUaMismatch:()=>o,vj:()=>c});var l=n(154);let d=[],u=[],m=0,f=0,h=null},154(e,t,n){n.d(t,{AO:()=>debugError,cY:()=>debugLog});const i=()=>{};"undefined"!=typeof localStorage&&localStorage.removeItem("debugMode");const debugLog=i,debugError=i},330(e){e.exports=JSON.parse('{"rE":"2.0.1.20260215"}')}},Dn={};e.d=(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),e.d(Mn={},{default:()=>da}),Pn=e(154),e(330);const $n="https://dd0gkif4bl.execute-api.us-east-2.amazonaws.com/Prod",Wn="production".toLowerCase(),Fn="development"===Wn||"staging"===Wn;["development","staging","production","test"].includes(Wn);const CST_LAMBDA_ENDPOINT=Fn?"https://dev-api.klrr.org/send":"https://api.klrr.org/send",Hn=Fn?"cstm-dev.js":"cstm.js",jn=Fn?"https://dev-api.klrr.org/shop":"https://api.klrr.org/shop",Un=Fn?"https://dev-api.klrr.org/pixel-context":"https://api.klrr.org/pixel-context";Fn&&(0,Pn.cY)("CST Configuration:",{environment:Wn,apiEndpoint:CST_LAMBDA_ENDPOINT,buildTime:(new Date).toISOString()});const zn="cst_fp",Vn="cst_tiid",qn=576e3,Bn="cst_sid",Kn="cst_sid_time",Gn="cst_active_time",Xn="cst_session_entry_url",Jn="cst_session_entry_referrer",Qn="cst_pvid",Zn="cst_pvid_ts",ei="cst_aq_context",ti="cst_acquisition_context",ni=240,ii=144e5,ri=18e5,oi="cst_cfp",ai="cst_loc",si="cst_pending_batches",ci={exact:["hubspotutk","pardot","visitor_id","pi_opt_in","_mkto_trk","_shopify_y","_shopify_s","_shopify_essential_","_orig_referrer","_shopify_sa_p","_shopify_sa_t","shopify_ga","_landing_page","cart","cart_ts","cart_currency","_tracking_consent","_shopify_analytics","_shopify_marketing","is_shopify_merchant","_fbp","_fbc","_ga","_gid","_gcl_aw","_gcl_au","_gcl_gs","FPID","FPLC","FPAU","FPGSID","_ttp","_tt_enable_cookie","ttwid","odin_tt","tta_attr_id_mirror","_pinterest_ct_rt","_pinterest_ct_ua","_pinterest_sess","_pinterest_cm","_pin_unauth","_derived_epik","_uetsid","_uetvid","_clck","_clsk","MUID","__kla_id","_kla_id","klaviyo","sc_at","li_fat_id","li_fat_id_s","bcookie","bscookie","lidc","personalization_id","guest_id","edgebucket","_rdt_uuid","reddit_session","__attentive_id","__attentive_cco","attntv_mstore_email","_ps_session","irclickid","awc","zanpid","rmStore","cto_bundle","ajs_anonymous_id","ajs_user_id","sparrow_id","_hjid","fs_uid","_fs_uid","distinct_id","_cio_id","_lo_uid","_dyjsession","_dy_soct","_dy_geo","_dy_df_geo","mprtcl-v4_","t_gid","t_pt_gid","obuid","s_ecid","AMCV_","s_cc","s_sq","OptanonConsent","eupubconsent-v2","zaraz-consent","transcy_tracking_token"],prefix:["_ga_","_gac_","ttcsid","__sc_","sc_","act_","_drip_","intercom-","mp_","_hjSessionUser_","ph_","amplitude_id_","pendo_","_hp2_","_attn","_dy_","mprtcl-","AMCV_","AMCVS_","kndctr_","_biz_","_cq_","__adroll","_db_"]},li=[/pass(word)?/i,/^pw$/i,"secret","token","apikey","api_key","auth","authentication","bearer","jwt",/credit[_-]?card/i,/card[_-]?number/i,/^cc[_-]?/i,"cvv","cvc","ccv",/expir(y|ation)/i,/card[_-]?holder/i,"billing","payment",/account[_-]?number/i,"routing","swift","iban","ssn",/social[_-]?security/i,/tax[_-]?id/i,"sin","passport","drivers_license","driving_license","national_id","birth_date","birthdate","dob","health_id","insurance_id","medical_record","patient_id","private","secure","hidden","confidential",/sensitive/i,"_token","csrf","xsrf","nonce",/document[_-]?upload/i,/id[_-]?upload/i,/passport[_-]?upload/i],di={5:!1,10:!1,15:!1,20:!1,25:!1,30:!1,35:!1,40:!1,45:!1,50:!1,55:!1,60:!1,65:!1,70:!1,75:!1,80:!1,85:!1,90:!1,95:!1,100:!1};let ui,mi=!1,fi=null;const hi="cst_loc_cache";!function(e){e[e.CLOSED=0]="CLOSED",e[e.OPEN=1]="OPEN",e[e.HALF_OPEN=2]="HALF_OPEN"}(xn||(xn={})),new WeakSet,Rn=e(53);const pi=(e,t)=>t,gi={botHint:pi(0,"bH"),suspectedBot:pi(0,"sB"),confidence:pi(0,"cf"),category:pi(0,"ct"),signals:pi(0,"sg"),detectorVersion:pi(0,"dV"),behavioral:pi(0,"bv"),scrollVelocity:pi(0,"sV"),velocityVariance:pi(0,"vV"),hasAcceleration:pi(0,"hA"),sampleCount:pi(0,"sC"),canvasUaMismatch:pi(0,"cU"),detected:pi(0,"dt"),fingerprint:pi(0,"fp"),fingerprintConfidence:pi(0,"fC"),cfp:pi(0,"cf_"),visitorId:pi(0,"vI"),hint_internal_restart:pi(0,"hIR"),hint_payment_gateway_return:pi(0,"hPG"),inherited_context:pi(0,"iC"),clientId:pi(0,"cI"),userId:pi(0,"uI"),sessionId:pi(0,"sI"),pageViewId:pi(0,"pI"),timestamp:pi(0,"ts"),start:pi(0,"st"),activeTime:pi(0,"aT"),lastActivityTime:pi(0,"lA"),timeSinceLastActive:pi(0,"tS"),eventType:pi(0,"eT"),eventId:pi(0,"eI"),events:pi(0,"ev"),session:pi(0,"ss"),entryUrl:pi(0,"eU"),entryReferrer:pi(0,"eR"),navigationType:pi(0,"nT"),visibilityState:pi(0,"vS"),historyLength:pi(0,"hL"),consentGranted:pi(0,"cG"),pageView:pi(0,"pV"),referrer:pi(0,"rf"),url:pi(0,"ur"),pathname:pi(0,"pn"),title:pi(0,"tt"),location:pi(0,"lo"),city:pi(0,"cy"),region:pi(0,"rg"),country:pi(0,"co"),ip:pi(0,"ip"),cookies:pi(0,"ck"),marketingTrackers:pi(0,"mT"),isBot:pi(0,"iB"),timeout:pi(0,"to"),time:pi(0,"tm"),cookieEnabled:pi(0,"cE"),doNotTrack:pi(0,"dN"),language:pi(0,"lg"),timezoneOffset:pi(0,"tO"),userAgent:pi(0,"uA")},vi=async(e,t)=>{var n;try{await stateManager.ensureInitialized();let i=stateManager.getState();const r=!i.session.id||"UNKNOWN - STATE"===i.session.id,o=!i.page.id||"UNKNOWN - STATE"===i.page.id;let a=H(i);const s=j(i);if(r||o||s){await stateManager.refreshStateManually(),await stateManager.ensureInitialized();const e=stateManager.getState(),t=!e.session.id||"UNKNOWN - STATE"===e.session.id,n=!e.page.id||"UNKNOWN - STATE"===e.page.id,r=H(e),o=j(e);if(t||n)throw new Error("State not initialized - missing session/page identifiers");i=e,a=r,o&&(0,Pn.cY)("buildUserBatch - Page URL unavailable after refresh; proceeding with empty url")}stateManager.isSessionValid().isValid||(0,Pn.cY)("buildUserBatch - Session is invalid, batch may be outdated");const c=N(),l={sessionId:i.session.id,pageViewId:i.page.id,timestamp:c,activeTime:i.session.activeTimeInSeconds,pageActiveTime:i.page.activeTimeInSeconds},d=[];t?d.push({[gi.eventId]:pe(),[gi.eventType]:t,[gi.time]:N(),[gi.activeTime]:i.page.activeTimeInSeconds,[gi.timeout]:!1}):e&&d.push(e);const u=stateManager.getBotDetection(),m=(0,Rn.vj)(),f=u?{[gi.suspectedBot]:u.isBot,[gi.category]:u.botType,[gi.confidence]:u.confidence,[gi.signals]:u.signals,[gi.detectorVersion]:"bot-detector-v1",[gi.behavioral]:Object.keys(m).length>0?m:void 0}:Object.keys(m).length>0?{[gi.suspectedBot]:!1,[gi.detectorVersion]:"bot-detector-v1",[gi.behavioral]:m}:void 0,h=i.session.hint_internal_restart,p=i.session.hint_payment_gateway_return,g=i.session.inherited_context,v=stateManager.getFingerprintConfidence(),y=t||(null==e?void 0:e.eventType)||"heartbeat",w=function(e,t){if(!e||"object"!=typeof e)return e;const n=Object.assign({},e);return function(e){const t=(e||"").trim().toLowerCase();return!!t&&(t.includes("cart")||t.includes("checkout"))}(t)||(delete n.shopify_cart_token,delete n.cartToken,delete n.cart_token,delete n.cart,delete n._shopify_cart_token),n}(i.parsedMarketingTrackers,String(y));return{[gi.clientId]:i.clientId,[gi.userId]:i.userId,[gi.visitorId]:i.visitorId,[gi.fingerprint]:i.fingerprint,[gi.timestamp]:l.timestamp,[gi.eventType]:y,[gi.isBot]:null!==(n=null==u?void 0:u.isBot)&&void 0!==n&&n,[gi.botHint]:f,[gi.fingerprintConfidence]:v,[gi.session]:{[gi.sessionId]:l.sessionId,[gi.start]:i.session.startTimestamp,[gi.entryUrl]:i.session.entryUrl||a,[gi.entryReferrer]:i.session.entryReferrer||void 0,[gi.cookies]:i.parsedCookies,[gi.marketingTrackers]:w,[gi.activeTime]:l.activeTime,[gi.lastActivityTime]:i.session.lastActivityTime,[gi.location]:i.location,[gi.consentGranted]:null===i.cookieConsent?void 0:i.cookieConsent,[gi.navigationType]:i.session.navigationType,[gi.visibilityState]:i.session.visibilityState,[gi.timeSinceLastActive]:i.session.timeSinceLastActive,[gi.historyLength]:i.session.historyLength,[gi.hint_internal_restart]:h,[gi.hint_payment_gateway_return]:p,[gi.inherited_context]:g,[gi.pageView]:{[gi.pageViewId]:l.pageViewId,[gi.activeTime]:l.pageActiveTime,[gi.referrer]:i.page.referrer,[gi.lastActivityTime]:i.page.lastActivityTime,[gi.url]:a,[gi.pathname]:i.page.pathname,[gi.title]:i.page.title,[gi.start]:i.page.startTimestamp,[gi.events]:d}}}}catch(e){throw(0,Pn.AO)("Error in buildUserBatch",e),e}},yi=new class{constructor(e){this.failures=0,this.lastFailureTime=0,this.isOpen=!1,this.config=e,setInterval(()=>{Date.now()-this.lastFailureTime>this.config.monitorInterval&&(this.failures=0)},this.config.monitorInterval)}isAllowed(){return!this.isOpen||Date.now()-this.lastFailureTime>this.config.resetTimeout&&(this.isOpen=!1,this.failures=0,!0)}recordSuccess(){this.failures=Math.max(0,this.failures-1)}recordFailure(){this.failures++,this.lastFailureTime=Date.now(),this.failures>=this.config.failureThreshold&&(this.isOpen=!0)}reset(){this.failures=0,this.lastFailureTime=0,this.isOpen=!1}}({failureThreshold:5,resetTimeout:3e4,monitorInterval:6e4});let wi=0,Si=null,bi=0;const Ti=Math.max(1,15);let _i=!1,Ii=!1;const ki=R(()=>{J()},200),Ai=1e3,Ei=si;let Oi=!1,Li=null,Ci=null;const Yi=function(e,t,n={}){let i=null,r=0;const{leading:o=!0,trailing:a=!0}=n;let s=!1;const c=function(...n){const c=Date.now();if(o&&!s)return s=!0,r=c,e.apply(this,n);r||!1!==o||(r=c);const l=t-(c-r);if(l<=0||l>t)return i&&(clearTimeout(i),i=null),r=c,e.apply(this,n);i||!1===a||(i=setTimeout(()=>function(t,n){r=!1===o?0:Date.now(),i=null,e.apply(t,n)}(this,n),l))};return c.cancel=function(){i&&(clearTimeout(i),i=null),r=0,s=!1},c}(async()=>{(0,Pn.cY)("Activity detected, updating state"),await stateManager.updateActivity()},5e3),Mi=()=>{Li&&clearTimeout(Li),Li=setTimeout(()=>{(0,Pn.cY)("Inactivity timeout reached, triggering session end"),stateManager.handleSessionTimeout()},ri),Yi()},Pi=new class{setItem(e,t,n){const i="local"===e?localStorage:sessionStorage;try{return i.setItem(t,n),!0}catch(r){if(this.isQuotaError(r)){(0,Pn.cY)(`Storage quota exceeded for ${e}Storage. Cleaning up.`),this.performEmergencyCleanup();try{return i.setItem(t,n),!0}catch(i){if("local"===e)try{return sessionStorage.setItem(t,n),!0}catch(e){return!1}}}return!1}}getItem(e,t){try{return("local"===e?localStorage:sessionStorage).getItem(t)}catch(e){return null}}removeItem(e,t){try{("local"===e?localStorage:sessionStorage).removeItem(t)}catch(e){}}isQuotaError(e){return e instanceof Error&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name||"QuotaExceededError"===e.name)}performEmergencyCleanup(){this.cleanupOldStorage()}cleanupOldStorage(){const e=D();Object.keys(localStorage).forEach(t=>{if(t!==ei&&t!==ti){if(t.startsWith("cst_")||t.startsWith("pageview_")){const n=localStorage.getItem(t);n&&!isNaN(Number(n))&&e-Number(n)>2592e6&&localStorage.removeItem(t)}}else fe(e)})}},xi=["shopify.com","paypal.com","stripe.com","squareup.com","afterpay.com","klarna.com","affirm.com","adyen.com"],Ri={ip:null,network:null,city:null,region:null,country:null,postal:null,latitude:null,longitude:null,in_eu:null,ipCompany:null,isp:null,asn:null,org:null,timezone:null};class Ni{addTickListener(e){return this.tickListeners.add(e),()=>{try{this.tickListeners.delete(e)}catch(e){}}}constructor(){this.initialized=!1,this.initialDataSent=!1,this.isInitializing=!1,this.state={parsedCookies:{},parsedMarketingTrackers:{},lastCookieUpdate:0,clientId:"",visitorId:"",userId:"",cookieConsent:null,fingerprintConfidence:null,fingerprint:{userAgent:"",language:"",timezoneOffset:0,doNotTrack:"",cfp:"",cookieEnabled:!1},location:Ri,session:{id:"",startTime:0,startTimestamp:"",lastActivityTime:0,activeTimeInSeconds:0,entryUrl:"",entryReferrer:"",isValid:!1,hint_internal_restart:!1,hint_payment_gateway_return:!1,inherited_context:void 0,navigationType:void 0,visibilityState:void 0,timeSinceLastActive:void 0,historyLength:void 0},page:{id:"",startTime:0,startTimestamp:"",lastActivityTime:0,activeTimeInSeconds:0,url:"",pathname:"",title:"",referrer:"",isValid:!1},botDetection:null},this.tickListeners=new Set,this.isTracking=!1,this.unifiedTimer=null,this.lastSaveTimestamp=0,this.stateChanged=!1,this.unifiedTicks=0,this.lastUserActivityTs=0,this.isHandlingSessionOperation=!1,this.formSubmitTimeout=null,this.cleanupHandler=()=>this.cleanup(),this.formSubmitHandler=e=>this.handleFormSubmit(e),"undefined"!=typeof window&&(window.addEventListener("beforeunload",this.cleanupHandler),window.addEventListener("unload",this.cleanupHandler),document.addEventListener("submit",this.formSubmitHandler,!0)),"test"!=="production".toLowerCase()&&this.initialize().catch(e=>(0,Pn.AO)("Error in constructor initialization",e))}publishContext(){try{const e={clientId:this.state.clientId||"",userId:this.state.userId||"",sessionId:this.state.session.id||"",pageViewId:this.state.page.id||"",timestamp:(new Date).toISOString()};globalThis.KLEERR_CST_CONTEXT=e}catch(e){}}setBotDetection(e){this.state.botDetection=e||null}getBotDetection(){return this.state.botDetection||null}setFingerprintConfidence(e){this.state.fingerprintConfidence=e}getFingerprintConfidence(){return this.state.fingerprintConfidence}clearAllIntervals(){this.unifiedTimer&&(clearInterval(this.unifiedTimer),this.unifiedTimer=null),this.formSubmitTimeout&&(clearTimeout(this.formSubmitTimeout),this.formSubmitTimeout=null)}sanitizeCookieData(e){return"string"!=typeof e?String(e||""):e.replace(/[\x00-\x1F\x7F]/g,"").substring(0,1e3)}getNavigationType(){var e;try{if("undefined"!=typeof performance&&"function"==typeof performance.getEntriesByType){const t=performance.getEntriesByType("navigation");if(t&&(null===(e=t[0])||void 0===e?void 0:e.type))return t[0].type}const t="undefined"!=typeof performance?performance.navigation:null;if(t&&"number"==typeof t.type)switch(t.type){case 1:return"reload";case 2:return"back_forward";default:return"navigate"}}catch(e){}}getInitialVisibilityState(){try{if("undefined"!=typeof document&&document.visibilityState)return document.visibilityState}catch(e){}}getHistoryLength(){try{if("undefined"!=typeof history&&"number"==typeof history.length)return history.length}catch(e){}}getLastActivityFromStorage(){try{const e=Pi.getItem("local","cst_last_activity_time");if(!e)return null;const t=$(e);return Number.isFinite(t)?t:null}catch(e){return null}}captureSessionStartSignals(e,t=D()){const n=this.getNavigationType(),i=this.getInitialVisibilityState(),r=this.getHistoryLength(),o="number"==typeof e?e:this.getLastActivityFromStorage();let a;if("number"==typeof o&&Number.isFinite(o)){const e=t-o;e>=0&&(a=e)}return{navigationType:n,visibilityState:i,timeSinceLastActive:a,historyLength:r}}captureEntryPoint(){const e=e=>this.sanitizeCookieData(e||"");return{url:(()=>{try{if("undefined"!=typeof location&&location.href)return e(location.href)}catch(e){}return""})(),referrer:(()=>{try{const t=window.__cst_spa_last_url;if(t)return e(t);if("undefined"!=typeof document&&document.referrer)return e(document.referrer)}catch(e){}return""})()}}getStoredActiveSeconds(e,t){const n=e=>{if(!e)return 0;const t=Number(e);return Number.isFinite(t)&&t>=0?t:0};return Math.max(n(e),n(t))}safeHostname(e){if(!e)return"";try{return new URL(e).hostname||""}catch(t){const n=e.match(/^[a-zA-Z]+:\/\/([^/?#]+)/);return(null==n?void 0:n[1])||""}}hasAttributionParams(e){if(!e)return!1;try{return!!e.includes("utm_")||/(gclid|fbclid|ttclid|msclkid|kmi)=/i.test(e)}catch(e){return!1}}retrySaveActiveTime(){try{if(!this.state.session.id)return;const e=`${Gn}_${this.state.session.id}`,t=this.state.session.activeTimeInSeconds.toString(),n=this.state.session.lastActivityTime.toString();Pi.setItem("session",e,t),Pi.setItem("local",e,t),Pi.setItem("local","cst_last_activity_time",n),(0,Pn.cY)(`Active time retry successful: ${t}s`)}catch(e){(0,Pn.AO)("Active time retry failed",e)}}handleFormSubmit(e){this.formSubmitTimeout&&clearTimeout(this.formSubmitTimeout),this.formSubmitTimeout=setTimeout(()=>{(0,Pn.cY)("Form submitted, refreshing state for new cookies"),this.refreshState().catch(e=>(0,Pn.AO)("Error refreshing state after form submit",e)),this.formSubmitTimeout=null},500)}isStoredSessionValid(e){const t=D();return!(t-e.startTime>ii||t-e.lastActivityTime>ri)}async initializeSession(){var e,t;(0,Pn.cY)("Initializing session");const n=this.loadStoredSession();if(console.log(`DEBUG: initializeSession storedSession=${n?n.id:"null"}\n`),n){if(this.isStoredSessionValid(n)){(0,Pn.cY)("Loaded existing session",n),this.state.session=Object.assign(Object.assign(Object.assign({},n),this.captureSessionStartSignals(n.lastActivityTime)),{hint_internal_restart:null!==(e=n.hint_internal_restart)&&void 0!==e&&e,hint_payment_gateway_return:null!==(t=n.hint_payment_gateway_return)&&void 0!==t&&t,inherited_context:n.inherited_context});const i=`${Gn}_${this.state.session.id}`,r=Pi.getItem("session",i),o=Pi.getItem("local",i);return this.state.session.activeTimeInSeconds=this.getStoredActiveSeconds(r,o),this.isTracking=!0,this.state.session.isValid=!0,this.startUnifiedTimer(),void await this.initializePageView()}(0,Pn.cY)("Session invalid, creating new session"),await this.handleSessionEnd("manual")}(0,Pn.cY)("No existing session, creating new session"),await this.createNewSession()}loadStoredSession(){try{const e=n(Bn)||Pi.getItem("local",Bn),t=n(Kn)||Pi.getItem("local",Kn),i=Pi.getItem("local","cst_last_activity_time"),r=n(Xn)||Pi.getItem("local",Xn)||"",o=n(Jn)||Pi.getItem("local",Jn)||"",a=this.captureEntryPoint(),s=`${Gn}_${e}`,c=Pi.getItem("session",s),l=Pi.getItem("local",s);if(!e||!t)return(0,Pn.cY)("No stored session found"),null;if(!i)return(0,Pn.cY)("No stored last activity time; stored session invalid"),null;const d=this.getStoredActiveSeconds(c,l);let u,m;try{u=$(t)}catch(e){return(0,Pn.cY)("Invalid stored session start time format",t),null}try{m=$(i)}catch(e){return(0,Pn.cY)("Invalid stored last activity time",i),null}if(!Number.isFinite(m)||m<=0)return(0,Pn.cY)("Parsed last activity time invalid",m),null;const f=new Date(u).toISOString();return(0,Pn.cY)("Found stored session",{sessionId:e,startTimeRaw:t,activeTimeInSeconds:d}),{id:e,startTime:u,startTimestamp:f,lastActivityTime:m,activeTimeInSeconds:d,entryUrl:r?this.sanitizeCookieData(r):a.url,entryReferrer:o?this.sanitizeCookieData(o):a.referrer,isValid:!0,hint_internal_restart:!1,hint_payment_gateway_return:!1,inherited_context:void 0}}catch(e){return(0,Pn.AO)("Error loading stored session",e),null}}isSessionValid(){if(!this.state.session.isValid)return(0,Pn.cY)("Session invalid: already marked as invalid"),{isValid:!1};const e=D(),t=e-this.state.session.startTime,n=e-this.state.session.lastActivityTime;return(0,Pn.cY)(`Session age: ${t/1e3}s, Inactivity time: ${n/1e3}s`),t>ii?((0,Pn.cY)("Session invalid: Max duration exceeded"),this.handleSessionEnd("maxDuration"),{isValid:!1,reason:"maxDuration"}):n>ri?((0,Pn.cY)("Session invalid: Inactivity timeout"),this.handleSessionEnd("timeout"),{isValid:!1,reason:"timeout"}):{isValid:!0}}async createNewSession(){if((0,Pn.cY)("createnewssession called"),this.isHandlingSessionOperation)(0,Pn.cY)("Session operation in progress, skipping new session creation");else{this.isHandlingSessionOperation=!0;try{(0,Pn.cY)("creating new session");const e=this.captureEntryPoint(),t=this.getLastActivityFromStorage();await this.handleSessionEnd("manual"),this.clearSessionStorage();const n=D(),i=N(),r=this.captureSessionStartSignals(t,n),o=fe(n),a=this.safeHostname(e.url),s=this.safeHostname(e.referrer),c=a?P(a):"",l=s?P(s):"",d=!(!e.referrer||!e.referrer.trim()),u=this.hasAttributionParams(e.url),m=!!l&&!!c&&l===c,f=!!l&&xi.some(e=>l===e);let h,p=!1,g=!1,v=!1,y=!1;f&&o?(h=o,p=!0):m&&o?(h=o,g=!0):u||d&&!m?v=!0:y=!0;const w=Object.assign({id:`s_${pe()}`,startTime:n,startTimestamp:i,lastActivityTime:n,activeTimeInSeconds:0,entryUrl:e.url,entryReferrer:e.referrer,isValid:!0,hint_internal_restart:g,hint_payment_gateway_return:p,inherited_context:null!=h?h:void 0},r);if(v?(function(e){var t;try{const n={sessionId:e.sessionId,entryUrl:e.entryUrl,entryReferrer:null!==(t=e.entryReferrer)&&void 0!==t?t:null,version:e.version||"v1",createdAt:e.createdAt};localStorage.setItem(ei,JSON.stringify(n))}catch(e){(0,Pn.AO)("Error saving acquisition context",e)}}({sessionId:w.id,entryUrl:e.url,entryReferrer:d?e.referrer:null,createdAt:i,version:"v1"}),(0,Pn.cY)("Persisted acquisition context for new arrival",{sessionId:w.id,hasReferrer:d,hasAttributionParams:u})):y&&he(),(0,Pn.cY)("Creating new session",w.id),this.state.session=w,this.isTracking=!0,this.state.session.isValid=!0,this.persistSession(w),this.startUnifiedTimer(),ue(),wt(),yt(),await this.initializePageView(),this.publishContext(),!this.isInitializing){this.initialDataSent=!1,this.initialDataSent=!0,(0,Pn.cY)("Sending initial data for new session",w.id);try{await Q()||(this.initialDataSent=!1)}catch(e){(0,Pn.AO)("Error sending initial data for new session",e),this.initialDataSent=!1}}}finally{this.isHandlingSessionOperation=!1}}}persistSession(e){try{if(!e.id||e.startTime<=0)return void(0,Pn.AO)("Invalid session data, cannot persist");const n=a();t(Bn,e.id,ni,{domain:n,path:"/",sameSite:"Lax"}),t(Kn,e.startTimestamp,ni,{domain:n,path:"/",sameSite:"Lax"}),Pi.setItem("local",Bn,e.id),Pi.setItem("local",Kn,e.startTimestamp);const i=this.sanitizeCookieData(e.entryUrl);t(Xn,i,ni,{domain:n,path:"/",sameSite:"Lax"});const r=this.sanitizeCookieData(e.entryReferrer);r?t(Jn,r,ni,{domain:n,path:"/",sameSite:"Lax"}):t(Jn,"",-1,{domain:n,path:"/",sameSite:"Lax"}),Pi.setItem("local",Xn,i),r?Pi.setItem("local",Jn,r):Pi.removeItem("local",Jn)}catch(e){(0,Pn.AO)("Error persisting session",e)}}async handleSessionEnd(e){try{(0,Pn.cY)(`Ending session due to: ${e}`),this.state.session.isValid=!1,this.isTracking=!1,this.clearAllIntervals(),wt(),this.saveActiveTime(),await le(),this.clearSessionStorage(),Pi.cleanupOldStorage(),this.publishContext()}catch(e){(0,Pn.AO)("Error ending session",e)}}static getInstance(){return Ni.instance||(Ni.instance=new Ni),Ni.instance}getState(){return D()-this.state.lastCookieUpdate>3e5&&this.refreshState().catch(e=>(0,Pn.AO)("Error in getState refresh",e)),this.state}setCookieConsent(e){this.state.cookieConsent=e}async refreshState(){var e;try{const{allCookies:s,marketingTrackers:c}=i(document.cookie),l={},d={};for(const[e,t]of Object.entries(r(s)))l[e]=this.sanitizeCookieData(t);for(const[e,t]of Object.entries(o(c)))d[e]=this.sanitizeCookieData(t);const m=await async function(){var e;const t=function(){try{return ge(n(Di)||n(Wi)||localStorage.getItem(Wi)||null)}catch(e){return null}}();try{let i=n(zn)||null;if(!i)try{"undefined"!=typeof localStorage&&(i=localStorage.getItem(zn))}catch(e){i=null}const r=ge(i);if(r){if((0,Pn.cY)("Using stored visitor ID from cookies:",r),t&&Se(t),function(e){if(!e||"string"!=typeof e)return!0;const t=e.trim();return!t||!t.startsWith("fp_")||28!==t.length}(r))return await Te(t);const n=null!==(e=function(e){if(!e||"string"!=typeof e)return null;if(e.startsWith("fp_")&&28===e.length){const t=e.charAt(15);if("h"===t)return"high";if("m"===t)return"medium";if("l"===t)return"low"}return null}(r))&&void 0!==e?e:null;return n?(be(r),stateManager.setFingerprintConfidence(n),r):await Te(t)}return await Te(t)}catch(e){return(0,Pn.AO)("Error in getVisitorId:",e),stateManager.setFingerprintConfidence(null),"UNKNOWN"}}()||"",f=await async function(){const e=n(oi);if(e)return e;const i=await u(),r=a();return t(oi,i,576e3,{domain:r,path:"/",sameSite:"Lax"}),i}()||"",h=await async function(){try{const e=function(){var e,t;const i=Date.now();try{const t=localStorage.getItem(hi);if(t){const n=JSON.parse(t);if((null==n?void 0:n.data)&&"number"==typeof n.cachedAt&&i-n.cachedAt<36e5)return Object.assign(Object.assign({},n.data),{source:null!==(e=n.data.source)&&void 0!==e?e:"cache"});localStorage.removeItem(hi)}}catch(e){(0,Pn.cY)("Unable to read location from localStorage",e)}const r=n(ai);if(r)try{const e=JSON.parse(r);return Object.assign(Object.assign({},e),{source:null!==(t=e.source)&&void 0!==t?t:"cache"})}catch(e){}return null}();if(e)return e;let i=null,r=!1;try{const e=function(){try{const e=new URL(CST_LAMBDA_ENDPOINT);return e.pathname="/geo",e.toString()}catch(e){return CST_LAMBDA_ENDPOINT.replace(/\/[^/]*$/,"/geo")}}();(0,Pn.cY)("Fetching geo from:",e);const t=new AbortController,n=setTimeout(()=>t.abort(),3e3);try{const n=await fetch(e,{method:"GET",signal:t.signal,credentials:"omit",cache:"no-store"});if(!n.ok)throw new Error(`Geo endpoint returned ${n.status}`);i=await n.json(),(0,Pn.cY)("Geo data from Cloudflare:",null==i?void 0:i.country)}finally{clearTimeout(n)}}catch(e){(0,Pn.cY)("Primary geo endpoint failed, trying fallback:",e);try{const e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{const t=await fetch("https://ipapi.co/json/",{signal:e.signal});t.ok&&(i=await t.json(),r=!0,(0,Pn.cY)("Geo data from fallback:",null==i?void 0:i.country_name))}finally{clearTimeout(t)}}catch(e){return(0,Pn.AO)("Fallback geo endpoint also failed:",e),null}}if(!i)return null;const o={ip:i.ip||null,network:i.network||null,city:i.city||null,region:i.region||null,country:r?i.country_name||null:i.country||null,postal:i.postal||i.postalCode||null,latitude:"number"==typeof i.latitude?i.latitude:null,longitude:"number"==typeof i.longitude?i.longitude:null,in_eu:"boolean"==typeof i.in_eu?i.in_eu:null,ipCompany:i.ip_company||null,isp:i.isp||null,asn:i.asn?String(i.asn):null,org:i.org||i.asOrganization||null,timezone:i.timezone||null,httpProtocol:i.httpProtocol||null,tlsVersion:i.tlsVersion||null,tlsCipher:i.tlsCipher||null,colo:i.colo||null,clientTcpRtt:"number"==typeof i.clientTcpRtt?i.clientTcpRtt:null,tlsClientExtensionsSha1:i.tlsClientExtensionsSha1||null,tlsClientHelloLength:"number"==typeof i.tlsClientHelloLength?i.tlsClientHelloLength:null,clientAcceptEncoding:i.clientAcceptEncoding||null,requestPriority:i.requestPriority||null,source:r?"ipapi":"cloudflare"};return function(e){var n;const i=Date.now();try{localStorage.setItem(hi,JSON.stringify({data:e,cachedAt:i}))}catch(e){(0,Pn.cY)("Unable to store location in localStorage",e)}const r={ip:e.ip,network:null,city:e.city,region:e.region,country:e.country,postal:e.postal,latitude:e.latitude,longitude:e.longitude,in_eu:e.in_eu,ipCompany:null,isp:null,asn:null,org:null,timezone:e.timezone,httpProtocol:null,tlsVersion:null,tlsCipher:null,colo:null,clientTcpRtt:null,tlsClientExtensionsSha1:null,tlsClientHelloLength:null,clientAcceptEncoding:null,requestPriority:null,source:null!==(n=e.source)&&void 0!==n?n:"cache"};t(ai,JSON.stringify(r),60)}(o),o}catch(e){return(0,Pn.AO)("Error fetching location:",e),null}}()||Ri,p=await L().catch(()=>null);this.state=Object.assign(Object.assign({},this.state),{parsedCookies:l,parsedMarketingTrackers:d,lastCookieUpdate:D(),clientId:_e()||"",visitorId:m,userId:Ie()||"",fingerprint:{userAgent:navigator.userAgent||"",language:navigator.language||"",timezoneOffset:(new Date).getTimezoneOffset(),doNotTrack:null!==(e=navigator.doNotTrack)&&void 0!==e?e:"",cfp:f,cookieEnabled:navigator.cookieEnabled,fpCurrent:null==p?void 0:p.raw,fpStable:null==p?void 0:p.stable,fpEntropy:null==p?void 0:p.entropy,fpConfidence:null==p?void 0:p.confidence,fpSignals:null==p?void 0:p.signals,fpStability:null==p?void 0:p.stability,fpAntiFingerprinting:null==p?void 0:p.antiFingerprinting,fpBrowser:null==p?void 0:p.browser,fpRaw:null==p?void 0:p.rawSignals,fpCollectedAt:null==p?void 0:p.collectedAt},location:h}),(0,Pn.cY)("State refreshed",this.state),this.publishContext()}catch(e){(0,Pn.AO)("Error refreshing state",e)}}getSessionId(){return this.state.session.id}getActiveTime(){return this.state.session.activeTimeInSeconds}async updateActivity(){try{(0,Pn.cY)("updateActivity called");const e=D();if(!e||e<0)return void(0,Pn.AO)("Invalid timestamp in updateActivity");if(!this.state.session.isValid)return void await this.createNewSession();this.state.session.lastActivityTime=e,this.state.page.lastActivityTime=e,this.lastUserActivityTs=e,this.stateChanged=!0,(0,Pn.cY)(`Updated session last activity time to ${new Date(e).toISOString()}`),this.unifiedTimer||this.startUnifiedTimer()}catch(e){(0,Pn.AO)("Error updating activity",e)}}async initialize(){var e,t;if(this.initialized)(0,Pn.cY)("StateManager already initialized");else{if(this.isInitializing){(0,Pn.cY)("StateManager is already initializing, waiting...");let e=0;for(;this.isInitializing&&e<50;)await new Promise(e=>setTimeout(e,100)),e++;if(this.initialized)return void(0,Pn.cY)("StateManager initialization completed while waiting")}(0,Pn.cY)("Initializing StateManager"),this.isInitializing=!0;try{let n=3,i=!1;for(;n>0&&!i;){await this.refreshState();const r=this.getState();r.userId&&r.clientId&&(null===(e=r.fingerprint)||void 0===e?void 0:e.userAgent)?(i=!0,(0,Pn.cY)("State validation successful during initialization")):(n--,(0,Pn.cY)(`State validation failed, retries left: ${n}`,{hasUserId:!!r.userId,hasClientId:!!r.clientId,hasUserAgent:!!(null===(t=r.fingerprint)||void 0===t?void 0:t.userAgent)}),n>0&&await new Promise(e=>setTimeout(e,200)))}if(i||(0,Pn.AO)("Failed to initialize state with valid data after retries"),await this.initializeSession(),this.state.session.isValid&&yt(),this.startUnifiedTimer(),this.initialized=!0,(0,Pn.cY)("StateManager initialization completed successfully"),this.publishContext(),!this.initialDataSent){this.initialDataSent=!0,(0,Pn.cY)("Sending initial data after initialization");try{await Q()||(this.initialDataSent=!1)}catch(e){(0,Pn.AO)("Error sending initial data after initialization",e),this.initialDataSent=!1}}ie()}catch(e){throw this.initialized=!1,(0,Pn.AO)("Error initializing StateManager",e),e}finally{this.isInitializing=!1}}}stopTracking(){(0,Pn.cY)("Stopping all tracking"),this.isTracking=!1,this.clearAllIntervals(),this.saveActiveTime()}pauseTracking(){(0,Pn.cY)("Pausing tracking"),this.isTracking=!1,this.clearAllIntervals(),this.saveActiveTime()}async resumeTracking(){(0,Pn.cY)("Resuming tracking"),this.isSessionValid().isValid?(this.isTracking=!0,this.startUnifiedTimer()):await this.createNewSession()}saveActiveTime(){try{if(!this.state.session.id)return;const e=`${Gn}_${this.state.session.id}`,t=this.state.session.activeTimeInSeconds.toString(),n=this.state.session.lastActivityTime.toString();Pi.setItem("session",e,t),Pi.setItem("local",e,t),Pi.setItem("local","cst_last_activity_time",n),(0,Pn.cY)(`Active time saved: ${t}s`)}catch(e){(0,Pn.AO)("Error saving active time",e),e instanceof Error&&"QuotaExceededError"===e.name&&(Pi.cleanupOldStorage(),this.retrySaveActiveTime())}}clearSessionStorage(){if(!this.state.session.isValid){const e=new Date(0).toUTCString(),t=a();document.cookie=`${Bn}=; expires=${e}; path=/; SameSite=Lax; Secure`,document.cookie=`${Kn}=; expires=${e}; path=/; SameSite=Lax; Secure`,document.cookie=`${Xn}=; expires=${e}; path=/; SameSite=Lax; Secure`,document.cookie=`${Jn}=; expires=${e}; path=/; SameSite=Lax; Secure`,t&&(document.cookie=`${Bn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`,document.cookie=`${Kn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`,document.cookie=`${Xn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`,document.cookie=`${Jn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`);const n=`${Gn}_${this.state.session.id}`;Pi.removeItem("session",n),Pi.removeItem("local",n),Pi.removeItem("local",Bn),Pi.removeItem("local",Kn)}}async endCurrentPageViewAndStartNew(e){(0,Pn.cY)("Starting page view transition",{currentSession:this.state.session,currentPage:this.state.page});const t=Object.assign({},this.state.session);await this.endCurrentPageView(),this.state.session=t;const{isValid:n}=this.isSessionValid();if(!n)return(0,Pn.cY)("Session became invalid during page transition, creating new session"),void await this.createNewSession();await this.initializePageView(e),(0,Pn.cY)("Page view transition complete",{session:this.state.session,newPage:this.state.page})}async endCurrentPageView(){try{(0,Pn.cY)("Ending current pageview",{currentSession:this.state.session,currentPage:this.state.page});const e=this.state.session.activeTimeInSeconds;this.stopPageTimeTracking(),this.clearPageViewStorage(),this.state.session.activeTimeInSeconds=e,this.saveActiveTime()}catch(e){(0,Pn.AO)("Error ending page view",e)}}async initializePageView(e){if((0,Pn.cY)("Initializing page view",{currentSession:this.state.session,pageState:e,initialDataSent:this.initialDataSent}),"UNKNOWN - STATE"!==this.state.page.id&&await this.endCurrentPageView(),!this.state.session.id){(0,Pn.cY)("Session state lost during page initialization, attempting recovery");const e=this.loadStoredSession();if(!e||!this.isStoredSessionValid(e))return void await this.createNewSession();this.state.session=e}const t=D(),n=N();this.state.page=Object.assign({id:`pv_${pe()}`,startTime:t,startTimestamp:n,lastActivityTime:t,activeTimeInSeconds:0,url:location.href,pathname:location.pathname,title:document.title,referrer:document.referrer,isValid:!0},e),this.persistPageViewState(),this.unifiedTimer||this.startUnifiedTimer(),this.publishContext(),(0,Pn.cY)("Page view initialized, initial data sending will be handled separately")}persistPageViewState(){try{const e=a();t(Qn,this.state.page.id,ni,{domain:e,path:"/",sameSite:"Lax"}),t(Zn,encodeURIComponent(this.state.page.startTimestamp),ni,{domain:e,path:"/",sameSite:"Lax"}),Pi.setItem("local",Qn,this.state.page.id),Pi.setItem("local",Zn,this.state.page.startTimestamp),this.savePageViewTime()}catch(e){(0,Pn.AO)("Error persisting page view state",e)}}stopPageTimeTracking(){this.savePageViewTime()}savePageViewTime(){try{if(!this.state.page.id)return;const e=`pageview_time_${this.state.page.id}`,t=`pageview_last_active_${this.state.page.id}`;Pi.setItem("session",e,this.state.page.activeTimeInSeconds.toString()),Pi.setItem("session",t,this.state.page.lastActivityTime.toString()),(0,Pn.cY)(`Page view time saved: ${this.state.page.activeTimeInSeconds}s`)}catch(e){(0,Pn.AO)("Error saving page view time",e)}}async sendPageViewEvent(){const e=await vi(null,"initial");await Z(e)}clearPageViewStorage(){const e=new Date(0).toUTCString(),t=a();document.cookie=`${Qn}=; expires=${e}; path=/; SameSite=Lax; Secure`,document.cookie=`${Zn}=; expires=${e}; path=/; SameSite=Lax; Secure`,t&&(document.cookie=`${Qn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`,document.cookie=`${Zn}=; expires=${e}; path=/; domain=${t}; SameSite=Lax; Secure`),Pi.removeItem("local",Qn),Pi.removeItem("local",Zn),Pi.removeItem("session",`pageview_time_${this.state.page.id}`),Pi.removeItem("session",`pageview_last_active_${this.state.page.id}`)}cleanup(){try{(0,Pn.cY)("Starting StateManager cleanup"),this.clearAllIntervals(),this.tickListeners.clear(),me(),Ir(),"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this.cleanupHandler),window.removeEventListener("unload",this.cleanupHandler),document.removeEventListener("submit",this.formSubmitHandler,!0)),this.clearPageViewStorage(),this.clearSessionStorage(),this.stopTracking(),wt(),this.isTracking=!1,this.initialized=!1,this.isHandlingSessionOperation=!1,this.initialDataSent=!1,this.state.botDetection=null,le().catch(e=>(0,Pn.AO)("Error clearing queued events during cleanup",e)),(0,Pn.cY)("StateManager cleanup completed")}catch(e){(0,Pn.AO)("Error during StateManager cleanup",e)}}async handleSessionTimeout(){if(this.isHandlingSessionOperation)(0,Pn.cY)("Session operation already in progress, skipping timeout handler");else{this.isHandlingSessionOperation=!0;try{(0,Pn.cY)("Session timeout triggered"),this.saveActiveTime(),wt(),this.stopTracking(),this.state.session.isValid=!1}finally{this.isHandlingSessionOperation=!1}}}async refreshStateManually(){(0,Pn.cY)("Manual state refresh requested"),await this.refreshState()}async ensureInitialized(){if(!this.initialized){if(this.isInitializing){let e=0;for(;this.isInitializing&&e<50;)await new Promise(e=>setTimeout(e,100)),e++}this.initialized||await this.initialize()}}startUnifiedTimer(){if(this.unifiedTimer)return;const e=D();if(this.lastSaveTimestamp=this.lastSaveTimestamp||e,this.state.session.id&&0===this.state.session.activeTimeInSeconds){const e=`${Gn}_${this.state.session.id}`;try{const t=Pi.getItem("session",e);t&&!isNaN(Number(t))&&(this.state.session.activeTimeInSeconds=Number(t))}catch(e){(0,Pn.AO)("Error loading saved active time",e)}}this.unifiedTimer=setInterval(async()=>{try{if(!this.isTracking)return;const{isValid:e,reason:t}=this.isSessionValid();if(!e)return(0,Pn.cY)(`Session invalid during timer tick: ${t}`),void(t||await this.handleSessionEnd("manual"));if("visible"!==document.visibilityState)return;if(D()-this.lastUserActivityTs>6e4)return;const n=5;this.state.session.activeTimeInSeconds=Math.min(this.state.session.activeTimeInSeconds+n,86400),this.state.page.activeTimeInSeconds=Math.min(this.state.page.activeTimeInSeconds+n,86400);const r=D();this.state.session.lastActivityTime=r,this.state.page.lastActivityTime=r,this.stateChanged=!0,this.unifiedTicks++;try{for(const e of Array.from(this.tickListeners))try{e(this.unifiedTicks)}catch(e){(0,Pn.AO)("Unified tick listener error",e)}}catch(e){}if(5e3*this.unifiedTicks>=288e5)return(0,Pn.cY)("Max timer runtime reached; restarting unified timer"),this.unifiedTicks=0,this.clearAllIntervals(),void this.startUnifiedTimer();if(this.unifiedTicks%60==0)try{const{marketingTrackers:e}=i(document.cookie),t=o(e);for(const[e,n]of Object.entries(t))this.state.parsedMarketingTrackers[e]=this.sanitizeCookieData(n);this.state.lastCookieUpdate=r}catch(e){(0,Pn.AO)("Unified timer marketing refresh error",e)}this.unifiedTicks%180==0&&this.refreshState().catch(e=>(0,Pn.AO)("Unified timer state refresh error",e)),this.unifiedTicks%4320==0&&Pi.cleanupOldStorage(),r-this.lastSaveTimestamp>=3e4&&(this.saveActiveTime(),this.savePageViewTime(),this.lastSaveTimestamp=r,this.stateChanged=!1)}catch(e){(0,Pn.AO)("Unified timer error",e),this.clearAllIntervals(),this.startUnifiedTimer()}},5e3)}}const stateManager=Ni.getInstance(),Di="_shopify_y",$i="_shopify_s",Wi="_cst_shopifyVisitorId",Fi=new WeakMap,Hi={MAX_FIELD_LENGTH:1e3,MAX_FORM_FIELDS:50,DEDUPLICATION_WINDOW:3e3,DISALLOWED_FIELD_TYPES:["file","password","image","video"],CONFIDENCE_THRESHOLD:.7,MAX_LEARNED_PATTERNS:100},ji={formsFound:0,formsSubmitted:0,buttonSubmissions:0,formsMissed:0,universalSuccess:0,providerSuccess:0,providerTriggers:{},errors:[],duplicatesBlocked:0};"undefined"!=typeof window&&(window.__cstFormMetrics=ji);const Ui=new Map,zi=new Map,Vi=Hi.DEDUPLICATION_WINDOW,qi=new Map,Bi=new Map,Ki=new Map,Gi=new Set(["email","phone","firstname","first_name","lastname","last_name","name","company","subject","message"]),Xi=new Set,Ji=new Map,Qi=new Set,Zi=new WeakMap;let er=0,tr=0,nr=null;const ir=new Set(["booking.scheduled","appointment.scheduled","meeting.scheduled","appointment booked","appointment.confirmed","booking_confirmed","booking.succeeded"]),rr=new Set(["calendar.view","view","load","impression"]),or=["contact","customer","email","phone","first_name","firstname","last_name","lastname"],ar=[{re:/https?:\/\/(?:[^\/]+\.)?backend\.leadconnectorhq\.com\/appengine\/appointment\b/i,provider:"leadconnector",signal:"appointment"},{re:/https?:\/\/(?:[^\/]+\.)?backend\.leadconnectorhq\.com\/calendars\/booking-analytics\/event\/submit\b/i,provider:"leadconnector",signal:"booking_analytics_submit"}],sr={hubspot:{name:"HubSpot",trigger:e=>e.includes("hsforms.com")||e.includes("forms.hubspot.com")||null!==document.querySelector(".hs-form, .hbspt-form, form[id^='hsForm_']"),selectors:[".hs-form","form[id^='hsForm_']",".hbspt-form"],events:["hsFormCallback","message"],submitPatterns:["/hsforms.com/submissions/","/forms.hubspot.com/"],active:!1},gravity:{name:"Gravity Forms",trigger:e=>e.includes("admin-ajax.php")||null!==document.querySelector(".gform_wrapper, #gform_1, [data-formid]"),selectors:[".gform_wrapper form","#gform_1, #gform_2, #gform_3, #gform_4, #gform_5, #gform_6, #gform_7, #gform_8, #gform_9","form[data-formid]",".gform_body"],events:["gform_confirmation_loaded","gform_post_render"],submitPatterns:["/wp-admin/admin-ajax.php"],active:!1},contactform7:{name:"Contact Form 7",trigger:e=>null!==document.querySelector(".wpcf7-form"),selectors:[".wpcf7-form","form.wpcf7-form"],events:["wpcf7submit","wpcf7mailsent"],submitPatterns:["/wp-json/contact-form-7/"],active:!1},typeform:{name:"Typeform",trigger:e=>e.includes("typeform.com")||null!==document.querySelector("[data-tf-widget]"),selectors:["[data-tf-widget]",".typeform-embed",'iframe[src*="typeform.com"]'],events:["tf-widget-loaded"],submitPatterns:["/forms/","typeform.com"],active:!1},mailchimp:{name:"Mailchimp",trigger:e=>e.includes("mailchimp.com")||null!==document.querySelector(".mc-embedded-subscribe-form"),selectors:[".mc-embedded-subscribe-form",'form[action*="mailchimp.com"]'],events:[],submitPatterns:["/subscribe/post"],active:!1},formstack:{name:"Formstack",trigger:e=>e.includes("formstack.com")||null!==document.querySelector(".fsForm"),selectors:[".fsForm",'form[action*="formstack.com"]'],events:[],submitPatterns:["/forms/"],active:!1},jotform:{name:"JotForm",trigger:e=>e.includes("jotform.com")||null!==document.querySelector(".jotform-form"),selectors:[".jotform-form",'form[action*="jotform.com"]'],events:[],submitPatterns:["/submit/"],active:!1},ninjaforms:{name:"Ninja Forms",trigger:e=>null!==document.querySelector(".ninja-forms-form"),selectors:[".ninja-forms-form",".nf-form-cont form"],events:["nfFormReady","nfFormSubmitResponse","nfFormSubmitted"],submitPatterns:["/wp-admin/admin-ajax.php"],active:!1},wpforms:{name:"WPForms",trigger:e=>null!==document.querySelector(".wpforms-form"),selectors:[".wpforms-form","form.wpforms-form"],events:["wpformsFormSubmitSuccess","wpformsAjaxSubmit","wpforms_submit_success"],submitPatterns:["/wp-admin/admin-ajax.php"],active:!1},elementor:{name:"Elementor Forms",trigger:e=>null!==document.querySelector(".elementor-form"),selectors:[".elementor-form","form.elementor-form"],events:["form_submit_success"],submitPatterns:["/wp-admin/admin-ajax.php"],active:!1},gohighlevel:{name:"Go High Level",trigger:e=>null!==document.querySelector(".ghl-form-wrap, .form-builder--wrap, #_builder-form, .hl_form-builder--main, .c-form"),selectors:[".ghl-form-wrap input, .ghl-form-wrap form",".form-builder--wrap input, .form-builder--wrap form","#_builder-form input, #_builder-form form",".hl_form-builder--main input, .hl_form-builder--main form",".c-form input, .c-form form"],events:[],submitPatterns:["leadconnector","gohighlevel","/funnels/","/forms/"],active:!1}},cr={inProgress:!1,completed:!1,lastAttemptAt:0},lr=(new Map,{submitted:["onformsubmitted","submitted","onformsubmit","submission"],ready:["onformready","ready","formready"],complete:["formsubmissioncomplete","complete","success"]}),dr="__cstWrapped",ur="__cstOriginal",mr=[new RegExp(CST_LAMBDA_ENDPOINT.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i"),/google-analytics\.com/i,/googletagmanager\.com/i,/facebook\.com\/tr/i,/hotjar\.com/i,/mixpanel\.com/i,/segment\.com/i,/amplitude\.com/i,/leadconnectorhq\.com\/calendars\/booking-analytics/i,/gohighlevel\.com\/calendars\/booking-analytics/i,/hscollectedforms\.net\/collected-forms/i],fr=[/https?:\/\/(?:[^\/]+\.)?hsforms\.com\/submissions\/v\d+\/public\/submit\//i,/https?:\/\/(?:[^\/]+\.)?forms\.hubspot\.com\/submissions\/v\d+\/public\/submit\//i,/https?:\/\/api\.hsforms\.com\/submissions\/v\d+\/integration\/submit\//i,/https?:\/\/forms\.hsforms\.com\/submissions\/v\d+\/public\/submit\/formsnext\//i,/https?:\/\/forms\.hsforms\.com\/submissions\/v\d+\/public\/submit\/legacy\//i,/https?:\/\/(?:[^\/]+\.)?hubspot\.com\/.*\/meetings?\//i,/https?:\/\/meetings\.hubspot\.com\//i,/https?:\/\/api\.hubapi\.com\/.*\/meetings?\//i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=gform_ajax_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=gform_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=gf_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php(?:.*action=gform_ajax_submit|.*gform_ajax=)/i,/https?:\/\/(?:[^\/]+\.)?wp-json\/contact-form-7\/v1\/contact-forms\/\d+\/feedback/i,/https?:\/\/api\.typeform\.com\/forms\/[A-Za-z0-9_-]+\/responses/i,/https?:\/\/list-manage\.com\/subscribe\/post/i,/https?:\/\/(?:[^\/]+\.)?formstack\.com\/forms\//i,/https?:\/\/submit\.jotform\.com\/form\/\d+/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=ninja_forms_ajax_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=wpforms_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=elementor_pro_forms_ajax/i,/\/wp-admin\/admin-ajax\.php.*action=.*form.*submit/i,/\/api\/.*\/forms\/.*\/submit$/i,/\/forms\/.*\/submissions$/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=wpcf7_submit/i,/https?:\/\/(?:[^\/]+\.)?wp-admin\/admin-ajax\.php\?action=wpforms_submit/i,/https?:\/\/docs\.google\.com\/forms\/d\/[A-Za-z0-9_-]+\/formResponse/i,/https?:\/\/(?:[^\/]+\.)?wufoo\.com\/forms\/[A-Za-z0-9_-]+\/def\/field/i,/https?:\/\/(?:[^\/]+\.)?surveymonkey\.com\/r\/[A-Za-z0-9_-]+/i,/https?:\/\/forms\.office\.com\/Pages\/ResponsePage\.aspx/i,/https?:\/\/(?:[^\/]+\.)?constantcontact\.com\/signup\/signup\.do/i,/https?:\/\/(?:[^\/]+\.)?leadconnectorhq\.com\//i,/https?:\/\/(?:[^\/]+\.)?gohighlevel\.com\//i],hr=[/hubspot/i,/hsforms/i,/hs-/i,/\.hs\./i,/meeting/i,/calendar/i,/schedule/i,/book/i],pr=new Set;let gr=new WeakSet,vr=!1,yr=null,wr=null,Sr=null,br=null;const Tr=3e4;let _r=null;const Ir=()=>{_r&&(document.removeEventListener("visibilitychange",_r),_r=null)};let kr=Object.assign({},di),Ar=null,Er=0,Or=!1,Lr=null,Cr=0,Yr=!1,Mr=!1,Pr=Object.assign({},{clickTrackingMode:"standard",autoEnhanceClicks:!0,alwaysIncludeClasses:!1,includeDataAnlInStandard:!1}),xr="",Rr=!1,Nr=null,Dr=null,$r=new WeakSet;const Wr=new Map,Fr=new WeakSet,Hr=new WeakMap;let jr=null;const Ur=new Map,zr=new WeakSet,Vr=new WeakMap,qr=new Map,Br=new Set,Kr=new WeakSet,Gr=new WeakMap,Xr=new Map,Jr=new Set,Qr=new WeakSet,Zr=new WeakMap;let eo=!1,to=null,no=!1,io=!1,ro=null;const oo=()=>io,ao=()=>{if(no)return;const e=document.createElement("script");e.src="https://www.youtube.com/iframe_api",e.async=!0,e.onload=()=>{(0,Pn.cY)("YouTube API script loaded")},e.onerror=()=>{(0,Pn.AO)("Failed to load YouTube API script"),no=!1,io=!1,setTimeout(ao,1e3)};const t=document.getElementsByTagName("script")[0];(null==t?void 0:t.parentNode)&&(t.parentNode.insertBefore(e,t),(0,Pn.cY)("YouTube API script loading"),no=!0)},so=()=>!(!window.YT||!window.YT.Player||(io=!0,(0,Pn.cY)("YouTube API loaded successfully"),Bt(!0),ro&&(clearInterval(ro),ro=null),0));window.onYouTubeIframeAPIReady=()=>{so()};const co=new Map,lo=new WeakMap,uo=20,mo=100;let fo=null;const ho=e=>{try{const t=e;t.id=t.id||`yt-${pe()}`;let n=new URL(t.src);const i=n.href,r=n.searchParams.get("enablejsapi"),o=n.searchParams.get("origin"),a=window.location.origin;return"1"===r&&o===a||(n.searchParams.set("enablejsapi","1"),n.searchParams.set("origin",a),n.searchParams.set("widget_referrer",window.location.href)),n.href!==i&&(t.src=n.toString(),(0,Pn.cY)("youtube iframe configured:",{id:t.id,src:t.src})),t}catch(t){return(0,Pn.AO)("Error adding ID and enablejsapi to YouTube iframe",t),e}},po=new WeakSet,go=new WeakMap;let vo=null,yo=null,wo=!1,So=null,bo=null,To=null;const _o=["[role='option']","li[role='option']","[aria-selected]","[data-value]",".multiselect__option",".select2-results__option",".MuiAutocomplete-option",".rc-select-item-option"].join(", "),Io=["[role='combobox']","[role='listbox']","[aria-haspopup='listbox']",".multiselect",".select2",".MuiAutocomplete-root",".rc-select"].join(", ");let ko=!1,Ao=null,Eo=null;const Oo=10;let Lo=null,Co=location.href,Yo=null;const Mo="__cstSpaHistoryWrapped";let Po=new WeakSet;const xo=R(()=>{try{vt()}catch(e){(0,Pn.AO)("Error in debounced enhanced form rescan",e)}},100),Ro=R(e=>{try{const t={depth:0,processedNodes:new Set,startTime:performance.now()};if(location.href!==Co)return(0,Pn.cY)("Mutation observer detected route change",{lastUrl:Co,currentUrl:location.href}),void rn();!function(e,t){if(performance.now()-t.startTime>100)(0,Pn.cY)("Mutation processing time limit exceeded");else if(t.depth>=Oo)(0,Pn.cY)("Maximum mutation depth reached");else for(const n of e)"childList"===n.type&&Array.from(n.addedNodes).forEach(e=>{t.processedNodes.has(e)||(t.processedNodes.add(e),t.processedNodes.size>100?(0,Pn.cY)("Maximum nodes per mutation reached"):e instanceof HTMLElement&&nn(e,t))})}(e,t)}catch(e){(0,Pn.AO)("Error in mutation observer callback",e)}},100);class No{static detectUserAgent(){const e=[],t=navigator.userAgent;return t?this.UA_PATTERNS.some(e=>e.test(t))&&e.push("suspicious_user_agent"):e.push("missing_user_agent"),e}static detectNavigatorProps(){const e=[];return navigator.languages&&navigator.platform||e.push("missing_navigator_info"),e}static detectAutomationGlobals(){const e=[],t=window;for(const n of Array.from(this.AUTOMATION_PROPERTIES))(n in t||n in document)&&e.push(`automation_global:${n}`);return e}static detectWebDriver(){return navigator.webdriver?["navigator_webdriver"]:[]}static detectBrowserFeatures(){const e=[];try{void 0!==window.localStorage&&void 0!==window.sessionStorage||e.push("no_storage");const t=document.createElement("canvas"),n=t.getContext("webgl")||t.getContext("experimental-webgl");if(n){const t=n.getExtension("WEBGL_debug_renderer_info"),i=t?n.getParameter(t.UNMASKED_RENDERER_WEBGL):"";/Headless|SwiftShader/i.test(i)&&e.push("headless_renderer")}0===(window.outerWidth||window.outerHeight)&&e.push("zero_window_size")}catch(t){(0,Pn.cY)("Browser feature check error",t),e.push("feature_check_error")}return e}static async detectPermissions(){const e=[];if(navigator.permissions)try{const t=await navigator.permissions.query({name:"notifications"});"denied"===Notification.permission&&"prompt"===t.state&&e.push("notif_permission_mismatch")}catch(e){(0,Pn.cY)("Permissions check error",e)}return e}static getConnectionSignalHints(){const e=[];try{const t=stateManager.getState(),n=(null==t?void 0:t.location)||null;if(!n)return e;n.httpProtocol&&"HTTP/2"!==n.httpProtocol&&"h3"!==n.httpProtocol&&e.push(`conn:http_protocol:${n.httpProtocol}`),n.tlsVersion&&"TLSv1.3"!==n.tlsVersion&&e.push(`conn:tls_version:${n.tlsVersion}`),"HTTP/2"!==n.httpProtocol||n.requestPriority||e.push("conn:missing_h2_priority"),n.tlsClientExtensionsSha1&&e.push(`conn:tls_ext_sha1:${n.tlsClientExtensionsSha1}`),"number"==typeof n.tlsClientHelloLength&&e.push(`conn:tls_hello_len:${n.tlsClientHelloLength}`),n.asn&&e.push(`conn:asn:${n.asn}`),n.colo&&e.push(`conn:colo:${n.colo}`)}catch(e){(0,Pn.cY)("Connection signal hint extraction error",e)}return e}static async detect(){const e=[...this.detectUserAgent(),...this.detectNavigatorProps(),...this.detectAutomationGlobals(),...this.detectWebDriver(),...this.detectBrowserFeatures(),...await this.detectPermissions()],t=this.getConnectionSignalHints(),n=Math.min(e.length*this.SIGNAL_WEIGHT,this.MAX_CONFIDENCE),i=e.length>=this.MIN_SIGNALS_FOR_BOT,r=i?this.getBotType(e):void 0;return{isBot:i,confidence:n,signals:[...e,...t],botType:r}}static getBotType(e){return e.some(e=>e.startsWith("automation_global")||"navigator_webdriver"===e)?"AUTOMATION":e.includes("suspicious_user_agent")?"CRAWLER":e.includes("headless_renderer")?"HEADLESS":"UNKNOWN"}}No.UA_PATTERNS=[/\b(bot|crawler|spider|crawl)\b/i,/HeadlessChrome/i,/PhantomJS/i,/Selenium/i,/puppeteer/i,/chrome\-lighthouse/i,/Googlebot/i,/Bingbot/i,/YandexBot/i,/Baiduspider/i,/FacebookExternalHit/i,/Twitterbot/i,/Applebot/i,/AhrefsBot/i],No.AUTOMATION_PROPERTIES=new Set(["webdriver","_phantom","__nightmare","__selenium_evaluate","__webdriver_script_fn","__fxdriver_evaluate","__driver_evaluate","callPhantom","ChromeDriver"]),No.MIN_SIGNALS_FOR_BOT=2,No.MAX_CONFIDENCE=1,No.SIGNAL_WEIGHT=.33;let Do=!1;const $o=[],Wo=[];let Fo=null;const Ho=new Map,jo=new Map,Uo=[];let zo=!1;const Vo="kleerr_cst",qo="2026-01";let Bo=null,Ko=null,Go=0,Xo="",Jo=0,Qo="",Zo=0,ea=!1,ta=0;const na=2e3;let ia=null,ra=0,oa=0,aa=!1,sa=!1,ca=null;const la="2.0.1.20260215";window.CST_VERSION=la,console.log("CST version:",la);try{if("undefined"!=typeof window){const e=window;e.__KLEERR_PIXEL_ENDPOINT||(e.__KLEERR_PIXEL_ENDPOINT=jn)}}catch(e){(0,Pn.AO)("Failed to seed pixel endpoint",e)}const CSTExport={initialize};if("undefined"!=typeof window&&"test"!=="production".toLowerCase()){const e=window;e.KLRR_CSTM_FX||(e.KLRR_CSTM_FX=CSTExport,(0,Pn.cY)("KLRR_CST_FX] Global set: window.KLRR_CSTM_FX")),e.KLRR_CST_FX||(e.KLRR_CST_FX=e.KLRR_CSTM_FX,(0,Pn.cY)("KLRR_CST_FX] Back-compat: window.KLRR_CST_FX → window.KLRR_CSTM_FX")),e.CST?(0,Pn.cY)("KLRR_CST_FX] window.CST already defined; keeping existing alias"):(e.CST=e.KLRR_CSTM_FX,(0,Pn.cY)("KLRR_CST_FX] Back-compat: window.CST → window.KLRR_CSTM_FX")),(0,Pn.cY)("CST attempting auto-initialization"),initialize().catch(e=>{console.error("CST initialization failed:",e)})}const da=CSTExport;return Mn.default})(),"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CST=e():this.CST=e();