@active-reach/web-sdk 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/aegis.min.js CHANGED
@@ -1,2 +1,2 @@
1
- var Aegis=function(){"use strict";const e={workspace_id:null,batch_size:10,batch_interval:1e3,capture_utm:!0,capture_referrer:!0,auto_page_view:!1,session_timeout:30,debug:!1,respect_dnt:!0,cross_domain_tracking:!1,secure_cookie:!0,enable_offline_mode:!0,max_offline_events:100,retry_failed_requests:!0,max_retries:3,retry_backoff_multiplier:2,request_timeout:5e3,rate_limit_burst:100,rate_limit_per_second:20,auto_region_detection:!0,wait_for_consent:!1,enable_consent_mode:!1,integrate_onetrust:!1,integrate_cookiebot:!1,integrate_google_consent_mode:!1,default_consent:{analytics:!1,marketing:!1,functional:!0},initialized:!1,api_host:null,cell_endpoints:[],preferred_region:null,cookie_domain:null,plugins:[],active_cell:null};function t(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function n(){return`msg_${Date.now()}_${t().slice(0,8)}`}const i=new class{constructor(){this.enabled=!1,this.prefix="[Aegis SDK]"}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}debug(e,...t){this.enabled&&this.prefix}info(e,...t){this.enabled&&console.info(`${this.prefix} ${e}`,...t)}warn(e,...t){console.warn(`${this.prefix} ${e}`,...t)}error(e,...t){console.error(`${this.prefix} ${e}`,...t)}};class s{constructor(e){this.userId=null,this.traits={},this.storage=e,this.anonymousId=this.getOrCreateAnonymousId(),this.loadUserIdentity()}getOrCreateAnonymousId(){let e=this.storage.get("anon_id");return e?i.debug("Loaded existing anonymous ID:",e):(e=t(),this.storage.set("anon_id",e,365),i.debug("Created new anonymous ID:",e)),e}loadUserIdentity(){const e=this.storage.get("user_id"),t=this.storage.get("user_traits");if(e&&(this.userId=e,i.debug("Loaded user ID:",e)),t)try{this.traits=JSON.parse(t),i.debug("Loaded user traits:",this.traits)}catch(n){i.warn("Failed to parse stored traits:",n),this.traits={}}}getAnonymousId(){return this.anonymousId}setUserId(e,t){this.userId=e,this.storage.set("user_id",e,365),i.info("User identified:",e),t&&this.setTraits(t)}getUserId(){return this.userId}setTraits(e){this.traits={...this.traits,...e},this.storage.set("user_traits",JSON.stringify(this.traits),365),i.debug("User traits updated:",this.traits)}getTraits(){return{...this.traits}}reset(){this.userId=null,this.traits={},this.anonymousId=t(),this.storage.remove("user_id"),this.storage.remove("user_traits"),this.storage.set("anon_id",this.anonymousId,365),i.info("Identity reset, new anonymous ID:",this.anonymousId)}alias(e){const t=this.userId||this.anonymousId;return this.setUserId(e),i.info("User aliased:",{previousId:t,newUserId:e}),{previousId:t,newUserId:e}}getState(){return{anonymousId:this.anonymousId,userId:this.userId,traits:this.getTraits()}}}class o{constructor(e,t=30){this.eventCount=0,this.checkInterval=null,this.activityThrottle=1e3,this.lastActivityUpdate=0,this.adClickIDs={},this.storage=e,this.sessionTimeout=60*t*1e3,this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now();const n=this.loadSession();n?(this.sessionId=n.sessionId,this.sessionStartTime=n.startTime,this.lastActivityTime=n.lastActivityTime,this.eventCount=n.eventCount,this.adClickIDs=n.adClickIDs||{},this.landingPage=n.landingPage,i.debug("Session loaded:",n)):this.sessionId=this.createNewSession(),this.startActivityTracking(),this.startExpiryCheck()}loadSession(){const e=this.storage.get("session");if(!e)return null;try{const t=JSON.parse(e);return Date.now()-t.lastActivityTime<this.sessionTimeout?t:(i.debug("Session expired, creating new session"),this.storage.remove("session"),null)}catch(t){return i.warn("Failed to parse session data:",t),this.storage.remove("session"),null}}createNewSession(){const e=`sess_${Date.now()}_${t().slice(0,8)}`;return this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.eventCount=0,this.persistSession(),i.info("New session created:",e),e}persistSession(){const e={sessionId:this.sessionId,startTime:this.sessionStartTime,lastActivityTime:this.lastActivityTime,eventCount:this.eventCount,adClickIDs:this.adClickIDs,landingPage:this.landingPage};this.storage.set("session",JSON.stringify(e))}startActivityTracking(){const e=()=>this.onActivity();["click","scroll","keypress","mousemove","touchstart"].forEach(t=>{window.addEventListener(t,e,{passive:!0})}),window.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.onActivity()})}startExpiryCheck(){this.checkInterval=window.setInterval(()=>{this.checkSessionExpiry()},6e4)}onActivity(){const e=Date.now();if(e-this.lastActivityUpdate<this.activityThrottle)return;this.lastActivityUpdate=e;e-this.lastActivityTime>this.sessionTimeout?(i.info("Session expired due to inactivity, creating new session"),this.sessionId=this.createNewSession()):(this.lastActivityTime=e,this.persistSession())}checkSessionExpiry(){Date.now()-this.lastActivityTime>this.sessionTimeout&&(i.info("Session expired during check, creating new session"),this.sessionId=this.createNewSession())}getSessionId(){return this.sessionId}incrementEventCount(){this.eventCount++,this.lastActivityTime=Date.now(),this.persistSession()}getSessionDuration(){return Date.now()-this.sessionStartTime}getEventCount(){return this.eventCount}getState(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,lastActivityTime:this.lastActivityTime,eventCount:this.eventCount,adClickIDs:this.adClickIDs,landingPage:this.landingPage}}setAdClickIDs(e,t){Object.keys(e).length>0&&(this.adClickIDs={...this.adClickIDs,...e},t&&(this.landingPage=t),this.persistSession(),i.info("Ad click IDs stored in session:",this.adClickIDs))}getAdClickIDs(){return this.adClickIDs}getLandingPage(){return this.landingPage}destroy(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null)}}class r{constructor(e,t,n){this.buffer=[],this.flushInterval=null,this.isFlushing=!1,this.offlineQueue=[],this.isOnline=navigator.onLine,this.config=e,this.transport=t,this.storage=n,e.enableOfflineMode&&(this.loadOfflineQueue(),this.setupOnlineListener()),this.startFlushTimer(),this.setupUnloadHandlers()}loadOfflineQueue(){const e=this.storage.get("offline_queue");if(e)try{const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.offlineQueue=t.slice(0,this.config.maxOfflineEvents),i.info(`Loaded ${this.offlineQueue.length} offline events`),this.isOnline&&this.flushOfflineQueue())}catch(t){i.warn("Failed to load offline queue:",t),this.storage.remove("offline_queue")}}saveOfflineQueue(){if(0!==this.offlineQueue.length)try{const e=JSON.stringify(this.offlineQueue);this.storage.set("offline_queue",e),i.debug(`Saved ${this.offlineQueue.length} events to offline queue`)}catch(e){i.warn("Failed to save offline queue:",e)}else this.storage.remove("offline_queue")}setupOnlineListener(){window.addEventListener("online",()=>{i.info("Connection restored"),this.isOnline=!0,this.flushOfflineQueue(),this.flush()}),window.addEventListener("offline",()=>{i.warn("Connection lost, entering offline mode"),this.isOnline=!1})}async flushOfflineQueue(){if(0===this.offlineQueue.length)return;i.info(`Flushing ${this.offlineQueue.length} offline events`);const e=[...this.offlineQueue];this.offlineQueue=[],this.storage.remove("offline_queue");(await this.transport.send(e)).success?i.info("Offline events sent successfully"):(i.warn("Failed to send offline events, re-queueing"),this.offlineQueue=[...e,...this.offlineQueue].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue())}push(e){this.isOnline||!this.config.enableOfflineMode?(this.buffer.push(e),i.debug("Event queued:",e.type,e),this.buffer.length>=this.config.batchSize&&this.flush()):this.addToOfflineQueue(e)}addToOfflineQueue(e){this.offlineQueue.length>=this.config.maxOfflineEvents&&(i.warn("Offline queue full, dropping oldest event"),this.offlineQueue.shift()),this.offlineQueue.push(e),this.saveOfflineQueue(),i.debug("Event added to offline queue")}async flush(){if(this.isFlushing)return void i.debug("Flush already in progress, skipping");if(0===this.buffer.length)return;this.isFlushing=!0;const e=[...this.buffer];this.buffer=[],i.info(`Flushing ${e.length} events`);try{const t=await this.transport.send(e);t.success?i.info("Events sent successfully"):(i.error("Failed to send events:",t.error),this.config.enableOfflineMode?(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),i.info("Events saved to offline queue")):(this.buffer.unshift(...e),i.warn("Events re-queued for retry")))}catch(t){i.error("Flush error:",t),this.config.enableOfflineMode&&(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue())}finally{this.isFlushing=!1}}startFlushTimer(){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=window.setInterval(()=>{this.flush()},this.config.batchInterval),i.debug(`Flush timer started with interval: ${this.config.batchInterval}ms`)}setupUnloadHandlers(){const e=()=>{(this.buffer.length>0||this.offlineQueue.length>0)&&(this.persistBufferToOfflineQueue(),this.flush())};document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&e()}),window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}persistBufferToOfflineQueue(){0!==this.buffer.length&&this.config.enableOfflineMode&&(this.offlineQueue=[...this.offlineQueue,...this.buffer].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),i.debug("Buffer persisted to offline queue before unload"))}getQueueSize(){return this.buffer.length}getOfflineQueueSize(){return this.offlineQueue.length}clear(){this.buffer=[],this.offlineQueue=[],this.storage.remove("offline_queue"),i.info("Queue cleared")}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}class a{constructor(e,t){this.activeCell=null,this.healthCheckInterval=null,this.regionLatencyMap=new Map,this.config=e,this.storage=t,e.cellEndpoints.length>0&&this.initializeCellularArchitecture()}async initializeCellularArchitecture(){const e=this.loadCachedCell();e&&this.isCellHealthy(e)?(this.activeCell=e,i.info("Using cached cell:",e)):await this.selectOptimalCell(),this.startHealthChecks()}loadCachedCell(){const e=this.storage.get("active_cell");if(!e)return null;try{return JSON.parse(e)}catch(t){return i.warn("Failed to parse cached cell:",t),null}}saveCachedCell(e){this.storage.set("active_cell",JSON.stringify(e),7)}isCellHealthy(e){return e.healthy&&this.config.cellEndpoints.some(t=>t.region===e.region&&t.url===e.url)}async selectOptimalCell(){if(i.info("Selecting optimal cell..."),this.config.preferredRegion){const e=this.config.cellEndpoints.find(e=>e.region===this.config.preferredRegion&&e.healthy);if(e)return this.activeCell=e,this.saveCachedCell(e),void i.info("Using preferred region cell:",e)}this.config.autoRegionDetection?await this.detectOptimalRegion():this.selectCellByPriority()}async detectOptimalRegion(){const e=this.config.cellEndpoints.filter(e=>e.healthy);if(0===e.length)return void i.error("No healthy cells available");const t=e.map(async e=>{const t=await this.measureLatency(e);return this.regionLatencyMap.set(e.region,t),{cell:e,latency:t}}),n=await Promise.all(t);n.sort((e,t)=>e.latency-t.latency);const s=n[0].cell;this.activeCell=s,this.saveCachedCell(s),i.info("Optimal cell selected:",{region:s.region,latency:n[0].latency})}async measureLatency(e){const t=performance.now();try{const n=new AbortController,i=setTimeout(()=>n.abort(),2e3),s=await fetch(`${e.url}/health`,{method:"GET",signal:n.signal});return clearTimeout(i),s.ok?performance.now()-t:1/0}catch(n){return i.warn(`Health check failed for ${e.region}:`,n),1/0}}selectCellByPriority(){const e=[...this.config.cellEndpoints].filter(e=>e.healthy).sort((e,t)=>e.priority-t.priority);e.length>0?(this.activeCell=e[0],this.saveCachedCell(e[0]),i.info("Cell selected by priority:",e[0])):i.error("No healthy cells available")}startHealthChecks(){this.healthCheckInterval=window.setInterval(()=>{this.performHealthChecks()},6e4)}async performHealthChecks(){const e=this.config.cellEndpoints.map(async e=>{const t=await this.checkCellHealth(e);return e.healthy=t,{cell:e,isHealthy:t}}),t=await Promise.all(e);this.activeCell&&!this.activeCell.healthy&&(i.warn("Active cell unhealthy, selecting new cell"),await this.selectOptimalCell()),i.debug("Health check results:",t)}async checkCellHealth(e){try{const t=new AbortController,n=setTimeout(()=>t.abort(),3e3),i=await fetch(`${e.url}/health`,{method:"GET",signal:t.signal});return clearTimeout(n),i.ok}catch(t){return!1}}async send(e){if(0===e.length)return{success:!0};const t=this.getActiveEndpoint(),n=this.buildPayload(e);if(i.debug("Sending batch:",{endpoint:t,eventCount:e.length}),"hidden"===document.visibilityState&&"function"==typeof navigator.sendBeacon){const e=this.sendViaBeacon(t,n);return Promise.resolve(e)}return this.sendViaFetch(t,n)}getActiveEndpoint(){if(this.activeCell)return`${this.activeCell.url}/v1/batch`;if(this.config.apiHost)return`${this.config.apiHost}/v1/batch`;throw new Error("No active endpoint available")}buildPayload(e){return{batch:e,sentAt:(new Date).toISOString(),writeKey:this.config.writeKey,context:this.activeCell?{cell:{region:this.activeCell.region,endpoint:this.activeCell.url}}:void 0}}sendViaBeacon(e,t){try{const n=new Blob([JSON.stringify(t)],{type:"application/json"});return navigator.sendBeacon(e,n)?(i.debug("Batch sent via Beacon"),{success:!0,endpoint:e}):(i.warn("Beacon send failed, falling back to fetch"),this.sendViaFetch(e,t))}catch(n){return i.error("Beacon send error:",n),{success:!1,error:n,endpoint:e}}}async sendViaFetch(e,t,n=1){try{const s=new AbortController,o=setTimeout(()=>s.abort(),this.config.requestTimeout),r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.writeKey}`},body:JSON.stringify(t),keepalive:!0,signal:s.signal});if(clearTimeout(o),r.ok){const t=await r.json();return i.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const s=await r.text(),o=new Error(`HTTP ${r.status}: ${s||r.statusText}`);return i.error("Batch send failed:",o),this.shouldRetry(r.status,n)?this.retryRequest(e,t,n):{success:!1,error:o,endpoint:e}}}catch(s){return i.error("Fetch error:",s),this.shouldRetry(0,n)?this.retryRequest(e,t,n):{success:!1,error:s,endpoint:e}}}shouldRetry(e,t){return!!this.config.retryFailedRequests&&(!(t>=this.config.maxRetries)&&(0===e||(e>=500||429===e)))}async retryRequest(e,t,n){const s=1e3*Math.pow(this.config.retryBackoffMultiplier,n);return i.info(`Retrying request in ${s}ms (attempt ${n+1})`),await new Promise(e=>setTimeout(e,s)),this.sendViaFetch(e,t,n+1)}getActiveCell(){return this.activeCell}getRegionLatencies(){return new Map(this.regionLatencyMap)}destroy(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}}const c="aegis_";class d{constructor(e={}){this.options=e,this.useLocalStorage=this.isLocalStorageAvailable()}isLocalStorageAvailable(){try{const e="__aegis_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}set(e,t,n=365){const i=c+e;if(this.useLocalStorage)try{const e={value:t,expiry:Date.now()+24*n*60*60*1e3};localStorage.setItem(i,JSON.stringify(e))}catch(s){console.warn("[Aegis Storage] localStorage.setItem failed:",s)}this.setCookie(i,t,n)}get(e){const t=c+e;if(this.useLocalStorage)try{const e=localStorage.getItem(t);if(e){const n=JSON.parse(e);if(Date.now()<n.expiry)return n.value;localStorage.removeItem(t)}}catch(n){console.warn("[Aegis Storage] localStorage.getItem failed:",n)}return this.getCookie(t)}remove(e){const t=c+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch(n){console.warn("[Aegis Storage] localStorage.removeItem failed:",n)}this.deleteCookie(t)}clear(){if(this.useLocalStorage)try{Object.keys(localStorage).forEach(e=>{e.startsWith(c)&&localStorage.removeItem(e)})}catch(e){console.warn("[Aegis Storage] localStorage.clear failed:",e)}document.cookie.split(";").forEach(e=>{const t=e.split("=")[0].trim();t.startsWith(c)&&this.deleteCookie(t)})}setCookie(e,t,n){try{const i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3);let s=`${e}=${t};${`expires=${i.toUTCString()}`};path=/`;if(this.options.secureCookie&&"https:"===window.location.protocol&&(s+=";Secure"),s+=";SameSite=Lax",this.options.cookieDomain)s+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(s+=`;domain=${e}`)}document.cookie=s}catch(i){console.warn("[Aegis Storage] setCookie failed:",i)}}getCookie(e){try{const t=e+"=",n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return i.substring(t.length,i.length)}}catch(t){console.warn("[Aegis Storage] getCookie failed:",t)}return null}deleteCookie(e){try{let t=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;if(this.options.cookieDomain)t+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(t+=`;domain=${e}`)}document.cookie=t}catch(t){console.warn("[Aegis Storage] deleteCookie failed:",t)}}getRootDomain(){try{const e=window.location.hostname;if(/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return null;if("localhost"===e)return null;const t=e.split(".");return t.length<=2?`.${e}`:`.${t.slice(-2).join(".")}`}catch(e){return console.warn("[Aegis Storage] getRootDomain failed:",e),null}}}function l(e,t){const n=e.capture_utm?function(e){try{const t=e?new URL(e).searchParams:new URLSearchParams(window.location.search),n={};return["source","medium","campaign","term","content","name"].forEach(e=>{const i=t.get(`utm_${e}`);i&&(n[e]=i)}),n}catch(t){return console.warn("[Aegis URL Parser] parseUTMParameters failed:",t),{}}}():void 0,i=function(){const e=navigator.userAgent;if(/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e))return{type:"tablet"};if(/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e))return{type:"mobile"};return{type:"desktop"}}(),s=function(){const e=navigator.userAgent;if(/Windows NT 10/i.test(e))return{name:"Windows",version:"10"};if(/Windows NT 6.3/i.test(e))return{name:"Windows",version:"8.1"};if(/Windows NT 6.2/i.test(e))return{name:"Windows",version:"8"};if(/Windows NT 6.1/i.test(e))return{name:"Windows",version:"7"};if(/Windows/i.test(e))return{name:"Windows",version:"Unknown"};if(/Mac OS X (\d+)[._](\d+)/.test(e)){const t=e.match(/Mac OS X (\d+)[._](\d+)/);return{name:"macOS",version:`${t[1]}.${t[2]}`}}if(/Mac/i.test(e))return{name:"macOS",version:"Unknown"};if(/Android (\d+\.\d+)/.test(e)){return{name:"Android",version:e.match(/Android (\d+\.\d+)/)[1]}}if(/Android/i.test(e))return{name:"Android",version:"Unknown"};if(/iPhone OS (\d+)_(\d+)/.test(e)){const t=e.match(/iPhone OS (\d+)_(\d+)/);return{name:"iOS",version:`${t[1]}.${t[2]}`}}if(/iPad.*OS (\d+)_(\d+)/.test(e)){const t=e.match(/iPad.*OS (\d+)_(\d+)/);return{name:"iOS",version:`${t[1]}.${t[2]}`}}return/iPhone|iPad/i.test(e)?{name:"iOS",version:"Unknown"}:/Linux/i.test(e)?{name:"Linux",version:"Unknown"}:{name:"Unknown",version:"Unknown"}}(),o=function(){const e=navigator.userAgent;if(/Edg\/(\d+\.\d+)/.test(e)){return{name:"Edge",version:e.match(/Edg\/(\d+\.\d+)/)[1]}}if(/Chrome\/(\d+\.\d+)/.test(e)&&!/Edg/.test(e)){return{name:"Chrome",version:e.match(/Chrome\/(\d+\.\d+)/)[1]}}if(/Firefox\/(\d+\.\d+)/.test(e)){return{name:"Firefox",version:e.match(/Firefox\/(\d+\.\d+)/)[1]}}if(/Safari\/(\d+\.\d+)/.test(e)&&!/Chrome/.test(e)){const t=e.match(/Version\/(\d+\.\d+)/);return{name:"Safari",version:t?t[1]:"Unknown"}}if(/MSIE (\d+\.\d+)/.test(e)||/Trident\//.test(e)){const t=e.match(/MSIE (\d+\.\d+)/)||e.match(/rv:(\d+\.\d+)/);return{name:"Internet Explorer",version:t?t[1]:"Unknown"}}return{name:"Unknown",version:"Unknown"}}(),r=function(){try{const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e)return{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt}}catch(e){console.warn("[Aegis Device] detectNetworkInfo failed:",e)}return}(),a=null==t?void 0:t.getAdClickIDs(),c=null==t?void 0:t.getLandingPage();return{library:{name:"@active-reach/web-sdk",version:"1.0.0"},page:{path:window.location.pathname,referrer:e.capture_referrer?document.referrer:"",search:window.location.search,title:document.title,url:window.location.href,hash:window.location.hash},userAgent:navigator.userAgent,locale:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screen:{width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio||1},viewport:{width:window.innerWidth,height:window.innerHeight},...n&&Object.keys(n).length>0&&{campaign:n},...a&&Object.keys(a).length>0&&{adClickIDs:a},...c&&{landingPage:c},...r&&{network:r},...i&&{device:i},...s&&{os:s},...o&&{browser:o},...e.active_cell&&{cell:{region:e.active_cell.region,endpoint:e.active_cell.url}}}}class h{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.name)?i.warn(`Plugin "${e.name}" already registered, skipping`):(this.plugins.set(e.name,e),i.info(`Plugin registered: ${e.name} v${e.version}`))}unregister(e){const t=this.plugins.get(e);if(t){if(t.destroy)try{t.destroy()}catch(n){i.error(`Error destroying plugin "${e}":`,n)}this.plugins.delete(e),i.info(`Plugin unregistered: ${e}`)}else i.warn(`Plugin "${e}" not found`)}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async executeHook(e,...t){for(const o of this.plugins.values()){const r=o[e];if("function"==typeof r)try{const e=await r.apply(o,t);if(void 0!==e)return e}catch(n){if(i.error(`Error executing ${String(e)} in plugin "${o.name}":`,n),o.onError)try{o.onError(n,{hookName:e,args:t})}catch(s){i.error(`Error in onError handler for plugin "${o.name}":`,s)}}}}async executeHookChain(e,t,...n){let s=t;for(const a of this.plugins.values()){const t=a[e];if("function"==typeof t)try{const e=await t.apply(a,[s,...n]);null!=e&&(s=e)}catch(o){if(i.error(`Error executing ${String(e)} in plugin "${a.name}":`,o),a.onError)try{a.onError(o,{hookName:e,value:s,additionalArgs:n})}catch(r){i.error(`Error in onError handler for plugin "${a.name}":`,r)}}}return s}async executeHookParallel(e,...t){const n=[];for(const s of this.plugins.values()){const o=s[e];if("function"==typeof o){const r=(async()=>{try{return await o.apply(s,t)}catch(n){if(i.error(`Error executing ${String(e)} in plugin "${s.name}":`,n),s.onError)try{s.onError(n,{hookName:e,args:t})}catch(r){i.error(`Error in onError handler for plugin "${s.name}":`,r)}return}})();n.push(r)}}return(await Promise.all(n)).filter(e=>void 0!==e)}clear(){for(const t of this.plugins.values())if(t.destroy)try{t.destroy()}catch(e){i.error(`Error destroying plugin "${t.name}":`,e)}this.plugins.clear(),i.info("All plugins cleared")}}class p{constructor(e,t={}){this.listeners=[],this.storage=e,this.config={defaultConsent:t.defaultConsent||{},waitForConsent:t.waitForConsent??!1,consentStorageKey:t.consentStorageKey||"aegis_consent"},this.preferences=this.loadPreferences()}loadPreferences(){const e=this.storage.get(this.config.consentStorageKey);if(e)try{const t=JSON.parse(e);return i.info("Loaded consent preferences:",t),this.mergeWithDefaults(t)}catch(t){i.warn("Failed to parse consent preferences:",t)}return this.getDefaultPreferences()}getDefaultPreferences(){return{analytics:this.config.defaultConsent.analytics??!1,marketing:this.config.defaultConsent.marketing??!1,functional:this.config.defaultConsent.functional??!0,necessary:!0}}mergeWithDefaults(e){return{necessary:!0,analytics:e.analytics??this.config.defaultConsent.analytics??!1,marketing:e.marketing??this.config.defaultConsent.marketing??!1,functional:e.functional??this.config.defaultConsent.functional??!0}}savePreferences(){try{this.storage.set(this.config.consentStorageKey,JSON.stringify(this.preferences),365),i.info("Saved consent preferences:",this.preferences)}catch(e){i.error("Failed to save consent preferences:",e)}}setConsent(e){const t={...this.preferences,...e};t.necessary=!0,this.preferences=t,this.savePreferences(),this.notifyListeners(),i.info("Consent updated:",this.preferences)}grantAll(){this.setConsent({analytics:!0,marketing:!0,functional:!0,necessary:!0})}denyAll(){this.setConsent({analytics:!1,marketing:!1,functional:!1,necessary:!0})}hasConsent(e){return this.preferences[e]}getPreferences(){return{...this.preferences}}getStatus(e){if(this.hasConsent(e))return"granted";return!this.storage.get(this.config.consentStorageKey)&&this.config.waitForConsent?"pending":"denied"}isAnalyticsEnabled(){return this.hasConsent("analytics")}isMarketingEnabled(){return this.hasConsent("marketing")}onChange(e){return this.listeners.push(e),()=>{const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getPreferences())}catch(t){i.error("Consent listener error:",t)}})}reset(){this.storage.remove(this.config.consentStorageKey),this.preferences=this.getDefaultPreferences(),this.notifyListeners(),i.info("Consent preferences reset")}integrateOneTrust(){if("undefined"==typeof window)return;if(!window.OneTrust)return void i.warn("OneTrust not detected");const e=()=>{const e=window.OnetrustActiveGroups||"";this.setConsent({necessary:!0,functional:e.includes("C0003"),analytics:e.includes("C0002"),marketing:e.includes("C0004")}),i.info("Synced with OneTrust consent")};if(window.OptanonWrapper){const t=window.OptanonWrapper;window.OptanonWrapper=function(){t(),e()}}else window.OptanonWrapper=e;e()}integrateCookiebot(){if("undefined"==typeof window)return;const e=window.Cookiebot;if(!e)return void i.warn("Cookiebot not detected");const t=()=>{const t=e.consent||{};this.setConsent({necessary:!0,functional:t.preferences||!1,analytics:t.statistics||!1,marketing:t.marketing||!1}),i.info("Synced with Cookiebot consent")};window.addEventListener("CookiebotOnAccept",t),window.addEventListener("CookiebotOnDecline",t),e.consent&&t()}integrateGoogleConsentMode(){if("undefined"==typeof window)return;const e=window.gtag;if(!e)return void i.warn("Google Tag Manager not detected");const t=()=>{e("consent","update",{ad_storage:this.preferences.marketing?"granted":"denied",analytics_storage:this.preferences.analytics?"granted":"denied",ad_user_data:this.preferences.marketing?"granted":"denied",ad_personalization:this.preferences.marketing?"granted":"denied",functionality_storage:this.preferences.functional?"granted":"denied",personalization_storage:this.preferences.functional?"granted":"denied",security_storage:"granted"}),i.info("Updated Google Consent Mode")};this.onChange(t),t()}}const u="_fbp",g="_fbc";function m(e){if("undefined"==typeof document)return null;try{const t=`${e}=`,n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length))}}catch{}return null}function f(e,t,n){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const i=new Date(Date.now()+24*n*60*60*1e3).toUTCString(),s=function(){if("undefined"==typeof window)return null;const e=window.location.hostname;if(!e||"localhost"===e)return null;if(/^\d+\.\d+\.\d+\.\d+$/.test(e))return null;const t=e.split(".");return t.length<2?null:"."+t.slice(-2).join(".")}(),o="https:"===window.location.protocol;let r=`${e}=${encodeURIComponent(t)};expires=${i};path=/;SameSite=Lax`;o&&(r+=";Secure"),s&&(r+=`;domain=${s}`),document.cookie=r}catch{}}function y(){if("undefined"==typeof window)return 1;const e=window.location.hostname;if(!e||"localhost"===e||/^\d+\.\d+\.\d+\.\d+$/.test(e))return 1;const t=e.split(".");return Math.max(1,t.length-1)}function x(){const e=m(u);if(e)return e;const t=`fb.${y()}.${Date.now()}.${Math.floor(1e10*Math.random()).toString().padStart(10,"0")}`;return f(u,t,90),t}function b(){const e=m(g);if(e)return e;const t=v();if(!t)return null;const n=`fb.${y()}.${Date.now()}.${t}`;return f(g,n,90),n}function v(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get("fbclid")}catch{return null}}function w(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function _(e){return e.map(e=>({product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency,category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label,position:e.position}))}class C{constructor(e){this.aegis=e}productViewed(e){this.aegis.track("product_viewed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label,image_url:e.image_url,url:e.url})}productListViewed(e){this.aegis.track("product_list_viewed",{list_id:e.list_id,list_name:e.list_name,category:e.category,products:_(e.products)})}productClicked(e,t){this.aegis.track("product_clicked",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}productImpressed(e,t){this.aegis.track("product_impression",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}categoryFiltered(e,t){this.aegis.track("category_filtered",{category:e,previous_category:null==t?void 0:t.previous_category,result_count:null==t?void 0:t.result_count})}searchPerformed(e){this.aegis.track("search_performed",{query:e.query,results_count:e.results_count,filters:e.filters})}addToCart(e){this.aegis.track("cart_item_added",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label})}removeFromCart(e){this.aegis.track("cart_item_removed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",variant_id:e.variant_id})}cartViewed(e){this.aegis.track("cart_viewed",{cart_id:e.cart_id,value:e.value,currency:e.currency??"INR",num_items:w(e.products),products:_(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:w(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:_(e.products)})}checkoutStep(e,t){this.aegis.track("checkout_step",{step:e,...t})}orderCompleted(e){this.aegis.track("order_completed",{order_id:e.order_id,value:e.value,revenue:e.revenue??e.value,currency:e.currency??"INR",num_items:w(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:_(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?_(n):void 0})}couponApplied(e){this.aegis.track("coupon_applied",{...e})}couponRemoved(e){this.aegis.track("coupon_removed",{...e})}wishlistItemAdded(e){this.aegis.track("wishlist_item_added",{wishlist_id:e.wishlist_id,wishlist_name:e.wishlist_name,product_id:e.product.product_id,sku:e.product.sku??e.product.product_id,name:e.product.name,price:e.product.price,variant_id:e.product.variant_id})}promotionViewed(e){this.aegis.track("promotion_viewed",{...e})}promotionClicked(e){this.aegis.track("promotion_clicked",{...e})}}class k{constructor(e={}){this.droppedThisWindow=0,this.firstDroppedName=null,this.windowFlushTimer=null,this.capacity=Math.max(1,e.burstCapacity??100),this.refillPerSecond=Math.max(1,e.refillPerSecond??20),this.windowMs=e.dropCoalesceWindowMs??1e3,this.onDropBatch=e.onDropBatch,this.tokens=this.capacity,this.lastRefillMs=Date.now()}tryConsume(e){return this.refill(),this.tokens>=1?(this.tokens-=1,!0):(this.droppedThisWindow+=1,null===this.firstDroppedName&&(this.firstDroppedName=e,i.warn(`[Aegis] Rate limit reached — dropping event "${e}" and any further events for ${this.windowMs}ms. Burst=${this.capacity}, refill=${this.refillPerSecond}/s.`)),this.windowFlushTimer||(this.windowFlushTimer=setTimeout(()=>this.flushWindow(),this.windowMs)),!1)}getAvailableTokens(){return this.refill(),Math.floor(this.tokens)}destroy(){this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.flushWindow()}refill(){const e=Date.now(),t=(e-this.lastRefillMs)/1e3;if(t<=0)return;const n=t*this.refillPerSecond;this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefillMs=e}flushWindow(){if(this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.droppedThisWindow>0&&this.onDropBatch)try{this.onDropBatch(this.droppedThisWindow,this.firstDroppedName)}catch(e){i.warn("[Aegis] RateLimiter.onDropBatch threw:",e)}this.droppedThisWindow=0,this.firstDroppedName=null}}const S=3432918353,E=461845907;function I(e,t=0){return function(e,t=0){const n=e.length,i=Math.floor(n/4);let s=t>>>0;for(let c=0;c<i;c++){const t=4*c;let n=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;n=Math.imul(n,S),n=n<<15|n>>>17,n=Math.imul(n,E),s^=n,s=s<<13|s>>>19,s=Math.imul(s,5)+3864292196>>>0}const o=4*i;let r=0;const a=n-o;3===a&&(r^=e[o+2]<<16);a>=2&&(r^=e[o+1]<<8);a>=1&&(r^=e[o],r=Math.imul(r,S),r=r<<15|r>>>17,r=Math.imul(r,E),s^=r);return s^=n,s^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}((new TextEncoder).encode(e),t)}class T{constructor(e,t){if(this.params=t,t.m&t.m-1)throw new Error(`Bloom filter m must be a power of 2, got ${t.m}`);if(e.length!==t.m>>3)throw new Error(`Bloom filter buffer size mismatch: expected ${t.m>>3} bytes, got ${e.length}`);this.buf=e,this.mask=t.m-1}static fromBase64(e,t){const n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const t=globalThis.Buffer;if(t&&"function"==typeof t.from){const n=t.from(e,"base64");return new Uint8Array(n)}throw new Error("No base64 decoder available (neither atob nor Buffer)")}(e);return new T(n,t)}has(e){const t=I(e,this.params.seedA),n=I(e,this.params.seedB);for(let i=0;i<this.params.k;i++){const e=t+Math.imul(i,n)>>>0&this.mask;if(0===(this.buf[e>>3]&1<<(7&e)))return!1}return!0}}class z{constructor(){this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,this.localNovelNames=new Set,this.droppedSinceLastReport=new Map,this.reportWindowStart=Date.now(),this.hasWarnedThisSession=!1}ingestHint(e){if(!e||"mmh3_x86_32_km"!==e.bloom_algo)return this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,void this.localNovelNames.clear();try{this.bloom=T.fromBase64(e.bloom_b64,{m:e.m,k:e.k,seedA:e.seed_a,seedB:e.seed_b})}catch{this.bloom=null}this.remainingNewNames=e.remaining_new_names??1/0,this.graceActive=!0===e.grace_active,this.localNovelNames.clear()}shouldSend(e){if(!this.bloom)return!0;if(this.graceActive)return!0;if(this.bloom.has(e))return!0;if(this.localNovelNames.has(e))return!0;if(this.remainingNewNames>0)return this.localNovelNames.add(e),this.remainingNewNames-=1,!0;const t=this.droppedSinceLastReport.get(e)??0;var n;return this.droppedSinceLastReport.set(e,t+1),this.hasWarnedThisSession||(this.hasWarnedThisSession=!0,n=`[aegis] Event-name cap reached — "${e}" dropped locally. Upgrade your plan or remove dynamically-generated event names.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(n)),!1}drainDropReport(){if(0===this.droppedSinceLastReport.size)return null;const e={};let t=0;for(const[i,s]of this.droppedSinceLastReport)e[i]=s,t+=s;const n=this.reportWindowStart;return this.droppedSinceLastReport.clear(),this.reportWindowStart=Date.now(),{events:e,total:t,since:n}}_debugState(){return{hasBloom:null!==this.bloom,remaining:this.remainingNewNames,localNovel:this.localNovelNames.size,graceActive:this.graceActive}}}const A=["system.","user.","loyalty.","review.","cart.","checkout.","product.","pos.","bill.","feedback.","chat.","delivery.","event.","$","_"],$=/(.)([A-Z][a-z]+)/g,D=/([a-z0-9])([A-Z])/g,L=/[\s\-.]+/g,M=/_+/g,P=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/,O=new Set(["at","on","date","time","timestamp","dob","birthday","joined","expired","expires","created","updated","started","ended"]);function F(e){if(!e)return null;return e.replace($,"$1_$2").replace(D,"$1_$2").replace(L,"_").toLowerCase().replace(M,"_").replace(/^_+|_+$/g,"")||null}function N(e){const t=e.toLowerCase();for(const n of A)if(t.startsWith(n))return n;return null}function R(e){for(const t of e.toLowerCase().split(/[_\-.\s]+/))if(O.has(t))return!0;return!1}function U(e){if("number"==typeof e&&Number.isFinite(e))return e<1e11?Math.floor(1e3*e):Math.floor(e);if("string"==typeof e&&e){const t=e.trim();if(P.test(t)){const e=Date.parse(t);if(!Number.isNaN(e))return e}const n=Number(t);if(Number.isFinite(n))return n<1e11?Math.floor(1e3*n):Math.floor(n)}return null}const B=class e{constructor(){this.warnCounts=new Map}process(e,t){const n={},i=[];if(!e||"object"!=typeof e)return{sanitized:n,drops:i};for(const s of Object.keys(e)){const t=N(s);if(null!==t){i.push({originalKey:s,verdict:"reserved_prefix",reason:`key uses reserved namespace ${JSON.stringify(t)}`});continue}const o=F(s);if(null===o){i.push({originalKey:s,verdict:"bad_key_format",reason:"key reduced to empty after normalization"});continue}if(null!==N(o)){i.push({originalKey:s,verdict:"reserved_prefix",reason:`normalized key ${JSON.stringify(o)} still uses a reserved namespace`});continue}let r=e[s];if("string"==typeof r){if(r.length>1e4){i.push({originalKey:s,verdict:"value_too_long",reason:`value length ${r.length} exceeds hard cap 10000`});continue}r.length>512&&(i.push({originalKey:s,verdict:"value_too_long",reason:`value truncated from ${r.length} to 512 chars`}),r=r.slice(0,512))}if(R(o)&&"string"==typeof r){const e=U(r);if(null===e){i.push({originalKey:s,verdict:"bad_date_format",reason:`value ${JSON.stringify(r)} on date-keyed field ${JSON.stringify(o)} didn't parse as ISO-8601 / epoch`});continue}r=e}n[o]=r}for(const s of i)this.maybeWarn(t??null,s);return{sanitized:n,drops:i}}maybeWarn(t,n){const i=t??"__no_workspace__";let s=this.warnCounts.get(i);s||(s=new Map,this.warnCounts.set(i,s));const o=s.get(n.verdict)??0;var r;o>=e.WARN_CAP||(s.set(n.verdict,o+1),r=`[Aegis SDK] trait ${n.verdict}: ${n.reason} (original key: ${JSON.stringify(n.originalKey)}). Backend will reject; fix the SDK call to silence this warning.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(r))}};B.WARN_CAP=3;let W=B;class j{constructor(){this.config=null,this.session=null,this.queue=null,this.transport=null,this.plugins=new h,this.initPromise=null,this.consent=null,this._ecommerce=null,this.rateLimiter=null,this.nameGovernor=new z,this.traitGovernor=new W,this._lastPageUrl=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._lastEventIds=new Map}async init(e,t){return this.initPromise||(this.initPromise=this._init(e,t)),this.initPromise}async _init(e,t){var n;(null==(n=this.config)?void 0:n.initialized)?i.warn("SDK already initialized"):this.shouldRespectDNT(t)?i.info("Do Not Track is enabled, SDK disabled"):!function(){const e=navigator.userAgent.toLowerCase();return["bot","crawl","spider","slurp","mediapartners","googlebot","bingbot","yahoo","duckduckbot","baiduspider","yandex","facebookexternalhit","linkedinbot","twitterbot","slackbot","telegrambot","whatsapp","pingdom","uptimerobot"].some(t=>e.includes(t))}()?(this.config=this.buildConfig(e,t),this.config.debug&&i.enable(),i.info("Initializing Aegis SDK...",this.config),this.storage=new d({cookieDomain:this.config.cookie_domain,secureCookie:this.config.secure_cookie,crossDomain:this.config.cross_domain_tracking}),this.identity=new s(this.storage),this.consent=new p(this.storage,{defaultConsent:this.config.default_consent,waitForConsent:this.config.wait_for_consent}),this.config.integrate_onetrust&&this.consent.integrateOneTrust(),this.config.integrate_cookiebot&&this.consent.integrateCookiebot(),this.config.integrate_google_consent_mode&&this.consent.integrateGoogleConsentMode(),this.session=new o(this.storage,this.config.session_timeout),this.captureAdClickIDsOnInit(),this.transport=new a({writeKey:this.config.write_key,apiHost:this.config.api_host,cellEndpoints:this.config.cell_endpoints,preferredRegion:this.config.preferred_region,autoRegionDetection:this.config.auto_region_detection,requestTimeout:this.config.request_timeout,retryFailedRequests:this.config.retry_failed_requests,maxRetries:this.config.max_retries,retryBackoffMultiplier:this.config.retry_backoff_multiplier},this.storage),this.config.active_cell=this.transport.getActiveCell(),this.queue=new r({batchSize:this.config.batch_size,batchInterval:this.config.batch_interval,enableOfflineMode:this.config.enable_offline_mode,maxOfflineEvents:this.config.max_offline_events},this.transport,this.storage),this.rateLimiter=new k({burstCapacity:this.config.rate_limit_burst,refillPerSecond:this.config.rate_limit_per_second,onDropBatch:(e,t)=>this.emitRateLimitMeta(e,t)}),await this.initializePlugins(),this.config.auto_page_view&&(this.page(),this.startSPATracking()),i.info("Aegis SDK initialized successfully")):i.info("Bot detected, SDK disabled")}startSPATracking(){this._lastPageUrl=window.location.href;const e=()=>{const e=window.location.href;e!==this._lastPageUrl&&(this._lastPageUrl=e,setTimeout(()=>{this.page()},50))};this._popstateHandler=e,window.addEventListener("popstate",this._popstateHandler),this._originalPushState=history.pushState.bind(history),this._originalReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this._originalPushState(...t),e()},history.replaceState=(...t)=>{this._originalReplaceState(...t),e()}}stopSPATracking(){this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null)}buildConfig(t,n){return{...e,...n,write_key:t,initialized:!0}}shouldRespectDNT(e){if(!(!1!==(null==e?void 0:e.respect_dnt)))return!1;const t=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===t||"yes"===t}captureAdClickIDsOnInit(){if(!this.session)return;const e=function(e){try{const t=e?new URL(e).searchParams:new URLSearchParams(window.location.search),n={};return["gclid","fbclid","msclkid","ctwa_clid","ttclid","li_fat_id"].forEach(e=>{const i=t.get(e);i&&(n[e]=i)}),n}catch(t){return console.warn("[Aegis URL Parser] parseAdClickIDs failed:",t),{}}}();(function(e){return Object.keys(e).length>0})(e)&&(this.session.setAdClickIDs(e,window.location.href),i.info("Ad click IDs captured on page load:",e))}async initializePlugins(){if(this.config){for(const e of this.config.plugins)i.debug(`Initializing plugin: ${e}`);await this.plugins.executeHook("init",this.config)}}use(e){var t;this.plugins.register(e),(null==(t=this.config)?void 0:t.initialized)&&e.init&&Promise.resolve(e.init(this.config)).catch(t=>{i.error(`Failed to initialize plugin "${e.name}":`,t)})}track(e,t){if(!this.assertInitialized())return;const i=n(),s={type:"track",event:e,properties:t||{},messageId:i,timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this._lastEventIds.set(e,i),this.captureEvent(s)}identify(e,t){if(!this.assertInitialized())return;const i=this.config.workspace_id||null,{sanitized:s}=this.traitGovernor.process(t,i);this.identity.setUserId(e,s);const o={type:"identify",traits:s,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this.captureEvent(o)}page(e,t){if(!this.assertInitialized())return;const i={type:"page",name:e||document.title,properties:t||{},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this.captureEvent(i)}group(e,t){if(!this.assertInitialized())return;const i=this.config.workspace_id||null,{sanitized:s}=this.traitGovernor.process(t,i),o={type:"group",groupId:e,traits:s,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};this.captureEvent(o)}alias(e){if(!this.assertInitialized())return;const{previousId:t}=this.identity.alias(e),i={type:"alias",previousId:t,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};this.captureEvent(i)}async captureEvent(e){var t;if((null==(t=this.config)?void 0:t.enable_consent_mode)&&this.consent&&("track"===e.type||"page"===e.type)&&!this.consent.hasConsent("analytics"))return void i.debug("Event blocked: analytics consent not granted");if("track"===e.type){const t=e;if(!("string"==typeof t.event&&t.event.startsWith("aegis.client."))&&!this.nameGovernor.shouldSend(t.event))return}if(this.rateLimiter){const t="track"===e.type&&e.event?e.event:e.type;if(!("track"===e.type&&"string"==typeof e.event&&e.event.startsWith("aegis.client."))&&!this.rateLimiter.tryConsume(t))return}const n=e.context,s=e.properties;if((null==n?void 0:n.campaign)&&s&&!s.campaign_id){const e=n.campaign;e.campaign&&(s.campaign_id=e.campaign),e.source&&(s.campaign_source=e.source),e.medium&&(s.campaign_medium=e.medium),e.content&&(s.campaign_content=e.content),e.term&&(s.campaign_term=e.term)}if((null==n?void 0:n.adClickIDs)&&s){const e=n.adClickIDs,t=e.gclid||e.fbclid||e.ctwa_clid||e.msclkid||e.ttclid;t&&!s.campaign_click_id&&(s.campaign_click_id=t)}if(s){const e={fbp:x(),fbc:b(),fbclid:v()};e.fbp&&!s.fbp&&(s.fbp=e.fbp),e.fbc&&!s.fbc&&(s.fbc=e.fbc),e.fbclid&&!s.fbclid&&(s.fbclid=e.fbclid)}i.debug("Capturing event:",e);const o=await this.plugins.executeHookChain("beforeEventCapture",e);o?(this.queue.push(o),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",o)):i.debug("Event cancelled by plugin")}emitRateLimitMeta(e,t){var i,s;if(!(null==(i=this.config)?void 0:i.initialized)||!this.session||!this.identity)return;const o={type:"track",event:"aegis.client.rate_limited",properties:{dropped_count:e,sample_event_name:t,burst_capacity:this.config.rate_limit_burst,refill_per_second:this.config.rate_limit_per_second},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};null==(s=this.queue)||s.push(o)}reset(){this.assertInitialized()&&(this.identity.reset(),i.info("User identity reset"))}ingestGovernanceHint(e){this.nameGovernor.ingestHint(e??null),i.debug("Governance hint ingested",e?{k:e.k,m:e.m,remaining:e.remaining_new_names}:"disabled")}emitGovernanceDropMeta(){var e,t;if(!(null==(e=this.config)?void 0:e.initialized)||!this.session||!this.identity)return;const i=this.nameGovernor.drainDropReport();if(!i)return;const s={type:"track",event:"aegis.client.name_governor_dropped",properties:{dropped_count:i.total,distinct_names:Object.keys(i.events).length,sample_names:Object.entries(i.events).sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({name:e,count:t})),window_start:i.since,window_end:Date.now()},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};null==(t=this.queue)||t.push(s)}async flush(){this.assertInitialized()&&(this.emitGovernanceDropMeta(),await this.queue.flush())}getAnonymousId(){return this.identity?this.identity.getAnonymousId():null}getUserId(){return this.identity?this.identity.getUserId():null}getSessionId(){return this.session?this.session.getSessionId():null}lastEventId(e){return this._lastEventIds.get(e)??null}debug(e=!0){e?i.enable():i.disable(),this.config&&(this.config.debug=e)}setCell(e){if(!this.config)return void i.warn("SDK not initialized");const t=this.config.cell_endpoints.find(t=>t.region===e.region);t?Object.assign(t,e):this.config.cell_endpoints.push(e),i.info("Cell endpoint configured:",e)}getCellInfo(){return this.transport?{activeCell:this.transport.getActiveCell(),latencies:this.transport.getRegionLatencies()}:null}setConsent(e){this.consent?(this.consent.setConsent(e),i.info("Consent preferences updated")):i.warn("Consent manager not initialized")}grantConsent(e){this.consent?e?this.consent.setConsent({[e]:!0}):this.consent.grantAll():i.warn("Consent manager not initialized")}denyConsent(e){this.consent?e?this.consent.setConsent({[e]:!1}):this.consent.denyAll():i.warn("Consent manager not initialized")}hasConsent(e){return!this.consent||this.consent.hasConsent(e)}getConsentPreferences(){return this.consent?this.consent.getPreferences():null}onConsentChange(e){return this.consent?this.consent.onChange(e):(i.warn("Consent manager not initialized"),()=>{})}assertInitialized(){var e;return!!(null==(e=this.config)?void 0:e.initialized)||(i.warn("SDK not initialized. Call aegis.init() first."),!1)}get ecommerce(){return this._ecommerce||(this._ecommerce=new C(this)),this._ecommerce}destroy(){this.stopSPATracking(),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.rateLimiter&&(this.rateLimiter.destroy(),this.rateLimiter=null),this.plugins.clear(),i.info("SDK destroyed")}}function V(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c=(Array.isArray(a.cards)?a.cards:[]).slice(0,10);if(0===c.length)return void o("carousel_cards rendered with zero cards — skipping","warn");const d=Number(a.autoplay_ms)||0,l=!1!==a.loop;r();const h=s(t.background_color||"#ffffff"),p=s(t.text_color||"#0f172a"),u=document.createElement("div");u.className="aegis-in-app-carousel-overlay",u.setAttribute("data-campaign-id",t.id),u.style.cssText='\n position: fixed; left: 0; right: 0; bottom: 0;\n z-index: 99999; padding: 12px 12px 20px;\n background: rgba(0,0,0,0.12); backdrop-filter: blur(8px);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n ';const g=document.createElement("div");g.style.cssText=`\n background: ${h}; color: ${p}; border-radius: 16px;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08); padding: 16px;\n max-width: 520px; margin: 0 auto; position: relative;\n `;const m=document.createElement("div");m.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 12px;";const f=document.createElement("div"),y=document.createElement("div");y.textContent=t.title,y.style.cssText="font-weight: 700; font-size: 15px; margin-bottom: 2px;";const x=document.createElement("div");x.textContent=t.body,x.style.cssText="font-size: 13px; opacity: 0.75;",f.appendChild(y),f.appendChild(x),m.appendChild(f);const b=document.createElement("button");b.textContent="✕",b.setAttribute("aria-label","Close"),b.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; opacity: 0.6; padding: 2px 6px;\n ",b.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),m.appendChild(b),g.appendChild(m);const v=document.createElement("div");v.style.cssText="\n display: flex; gap: 10px; overflow-x: auto; scroll-snap-type: x mandatory;\n scrollbar-width: none; -ms-overflow-style: none; padding-bottom: 4px;\n ",v.style.msOverflowStyle="none",v.addEventListener("wheel",e=>{Math.abs(e.deltaX)<Math.abs(e.deltaY)||(v.scrollLeft+=e.deltaX)}),c.forEach((e,s)=>{const o=document.createElement("div");if(o.setAttribute("data-card-index",String(s)),o.style.cssText=`\n flex: 0 0 auto; width: 140px; scroll-snap-align: start;\n background: ${p}0a; border-radius: 12px; padding: 10px;\n display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",o.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",o.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",o.appendChild(t)}if(e.cta_text&&e.cta_url){const s=document.createElement("button");s.textContent=e.cta_text,s.style.cssText=`\n margin-top: auto; background: ${p}; color: ${h};\n border: none; padding: 6px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const r=s=>{s.stopPropagation(),n(t.id,"clicked");const o=i(e.cta_url);o&&(window.location.href=o)};s.addEventListener("click",r),o.appendChild(s),o.addEventListener("click",r)}v.appendChild(o)}),g.appendChild(v);const w=document.createElement("div");w.style.cssText="display: flex; justify-content: center; gap: 6px; margin-top: 10px;";const _=[];c.forEach(()=>{const e=document.createElement("span");e.style.cssText=`\n width: 6px; height: 6px; border-radius: 999px; background: ${p};\n opacity: 0.25; transition: opacity 0.2s;\n `,_.push(e),w.appendChild(e)}),g.appendChild(w);const C=e=>{_.forEach((t,n)=>t.style.opacity=n===e?"0.9":"0.25")};C(0);let k=0;const S=v.querySelectorAll("[data-card-index]");let E=null;d>0&&c.length>1&&(E=setInterval(()=>{const e=k+1;e>=c.length&&!l?E&&clearInterval(E):(e=>{k=(e%c.length+c.length)%c.length;const t=S[k];t&&(t.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"}),C(k))})(e)},d)),u.addEventListener("remove",()=>{E&&clearInterval(E)}),v.addEventListener("scroll",()=>{const e=Math.round(v.scrollLeft/150);e!==k&&e>=0&&e<c.length&&(k=e,C(k))}),u.appendChild(g),document.body.appendChild(u)}const H="aegis_sticky_dismissed:";function q(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:s,addAnimationStyles:o}=e,r=t.interactive_config||{},a=r.progress_goal_type||"cart_total",c=Number(r.progress_threshold);if(!(c>0))return void s("progress_bar requires a positive progress_threshold — skipping","warn");const d=r.progress_reward_text||t.body||"Unlocked!",l="sse"===r.progress_source?"sse":"client";o();const h=i(t.background_color||"#f8fafc"),p=i(t.text_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-progress-bar",u.setAttribute("data-campaign-id",t.id),u.style.cssText=`\n position: fixed; left: 12px; right: 12px; bottom: 12px;\n max-width: 540px; margin: 0 auto;\n background: ${h}; color: #0f172a; border-radius: 12px;\n padding: 10px 14px; z-index: 999997;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `;const g=document.createElement("div");g.style.cssText="display: flex; justify-content: space-between; font-size: 13px; font-weight: 600; margin-bottom: 6px;";const m=document.createElement("span");m.textContent=t.title,g.appendChild(m);const f=document.createElement("span");f.style.cssText="opacity: 0.7; font-weight: 500;",g.appendChild(f),u.appendChild(g);const y=document.createElement("div");y.style.cssText=`\n height: 8px; border-radius: 999px; background: ${p}22;\n overflow: hidden;\n `;const x=document.createElement("div");x.style.cssText=`\n height: 100%; border-radius: 999px; background: ${p};\n width: 0%; transition: width 0.4s cubic-bezier(.4,0,.2,1);\n `,y.appendChild(x),u.appendChild(y);const b=document.createElement("div");b.style.cssText="font-size: 11.5px; opacity: 0.65; margin-top: 6px;",u.appendChild(b);let v=!1;const w=()=>{const e=(()=>{var e,n;if("sse"===l){const e=window.__aegisProgressSSE;return e&&"number"==typeof e[t.id]?e[t.id]:0}try{if("cart_total"===a||"items_in_cart"===a){const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=parseFloat(String(t.Shopify.checkout.total_price||0));return"cart_total"===a?e:0}if(t.aegis_cart)return"items_in_cart"===a?Array.isArray(t.aegis_cart.cart_items)?t.aegis_cart.cart_items.length:0:Number(t.aegis_cart.cart_total||0);try{const e=null==(n=window.localStorage)?void 0:n.getItem("mage-cache-storage");if(e){const t=JSON.parse(e).cart;if(t)return"cart_total"===a?Number(t.subtotalAmount||0):Array.isArray(t.items)?t.items.length:0}}catch{}}return 0}catch{return 0}})(),i=Math.max(0,Math.min(100,e/c*100));if(x.style.width=`${i}%`,f.textContent=`${e.toFixed(0)} / ${c.toFixed(0)}`,i>=100)b.textContent=d,v||(v=!0,n(t.id,"clicked"));else{const t=Math.max(0,c-e);b.textContent=`Add ${t.toFixed(0)} more to unlock: ${d}`}};w();const _=setInterval(w,1e3),C=()=>clearInterval(_);window.addEventListener("beforeunload",C,{once:!0}),u.addEventListener("remove",C),document.body.appendChild(u)}const K="aegis_coachmark_progress:";function X(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(K+e,String(t))}catch{}}function Q(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:s,addAnimationStyles:o}=e,r=t.interactive_config||{},a=r.resume_key;if(!a)return void s("coachmark_tour requires interactive_config.resume_key — skipping","warn");const c=Array.isArray(r.steps)?r.steps:[];if(0===c.length)return void s("coachmark_tour has no steps — skipping","warn");const d=!1!==r.allow_skip,l=!1!==r.show_progress_dots;o();const h=i(t.background_color||"#0f172a"),p=i(t.text_color||"#ffffff");let u=function(e){try{if("undefined"==typeof localStorage)return 0;const t=localStorage.getItem(K+e),n=t?parseInt(t,10):0;return Number.isFinite(n)&&n>=0?n:0}catch{return 0}}(a);if(u>=c.length)return void s(`coachmark_tour ${a} already complete — not re-showing`);n(t.id,"impression");let g=null,m=null,f=null;const y=()=>{null==g||g.remove(),null==m||m.remove(),null==f||f.remove(),g=null,m=null,f=null},x=e=>{y(),e.skipped?n(t.id,"dismissed"):n(t.id,"clicked"),X(a,c.length)},b=e=>{y();const n=c[e];if(!n)return void x({skipped:!1});X(a,e);const i=n.anchor_web;let o=null;if(i)try{o=document.querySelector(i)}catch{o=null}if(!o)return s(`coachmark step ${e} — selector '${i}' not found; advancing`,"warn"),void b(e+1);const r=o.getBoundingClientRect();f=document.createElement("div"),f.style.cssText=`\n position: fixed;\n top: ${r.top-6}px; left: ${r.left-6}px;\n width: ${r.width+12}px; height: ${r.height+12}px;\n border-radius: 10px; z-index: 999998;\n box-shadow: 0 0 0 2px ${p}, 0 0 0 9999px rgba(0,0,0,0.4);\n pointer-events: none;\n transition: all 0.2s ease;\n `,document.body.appendChild(f);const u=n.placement||"bottom";m=document.createElement("div"),m.setAttribute("data-campaign-id",t.id),m.style.cssText=`\n position: fixed; z-index: 999999;\n background: ${h}; color: ${p};\n padding: 12px 14px; border-radius: 12px;\n max-width: 260px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.25);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.2s ease;\n `;const g=document.createElement("div");g.textContent=n.title,g.style.cssText="font-weight: 700; font-size: 13px; margin-bottom: 4px;",m.appendChild(g);const v=document.createElement("div");v.textContent=n.body,v.style.cssText="font-size: 12.5px; line-height: 1.4; opacity: 0.9;",m.appendChild(v);const w=document.createElement("div");if(w.style.cssText="display: flex; align-items: center; justify-content: space-between; margin-top: 10px; gap: 8px;",l){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px;",c.forEach((n,i)=>{const s=document.createElement("span");s.style.cssText=`\n width: 5px; height: 5px; border-radius: 999px;\n background: ${p}; opacity: ${i===e?"0.95":"0.3"};\n `,t.appendChild(s)}),w.appendChild(t)}else w.appendChild(document.createElement("span"));const _=document.createElement("div");if(_.style.cssText="display: flex; gap: 6px;",d&&e<c.length-1){const e=document.createElement("button");e.textContent="Skip",e.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",e.addEventListener("click",()=>x({skipped:!0})),_.appendChild(e)}const C=document.createElement("button"),k=e===c.length-1;C.textContent=n.cta_text||(k?"Done":"Next"),C.style.cssText=`\n background: ${p}; color: ${h};\n border: none; padding: 6px 12px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer;\n `,C.addEventListener("click",()=>{k?x({skipped:!1}):b(e+1)}),_.appendChild(C),w.appendChild(_),m.appendChild(w),document.body.appendChild(m);const S=m.getBoundingClientRect();let E=r.bottom+12,I=r.left;"top"===u?E=r.top-S.height-12:"left"===u?(E=r.top,I=r.left-S.width-12):"right"===u&&(E=r.top,I=r.right+12),E=Math.max(8,Math.min(window.innerHeight-S.height-8,E)),I=Math.max(8,Math.min(window.innerWidth-S.width-8,I)),m.style.top=`${E}px`,m.style.left=`${I}px`};b(u),window.aegisResetTour=e=>function(e){try{"undefined"!=typeof localStorage&&localStorage.removeItem(K+e)}catch{}}(e)}const J=class e{constructor(e){this.campaigns=[],this.displayedCampaigns=new Set,this.suppressedUntil=new Map,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.hooks=new Map,this.ready=new Promise(e=>{this.readyResolve=e}),this.filledSlots=new WeakSet,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new d).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.propertyId=e.propertyId,this.debugMode=e.debugMode||!1,this.enableSSE=!0===e.enableSSE,this.onInteractiveCampaign=e.onInteractiveCampaign}emit(e,t){const n=this.hooks.get(e);if(!n||0===n.size)return!0;let i=!0;for(const o of n)try{!1===o(t)&&(i=!1)}catch(s){this.emitError(s,{event:e})}return i}emitError(e,t){const n=this.hooks.get("error");if(n&&0!==n.size)for(const i of n)try{i({message:e instanceof Error?e.message:String(e),error:e,context:t??{}})}catch{}else this.log(`Aegis SDK error: ${e instanceof Error?e.message:String(e)}`,"error")}register(e,t){return this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add(t),()=>{var n;null==(n=this.hooks.get(e))||n.delete(t)}}on(e,t){return this.register(e,t)}onCampaignsLoaded(e){return this.register("campaigns-loaded",e)}onCampaignWillShow(e){return this.register("campaign-will-show",e)}onCampaignShown(e){return this.register("campaign-shown",e)}onCampaignClick(e){return this.register("campaign-click",e)}onCampaignDismiss(e){return this.register("campaign-dismiss",e)}onError(e){return this.register("error",e)}async initialize(){this.isInitialized?this.log("AegisInApp already initialized"):("undefined"!=typeof localStorage&&localStorage.setItem("aegis_returning_user","1"),await this.refreshCampaigns(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisInApp initialized successfully"))}updateUserId(e){this.userId=e,this.refreshCampaigns()}updateContactId(e){this.contactId=e,this.disconnectSSE(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.refreshCampaigns()}notifyConversion(t){if(!t)return void this.log("notifyConversion called with empty goalName; ignored","warn");const n=Date.now();if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(`${e.CONVERSION_STORAGE_PREFIX}${t}`,JSON.stringify({ts:n}))}catch{}this.applySuppressionFromCampaigns(n),this.log(`notifyConversion: ${t} — suppressing ${this.suppressedUntil.size} armed campaigns`)}applySuppressionFromCampaigns(e){var t,n;for(const i of this.campaigns){const s=null==(t=i.frequency)?void 0:t.suppress_after_conversion_seconds;if("number"!=typeof s||s<=0)continue;const o=(null==(n=i.frequency)?void 0:n.scope)??"session";"session"!==o&&this.log(`applySuppressionFromCampaigns: scope=${o} not implemented; degrading to session for campaign ${i.id}`,"warn");const r=e+1e3*s,a=this.suppressedUntil.get(i.id);(void 0===a||a<r)&&this.suppressedUntil.set(i.id,r)}}rehydrateSuppressionFromStorage(){if("undefined"==typeof sessionStorage)return;let t=null;try{for(let n=0;n<sessionStorage.length;n++){const i=sessionStorage.key(n);if(!i||!i.startsWith(e.CONVERSION_STORAGE_PREFIX))continue;const s=sessionStorage.getItem(i);if(!s)continue;const o=JSON.parse(s);"number"==typeof o.ts&&(t=null===t?o.ts:Math.min(t,o.ts))}}catch{return}null!==t&&this.applySuppressionFromCampaigns(t)}isSuppressed(e){const t=this.suppressedUntil.get(e);return void 0!==t&&(!(Date.now()>=t)||(this.suppressedUntil.delete(e),!1))}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID","warn");const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("in_app_campaign_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received in-app campaign update: ${t.campaign_id}`),this.refreshCampaigns()}catch(t){this.log(`Error parsing SSE event: ${t}`,"error")}}),this.eventSource.addEventListener("heartbeat",e=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",e=>{var t;this.log("SSE connection error","error"),(null==(t=this.eventSource)?void 0:t.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up","warn");this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}async refreshCampaigns(){try{const e=new URLSearchParams({device_type:this.detectDeviceType(),page_url:"undefined"!=typeof window?window.location.pathname:"/"});e.set("is_new_user",this.isNewUser()?"true":"false");const t=`${this.apiHost}/v1/in-app/active?${e.toString()}`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId),this.propertyId&&(n["X-Property-Id"]=this.propertyId);const i=this.getABAssignments();Object.keys(i).length>0&&(n["X-AB-Assignments"]=btoa(JSON.stringify(i)));const s=await fetch(t,{method:"GET",headers:n,credentials:"include"});if(!s.ok)throw new Error(`Failed to fetch campaigns: ${s.status}`);const o=await s.json();this.campaigns=Array.isArray(o)?o:[],this.processABAssignments(this.campaigns),this.rehydrateSuppressionFromStorage(),this.log(`Fetched ${this.campaigns.length} campaigns`),this.emit("campaigns-loaded",this.campaigns),this.readyResolve(),this.tryDisplayNextCampaign(),this.renderIntoSlots(),this.renderTokenAnchors()}catch(e){this.emitError(e,{stage:"refresh-campaigns"}),this.log(`Error refreshing campaigns: ${e}`,"error")}}detectDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/Mobi|Android/i.test(e)?"mobile":/iPad|Tablet/i.test(e)?"tablet":"desktop"}isNewUser(){return"undefined"==typeof localStorage||!localStorage.getItem("aegis_returning_user")}getABAssignments(){if("undefined"==typeof localStorage)return{};try{return JSON.parse(localStorage.getItem("aegis_ab_assignments")||"{}")}catch{return{}}}processABAssignments(e){if("undefined"==typeof localStorage)return;const t=this.getABAssignments();for(const n of e)n.assigned_variant_id&&(t[n.id]=n.assigned_variant_id);localStorage.setItem("aegis_ab_assignments",JSON.stringify(t))}getVariantId(e){return this.getABAssignments()[e]??void 0}tryDisplayNextCampaign(){const e=this.campaigns.find(e=>!this.displayedCampaigns.has(e.id)&&!e.client_trigger&&!this.isSuppressed(e.id));e&&this.displayCampaign(e)}renderIntoSlots(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-slot]");if(0===e.length)return;const t=new Map;for(const n of this.campaigns){const e=n.delivery_modes,i=n.widget_category;e&&e.includes("embedded_card")&&(i&&(t.has(i)||t.set(i,n)))}0!==t.size&&e.forEach(e=>{if(this.filledSlots.has(e))return;const n=e.getAttribute("data-aegis-slot");if(!n)return;const i=t.get(n);i&&(this.renderCampaignIntoSlot(i,e),this.filledSlots.add(e))})}renderTokenAnchors(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-token-data]");0!==e.length&&e.forEach(e=>{if(this.filledSlots.has(e))return;const t=e.getAttribute("data-aegis-token-data");if(!t)return;let n=null;try{n=JSON.parse(t)}catch(i){return this.log(`data-aegis-token-data: invalid JSON, skipping anchor (${i})`,"warn"),void this.filledSlots.add(e)}if(!n||!n.campaign||!n.campaign.id)return this.log("data-aegis-token-data: missing `campaign` in payload, skipping","warn"),void this.filledSlots.add(e);this.renderCampaignIntoSlot(n.campaign,e,{submitUrl:n.submit_url}),this.filledSlots.add(e)})}renderCampaignIntoSlot(e,t,n){if(!this.emit("campaign-will-show",e))return void this.log(`slot campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id),this.addAnimationStyles();const i=e.interactive_config||{},s=this.sanitizeColor(e.background_color||"#4169e1"),o=this.sanitizeColor(e.text_color||"#ffffff"),r=null==n?void 0:n.submitUrl;let a=!1;switch(e.sub_type){case"star_rating":a=this.renderStarRatingSlot(e,i,s,o,t,r);break;case"nps_survey":a=this.renderNPSSurveySlot(e,i,s,o,t,r);break;default:return this.log(`slot mode not yet supported for sub_type: ${e.sub_type??e.type}`,"warn"),void this.displayedCampaigns.delete(e.id)}a&&(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))}renderStarRatingSlot(e,t,n,i,s,o){const r=this._wrapInSlotCard("aegis-in-app-rating-card",e.id,n,i);return r.appendChild(this._buildStarRatingBody(e,t,i,"slot",o)),s.appendChild(r),!0}renderNPSSurveySlot(e,t,n,i,s,o){const r=this._wrapInSlotCard("aegis-in-app-nps-card",e.id,n,i);return r.appendChild(this._buildNPSSurveyBody(e,t,i,"slot",o)),s.appendChild(r),!0}_submitTokenResponse(e,t){e&&fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({response:t}),keepalive:!0}).catch(e=>{this.log(`token submit failed: ${e}`,"warn")})}_wrapInSlotCard(e,t,n,i){const s=document.createElement("div");return s.className=e,s.setAttribute("data-campaign-id",t),s.style.cssText=`\n width: 100%; border-radius: 12px; overflow: hidden;\n background: ${n}; color: ${i};\n box-shadow: 0 4px 12px rgba(0,0,0,0.06);\n `,s}_buildStarRatingBody(e,t,n,i,s){const o="overlay"===i,r=o?"24px":"20px",a=o?"18px":"16px",c=o?"700":"600",d=o?"16px":"12px",l=o?"32px":"28px",h=o?"16px":"0",p=o?"1.2":"1.15",u=document.createElement("div");u.style.cssText=`padding: ${r}; text-align: center;`;const g=document.createElement("div");g.style.cssText=`font-size: ${a}; font-weight: ${c}; margin-bottom: ${d};`,g.textContent=e.title||"Rate your experience",u.appendChild(g);const m=document.createElement("div");m.style.cssText="display: flex; gap: 8px; justify-content: center;"+("0"!==h?` margin-bottom: ${h};`:"");const f=t.rating_scale||5;for(let y=1;y<=f;y++){const t=document.createElement("span");t.style.cssText=`font-size: ${l}; cursor: pointer; transition: transform 0.1s; user-select: none;`+(n?` color: ${n};`:""),t.textContent="☆";const i=y;t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"star_rating",value:i})}),t.addEventListener("mouseenter",()=>{t.style.transform=`scale(${p})`}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),m.appendChild(t)}return u.appendChild(m),u}_buildNPSSurveyBody(e,t,n,i,s){const o="overlay"===i,r=o?"24px":"20px",a=document.createElement("div");a.style.cssText=`padding: ${r};`+(o?" text-align: center;":"");const c=document.createElement("div");if(c.style.cssText=`font-size: 16px; font-weight: ${o?"700":"600"}; margin-bottom: ${o?"16px":"12px"}; text-align: center;`,c.textContent=t.nps_question||e.title||"How likely are you to recommend us?",a.appendChild(c),o){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;";for(let a=0;a<=10;a++){const i=document.createElement("span");i.style.cssText=`\n width: 28px; height: 28px; border-radius: 6px; display: flex;\n align-items: center; justify-content: center; font-size: 11px;\n font-weight: 600; cursor: pointer; background: ${n}33; color: ${n};\n transition: transform 0.1s;\n `,i.textContent=String(a);const o=a;i.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"nps_survey",value:o})}),t.appendChild(i)}a.appendChild(t);const i=document.createElement("div");i.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const o=document.createElement("span");o.textContent="Not likely";const r=document.createElement("span");return r.textContent="Very likely",i.appendChild(o),i.appendChild(r),a.appendChild(i),a}const d=document.createElement("div");d.style.cssText="display: grid; grid-template-columns: repeat(11, 1fr); gap: 4px;";for(let l=0;l<=10;l++){const t=document.createElement("button");t.style.cssText=`\n padding: 8px 0; border-radius: 6px; border: 1px solid ${n}33;\n background: transparent; color: ${n}; font-size: 13px; font-weight: 600;\n cursor: pointer; transition: background 0.15s;\n `,t.textContent=String(l);const i=l;t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"nps_survey",value:i})}),d.appendChild(t)}return a.appendChild(d),a}onClientEvent(e,t={}){for(const n of this.campaigns)this.displayedCampaigns.has(n.id)||n.client_trigger&&(this.isSuppressed(n.id)||this.matchesClientTrigger(n.client_trigger,e,t)&&this.displayCampaign(n))}matchesClientTrigger(e,t,n){var i;const s=e.config||{};switch(e.type){case"custom_event":return"string"==typeof s.event&&s.event===t;case"product_match":{if("product_viewed"!==t&&"product_view"!==t)return!1;const e=s.product_id,o=Array.isArray(e)?e:"string"==typeof e?[e]:[];if(0===o.length)return!1;const r=String(n.product_id??n.productId??(null==(i=n.product)?void 0:i.id)??"");return o.includes(r)}default:return!1}}displayCampaign(e){if(!this.emit("campaign-will-show",e))return void this.log(`campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id);const t=new Set(["spin_wheel","scratch_card","nps_survey","quiz","countdown_offer","star_rating","quick_poll"]);if(e.sub_type&&t.has(e.sub_type))return this.renderInteractive(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);switch(e.type){case"modal":this.renderModal(e);break;case"banner":this.renderBanner(e);break;case"full_screen":this.renderFullScreen(e);break;case"half_interstitial":this.renderHalfInterstitial(e);break;case"alert":this.renderAlert(e);break;case"pip":this.renderPIP(e);break;case"tooltip":this.renderTooltip(e);break;case"carousel_cards":return V(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"sticky_bar":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c="top"===a.sticky_position?"top":"bottom",d=!1!==a.sticky_dismissible,l=Number(a.sticky_auto_hide_ms)||0;try{if("undefined"!=typeof localStorage&&localStorage.getItem(H+t.id))return void o(`sticky_bar ${t.id} suppressed — user dismissed earlier`)}catch{}r();const h=s(a.sticky_bg_color||t.background_color||"#4169e1"),p=s(t.text_color||"#ffffff"),u=document.createElement("div");u.className="aegis-in-app-sticky-bar",u.setAttribute("data-campaign-id",t.id);const g="top"===c?"top: 0; left: 0; right: 0; animation: aegisSlideDown 0.3s ease-out;":"bottom: 0; left: 0; right: 0; animation: aegisSlideInFromBottom 0.3s ease-out;";u.style.cssText=`\n position: fixed; ${g}\n background: ${h}; color: ${p};\n padding: 10px 14px; z-index: 999998;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex; align-items: center; gap: 12px; justify-content: center;\n box-shadow: 0 ${"top"===c?"2px":"-2px"} 8px rgba(0,0,0,0.08);\n `;const m=document.createElement("div");m.style.cssText="flex: 0 1 auto; font-size: 13px; font-weight: 500; text-align: center;";const f=document.createElement("strong");if(f.textContent=t.title,f.style.cssText="margin-right: 6px; font-weight: 700;",m.appendChild(f),m.appendChild(document.createTextNode(t.body)),u.appendChild(m),t.action_url&&t.button_text){const e=document.createElement("button");e.textContent=t.button_text,e.style.cssText=`\n background: ${p}; color: ${h};\n border: none; padding: 6px 14px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer; white-space: nowrap;\n `,e.addEventListener("click",()=>{n(t.id,"clicked");const e=i(t.action_url);e&&(window.location.href=e)}),u.appendChild(e)}let y=null;const x=e=>{if(y&&clearTimeout(y),e)try{"undefined"!=typeof localStorage&&localStorage.setItem(H+t.id,"1")}catch{}u.remove()};if(d){const e=document.createElement("button");e.textContent="✕",e.setAttribute("aria-label","Dismiss"),e.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; padding: 0 4px; opacity: 0.75;\n ",e.addEventListener("click",()=>{n(t.id,"dismissed"),x(!0)}),u.appendChild(e)}l>0&&(y=setTimeout(()=>x(!1),l)),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"progress_bar":return q(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"coachmark_tour":return Q(this.buildRenderContext(e)),void this.emit("campaign-shown",e);case"product_recommendation":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c=(Array.isArray(a.cards)?a.cards:[]).slice(0,24);if(0===c.length)return void o("product_recommendation rendered with zero products — skipping","warn");const d=a.rec_layout||"grid",l=a.rec_cta_text||"Shop now";r();const h=s(t.background_color||"#ffffff"),p=s(t.text_color||"#0f172a"),u=s("#4169e1"),g=document.createElement("div");g.className="aegis-in-app-product-rec",g.setAttribute("data-campaign-id",t.id),g.style.cssText="\n position: fixed; inset: 0;\n background: rgba(15,23,42,0.55); backdrop-filter: blur(4px);\n display: flex; align-items: flex-end; justify-content: center;\n z-index: 99999; animation: aegisFadeIn 0.25s ease;\n ";const m=document.createElement("div");m.style.cssText=`\n background: ${h}; color: ${p};\n max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;\n border-radius: 20px 20px 0 0;\n padding: 18px 16px 22px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n box-shadow: 0 -12px 30px rgba(0,0,0,0.12);\n `;const f=document.createElement("div");f.style.cssText=`\n width: 36px; height: 4px; border-radius: 999px; background: ${p}1f;\n margin: 0 auto 12px;\n `,m.appendChild(f);const y=document.createElement("div");y.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;";const x=document.createElement("div"),b=document.createElement("div");b.textContent=t.title,b.style.cssText="font-weight: 700; font-size: 16px; margin-bottom: 2px;";const v=document.createElement("div");v.textContent=t.body,v.style.cssText="font-size: 13px; opacity: 0.7; line-height: 1.4;",x.appendChild(b),x.appendChild(v),y.appendChild(x);const w=document.createElement("button");w.textContent="✕",w.setAttribute("aria-label","Close"),w.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 18px; cursor: pointer; padding: 4px 8px; opacity: 0.7;\n ",w.addEventListener("click",()=>{n(t.id,"dismissed"),g.remove()}),y.appendChild(w),m.appendChild(y);const _=document.createElement("div");_.style.cssText="row"===d||"carousel"===d?"\n display: flex; gap: 10px; overflow-x: auto;\n scroll-snap-type: x mandatory; padding: 14px 0 4px;\n ":"\n display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;\n padding-top: 14px;\n ",c.forEach(e=>{const s=document.createElement("div"),o="row"===d||"carousel"===d;if(s.style.cssText=`\n background: ${p}08; border-radius: 12px;\n padding: 10px; display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n ${o?"flex: 0 0 150px; scroll-snap-align: start;":""}\n transition: transform 0.15s ease;\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; aspect-ratio: 1 / 1; border-radius: 8px; object-fit: cover;",s.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",s.appendChild(t)}const r=e.metadata&&"object"==typeof e.metadata?e.metadata.price:void 0;if(void 0!==r){const e=document.createElement("div");e.textContent=String(r),e.style.cssText=`color: ${u}; font-weight: 700; font-size: 13px;`,s.appendChild(e)}else if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",s.appendChild(t)}const a=document.createElement("button");a.textContent=e.cta_text||l,a.style.cssText=`\n margin-top: auto;\n background: ${u}; color: #fff;\n border: none; padding: 7px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const c=s=>{if(s.stopPropagation(),n(t.id,"clicked"),e.cta_url){const t=i(e.cta_url);t&&(window.location.href=t)}};a.addEventListener("click",c),s.appendChild(a),e.cta_url&&s.addEventListener("click",c),_.appendChild(s)}),m.appendChild(_),g.appendChild(m),g.addEventListener("click",e=>{e.target===g&&(n(t.id,"dismissed"),g.remove())}),document.body.appendChild(g)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e)}this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)}buildRenderContext(e){return{campaign:e,trackEvent:(e,t)=>{this.trackEvent(e,t)},sanitizeUrl:e=>this.sanitizeUrl(e),sanitizeColor:e=>this.sanitizeColor(e),log:(e,t)=>this.log(e,t),addAnimationStyles:()=>this.addAnimationStyles()}}renderInteractive(e){const t=e.interactive_config||{},n=this.sanitizeColor(e.background_color||"#4169e1"),i=this.sanitizeColor(e.text_color||"#ffffff");switch(e.sub_type){case"nps_survey":this.renderNPSSurvey(e,t,n,i);break;case"countdown_offer":this.renderCountdownOffer(e,t,n,i);break;case"star_rating":this.renderStarRating(e,t,n,i);break;case"quick_poll":this.renderQuickPoll(e,t,n,i);break;case"quiz":this.renderQuiz(e,t,n,i);break;case"spin_wheel":case"scratch_card":this.onInteractiveCampaign?this.onInteractiveCampaign(e):this.log(`${e.sub_type} campaign received but no onInteractiveCampaign handler wired — install via AegisMessageRuntime`,"warn");break;default:this.log(`Unknown interactive sub_type: ${e.sub_type}`,"warn"),this.renderModal(e)}}renderNPSSurvey(e,t,n,i){const s=this.createOverlay("aegis-in-app-nps-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 360px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=this._buildNPSSurveyBody(e,t,i,"overlay");this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderCountdownOffer(e,t,n,i){const s=this.createOverlay("aegis-in-app-countdown-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 20px; font-weight: 700; margin-bottom: 8px;",a.textContent=e.title||"Flash Sale",r.appendChild(a);const c=document.createElement("div");c.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 12px;",c.textContent=t.countdown_label||"Sale ends in:",r.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 8px; justify-content: center; margin-bottom: 16px;";const l=`padding: 8px 12px; border-radius: 8px; font-size: 24px; font-weight: 700; font-family: monospace; background: ${i}22;`;for(const p of["00",":","00",":","00"]){const e=document.createElement("span");e.style.cssText=":"===p?"font-size: 24px; font-weight: 700; align-self: center;":l,e.textContent=p,d.appendChild(e)}r.appendChild(d);const h=t.countdown_target;if(h){const e=new Date(h).getTime(),t=()=>{const n=Math.max(0,e-Date.now()),i=String(Math.floor(n/36e5)).padStart(2,"0"),s=String(Math.floor(n%36e5/6e4)).padStart(2,"0"),o=String(Math.floor(n%6e4/1e3)).padStart(2,"0"),r=d.querySelectorAll("span");r.length>=5&&(r[0].textContent=i,r[2].textContent=s,r[4].textContent=o),n>0&&requestAnimationFrame(t)};t()}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 14px; opacity: 0.85; margin-bottom: 16px;",t.textContent=e.body,r.appendChild(t)}if(e.button_text){const t=this.createCTAButton(e,n,i);r.appendChild(t)}this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderStarRating(e,t,n,i){const s=this.createOverlay("aegis-in-app-rating-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=this._buildStarRatingBody(e,t,i,"overlay");this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderQuickPoll(e,t,n,i){const s=this.createOverlay("aegis-in-app-poll-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",a.textContent=e.title||"Quick question",r.appendChild(a);const c=t.poll_options||[],d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;";for(const l of c){const t=document.createElement("button");t.style.cssText=`\n padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33;\n background: transparent; color: ${i}; font-size: 14px; cursor: pointer;\n text-align: left; transition: background 0.15s;\n `,t.textContent=l,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),d.appendChild(t)}r.appendChild(d),this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderQuiz(e,t,n,i){const s=this.createOverlay("aegis-in-app-quiz-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 360px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",a.textContent=e.title||"Quiz",r.appendChild(a);const c=t.questions||[];let d=0;const l=()=>{for(;r.childNodes.length>1;)r.removeChild(r.lastChild);if(d>=c.length){const n=document.createElement("div");return n.style.cssText="font-size: 16px; margin: 16px 0;",n.textContent=t.thank_you_message||"Thanks for completing the quiz!",r.appendChild(n),this.trackEvent(e.id,"clicked"),void this.addCloseButton(r,s,e.id)}const n=c[d],o=document.createElement("div");o.style.cssText="font-size: 12px; opacity: 0.6; margin-bottom: 12px;",o.textContent=`Question ${d+1} of ${c.length}`,r.appendChild(o);const a=document.createElement("div");a.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 16px;",a.textContent=n.question,r.appendChild(a);const h=document.createElement("div");h.style.cssText="display: flex; flex-direction: column; gap: 8px;";for(const e of n.options){const t=document.createElement("button");t.style.cssText=`\n padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33;\n background: transparent; color: ${i}; font-size: 14px; cursor: pointer;\n text-align: left; transition: background 0.15s;\n `,t.textContent=e,t.addEventListener("click",()=>{d++,l()}),h.appendChild(t)}r.appendChild(h),this.addCloseButton(r,s,e.id)};l(),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}createOverlay(e){const t=document.createElement("div");return t.className=e,t.style.cssText="\n position: fixed; top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.5); display: flex; align-items: center;\n justify-content: center; z-index: 99999; animation: aegisFadeIn 0.3s ease;\n ",t}createCTAButton(e,t,n){const i=document.createElement("button");return i.style.cssText=`\n display: inline-block; padding: 10px 28px; border-radius: 999px;\n font-size: 14px; font-weight: 600; cursor: pointer; border: none;\n background: ${n}; color: ${t}; transition: transform 0.15s;\n `,i.textContent=e.button_text||"OK",i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&window.open(t,"_blank")}}),i}addCloseButton(e,t,n){const i=document.createElement("div");i.style.cssText="margin-top: 12px; font-size: 12px; opacity: 0.6; cursor: pointer;",i.textContent="Close",i.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(i)}navigateToCampaignAction(e,t,n="cta"){if("undefined"==typeof window)return;let i=!1;const s={campaign:e,action_url:t,button_id:n,preventDefault:()=>{i=!0,s.defaultPrevented=!0},defaultPrevented:!1},o=this.emit("campaign-click",s),r=new CustomEvent("aegis:campaign-click",{detail:{campaign_id:e.id,campaign_type:e.type,action_url:t,button_id:n},cancelable:!0}),a=window.dispatchEvent(r);!o||i||!a||r.defaultPrevented||(window.location.href=t)}renderBanner(e){const t=document.createElement("div");t.className="aegis-in-app-banner",t.setAttribute("data-campaign-id",e.id),t.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n padding: 16px;\n z-index: 999999;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n display: flex;\n align-items: center;\n justify-content: space-between;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideDown 0.3s ease-out;\n `;const n=document.createElement("div");if(n.style.cssText="flex: 1; display: flex; align-items: center; gap: 12px;",e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 40px; height: 40px; border-radius: 4px; object-fit: cover;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="flex: 1;";const s=document.createElement("div");s.textContent=e.title,s.style.cssText="font-weight: 600; font-size: 14px; margin-bottom: 4px;",i.appendChild(s);const o=document.createElement("div");o.textContent=e.body,o.style.cssText="font-size: 13px; opacity: 0.9;",i.appendChild(o),n.appendChild(i);const r=document.createElement("div");if(r.style.cssText="display: flex; align-items: center; gap: 12px; margin-left: 16px;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n font-weight: 600;\n cursor: pointer;\n font-size: 13px;\n white-space: nowrap;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeBanner(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="✕",a.setAttribute("aria-label","Close"),a.style.cssText="\n background: transparent;\n border: none;\n color: inherit;\n font-size: 20px;\n cursor: pointer;\n padding: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),r.appendChild(a),t.appendChild(n),t.appendChild(r),this.addAnimationStyles(),document.body.appendChild(t)}renderModal(e){const t=document.createElement("div");t.className="aegis-in-app-modal-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");if(n.className="aegis-in-app-modal",n.style.cssText='\n background: white;\n border-radius: 8px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow: auto;\n box-shadow: 0 10px 40px rgba(0,0,0,0.2);\n animation: aegisScaleIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 100%; height: 200px; object-fit: cover; border-radius: 8px 8px 0 0;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="padding: 24px;";const s=document.createElement("h2");s.textContent=e.title,s.style.cssText="margin: 0 0 12px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=e.body,o.style.cssText="margin: 0 0 20px 0; font-size: 15px; line-height: 1.5; color: #4a4a4a;",i.appendChild(o);const r=document.createElement("div");if(r.style.cssText="display: flex; gap: 12px; justify-content: flex-end;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n border: none;\n padding: 10px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="Close",a.style.cssText="\n background: transparent;\n border: 1px solid #d0d0d0;\n color: #4a4a4a;\n padding: 10px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),r.appendChild(a),i.appendChild(r),n.appendChild(i),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderFullScreen(e){const t=document.createElement("div");if(t.className="aegis-in-app-fullscreen-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: ${this.sanitizeColor(e.background_color||"#ffffff")};\n color: ${this.sanitizeColor(e.text_color||"#1a1a1a")};\n z-index: 1000001;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px 20px;\n animation: aegisFadeIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow-y: auto;\n `,e.image_url){const n=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(n.src=i,n.alt="",n.style.cssText="max-width: 100%; max-height: 40vh; object-fit: contain; margin-bottom: 32px;",t.appendChild(n))}const n=document.createElement("div");n.style.cssText="max-width: 600px; text-align: center;";const i=document.createElement("h1");i.textContent=e.title,i.style.cssText="margin: 0 0 16px 0; font-size: 32px; font-weight: 700;",n.appendChild(i);const s=document.createElement("p");if(s.textContent=e.body,s.style.cssText="margin: 0 0 32px 0; font-size: 18px; line-height: 1.6; opacity: 0.9;",n.appendChild(s),e.action_url&&e.button_text){const i=document.createElement("button");i.textContent=e.button_text,i.style.cssText=`\n background: ${this.sanitizeColor(e.text_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.background_color||"#ffffff")};\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 18px;\n cursor: pointer;\n margin-bottom: 16px;\n `,i.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),n.appendChild(i)}t.appendChild(n);const o=document.createElement("button");o.textContent="✕",o.setAttribute("aria-label","Close"),o.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: transparent;\n border: none;\n color: inherit;\n font-size: 32px;\n cursor: pointer;\n padding: 0;\n width: 48px;\n height: 48px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.6;\n ",o.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),t.appendChild(o),this.addAnimationStyles(),document.body.appendChild(t)}renderHalfInterstitial(e){const t=document.createElement("div");t.className="aegis-in-app-half-interstitial-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000000;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");if(n.className="aegis-in-app-half-interstitial",n.style.cssText='\n background: white;\n border-radius: 16px 16px 0 0;\n width: 100%;\n max-width: 600px;\n max-height: 60vh;\n overflow: auto;\n box-shadow: 0 -4px 20px rgba(0,0,0,0.2);\n animation: aegisSlideUp 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 100%; height: 200px; object-fit: cover;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="padding: 32px 24px;";const s=document.createElement("h2");s.textContent=e.title,s.style.cssText="margin: 0 0 12px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");if(o.textContent=e.body,o.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5; color: #4a4a4a;",i.appendChild(o),e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n border: none;\n padding: 14px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),i.appendChild(n)}n.appendChild(i);const r=document.createElement("button");r.textContent="✕",r.setAttribute("aria-label","Close"),r.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: rgba(255,255,255,0.9);\n border: none;\n color: #333;\n font-size: 24px;\n cursor: pointer;\n width: 36px;\n height: 36px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0,0,0,0.2);\n ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),n.style.position="relative",n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderAlert(e){const t=document.createElement("div");t.className="aegis-in-app-alert-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.6);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.2s ease-out;\n ";const n=document.createElement("div");n.className="aegis-in-app-alert",n.style.cssText='\n background: white;\n border-radius: 12px;\n max-width: 320px;\n width: 85%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n animation: aegisScaleIn 0.2s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow: hidden;\n ';const i=document.createElement("div");i.style.cssText="padding: 24px 20px; text-align: center;";const s=document.createElement("h3");s.textContent=e.title,s.style.cssText="margin: 0 0 8px 0; font-size: 18px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=e.body,o.style.cssText="margin: 0; font-size: 14px; line-height: 1.4; color: #666;",i.appendChild(o),n.appendChild(i);const r=document.createElement("div");if(r.style.cssText="display: flex; border-top: 1px solid #e0e0e0;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText="\n flex: 1;\n background: transparent;\n border: none;\n border-right: 1px solid #e0e0e0;\n color: #1a73e8;\n padding: 14px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n ",n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="Cancel",a.style.cssText="\n flex: 1;\n background: transparent;\n border: none;\n color: #666;\n padding: 14px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),r.appendChild(a),n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderPIP(e){const t=document.createElement("div");if(t.className="aegis-in-app-pip",t.setAttribute("data-campaign-id",e.id),t.style.cssText='\n position: fixed;\n bottom: 20px;\n right: 20px;\n width: 320px;\n background: black;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 8px 24px rgba(0,0,0,0.3);\n z-index: 999999;\n animation: aegisSlideUp 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.video_url){const n=document.createElement("video"),i=this.sanitizeUrl(e.video_url);i&&(n.src=i,n.controls=!0,n.autoplay=!0,n.muted=!0,n.style.cssText="width: 100%; display: block;",t.appendChild(n))}else if(e.image_url){const n=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(n.src=i,n.alt="",n.style.cssText="width: 100%; display: block;",t.appendChild(n))}const n=document.createElement("div");n.style.cssText="\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0,0,0,0.9), transparent);\n padding: 40px 16px 16px;\n color: white;\n ";const i=document.createElement("div");i.textContent=e.title,i.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 4px;",n.appendChild(i);const s=document.createElement("div");s.textContent=e.body,s.style.cssText="font-size: 12px; opacity: 0.9;",n.appendChild(s),t.appendChild(n);const o=document.createElement("button");o.textContent="✕",o.setAttribute("aria-label","Close"),o.style.cssText="\n position: absolute;\n top: 8px;\n right: 8px;\n background: rgba(0,0,0,0.6);\n border: none;\n color: white;\n font-size: 18px;\n cursor: pointer;\n width: 28px;\n height: 28px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n ",o.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),t.style.animation="aegisSlideDown 0.3s ease-out",setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},300)}),t.appendChild(o),e.action_url&&(t.style.cursor="pointer",t.addEventListener("click",t=>{if(t.target!==o){this.trackEvent(e.id,"clicked");const t=this.sanitizeUrl(e.action_url);t&&window.open(t,"_blank")}})),this.addAnimationStyles(),document.body.appendChild(t)}removeBanner(e){e.style.animation="aegisSlideUp 0.3s ease-out",setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},300)}removeModal(e){e.style.animation="aegisFadeOut 0.3s ease-out",setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},300)}renderTooltip(e){const t=e.interactive_config||{},n=t.tooltip_anchor_selector||"[data-aegis-tooltip]",i=t.tooltip_position||"bottom",s=document.querySelector(n);if(!s)return void this.log(`Tooltip anchor not found: ${n}`,"warn");const o=this.sanitizeColor(e.background_color||"#1a1a1a"),r=this.sanitizeColor(e.text_color||"#ffffff"),a=document.createElement("div");a.className="aegis-in-app-tooltip",a.setAttribute("data-campaign-id",e.id),a.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${o}; color: ${r}; border-radius: 10px; padding: 14px 16px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.18); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.2s ease-out; pointer-events: auto;\n `;const c=document.createElement("div");c.className="aegis-tooltip-arrow",c.style.cssText=`\n position: absolute; width: 10px; height: 10px; background: ${o};\n transform: rotate(45deg);\n `;const d=document.createElement("button");d.textContent="×",d.style.cssText=`\n position: absolute; top: 6px; right: 8px; background: none; border: none;\n color: ${r}; opacity: 0.6; font-size: 16px; cursor: pointer; padding: 0; line-height: 1;\n `;const l=()=>{a.style.animation="aegisFadeOut 0.2s ease-out",setTimeout(()=>{var e;null==(e=a.parentNode)||e.removeChild(a)},200),this.trackEvent(e.id,"dismissed")};if(d.addEventListener("click",e=>{e.stopPropagation(),l()}),e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-size: 13px; font-weight: 700; margin-bottom: 4px; padding-right: 16px;",a.appendChild(t)}const h=document.createElement("div");if(h.textContent=e.body,h.style.cssText="font-size: 12px; line-height: 1.4; opacity: 0.9;",a.appendChild(h),e.button_text&&e.action_url){const t=document.createElement("a");t.textContent=e.button_text,t.href=e.action_url,t.style.cssText=`\n display: inline-block; margin-top: 8px; font-size: 12px; font-weight: 600;\n color: ${r}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),a.appendChild(t)}a.appendChild(d),a.appendChild(c),document.body.appendChild(a);const p=s.getBoundingClientRect(),u=a.getBoundingClientRect(),g=window.scrollX,m=window.scrollY;let f=0,y=0,x="",b="",v="",w="";switch(i){case"top":f=p.top+m-u.height-10,y=p.left+g+(p.width-u.width)/2,v="-5px",b=u.width/2-5+"px";break;case"left":f=p.top+m+(p.height-u.height)/2,y=p.left+g-u.width-10,w="-5px",x=u.height/2-5+"px";break;case"right":f=p.top+m+(p.height-u.height)/2,y=p.right+g+10,b="-5px",x=u.height/2-5+"px";break;default:f=p.bottom+m+10,y=p.left+g+(p.width-u.width)/2,x="-5px",b=u.width/2-5+"px"}y=Math.max(8,Math.min(y,window.innerWidth+g-u.width-8)),f=Math.max(8,f),a.style.top=`${f}px`,a.style.left=`${y}px`,c.style.top=x||"",c.style.left=b||"",c.style.bottom=v||"",c.style.right=w||"";const _=e=>{a.contains(e.target)||s.contains(e.target)||(document.removeEventListener("click",_),l())};setTimeout(()=>document.addEventListener("click",_),100)}addAnimationStyles(){if(document.getElementById("aegis-in-app-styles"))return;const e=document.createElement("style");e.id="aegis-in-app-styles",e.textContent="\n @keyframes aegisSlideDown {\n from { transform: translateY(-100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisSlideUp {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(-100%); opacity: 0; }\n }\n \n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.9); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n\n /* Bottom-anchored slide IN (opposite of aegisSlideUp which slides OUT).\n Used by the preload-first renderers: sticky_bar (bottom),\n progress_bar, carousel_cards, product_recommendation. */\n @keyframes aegisSlideInFromBottom {\n from { transform: translateY(100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n ",document.head.appendChild(e)}sanitizeUrl(e){try{const t=new URL(e,window.location.origin);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked unsafe URL: ${e}`,"error"),null):t.href}catch(t){return this.log(`Invalid URL: ${e}`,"error"),null}}sanitizeColor(e){if(/^#[0-9A-Fa-f]{3,6}$/.test(e))return e;if(/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/.test(e))return e;if(/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/.test(e))return e;return["white","black","red","green","blue","yellow","orange","purple","pink","gray","transparent"].includes(e.toLowerCase())?e:"#000000"}async trackEvent(e,t){if("dismissed"===t){const t=this.campaigns.find(t=>t.id===e);t&&this.emit("campaign-dismiss",{campaign:t,source:"close_button"})}try{const n=`${this.apiHost}/v1/in_app/events`,i=`inapp_${e}_${t}_${Date.now()}`,s={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey};this.organizationId&&(s["X-Organization-ID"]=this.organizationId),this.userId&&(s["X-User-ID"]=this.userId),this.contactId&&(s["X-Contact-ID"]=this.contactId);const o={campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,anonymous_id:this.userId,platform:"web",metadata:{property_id:this.propertyId,variant_id:this.getVariantId(e)??void 0},idempotency_key:i};fetch(n,{method:"POST",headers:s,body:JSON.stringify(o),credentials:"include"}).catch(e=>{this.log(`Error tracking event: ${e}`,"error")}),this.log(`Tracked ${t} event for campaign ${e}`)}catch(n){this.log(`Error tracking event: ${n}`,"error")}}log(e,t="log"){this.debugMode&&console[t](`[AegisInApp] ${e}`)}destroy(e){if(this.disconnectSSE(),"undefined"!=typeof document){document.querySelectorAll(".aegis-in-app-banner, .aegis-in-app-modal-overlay, .aegis-in-app-fullscreen-overlay, .aegis-in-app-half-interstitial-overlay, .aegis-in-app-alert-overlay, .aegis-in-app-pip, .aegis-in-app-nps-overlay, .aegis-in-app-countdown-overlay, .aegis-in-app-rating-overlay, .aegis-in-app-poll-overlay, .aegis-in-app-quiz-overlay, .aegis-in-app-rating-card, .aegis-in-app-nps-card").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const e=document.getElementById("aegis-in-app-styles");e&&e.parentNode&&e.parentNode.removeChild(e)}(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}};J.CONVERSION_STORAGE_PREFIX="aegis_conv_";let G=J;class Y{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.isDestroyed=!1,this.prefetchWidgetConfigs={},this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new d).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.triggerEngine=e.triggerEngine,this.ownsTriggerEngine=!0===e.ownsTriggerEngine,this.enablePrefetch=!1!==e.enablePrefetch,this.cssCustomization=e.cssCustomization||{},this.onEvent=e.onEvent,this.sourcePlatform=e.sourcePlatform}updateCSSCustomization(e){this.cssCustomization={...this.cssCustomization,...e},this.log("CSS customization updated")}async updateContactId(e){this.contactId!==e&&(this.contactId=e,this.log(`Contact ID updated → ${e??"(cleared)"}`),this.isInitialized&&!this.isDestroyed&&this.enablePrefetch&&e&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()))}renderInteractiveCampaign(e){if(this.isDestroyed)return;if("undefined"==typeof document)return;const t=e.sub_type;if("spin_wheel"!==t&&"scratch_card"!==t)return void this.log(`renderInteractiveCampaign: unsupported sub_type "${t}"`,!0);const n={widget_id:e.id,widget_type:t,name:e.title,config:e.interactive_config??{},priority:e.priority??0};this.renderedWidgets.has(n.widget_id)||(this.renderedWidgets.add(n.widget_id),"spin_wheel"===t?this.renderSpinWheel(n):this.renderScratchCard(n))}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.triggerEngine&&this.ownsTriggerEngine&&this.triggerEngine.stop(),"undefined"!=typeof document){const e=document.getElementById("aegis-widget-animations");null==e||e.remove(),document.querySelectorAll("[data-aegis-widget-root]").forEach(e=>{e.remove()})}this.renderedWidgets.clear(),this.widgets=[],this.isInitialized=!1,this.log("AegisWidgets destroyed")}}emitEvent(e,t){if(this.onEvent)try{this.onEvent(e,t)}catch(n){this.log(`Error in event callback: ${n}`,!0)}}async initialize(){this.isInitialized?this.log("AegisWidgets already initialized"):(this.enablePrefetch&&this.contactId&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()),await this.fetchWidgets(),this.renderImmediateWidgets(),this.setupTriggerListeners(),this.setupExitIntentWithPrefetch(),this.isInitialized=!0,this.log("AegisWidgets initialized successfully"))}setCartData(e){this.cartData=e,this.log(`Cart data updated: ${e.cart_items.length} items, total: ${e.cart_currency} ${e.cart_total}`)}detectPlatformCart(){const e=this.normalizeShopifyCart();if(e)return this.log("Detected Shopify cart via browser globals"),e;const t=this.normalizeWooCart();if(t)return this.log("Detected WooCommerce cart via injected data"),t;const n=this.normalizeMagentoCart();return n?(this.log("Detected Magento cart via localStorage"),n):this.cartData?(this.log("Using manually set cart data"),this.cartData):null}normalizeShopifyCart(){var e;try{if("undefined"==typeof window)return null;const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=t.Shopify.checkout;return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:parseFloat(e.total_price)||0,cart_currency:e.currency||"USD",cart_items:(e.line_items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.title||e.product_title,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}const n=document.getElementById("cart-json");if(null==n?void 0:n.textContent){const e=JSON.parse(n.textContent);return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:(e.total_price||0)/100,cart_currency:e.currency||"USD",cart_items:(e.items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.product_title||e.title,quantity:e.quantity||1,price:(e.price||0)/100}))}}return null}catch(t){return this.log(`Error detecting Shopify cart: ${t}`,!0),null}}normalizeWooCart(){try{if("undefined"==typeof window)return null;const e=window;if(e.aegis_cart){const t=e.aegis_cart;return{cart_id:t.cart_id||`woo_${Date.now()}`,cart_total:parseFloat(t.cart_total)||0,cart_currency:t.cart_currency||"USD",cart_items:(t.cart_items||[]).map(e=>({product_id:String(e.product_id),product_name:e.product_name,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}return null}catch(e){return this.log(`Error detecting WooCommerce cart: ${e}`,!0),null}}normalizeMagentoCart(){try{if("undefined"==typeof window||!window.localStorage)return null;const e=localStorage.getItem("mage-cache-storage");if(!e)return null;const t=JSON.parse(e);if(!(null==t?void 0:t.cart))return null;const n=t.cart;return{cart_id:n.quote_id||n.id||`magento_${Date.now()}`,cart_total:parseFloat(n.subtotalAmount||n.subtotal||0),cart_currency:n.currencyCode||"USD",cart_items:(n.items||[]).map(e=>({product_id:String(e.item_id||e.product_id),product_name:e.product_name||e.name,quantity:e.qty||1,price:parseFloat(e.product_price_value||e.price||0)}))}}catch(e){return this.log(`Error detecting Magento cart: ${e}`,!0),null}}preloadWidgetAssets(){try{const e=this.prefetchWidgetConfigs.exit_intent;if(null==e?void 0:e.enabled){const t=e.image_url;if(t){(new Image).src=t,this.log(`Preloading exit intent image: ${t}`)}}const t=this.prefetchWidgetConfigs.spin_wheel;if(null==t?void 0:t.enabled){const e=t.image_url;if(e){(new Image).src=e,this.log(`Preloading spin wheel image: ${e}`)}}}catch(e){this.log(`Error preloading widget assets: ${e}`,!0)}}async fetchPrefetchConfigs(){try{const e=performance.now(),t=`${this.apiHost}/v1/widgets/config/prefetch`,n={"X-Aegis-Write-Key":this.writeKey};this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n,credentials:"include"});if(!i.ok)throw new Error(`Failed to fetch prefetch configs: ${i.status}`);this.prefetchWidgetConfigs=await i.json();const s=performance.now()-e;this.log(`Fetched prefetch widget configs in ${s.toFixed(2)}ms`)}catch(e){this.log(`Error fetching prefetch configs: ${e}`,!0)}}async fetchWidgets(){try{const e=`${this.apiHost}/v1/widgets/config`,t={"X-Aegis-Write-Key":this.writeKey,"X-Device-Platform":"web","X-Device-Type":this.getDeviceType()};this.userId&&(t["X-User-ID"]=this.userId),this.contactId&&(t["X-Contact-ID"]=this.contactId),this.organizationId&&(t["X-Organization-ID"]=this.organizationId),this.sourcePlatform&&(t["X-Source-Platform"]=this.sourcePlatform);const n=await fetch(e,{headers:t,credentials:"include"});if(!n.ok)throw new Error(`Failed to fetch widgets: ${n.status}`);this.widgets=await n.json(),this.log(`Fetched ${this.widgets.length} widgets`)}catch(e){this.log(`Error fetching widgets: ${e}`,!0)}}renderImmediateWidgets(){this.widgets.filter(e=>!e.trigger_rules||"immediate"===e.trigger_rules.type).forEach(e=>this.renderWidget(e))}setupTriggerListeners(){this.triggerEngine?this.widgets.forEach(e=>{if(!e.trigger_rules)return;const{type:t,config:n}=e.trigger_rules;switch(t){case"exit_intent":this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"scroll_depth":const t=(null==n?void 0:n.depth_percent)||50;this.triggerEngine.registerScrollDepth(t),this.triggerEngine.on(`scroll_depth_${t}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"time_on_page":const i=(null==n?void 0:n.seconds)||30;this.triggerEngine.registerTimeOnPage(i),this.triggerEngine.on(`time_on_page_${i}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)})}}):this.log("TriggerEngine not provided, skipping trigger-based widgets")}setupExitIntentWithPrefetch(){if(!this.enablePrefetch||!this.triggerEngine)return;const e=this.prefetchWidgetConfigs.spin_wheel,t=this.prefetchWidgetConfigs.exit_intent;if(e&&e.enabled){const n=this.isMobileDevice(),i=(null==t?void 0:t.mobile_triggers)||{},s=()=>{const t=`prefetch_spin_wheel_${Date.now()}`;if(this.renderedWidgets.has(t))return;this.renderedWidgets.add(t);const n=this.detectPlatformCart();"cart_recovery"===e.type&&n?(this.cartData=n,this.renderSpinWheelWidget(t,e),this.sendCartAbandonmentBeacon()):"lead_gen"===e.type&&this.renderSpinWheelWidget(t,e)};if(n){!1!==i.scroll_velocity&&(this.triggerEngine.registerScrollVelocity({threshold:i.scroll_threshold||.5,minScrollPosition:i.scroll_min_position||100,cooldown:i.scroll_cooldown||5e3}),this.triggerEngine.on("mobile_exit_intent",s),this.log("Registered mobile scroll velocity trigger for spin wheel"));if(!1!==i.idle_timer){const e=i.idle_seconds||15;this.triggerEngine.registerInactivity(e),this.triggerEngine.on(`inactivity_${e}`,s),this.log(`Registered mobile idle timer trigger for spin wheel: ${e}s`)}if(!1!==i.visibility_change){const e=this.detectPlatformCart();e&&e.cart_items&&e.cart_items.length>0&&(this.triggerEngine.registerVisibilityChange(),this.triggerEngine.on("visibility_hidden",s),this.log("Registered mobile visibility change trigger for spin wheel (cart detected)"))}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",s),this.log("Registered mobile back button trigger for spin wheel")),this.log(`Setup mobile spin wheel: type=${e.type}, priority=${e.priority}`)}else this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",s),this.log(`Setup desktop spin wheel exit intent: type=${e.type}, priority=${e.priority}`);return}if(!t||!t.enabled)return void this.log("No exit intent config found in prefetch");const n=this.isMobileDevice(),i=t.mobile_triggers||{},s=()=>{const e=`prefetch_exit_intent_${Date.now()}`;if(this.renderedWidgets.has(e))return;this.renderedWidgets.add(e);const n=this.detectPlatformCart();"cart_recovery"===t.type&&n?(this.cartData=n,this.renderCartRecoveryPopup(e,t),this.sendCartAbandonmentBeacon()):"lead_gen"===t.type?this.renderLeadGenPopup(e,t):this.log("Unknown exit intent type or missing cart data")};if(n){!1!==i.scroll_velocity&&(this.triggerEngine.registerScrollVelocity({threshold:i.scroll_threshold||.5,minScrollPosition:i.scroll_min_position||100,cooldown:i.scroll_cooldown||5e3}),this.triggerEngine.on("mobile_exit_intent",s),this.log("Registered mobile scroll velocity trigger"));if(!1!==i.idle_timer){const e=i.idle_seconds||15;this.triggerEngine.registerInactivity(e),this.triggerEngine.on(`inactivity_${e}`,s),this.log(`Registered mobile idle timer trigger: ${e}s`)}if(!1!==i.visibility_change){const e=this.detectPlatformCart();e&&e.cart_items&&e.cart_items.length>0?(this.triggerEngine.registerVisibilityChange(),this.triggerEngine.on("visibility_hidden",s),this.log("Registered mobile visibility change trigger (cart detected)")):this.log("Skipped visibility change trigger (no cart items)")}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",s),this.log("Registered mobile back button trigger (aggressive mode)")),this.log(`Setup mobile exit intent: type=${t.type}, priority=${t.priority}`)}else this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",s),this.log(`Setup desktop exit intent: type=${t.type}, priority=${t.priority}`)}sendCartAbandonmentBeacon(){if(!this.cartData)return void this.log("No cart data available for beacon",!0);const e={organization_id:this.organizationId||"default",contact_id:this.contactId,cart_id:this.cartData.cart_id,cart_total:this.cartData.cart_total,cart_currency:this.cartData.cart_currency,cart_items:this.cartData.cart_items,user_email:this.userId,abandoned_at:(new Date).toISOString(),page_url:window.location.href,referrer:document.referrer},t=`${this.apiHost}/v1/widgets/beacon/cart-abandoned`;if(navigator.sendBeacon){const n=new Blob([JSON.stringify(e)],{type:"application/json"});navigator.sendBeacon(t,n)?this.log("Cart abandonment beacon sent successfully"):this.log("Failed to send cart abandonment beacon",!0)}else fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(e),keepalive:!0,credentials:"include"}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!this.isDestroyed&&!this.renderedWidgets.has(e.widget_id)){switch(this.renderedWidgets.add(e.widget_id),e.widget_type){case"chat_bubble":this.renderChatBubble(e);break;case"spin_wheel":this.renderSpinWheel(e);break;case"scratch_card":this.renderScratchCard(e);break;case"toast":this.renderToast(e);break;case"feedback_form":this.renderFeedbackForm(e);break;case"exit_intent_popup":this.renderExitIntentPopup(e);break;default:this.log(`Unknown widget type: ${e.widget_type}`,!0)}this.trackEvent(e.widget_id,"show")}}renderChatBubble(e){const{text:t,icon_url:n,link_url:i,background_color:s,text_color:o}=e.config,r=e.position||"bottom_right",a=document.createElement("div");a.className="aegis-chat-bubble",a.setAttribute("data-widget-id",e.widget_id);const c={bottom_right:"bottom: 20px; right: 20px;",bottom_left:"bottom: 20px; left: 20px;",top_right:"top: 20px; right: 20px;",top_left:"top: 20px; left: 20px;"};if(a.style.cssText=`\n position: fixed;\n ${c[r]||c.bottom_right}\n background: ${this.sanitizeColor(s||"#25D366")};\n color: ${this.sanitizeColor(o||"#ffffff")};\n padding: 16px 24px;\n border-radius: 50px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n cursor: pointer;\n z-index: 999999;\n display: flex;\n align-items: center;\n gap: 12px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n font-weight: 600;\n font-size: 14px;\n animation: aegisBubbleIn 0.3s ease-out;\n `,n){const e=document.createElement("img"),t=this.sanitizeUrl(n);t&&(e.src=t,e.alt="",e.style.cssText="width: 24px; height: 24px;",a.appendChild(e))}const d=document.createElement("span");d.textContent=t||"Chat with us",a.appendChild(d),a.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(i);t&&window.open(t,"_blank")}),this.addAnimationStyles(),a.setAttribute("data-aegis-widget-root",""),document.body.appendChild(a)}renderSpinWheel(e){const t=document.createElement("div");t.className="aegis-gamification-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");n.className="aegis-spin-wheel-modal",n.style.cssText='\n background: white;\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ';const i=document.createElement("h2");i.textContent=e.config.title||"Spin to Win!",i.style.cssText="margin: 0 0 16px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",n.appendChild(i);const s=document.createElement("p");s.textContent=e.config.description||"Try your luck and win exclusive prizes!",s.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(s);const o=Array.isArray(e.config.segments)?e.config.segments:[{label:"Prize 1",color:"#ff6b6b"},{label:"Prize 2",color:"#feca57"},{label:"Prize 3",color:"#48dbfb"},{label:"Prize 4",color:"#ff6348"}],r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg");a.setAttribute("viewBox","-160 -160 320 320"),a.setAttribute("width","300"),a.setAttribute("height","300"),a.style.cssText="margin: 0 auto 24px; display: block;";const c=o.length,d=2*Math.PI/c,l=140;for(let u=0;u<c;u++){const e=u*d-Math.PI/2,t=e+d,n=Math.cos(e)*l,i=Math.sin(e)*l,s=Math.cos(t)*l,c=Math.sin(t)*l,h=d>Math.PI?1:0,p=document.createElementNS(r,"path");p.setAttribute("d",`M 0 0 L ${n.toFixed(2)} ${i.toFixed(2)} A 140 140 0 ${h} 1 ${s.toFixed(2)} ${c.toFixed(2)} Z`),p.setAttribute("fill",this.sanitizeColor(o[u].color||"#cccccc")),p.setAttribute("stroke","#ffffff"),p.setAttribute("stroke-width","2"),a.appendChild(p);const g=e+d/2,m=Math.cos(g)*l*.65,f=Math.sin(g)*l*.65,y=document.createElementNS(r,"text");y.setAttribute("x",m.toFixed(2)),y.setAttribute("y",f.toFixed(2)),y.setAttribute("fill","#ffffff"),y.setAttribute("font-size","13"),y.setAttribute("font-weight","600"),y.setAttribute("text-anchor","middle"),y.setAttribute("dominant-baseline","middle"),y.textContent=o[u].label||`#${u+1}`,a.appendChild(y)}n.appendChild(a);const h=document.createElement("button");h.textContent="SPIN NOW!",h.style.cssText="\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n margin-bottom: 16px;\n ",h.addEventListener("click",async()=>{h.disabled=!0,h.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);a.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),h.disabled=!1,h.textContent="TRY AGAIN"}}),n.appendChild(h);const p=document.createElement("button");p.textContent="×",p.setAttribute("aria-label","Close"),p.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",p.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(p),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderSpinWheelWidget(e,t){if(this.isDestroyed)return;const n=this.detectPlatformCart();if("cart_recovery"===t.type&&!n)return void this.log("Spin wheel requires cart, but none detected");n&&(this.cartData=n);const i=this.cssCustomization.spinWheel||{},s=i.accentColor||t.accent_color||"#FF6B6B",o=i.backgroundColor||t.background_color||"#FFFFFF",r=i.textColor||t.text_color||"#333333",a=i.buttonColor||t.button_color||s,c=i.wheelColors||["#FF6B6B","#4ECDC4","#FFE66D","#95E1D3"],d=document.createElement("div");d.className="aegis-spin-wheel-overlay",d.setAttribute("data-widget-id",e),d.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.7);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n animation: aegisFadeIn 0.3s ease;\n ";const l=document.createElement("div");l.className="aegis-spin-wheel-modal",l.style.cssText=`\n background: ${this.sanitizeColor(o)};\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 20px 60px rgba(0,0,0,0.3);\n position: relative;\n animation: aegisScaleIn 0.4s ease;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `;const h=document.createElement("button");h.innerHTML="✕",h.className="aegis-spin-wheel-close",h.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n color: #999;\n ",h.onclick=()=>{this.trackEvent(e,"dismiss",{type:"spin_wheel"}),document.body.removeChild(d),this.renderedWidgets.delete(e)},l.appendChild(h);const p=document.createElement("h2");if(p.textContent=this.interpolateCartVariables(t.title||"Spin to Win!"),p.style.cssText=`\n margin: 0 0 16px 0;\n font-size: 28px;\n font-weight: bold;\n text-align: center;\n color: ${this.sanitizeColor(r)};\n `,l.appendChild(p),n){const e=document.createElement("p");e.textContent=`Complete your ${n.cart_currency} ${n.cart_total.toFixed(2)} order and save!`,e.style.cssText="\n margin: 0 0 24px 0;\n font-size: 16px;\n text-align: center;\n color: #666;\n ",l.appendChild(e)}const u=document.createElement("div");u.className="aegis-wheel-container",u.style.cssText=`\n width: 300px;\n height: 300px;\n margin: 0 auto 24px auto;\n background: conic-gradient(\n from 0deg,\n ${c[0]} 0deg 90deg,\n ${c[1]} 90deg 180deg,\n ${c[2]} 180deg 270deg,\n ${c[3]} 270deg 360deg\n );\n border-radius: 50%;\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n `;const g=document.createElement("form");g.className="aegis-spin-form",g.style.cssText="display: block;";const m=document.createElement("input");m.type="tel",m.placeholder="Enter your phone number",m.required=!0,m.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(m);const f=document.createElement("input");f.type="email",f.placeholder="Enter your email (optional)",f.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(f);const y=document.createElement("input");y.type="text",y.placeholder="Enter your name (optional)",y.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(y);const x=document.createElement("button");x.type="submit",x.textContent="Spin the Wheel!",x.style.cssText=`\n width: 100%;\n padding: 14px;\n background: ${this.sanitizeColor(a)};\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 700;\n cursor: pointer;\n `,g.appendChild(x);const b=document.createElement("div");b.className="aegis-spin-error",b.style.cssText="\n color: #d32f2f;\n font-size: 14px;\n margin-top: 12px;\n text-align: center;\n display: none;\n ",g.appendChild(b),g.addEventListener("submit",async t=>{t.preventDefault();const i=m.value.trim(),s=f.value.trim(),o=y.value.trim();return this.validatePhone(i)?s&&!this.validateEmail(s)?(b.textContent="Please enter a valid email address",void(b.style.display="block")):(b.style.display="none",x.disabled=!0,x.textContent="Spinning...",u.style.animation="aegisSpin 2s ease-out",void setTimeout(async()=>{try{const t=await this.submitSpinWheel({phone:i,email:s,name:o,cart:n,widgetId:e});this.showSpinWheelPrize(l,t),this.trackEvent(e,"submit",{type:"spin_wheel",prize_label:t.prize_label,has_email:!!s})}catch(t){this.log(`Error submitting spin wheel: ${t}`,!0),b.textContent="Failed to submit. Please try again.",b.style.display="block",x.disabled=!1,x.textContent="Spin the Wheel!",u.style.animation=""}},2e3)):(b.textContent="Please enter a valid phone number (e.g., +1234567890)",void(b.style.display="block"))}),l.appendChild(u),l.appendChild(g),d.appendChild(l),this.addAnimationStyles(),d.setAttribute("data-aegis-widget-root",""),document.body.appendChild(d),this.trackEvent(e,"show",{type:"spin_wheel"})}validatePhone(e){return/^\+?[1-9]\d{1,14}$/.test(e.replace(/[\s()-]/g,""))}validateEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}async submitSpinWheel(e){var t,n,i,s,o;const r=`${this.apiHost}/v1/widgets/spin-wheel/submit`,a={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.organizationId&&(a["X-Organization-ID"]=this.organizationId);const c=this.detectGeoRegion(),d=this.getDeviceType(),l=this.getUTMParams(),h={phone:e.phone.replace(/[\s()-]/g,""),email:e.email||void 0,name:e.name||void 0,cart_id:(null==(t=e.cart)?void 0:t.cart_id)||`web_${Date.now()}`,cart_token:null==(n=e.cart)?void 0:n.cart_id,cart_total:(null==(i=e.cart)?void 0:i.cart_total)||0,cart_currency:(null==(s=e.cart)?void 0:s.cart_currency)||"USD",cart_items:(null==(o=e.cart)?void 0:o.cart_items)||[],cart_url:window.location.href,platform:"web",geo_region:c,device_type:d,session_id:this.getSessionId()||void 0,anonymous_id:this.getAnonymousId()||void 0,utm_source:l.utm_source,utm_medium:l.utm_medium,utm_campaign:l.utm_campaign},p=await fetch(r,{method:"POST",headers:a,body:JSON.stringify(h),credentials:"include"});if(!p.ok){const e=await p.text();throw new Error(`Failed to submit spin wheel: ${p.status} - ${e}`)}return await p.json()}showSpinWheelPrize(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const s=document.createElement("h2");s.textContent="Congratulations!",s.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(s);const o=document.createElement("p");if(o.textContent=t.prize_label,o.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(o),t.coupon_code){const e=document.createElement("div");e.style.cssText="\n background: #f5f5f5;\n padding: 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 2px dashed #1a73e8;\n ";const i=document.createElement("div");i.textContent="Your coupon code:",i.style.cssText="font-size: 12px; color: #666; margin-bottom: 8px;",e.appendChild(i);const s=document.createElement("div");s.textContent=t.coupon_code,s.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(s),n.appendChild(e)}const r=document.createElement("p");r.textContent="Check your WhatsApp/SMS for your discount code and cart link!",r.style.cssText="margin: 0 0 20px 0; font-size: 14px; color: #666;",n.appendChild(r);const a=document.createElement("button");a.textContent="Close",a.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",a.addEventListener("click",()=>{const t=e.parentElement;t&&document.body.contains(t)&&document.body.removeChild(t)}),n.appendChild(a),e.appendChild(n)}detectGeoRegion(){const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e.includes("America")?"north_america":e.includes("Europe")?"europe":e.includes("Asia/Kolkata")||e.includes("Asia/Calcutta")?"india":e.includes("Asia/Singapore")||e.includes("Asia/Bangkok")||e.includes("Asia/Jakarta")?"southeast_asia":e.includes("Asia/Dubai")||e.includes("Asia/Riyadh")?"middle_east":e.includes("America")&&(e.includes("Sao_Paulo")||e.includes("Buenos_Aires"))?"latin_america":e.includes("Australia")||e.includes("Pacific/Auckland")?"oceania":"north_america"}getUTMParams(){const e=new URLSearchParams(window.location.search);return{utm_source:e.get("utm_source")||void 0,utm_medium:e.get("utm_medium")||void 0,utm_campaign:e.get("utm_campaign")||void 0}}getSessionId(){return sessionStorage.getItem("aegis_session_id")}getAnonymousId(){return localStorage.getItem("aegis_anonymous_id")}renderScratchCard(e){const t=document.createElement("div");t.className="aegis-gamification-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");n.className="aegis-scratch-card-modal",n.style.cssText='\n background: white;\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ';const i=document.createElement("h2");i.textContent=e.config.title||"Scratch & Win!",i.style.cssText="margin: 0 0 16px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",n.appendChild(i);const s=document.createElement("p");s.textContent=e.config.description||"Scratch to reveal your prize!",s.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(s);const o=document.createElement("canvas");o.width=300,o.height=200,o.style.cssText="\n border-radius: 8px;\n cursor: pointer;\n margin: 0 auto 24px;\n display: block;\n box-shadow: 0 4px 12px rgba(0,0,0,0.1);\n ",n.appendChild(o);const r=o.getContext("2d");if(r){r.fillStyle="#c0c0c0",r.fillRect(0,0,o.width,o.height),r.fillStyle="#888",r.font="20px Arial",r.textAlign="center",r.fillText("Scratch here!",o.width/2,o.height/2);let e=!1;const t=(e,t)=>{r.globalCompositeOperation="destination-out",r.beginPath(),r.arc(e,t,20,0,2*Math.PI),r.fill()};o.addEventListener("mousedown",()=>{e=!0}),o.addEventListener("mouseup",()=>{e=!1}),o.addEventListener("mousemove",n=>{if(e){const e=o.getBoundingClientRect();t(n.clientX-e.left,n.clientY-e.top)}})}const a=document.createElement("button");a.textContent="REVEAL PRIZE",a.style.cssText="\n background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);\n color: white;\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n ",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="REVEALING...";try{const t=await this.generatePrize(e.config.config_id);this.showPrizeResult(n,t)}catch(t){this.log(`Error generating prize: ${t}`,!0),a.disabled=!1,a.textContent="TRY AGAIN"}}),n.appendChild(a),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderToast(e){const{message:t,icon:n,duration:i}=e.config,s=e.position||"bottom_left",o=document.createElement("div");o.className="aegis-toast",o.setAttribute("data-widget-id",e.widget_id);const r={bottom_left:"bottom: 20px; left: 20px;",bottom_right:"bottom: 20px; right: 20px;",top_left:"top: 20px; left: 20px;",top_right:"top: 20px; right: 20px;"};if(o.style.cssText=`\n position: fixed;\n ${r[s]||r.bottom_left}\n background: white;\n padding: 16px 20px;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n z-index: 999998;\n display: flex;\n align-items: center;\n gap: 12px;\n max-width: 350px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisToastIn 0.3s ease-out;\n `,n){const e=document.createElement("div");e.textContent=n,e.style.cssText="font-size: 20px;",o.appendChild(e)}const a=document.createElement("div");a.textContent=t||"Someone just made a purchase!",a.style.cssText="flex: 1; font-size: 13px; color: #333;",o.appendChild(a),this.addAnimationStyles(),o.setAttribute("data-aegis-widget-root",""),document.body.appendChild(o),setTimeout(()=>{o.style.animation="aegisToastOut 0.3s ease-out",setTimeout(()=>{document.body.contains(o)&&document.body.removeChild(o),this.renderedWidgets.delete(e.widget_id)},300)},i||5e3)}renderFeedbackForm(e){const t=document.createElement("div");t.className="aegis-feedback-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText='\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 400px;\n background: white;\n box-shadow: -4px 0 20px rgba(0,0,0,0.15);\n z-index: 1000000;\n padding: 32px;\n overflow-y: auto;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInRight 0.3s ease-out;\n ';const n=document.createElement("h2");n.textContent=e.config.title||"We value your feedback!",n.style.cssText="margin: 0 0 8px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",t.appendChild(n);const i=document.createElement("p");i.textContent=e.config.description||"Help us improve your experience.",i.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",t.appendChild(i);const s=document.createElement("form"),o=document.createElement("label");o.textContent="How likely are you to recommend us? (0-10)",o.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(o);const r=document.createElement("input");r.type="number",r.min="0",r.max="10",r.style.cssText="\n width: 100%;\n padding: 12px;\n border: 1px solid #ddd;\n border-radius: 6px;\n font-size: 14px;\n margin-bottom: 16px;\n ",s.appendChild(r);const a=document.createElement("label");a.textContent="Tell us more (optional)",a.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(a);const c=document.createElement("textarea");c.rows=4,c.style.cssText="\n width: 100%;\n padding: 12px;\n border: 1px solid #ddd;\n border-radius: 6px;\n font-size: 14px;\n resize: vertical;\n margin-bottom: 16px;\n font-family: inherit;\n ",s.appendChild(c);const d=document.createElement("button");d.type="submit",d.textContent="Submit Feedback",d.style.cssText="\n width: 100%;\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px;\n border-radius: 6px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",s.appendChild(d),s.addEventListener("submit",async n=>{n.preventDefault(),d.disabled=!0,d.textContent="Submitting...";try{await this.submitFeedback(e.widget_id,{score:parseInt(r.value),comment:c.value}),t.innerHTML='<div style="text-align: center; padding: 60px 20px;"><h3 style="margin: 0 0 12px 0; color: #1a73e8;">Thank you!</h3><p style="margin: 0; color: #666;">Your feedback helps us improve.</p></div>',setTimeout(()=>{document.body.removeChild(t)},2e3)}catch(i){this.log(`Error submitting feedback: ${i}`,!0),d.disabled=!1,d.textContent="Submit Feedback"}}),t.appendChild(s);const l=document.createElement("button");l.textContent="×",l.setAttribute("aria-label","Close"),l.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",l.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),t.appendChild(l),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:s,image_url:o}=e.config,r=document.createElement("div");r.className="aegis-exit-popup-overlay",r.setAttribute("data-widget-id",e.widget_id),r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const a=document.createElement("div");if(a.className="aegis-exit-popup-modal",a.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n overflow: hidden;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ',o){const e=document.createElement("img"),t=this.sanitizeUrl(o);t&&(e.src=t,e.alt="",e.style.cssText="width: 100%; height: 250px; object-fit: cover;",a.appendChild(e))}const c=document.createElement("div");c.style.cssText="padding: 32px;";const d=document.createElement("h2");d.textContent=t||"Wait! Don't leave yet!",d.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",c.appendChild(d);const l=document.createElement("p");if(l.textContent=n||"Get 10% off your first order!",l.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666; line-height: 1.5;",c.appendChild(l),i&&s){const t=document.createElement("button");t.textContent=i,t.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n ",t.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(s);t&&(window.location.href=t)}),c.appendChild(t)}a.appendChild(c);const h=document.createElement("button");h.textContent="×",h.setAttribute("aria-label","Close"),h.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: white;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #666;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n box-shadow: 0 2px 8px rgba(0,0,0,0.2);\n ",h.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(r),this.renderedWidgets.delete(e.widget_id)}),a.style.position="relative",a.appendChild(h),r.appendChild(a),this.addAnimationStyles(),r.setAttribute("data-aegis-widget-root",""),document.body.appendChild(r)}async generatePrize(e){const t=`${this.apiHost}/v1/widgets/gamification/generate-prize`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{method:"POST",headers:n,body:JSON.stringify({config_id:e}),credentials:"include"});if(!i.ok)throw new Error(`Failed to generate prize: ${i.status}`);return await i.json()}showPrizeResult(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const s=document.createElement("h2");s.textContent="Congratulations!",s.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(s);const o=document.createElement("p");if(o.textContent=t.prize_label,o.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(o),t.coupon_code){const e=document.createElement("div");e.style.cssText="\n background: #f5f5f5;\n padding: 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 2px dashed #1a73e8;\n ";const i=document.createElement("div");i.textContent="Your coupon code:",i.style.cssText="font-size: 12px; color: #666; margin-bottom: 8px;",e.appendChild(i);const s=document.createElement("div");s.textContent=t.coupon_code,s.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(s),n.appendChild(e)}const r=document.createElement("button");r.textContent="Close",r.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",r.addEventListener("click",()=>{const t=e.parentElement;t&&document.body.contains(t)&&document.body.removeChild(t)}),n.appendChild(r),e.appendChild(n)}async submitFeedback(e,t){const n=`${this.apiHost}/v1/widgets/track-event`,i={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(i["X-User-ID"]=this.userId),this.contactId&&(i["X-Contact-ID"]=this.contactId),this.organizationId&&(i["X-Organization-ID"]=this.organizationId);const s=await fetch(n,{method:"POST",headers:i,body:JSON.stringify({widget_id:e,event_type:"submit",event_data:t}),credentials:"include"});if(!s.ok)throw new Error(`Failed to submit feedback: ${s.status}`)}async trackEvent(e,t,n){try{const i=`${this.apiHost}/v1/widgets/track-event`,s={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(s["X-User-ID"]=this.userId),this.contactId&&(s["X-Contact-ID"]=this.contactId),this.organizationId&&(s["X-Organization-ID"]=this.organizationId),await fetch(i,{method:"POST",headers:s,body:JSON.stringify({widget_id:e,event_type:t,event_data:n||{}}),credentials:"include"})}catch(i){this.log(`Error tracking widget event: ${i}`,!0)}}sanitizeUrl(e){if(!e)return null;try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked dangerous URL: ${e}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-F]{3,8}$/i.test(e)||/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/i.test(e)||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/i.test(e)?e:"#1a73e8"}getDeviceType(){const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"}isMobileDevice(){const e=this.getDeviceType();return"mobile"===e||"tablet"===e}addAnimationStyles(){if(document.getElementById("aegis-widget-animations"))return;const e=document.createElement("style");e.id="aegis-widget-animations",e.textContent="\n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.8); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n \n @keyframes aegisBubbleIn {\n from { transform: translateY(20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisToastIn {\n from { transform: translateX(-100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n \n @keyframes aegisToastOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(-100%); opacity: 0; }\n }\n \n @keyframes aegisSlideInRight {\n from { transform: translateX(100%); }\n to { transform: translateX(0); }\n }\n \n @keyframes aegisSpin {\n from { transform: rotate(0deg); }\n to { transform: rotate(1440deg); }\n }\n ",document.head.appendChild(e)}renderCartRecoveryPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-cart-recovery-modal",i.style.cssText=`\n background: ${this.sanitizeColor(t.background_color||"#FFFFFF")};\n color: ${this.sanitizeColor(t.text_color||"#333333")};\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n `;const s=document.createElement("h2"),o=this.interpolateCartVariables(t.title||"Complete Your Order");s.textContent=o,s.style.cssText=`margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: ${this.sanitizeColor(t.accent_color||"#FF6B00")};`,i.appendChild(s);const r=document.createElement("p"),a=this.interpolateCartVariables(t.message||"Your cart is waiting for you!");if(r.textContent=a,r.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5;",i.appendChild(r),t.show_cart_items&&this.cartData){const e=document.createElement("div");e.style.cssText="margin: 0 0 24px 0; padding: 16px; background: rgba(0,0,0,0.05); border-radius: 8px;";const t=document.createElement("div");t.textContent=`${this.cartData.cart_items.length} items in your cart`,t.style.cssText="font-weight: 600; margin-bottom: 12px;",e.appendChild(t),this.cartData.cart_items.slice(0,3).forEach(t=>{const n=document.createElement("div");n.textContent=`${t.quantity}× ${t.product_name||t.product_id}`,n.style.cssText="font-size: 14px; margin-bottom: 4px;",e.appendChild(n)}),i.appendChild(e)}if(t.discount_code){const e=document.createElement("div");e.style.cssText=`\n margin: 0 0 24px 0;\n padding: 16px;\n background: ${this.sanitizeColor(t.accent_color||"#FF6B00")};\n color: white;\n border-radius: 8px;\n text-align: center;\n font-weight: 700;\n font-size: 18px;\n `,e.textContent=`Use code: ${t.discount_code} for ${t.discount_percentage||10}% off!`,i.appendChild(e)}if(t.show_timer&&t.timer_minutes){const e=document.createElement("div");e.style.cssText="margin: 0 0 24px 0; text-align: center; font-size: 14px; color: #999;",e.textContent=`⏰ Offer expires in ${t.timer_minutes} minutes`,i.appendChild(e)}const c=document.createElement("button");c.textContent=t.cta_text||"Complete Checkout",c.style.cssText=`\n background: ${this.sanitizeColor(t.accent_color||"#FF6B00")};\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,c.addEventListener("click",()=>{this.trackEvent(e,"click",{type:"cart_recovery"});const n=this.sanitizeUrl(t.cta_url||"/checkout");n&&(window.location.href=n)}),i.appendChild(c);const d=document.createElement("button");d.textContent="×",d.setAttribute("aria-label","Close"),d.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",d.addEventListener("click",()=>{this.trackEvent(e,"dismiss",{type:"cart_recovery"}),document.body.removeChild(n),this.renderedWidgets.delete(e)}),i.appendChild(d),n.appendChild(i),this.addAnimationStyles(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-leadgen-modal",i.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 500px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n ';const s=document.createElement("h2");s.textContent=t.title||"Get 10% Off Your First Order!",s.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=t.message||"Subscribe to our newsletter and get an exclusive discount code.",o.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666;",i.appendChild(o);const r=document.createElement("form"),a=document.createElement("input");a.type="email",a.placeholder="Enter your email",a.required=!0,a.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 16px;\n box-sizing: border-box;\n ",r.appendChild(a);const c=document.createElement("button");c.type="submit",c.textContent="Get My Discount",c.style.cssText="\n width: 100%;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n ",r.appendChild(c),r.addEventListener("submit",async t=>{t.preventDefault(),c.disabled=!0,c.textContent="Submitting...";try{await this.trackEvent(e,"submit",{type:"lead_gen",email:a.value}),i.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 48px; margin-bottom: 16px;">✅</div>\n <h3 style="margin: 0 0 12px 0; color: #1a73e8;">Thank You!</h3>\n <p style="margin: 0; color: #666;">Check your email for your discount code!</p>\n </div>\n ',setTimeout(()=>{document.body.removeChild(n)},2500)}catch(s){this.log(`Error submitting lead gen form: ${s}`,!0),c.disabled=!1,c.textContent="Get My Discount"}}),i.appendChild(r);const d=document.createElement("button");d.textContent="×",d.setAttribute("aria-label","Close"),d.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",d.addEventListener("click",()=>{this.trackEvent(e,"dismiss",{type:"lead_gen"}),document.body.removeChild(n),this.renderedWidgets.delete(e)}),i.appendChild(d),n.appendChild(i),this.addAnimationStyles(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"lead_gen"})}interpolateCartVariables(e){return this.cartData?e.replace(/\{\{cart_total\}\}/g,`${this.cartData.cart_currency} ${this.cartData.cart_total.toFixed(2)}`).replace(/\{\{cart_currency\}\}/g,this.cartData.cart_currency).replace(/\{\{cart_items_count\}\}/g,this.cartData.cart_items.length.toString()):e}log(e,t=!1){if(this.debugMode||t){console[t?"error":"log"](`[AegisWidgets] ${e}`)}}}class Z{constructor(){this.listeners=new Map,this.isStarted=!1,this.scrollDepthTargets=new Set,this.scrollDepthReached=new Set,this.timeOnPageTargets=new Map,this.exitIntentEnabled=!1,this.exitIntentFired=!1,this.inactivityTargets=new Map,this.lastActivityTime=Date.now(),this.scrollVelocityEnabled=!1,this.scrollVelocityFired=!1,this.scrollVelocityConfig={threshold:.5,minScrollPosition:100,cooldown:5e3},this.lastScrollY=0,this.lastScrollTime=Date.now(),this.visibilityChangeEnabled=!1,this.backButtonEnabled=!1,this.backButtonFired=!1,this.rageClickEnabled=!1,this.rageClickConfig={threshold:3,windowMs:1e3},this.rageClickBuffer=new Map,this.rageClickFiredInBurst=new Set,this.hoverEnabled=!1,this.hoverStartAt=new Map,this.hoverLastMs=new Map,this.hoverThresholds=new Map([["price",[1500]],["cta",[1500]]]),this.hoverThresholdsFired=new Map,this.hoverThresholdTimers=new Map,this.mouseVelEnabled=!1,this.mouseVelConfig={threshold:1.5,windowMs:400,cooldownMs:5e3},this.mouseSamples=[],this.mouseVelLast=0,this.mouseVelLastFiredAt=0,this.handleScroll=()=>{const e=window.pageYOffset||document.documentElement.scrollTop,t=document.documentElement.scrollHeight-window.innerHeight,n=t>0?e/t*100:0;for(const i of this.scrollDepthTargets)n>=i&&!this.scrollDepthReached.has(i)&&(this.scrollDepthReached.add(i),this.emit(`scroll_depth_${i}`,{depth_percent:i,actual_percent:n,scroll_top:e,scroll_height:t}))},this.handleExitIntent=e=>{this.exitIntentFired||e.clientY<10&&(this.exitIntentFired=!0,this.emit("exit_intent",{client_y:e.clientY,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleScrollVelocity=()=>{if(this.scrollVelocityFired)return;const e=window.scrollY||document.documentElement.scrollTop,t=Date.now(),n=t-this.lastScrollTime;if(n>100){const i=this.lastScrollY-e,s=Math.abs(i/n);i>0&&s>this.scrollVelocityConfig.threshold&&e>this.scrollVelocityConfig.minScrollPosition&&(this.scrollVelocityFired=!0,this.emit("mobile_exit_intent",{scroll_velocity:s,scroll_distance:i,current_position:e,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}),this.scrollVelocityCooldownTimer=window.setTimeout(()=>{this.scrollVelocityFired=!1},this.scrollVelocityConfig.cooldown)),this.lastScrollY=e,this.lastScrollTime=t}},this.handleVisibilityChange=()=>{document.hidden?this.emit("visibility_hidden",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}):this.emit("visibility_visible",{page_url:window.location.href})},this.handleBackButton=()=>{this.backButtonFired||(this.backButtonFired=!0,window.history.pushState(null,"",window.location.href),this.emit("back_button",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleActivity=()=>{this.lastActivityTime=Date.now()}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}registerScrollDepth(e){this.scrollDepthTargets.add(e)}registerTimeOnPage(e){if(!this.timeOnPageTargets.has(e)){const t=window.setTimeout(()=>{this.emit(`time_on_page_${e}`,{seconds:e,page_url:window.location.href}),this.timeOnPageTargets.delete(e)},1e3*e);this.timeOnPageTargets.set(e,t)}}registerExitIntent(){this.exitIntentEnabled=!0}registerInactivity(e){if(!this.inactivityTargets.has(e)){const t=window.setTimeout(()=>{const t=(Date.now()-this.lastActivityTime)/1e3;t>=e&&this.emit(`inactivity_${e}`,{idle_seconds:e,actual_idle_time:t}),this.inactivityTargets.delete(e)},1e3*e);this.inactivityTargets.set(e,t)}}registerScrollVelocity(e){this.scrollVelocityEnabled=!0,e&&(this.scrollVelocityConfig={threshold:e.threshold??this.scrollVelocityConfig.threshold,minScrollPosition:e.minScrollPosition??this.scrollVelocityConfig.minScrollPosition,cooldown:e.cooldown??this.scrollVelocityConfig.cooldown})}registerVisibilityChange(){this.visibilityChangeEnabled=!0}registerBackButton(){this.backButtonEnabled=!0}registerRageClick(e){this.rageClickEnabled=!0,e&&(this.rageClickConfig={threshold:e.threshold??this.rageClickConfig.threshold,windowMs:e.windowMs??this.rageClickConfig.windowMs})}noteClick(e,t=Date.now()){if(!this.rageClickEnabled)return 0;const n=this.rageClickBuffer.get(e)??[],i=t-this.rageClickConfig.windowMs;let s=0;for(;s<n.length&&n[s]<i;)s++;const o=0===s?n:n.slice(s);return o.push(t),this.rageClickBuffer.set(e,o),o.length<this.rageClickConfig.threshold&&this.rageClickFiredInBurst.delete(e),o.length>=this.rageClickConfig.threshold&&!this.rageClickFiredInBurst.has(e)&&(this.rageClickFiredInBurst.add(e),this.emit("rage_click",{intent:e,count:o.length,window_ms:this.rageClickConfig.windowMs})),o.length}getRageClickCount(e){if(!this.rageClickEnabled)return 0;const t=this.rageClickBuffer.get(e);if(!t)return 0;const n=Date.now()-this.rageClickConfig.windowMs;let i=0;for(const s of t)s>=n&&i++;return i}registerHoverDwell(e){if(this.hoverEnabled=!0,null==e?void 0:e.thresholdsByIntent)for(const[t,n]of Object.entries(e.thresholdsByIntent))n&&this.hoverThresholds.set(t,n)}noteHoverStart(e,t=Date.now()){if(!this.hoverEnabled)return;this.hoverStartAt.has(e)&&this.noteHoverEnd(e,t),this.hoverStartAt.set(e,t),this.hoverThresholdsFired.set(e,new Set);const n=this.hoverThresholds.get(e);if(n){const i=[];for(const s of n){const n=setTimeout(()=>{if(!this.hoverStartAt.has(e))return;const n=this.hoverThresholdsFired.get(e);(null==n?void 0:n.has(s))||(null==n||n.add(s),this.emit(`${e}_hover_dwell_${s}`,{intent:e,threshold_ms:s,actual_ms:Date.now()-t}))},s);i.push(n)}this.hoverThresholdTimers.set(e,i)}}noteHoverEnd(e,t=Date.now()){if(!this.hoverEnabled)return;const n=this.hoverStartAt.get(e);if(void 0===n)return;const i=Math.max(0,t-n);this.hoverLastMs.set(e,i),this.hoverStartAt.delete(e);const s=this.hoverThresholdTimers.get(e);if(s){for(const e of s)clearTimeout(e);this.hoverThresholdTimers.delete(e)}this.hoverThresholdsFired.delete(e)}registerMouseVelocityToTop(e){this.mouseVelEnabled=!0,e&&(this.mouseVelConfig={threshold:e.threshold??this.mouseVelConfig.threshold,windowMs:e.windowMs??this.mouseVelConfig.windowMs,cooldownMs:e.cooldownMs??this.mouseVelConfig.cooldownMs})}noteMousePosition(e,t,n=Date.now()){if(!this.mouseVelEnabled)return 0;const i=n-this.mouseVelConfig.windowMs;let s=0;for(;s<this.mouseSamples.length&&this.mouseSamples[s].ts<i;)s++;if(s>0&&(this.mouseSamples=this.mouseSamples.slice(s)),this.mouseSamples.push({x:e,y:t,ts:n}),this.mouseSamples.length<2)return this.mouseVelLast=0,0;const o=this.mouseSamples[0],r=this.mouseSamples[this.mouseSamples.length-1],a=r.ts-o.ts;if(a<=0)return this.mouseVelLast=0,0;const c=-(r.y-o.y)/a;this.mouseVelLast=c;const d=0===this.mouseVelLastFiredAt||n-this.mouseVelLastFiredAt>=this.mouseVelConfig.cooldownMs;return c>=this.mouseVelConfig.threshold&&d&&(this.mouseVelLastFiredAt=n,this.emit("mouse_velocity_to_top",{velocity:c,threshold:this.mouseVelConfig.threshold,window_ms:this.mouseVelConfig.windowMs,samples:this.mouseSamples.length})),c}getMouseVelocityToTop(){return this.mouseVelEnabled?this.mouseVelLast:0}getHoverMs(e){if(!this.hoverEnabled)return 0;const t=this.hoverStartAt.get(e);return void 0!==t?Math.max(0,Date.now()-t):this.hoverLastMs.get(e)??0}start(){this.isStarted||(this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollDepthTargets.size>0&&this.attachScrollListener(),this.exitIntentEnabled&&this.attachExitIntentListener(),this.scrollVelocityEnabled&&this.attachScrollVelocityListener(),this.visibilityChangeEnabled&&this.attachVisibilityChangeListener(),this.backButtonEnabled&&this.attachBackButtonListener(),this.attachActivityListeners(),this.startInactivityCheck(),this.isStarted=!0)}stop(){this.isStarted&&(this.removeScrollListener(),this.removeExitIntentListener(),this.removeScrollVelocityListener(),this.removeVisibilityChangeListener(),this.removeBackButtonListener(),this.removeActivityListeners(),this.timeOnPageTargets.forEach(e=>clearTimeout(e)),this.timeOnPageTargets.clear(),this.inactivityTargets.forEach(e=>clearTimeout(e)),this.inactivityTargets.clear(),this.inactivityCheckInterval&&(clearInterval(this.inactivityCheckInterval),this.inactivityCheckInterval=void 0),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0),this.isStarted=!1)}reset(){this.scrollDepthReached.clear(),this.exitIntentFired=!1,this.scrollVelocityFired=!1,this.backButtonFired=!1,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0)}attachScrollListener(){window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.handleScroll()}removeScrollListener(){window.removeEventListener("scroll",this.handleScroll)}attachExitIntentListener(){document.addEventListener("mouseleave",this.handleExitIntent)}removeExitIntentListener(){document.removeEventListener("mouseleave",this.handleExitIntent)}attachScrollVelocityListener(){window.addEventListener("scroll",this.handleScrollVelocity,{passive:!0})}removeScrollVelocityListener(){window.removeEventListener("scroll",this.handleScrollVelocity)}attachVisibilityChangeListener(){document.addEventListener("visibilitychange",this.handleVisibilityChange)}removeVisibilityChangeListener(){document.removeEventListener("visibilitychange",this.handleVisibilityChange)}attachBackButtonListener(){"undefined"!=typeof window&&window.history&&(window.history.pushState(null,"",window.location.href),window.addEventListener("popstate",this.handleBackButton))}removeBackButtonListener(){window.removeEventListener("popstate",this.handleBackButton)}attachActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.addEventListener(e,this.handleActivity,{passive:!0})})}removeActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.removeEventListener(e,this.handleActivity)})}startInactivityCheck(){this.inactivityCheckInterval=window.setInterval(()=>{const e=(Date.now()-this.lastActivityTime)/1e3;for(const[t]of this.inactivityTargets)if(e>=t){this.emit(`inactivity_${t}`,{idle_seconds:t,actual_idle_time:e});const n=this.inactivityTargets.get(t);n&&(clearTimeout(n),this.inactivityTargets.delete(t))}},1e3)}emit(e,t){const n={type:e,data:t,timestamp:Date.now()},i=this.listeners.get(e);i&&i.forEach(t=>{try{t(n)}catch(i){console.error(`Error in trigger callback for ${e}:`,i)}});const s=this.listeners.get("*");s&&s.forEach(e=>{try{e(n)}catch(t){console.error("Error in wildcard trigger callback:",t)}})}}const ee="aegis_fpc";class te extends Error{constructor(e,t){super(t),this.status=e,this.name="BootstrapError"}}const ne="aegis",ie=window[ne]||[],se=new j;if(Array.isArray(ie)){const e=ie._loadOptions;ie.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("function"==typeof se[t])try{se[t].apply(se,n)}catch(i){console.error(`[Aegis SDK] Error executing queued method "${t}":`,i)}else console.warn(`[Aegis SDK] Unknown method "${t}"`)}),(null==e?void 0:e.key)&&se.init(e.key,e.options).catch(e=>{console.error("[Aegis SDK] Initialization failed:",e)})}return window[ne]=se,window.Aegis=j,window.AegisMessageRuntime=class{constructor(e){this.initialized=!1,this.ownedTriggerEngine=null;const t=e.triggerEngine??new Z,n=!e.triggerEngine;n&&(this.ownedTriggerEngine=t),this.widgets=new Y({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,debugMode:e.debugMode,triggerEngine:t,ownsTriggerEngine:n,enablePrefetch:!1!==e.enableWidgetPrefetch,sourcePlatform:e.sourcePlatform}),this.inApp=new G({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,propertyId:e.propertyId,debugMode:e.debugMode,enableSSE:e.enableSSE,onInteractiveCampaign:e=>{this.widgets.renderInteractiveCampaign(e)}})}async initialize(){this.initialized||(this.initialized=!0,await Promise.all([this.inApp.initialize(),this.widgets.initialize()]))}async updateContactId(e){var t,n;null==(n=(t=this.inApp).updateContactId)||n.call(t,e),await this.widgets.updateContactId(e)}onClientEvent(e,t={}){var n,i;null==(i=(n=this.inApp).onClientEvent)||i.call(n,e,t)}notifyConversion(e){var t,n;null==(n=(t=this.inApp).notifyConversion)||n.call(t,e)}destroy(){var e,t;null==(t=(e=this.inApp).destroy)||t.call(e),this.widgets.destroy(),this.ownedTriggerEngine=null,this.initialized=!1}getCampaigns(){return this.inApp.campaigns??[]}},window.AegisPlacementManager=class{constructor(e){this.placements=new Map,this.slots=new Map,this.renderedSlots=new Set,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId,this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.enableSSE=!1!==e.enableSSE}async initialize(){this.isInitialized?this.log("AegisPlacements already initialized"):(await this.refreshPlacements(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisPlacements initialized successfully"))}register(e,t){const n={placementId:e,...t};this.slots.set(e,n),this.log(`Registered placement slot: ${e}`);const i=this.placements.get(e);i?this.renderSlot(n,i):t.fallbackContent&&this.renderFallback(n)}unregister(e){this.slots.delete(e),this.renderedSlots.delete(e),this.log(`Unregistered placement slot: ${e}`)}async refreshPlacements(){try{const e=Array.from(this.slots.keys());if(0===e.length)return void this.log("No registered slots, skipping refresh");const t=`${this.apiHost}/v1/placements/content?placement_ids=${e.join(",")}`,n={"X-Aegis-Write-Key":this.writeKey,"X-Device-Type":this.getDeviceType(),"X-Platform":"web"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n});if(!i.ok)throw new Error(`Failed to fetch placements: ${i.status}`);const s=await i.json();this.placements.clear();for(const o of s.placements||[])this.placements.set(o.placement_id,o);this.renderAllSlots(),this.log(`Refreshed ${this.placements.size} placements`)}catch(e){this.log(`Error refreshing placements: ${e}`,!0)}}renderAllSlots(){for(const[e,t]of this.slots.entries()){const n=this.placements.get(e);n?this.renderSlot(t,n):t.fallbackContent&&this.renderFallback(t)}}renderSlot(e,t){try{if("dynamic_injection"===t.content_type)this.renderDynamicInjection(t);else{const n=document.getElementById(e.containerId);if(!n)return void this.log(`Container not found: ${e.containerId}`,!0);switch(n.innerHTML="",t.content_type){case"banner":this.renderBanner(n,t);break;case"card":this.renderCard(n,t);break;case"carousel":this.renderCarousel(n,t);break;case"video":this.renderVideo(n,t);break;case"html":this.renderHTML(n,t);break;default:return void this.log(`Unknown content type: ${t.content_type}`,!0)}}this.renderedSlots.has(e.placementId)||(this.trackEvent(t.placement_id,t.variant_id,"impression"),this.renderedSlots.add(e.placementId)),e.onRender&&e.onRender(t),this.log(`Rendered placement: ${t.placement_id} (${t.content_type})`)}catch(n){this.log(`Error rendering placement: ${n}`,!0),e.onError&&e.onError(n)}}renderBanner(e,t){const{title:n,body:i,image_url:s,cta_text:o,cta_url:r,background_color:a,text_color:c}=t.content,d=document.createElement("div");if(d.className="aegis-placement-banner",d.style.cssText=`\n background: ${this.sanitizeColor(a||"#1a73e8")};\n color: ${this.sanitizeColor(c||"#ffffff")};\n padding: 24px;\n border-radius: 8px;\n display: flex;\n align-items: center;\n gap: 16px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,s){const e=document.createElement("img"),t=this.sanitizeUrl(s);t&&(e.src=t,e.alt="",e.style.cssText="width: 80px; height: 80px; border-radius: 8px; object-fit: cover;",d.appendChild(e))}const l=document.createElement("div");if(l.style.cssText="flex: 1;",n){const e=document.createElement("div");e.textContent=n,e.style.cssText="font-size: 18px; font-weight: 600; margin-bottom: 8px;",l.appendChild(e)}if(i){const e=document.createElement("div");e.textContent=i,e.style.cssText="font-size: 14px; opacity: 0.9;",l.appendChild(e)}if(d.appendChild(l),o&&r){const e=document.createElement("button");e.textContent=o,e.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(a||"#1a73e8")};\n border: none;\n padding: 12px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n white-space: nowrap;\n `,e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click");const e=this.sanitizeUrl(r);e&&(window.location.href=e)}),d.appendChild(e)}e.appendChild(d)}renderCard(e,t){const{title:n,body:i,image_url:s,cta_text:o,cta_url:r}=t.content,a=document.createElement("div");if(a.className="aegis-placement-card",a.style.cssText='\n background: white;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',s){const e=document.createElement("img"),t=this.sanitizeUrl(s);t&&(e.src=t,e.alt=n||"",e.style.cssText="width: 100%; height: 200px; object-fit: cover;",a.appendChild(e))}const c=document.createElement("div");if(c.style.cssText="padding: 20px;",n){const e=document.createElement("h3");e.textContent=n,e.style.cssText="margin: 0 0 12px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",c.appendChild(e)}if(i){const e=document.createElement("p");e.textContent=i,e.style.cssText="margin: 0 0 16px 0; font-size: 14px; color: #666; line-height: 1.5;",c.appendChild(e)}if(o&&r){const e=document.createElement("button");e.textContent=o,e.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n ",e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click");const e=this.sanitizeUrl(r);e&&(window.location.href=e)}),c.appendChild(e)}a.appendChild(c),e.appendChild(a)}renderCarousel(e,t){const{items:n}=t.content;if(!Array.isArray(n)||0===n.length)return void this.log("Carousel items empty or invalid",!0);const i=document.createElement("div");i.className="aegis-placement-carousel",i.style.cssText="\n display: flex;\n gap: 16px;\n overflow-x: auto;\n padding: 8px 0;\n scroll-behavior: smooth;\n -webkit-overflow-scrolling: touch;\n ";for(const s of n){const e=document.createElement("div");if(e.style.cssText='\n flex: 0 0 250px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n overflow: hidden;\n cursor: pointer;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',s.image_url){const t=document.createElement("img"),n=this.sanitizeUrl(s.image_url);n&&(t.src=n,t.alt=s.title||"",t.style.cssText="width: 100%; height: 150px; object-fit: cover;",e.appendChild(t))}const o=document.createElement("div");if(o.style.cssText="padding: 12px;",s.title){const e=document.createElement("div");e.textContent=s.title,e.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 4px; color: #1a1a1a;",o.appendChild(e)}if(s.price){const e=document.createElement("div");e.textContent=s.price,e.style.cssText="font-size: 16px; font-weight: 700; color: #1a73e8;",o.appendChild(e)}e.appendChild(o),s.url&&e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{item_index:n.indexOf(s)});const e=this.sanitizeUrl(s.url);e&&(window.location.href=e)}),i.appendChild(e)}e.appendChild(i)}renderVideo(e,t){const{video_url:n,poster_url:i,autoplay:s,muted:o}=t.content;if(!n)return void this.log("Video URL missing",!0);const r=this.sanitizeUrl(n);if(!r)return void this.log("Invalid video URL",!0);const a=document.createElement("video");if(a.src=r,a.controls=!0,a.autoplay=s||!1,a.muted=o||!1,a.style.cssText="width: 100%; border-radius: 8px;",i){const e=this.sanitizeUrl(i);e&&(a.poster=e)}a.addEventListener("play",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{action:"video_play"})}),e.appendChild(a)}renderHTML(e,t){const{html:n}=t.content;if(!n)return void this.log("HTML content missing",!0);const i=document.createElement("div");i.className="aegis-placement-html",i.innerHTML=this.sanitizeHTML(n);i.querySelectorAll("a").forEach(e=>{e.addEventListener("click",e=>{this.trackEvent(t.placement_id,t.variant_id,"click")})}),e.appendChild(i)}renderDynamicInjection(e){const{html:t}=e.content,n=e.css_selector,i=e.injection_mode||"replace";if(!n)return void this.log("CSS selector missing for dynamic injection",!0);if(!t)return void this.log("HTML content missing for dynamic injection",!0);let s=null;try{s=document.querySelector(n)}catch(r){return void this.log(`Invalid CSS selector: ${n}`,!0)}if(!s)return void this.log(`Target element not found for selector: ${n}`,!0);const o=document.createElement("div");o.className="aegis-dynamic-injection",o.setAttribute("data-placement-id",e.placement_id),o.setAttribute("data-variant-id",e.variant_id),o.innerHTML=this.sanitizeHTML(t);switch(o.querySelectorAll("a").forEach(t=>{t.addEventListener("click",()=>{this.trackEvent(e.placement_id,e.variant_id,"click")})}),i){case"replace":s.innerHTML="",s.appendChild(o),this.log(`Replaced content in ${n}`,!1);break;case"append":s.appendChild(o),this.log(`Appended content to ${n}`,!1);break;case"prepend":s.insertBefore(o,s.firstChild),this.log(`Prepended content to ${n}`,!1);break;default:return void this.log(`Unknown injection mode: ${i}`,!0)}this.log(`Dynamically injected content for ${e.placement_id} into ${n} (${i})`)}renderFallback(e){if(!e.fallbackContent)return;const t=document.getElementById(e.containerId);t&&(t.innerHTML=e.fallbackContent,this.log(`Rendered fallback content for: ${e.placementId}`))}async trackEvent(e,t,n,i={}){try{const s=`${this.apiHost}/v1/placements/track`,o={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Device-Type":this.getDeviceType(),"X-Platform":"web"};this.userId&&(o["X-User-ID"]=this.userId),this.contactId&&(o["X-Contact-ID"]=this.contactId),this.organizationId&&(o["X-Organization-ID"]=this.organizationId);const r={placement_id:e,variant_id:t,event_type:n,metadata:{device_type:this.getDeviceType(),platform:"web",...i}};fetch(s,{method:"POST",headers:o,body:JSON.stringify(r)}).catch(e=>this.log(`Track event failed: ${e}`,!0)),this.log(`Tracked ${n}: ${e}`)}catch(s){this.log(`Error tracking event: ${s}`,!0)}}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID",!0);const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("placement_content_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received placement content update: ${t.placement_id}`),this.refreshPlacements()}catch(t){this.log(`Error parsing SSE event: ${t}`,!0)}}),this.eventSource.addEventListener("heartbeat",e=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",e=>{var t;this.log("SSE connection error",!0),(null==(t=this.eventSource)?void 0:t.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up",!0);this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}getDeviceType(){const e=window.innerWidth;return e<768?"mobile_web":e<1024?"tablet_web":"desktop_web"}sanitizeUrl(e){try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked unsafe URL protocol: ${t.protocol}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-Fa-f]{3,6}$/.test(e)||/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/.test(e)||["white","black","red","blue","green","yellow","transparent"].includes(e.toLowerCase())?e:(this.log(`Invalid color: ${e}`,!0),"#000000")}sanitizeHTML(e){const t=window.DOMPurify;if(null==t?void 0:t.sanitize)return t.sanitize(e,{ALLOWED_TAGS:["a","b","br","div","em","h1","h2","h3","h4","h5","h6","i","img","li","ol","p","span","strong","u","ul","table","thead","tbody","tr","th","td","blockquote","hr","figure","figcaption","picture","source","video","section","article"],ALLOWED_ATTR:["href","target","rel","src","alt","width","height","class","id","style","title","loading","srcset","sizes","type","media","controls","poster"],ALLOW_DATA_ATTR:!1});this.log('DOMPurify not found — falling back to built-in sanitizer. For full HTML placement support, add <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.4/purify.min.js"><\/script>',!1);const n=document.createElement("div");return n.textContent=e,n.innerHTML}log(e,t=!1){(this.debugMode||t)&&console[t?"error":"log"](`[AegisPlacements] ${e}`)}destroy(){this.disconnectSSE(),this.slots.clear(),this.placements.clear(),this.renderedSlots.clear(),this.isInitialized=!1,this.log("AegisPlacements destroyed")}},window.TriggerEngine=Z,window.aegisBootstrap=async function(e,t){const n={writeKey:t.writeKey};t.currentOrigin&&(n.currentOrigin=t.currentOrigin),t.firstPartyCookieId&&(n.firstPartyCookieId=t.firstPartyCookieId),t.attestationToken&&(n.attestationToken=t.attestationToken),t.userAgent&&(n.userAgent=t.userAgent);const i=`${e.replace(/\/$/,"")}/v1/sdk/bootstrap`,s=async()=>fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"omit"});let o=await s();if(o.status>=500&&(await new Promise(e=>setTimeout(e,750)),o=await s()),401===o.status)throw new te(401,"writeKey not recognized or revoked");if(403===o.status)throw new te(403,"Origin validation failed — this writeKey is bound to a different property");if(!o.ok)throw new te(o.status,`Bootstrap failed: HTTP ${o.status}`);const r=await o.json();return function(e){if("undefined"==typeof document)return;const t=new Date;t.setDate(t.getDate()+730),document.cookie=`${ee}=${encodeURIComponent(e)};expires=${t.toUTCString()};path=/;SameSite=Lax`;try{window.localStorage.setItem(ee,e)}catch{}}(r.firstPartyCookieId),r},se}();
1
+ var Aegis=function(){"use strict";const e={workspace_id:null,batch_size:10,batch_interval:1e3,capture_utm:!0,capture_referrer:!0,auto_page_view:!1,session_timeout:30,debug:!1,respect_dnt:!0,cross_domain_tracking:!1,secure_cookie:!0,enable_offline_mode:!0,max_offline_events:100,retry_failed_requests:!0,max_retries:3,retry_backoff_multiplier:2,request_timeout:5e3,rate_limit_burst:100,rate_limit_per_second:20,auto_region_detection:!0,wait_for_consent:!1,enable_consent_mode:!1,integrate_onetrust:!1,integrate_cookiebot:!1,integrate_google_consent_mode:!1,default_consent:{analytics:!1,marketing:!1,functional:!0},initialized:!1,api_host:null,cell_endpoints:[],preferred_region:null,cookie_domain:null,plugins:[],active_cell:null};function t(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function n(){return`msg_${Date.now()}_${t().slice(0,8)}`}const i=new class{constructor(){this.enabled=!1,this.prefix="[Aegis SDK]"}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}debug(e,...t){this.enabled&&this.prefix}info(e,...t){this.enabled&&console.info(`${this.prefix} ${e}`,...t)}warn(e,...t){console.warn(`${this.prefix} ${e}`,...t)}error(e,...t){console.error(`${this.prefix} ${e}`,...t)}};class s{constructor(e){this.userId=null,this.traits={},this.storage=e,this.anonymousId=this.getOrCreateAnonymousId(),this.loadUserIdentity()}getOrCreateAnonymousId(){let e=this.storage.get("anon_id");return e?i.debug("Loaded existing anonymous ID:",e):(e=t(),this.storage.set("anon_id",e,365),i.debug("Created new anonymous ID:",e)),e}loadUserIdentity(){const e=this.storage.get("user_id"),t=this.storage.get("user_traits");if(e&&(this.userId=e,i.debug("Loaded user ID:",e)),t)try{this.traits=JSON.parse(t),i.debug("Loaded user traits:",this.traits)}catch(n){i.warn("Failed to parse stored traits:",n),this.traits={}}}getAnonymousId(){return this.anonymousId}setUserId(e,t){this.userId=e,this.storage.set("user_id",e,365),i.info("User identified:",e),t&&this.setTraits(t)}getUserId(){return this.userId}setTraits(e){this.traits={...this.traits,...e},this.storage.set("user_traits",JSON.stringify(this.traits),365),i.debug("User traits updated:",this.traits)}getTraits(){return{...this.traits}}reset(){this.userId=null,this.traits={},this.anonymousId=t(),this.storage.remove("user_id"),this.storage.remove("user_traits"),this.storage.set("anon_id",this.anonymousId,365),i.info("Identity reset, new anonymous ID:",this.anonymousId)}alias(e){const t=this.userId||this.anonymousId;return this.setUserId(e),i.info("User aliased:",{previousId:t,newUserId:e}),{previousId:t,newUserId:e}}getState(){return{anonymousId:this.anonymousId,userId:this.userId,traits:this.getTraits()}}}class o{constructor(e,t=30){this.eventCount=0,this.checkInterval=null,this.activityThrottle=1e3,this.lastActivityUpdate=0,this.adClickIDs={},this.storage=e,this.sessionTimeout=60*t*1e3,this.lastActivityTime=Date.now(),this.sessionStartTime=Date.now();const n=this.loadSession();n?(this.sessionId=n.sessionId,this.sessionStartTime=n.startTime,this.lastActivityTime=n.lastActivityTime,this.eventCount=n.eventCount,this.adClickIDs=n.adClickIDs||{},this.landingPage=n.landingPage,i.debug("Session loaded:",n)):this.sessionId=this.createNewSession(),this.startActivityTracking(),this.startExpiryCheck()}loadSession(){const e=this.storage.get("session");if(!e)return null;try{const t=JSON.parse(e);return Date.now()-t.lastActivityTime<this.sessionTimeout?t:(i.debug("Session expired, creating new session"),this.storage.remove("session"),null)}catch(t){return i.warn("Failed to parse session data:",t),this.storage.remove("session"),null}}createNewSession(){const e=`sess_${Date.now()}_${t().slice(0,8)}`;return this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.eventCount=0,this.persistSession(),i.info("New session created:",e),e}persistSession(){const e={sessionId:this.sessionId,startTime:this.sessionStartTime,lastActivityTime:this.lastActivityTime,eventCount:this.eventCount,adClickIDs:this.adClickIDs,landingPage:this.landingPage};this.storage.set("session",JSON.stringify(e))}startActivityTracking(){const e=()=>this.onActivity();["click","scroll","keypress","mousemove","touchstart"].forEach(t=>{window.addEventListener(t,e,{passive:!0})}),window.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.onActivity()})}startExpiryCheck(){this.checkInterval=window.setInterval(()=>{this.checkSessionExpiry()},6e4)}onActivity(){const e=Date.now();if(e-this.lastActivityUpdate<this.activityThrottle)return;this.lastActivityUpdate=e;e-this.lastActivityTime>this.sessionTimeout?(i.info("Session expired due to inactivity, creating new session"),this.sessionId=this.createNewSession()):(this.lastActivityTime=e,this.persistSession())}checkSessionExpiry(){Date.now()-this.lastActivityTime>this.sessionTimeout&&(i.info("Session expired during check, creating new session"),this.sessionId=this.createNewSession())}getSessionId(){return this.sessionId}incrementEventCount(){this.eventCount++,this.lastActivityTime=Date.now(),this.persistSession()}getSessionDuration(){return Date.now()-this.sessionStartTime}getEventCount(){return this.eventCount}getState(){return{sessionId:this.sessionId,startTime:this.sessionStartTime,lastActivityTime:this.lastActivityTime,eventCount:this.eventCount,adClickIDs:this.adClickIDs,landingPage:this.landingPage}}setAdClickIDs(e,t){Object.keys(e).length>0&&(this.adClickIDs={...this.adClickIDs,...e},t&&(this.landingPage=t),this.persistSession(),i.info("Ad click IDs stored in session:",this.adClickIDs))}getAdClickIDs(){return this.adClickIDs}getLandingPage(){return this.landingPage}destroy(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null)}}class r{constructor(e,t,n){this.buffer=[],this.flushInterval=null,this.isFlushing=!1,this.offlineQueue=[],this.isOnline=navigator.onLine,this.config=e,this.transport=t,this.storage=n,e.enableOfflineMode&&(this.loadOfflineQueue(),this.setupOnlineListener()),this.startFlushTimer(),this.setupUnloadHandlers()}loadOfflineQueue(){const e=this.storage.get("offline_queue");if(e)try{const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.offlineQueue=t.slice(0,this.config.maxOfflineEvents),i.info(`Loaded ${this.offlineQueue.length} offline events`),this.isOnline&&this.flushOfflineQueue())}catch(t){i.warn("Failed to load offline queue:",t),this.storage.remove("offline_queue")}}saveOfflineQueue(){if(0!==this.offlineQueue.length)try{const e=JSON.stringify(this.offlineQueue);this.storage.set("offline_queue",e),i.debug(`Saved ${this.offlineQueue.length} events to offline queue`)}catch(e){i.warn("Failed to save offline queue:",e)}else this.storage.remove("offline_queue")}setupOnlineListener(){window.addEventListener("online",()=>{i.info("Connection restored"),this.isOnline=!0,this.flushOfflineQueue(),this.flush()}),window.addEventListener("offline",()=>{i.warn("Connection lost, entering offline mode"),this.isOnline=!1})}async flushOfflineQueue(){if(0===this.offlineQueue.length)return;i.info(`Flushing ${this.offlineQueue.length} offline events`);const e=[...this.offlineQueue];this.offlineQueue=[],this.storage.remove("offline_queue");(await this.transport.send(e)).success?i.info("Offline events sent successfully"):(i.warn("Failed to send offline events, re-queueing"),this.offlineQueue=[...e,...this.offlineQueue].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue())}push(e){this.isOnline||!this.config.enableOfflineMode?(this.buffer.push(e),i.debug("Event queued:",e.type,e),this.buffer.length>=this.config.batchSize&&this.flush()):this.addToOfflineQueue(e)}addToOfflineQueue(e){this.offlineQueue.length>=this.config.maxOfflineEvents&&(i.warn("Offline queue full, dropping oldest event"),this.offlineQueue.shift()),this.offlineQueue.push(e),this.saveOfflineQueue(),i.debug("Event added to offline queue")}async flush(){if(this.isFlushing)return void i.debug("Flush already in progress, skipping");if(0===this.buffer.length)return;this.isFlushing=!0;const e=[...this.buffer];this.buffer=[],i.info(`Flushing ${e.length} events`);try{const t=await this.transport.send(e);t.success?i.info("Events sent successfully"):(i.error("Failed to send events:",t.error),this.config.enableOfflineMode?(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),i.info("Events saved to offline queue")):(this.buffer.unshift(...e),i.warn("Events re-queued for retry")))}catch(t){i.error("Flush error:",t),this.config.enableOfflineMode&&(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue())}finally{this.isFlushing=!1}}startFlushTimer(){this.flushInterval&&clearInterval(this.flushInterval),this.flushInterval=window.setInterval(()=>{this.flush()},this.config.batchInterval),i.debug(`Flush timer started with interval: ${this.config.batchInterval}ms`)}setupUnloadHandlers(){const e=()=>{(this.buffer.length>0||this.offlineQueue.length>0)&&(this.persistBufferToOfflineQueue(),this.flush())};document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&e()}),window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}persistBufferToOfflineQueue(){0!==this.buffer.length&&this.config.enableOfflineMode&&(this.offlineQueue=[...this.offlineQueue,...this.buffer].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),i.debug("Buffer persisted to offline queue before unload"))}getQueueSize(){return this.buffer.length}getOfflineQueueSize(){return this.offlineQueue.length}clear(){this.buffer=[],this.offlineQueue=[],this.storage.remove("offline_queue"),i.info("Queue cleared")}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}class a{constructor(e,t){this.activeCell=null,this.healthCheckInterval=null,this.regionLatencyMap=new Map,this.config=e,this.storage=t,e.cellEndpoints.length>0&&this.initializeCellularArchitecture()}async initializeCellularArchitecture(){const e=this.loadCachedCell();e&&this.isCellHealthy(e)?(this.activeCell=e,i.info("Using cached cell:",e)):await this.selectOptimalCell(),this.startHealthChecks()}loadCachedCell(){const e=this.storage.get("active_cell");if(!e)return null;try{return JSON.parse(e)}catch(t){return i.warn("Failed to parse cached cell:",t),null}}saveCachedCell(e){this.storage.set("active_cell",JSON.stringify(e),7)}isCellHealthy(e){return e.healthy&&this.config.cellEndpoints.some(t=>t.region===e.region&&t.url===e.url)}async selectOptimalCell(){if(i.info("Selecting optimal cell..."),this.config.preferredRegion){const e=this.config.cellEndpoints.find(e=>e.region===this.config.preferredRegion&&e.healthy);if(e)return this.activeCell=e,this.saveCachedCell(e),void i.info("Using preferred region cell:",e)}this.config.autoRegionDetection?await this.detectOptimalRegion():this.selectCellByPriority()}async detectOptimalRegion(){const e=this.config.cellEndpoints.filter(e=>e.healthy);if(0===e.length)return void i.error("No healthy cells available");const t=e.map(async e=>{const t=await this.measureLatency(e);return this.regionLatencyMap.set(e.region,t),{cell:e,latency:t}}),n=await Promise.all(t);n.sort((e,t)=>e.latency-t.latency);const s=n[0].cell;this.activeCell=s,this.saveCachedCell(s),i.info("Optimal cell selected:",{region:s.region,latency:n[0].latency})}async measureLatency(e){const t=performance.now();try{const n=new AbortController,i=setTimeout(()=>n.abort(),2e3),s=await fetch(`${e.url}/health`,{method:"GET",signal:n.signal});return clearTimeout(i),s.ok?performance.now()-t:1/0}catch(n){return i.warn(`Health check failed for ${e.region}:`,n),1/0}}selectCellByPriority(){const e=[...this.config.cellEndpoints].filter(e=>e.healthy).sort((e,t)=>e.priority-t.priority);e.length>0?(this.activeCell=e[0],this.saveCachedCell(e[0]),i.info("Cell selected by priority:",e[0])):i.error("No healthy cells available")}startHealthChecks(){this.healthCheckInterval=window.setInterval(()=>{this.performHealthChecks()},6e4)}async performHealthChecks(){const e=this.config.cellEndpoints.map(async e=>{const t=await this.checkCellHealth(e);return e.healthy=t,{cell:e,isHealthy:t}}),t=await Promise.all(e);this.activeCell&&!this.activeCell.healthy&&(i.warn("Active cell unhealthy, selecting new cell"),await this.selectOptimalCell()),i.debug("Health check results:",t)}async checkCellHealth(e){try{const t=new AbortController,n=setTimeout(()=>t.abort(),3e3),i=await fetch(`${e.url}/health`,{method:"GET",signal:t.signal});return clearTimeout(n),i.ok}catch(t){return!1}}async send(e){if(0===e.length)return{success:!0};const t=this.getActiveEndpoint(),n=this.buildPayload(e);if(i.debug("Sending batch:",{endpoint:t,eventCount:e.length}),"hidden"===document.visibilityState&&"function"==typeof navigator.sendBeacon){const e=this.sendViaBeacon(t,n);return Promise.resolve(e)}return this.sendViaFetch(t,n)}getActiveEndpoint(){if(this.activeCell)return`${this.activeCell.url}/v1/batch`;if(this.config.apiHost)return`${this.config.apiHost}/v1/batch`;throw new Error("No active endpoint available")}buildPayload(e){return{batch:e,sentAt:(new Date).toISOString(),writeKey:this.config.writeKey,context:this.activeCell?{cell:{region:this.activeCell.region,endpoint:this.activeCell.url}}:void 0}}sendViaBeacon(e,t){try{const n=new Blob([JSON.stringify(t)],{type:"application/json"});return navigator.sendBeacon(e,n)?(i.debug("Batch sent via Beacon"),{success:!0,endpoint:e}):(i.warn("Beacon send failed, falling back to fetch"),this.sendViaFetch(e,t))}catch(n){return i.error("Beacon send error:",n),{success:!1,error:n,endpoint:e}}}async sendViaFetch(e,t,n=1){try{const s=new AbortController,o=setTimeout(()=>s.abort(),this.config.requestTimeout),r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.writeKey}`},body:JSON.stringify(t),keepalive:!0,signal:s.signal});if(clearTimeout(o),r.ok){const t=await r.json();return i.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const s=await r.text(),o=new Error(`HTTP ${r.status}: ${s||r.statusText}`);return i.error("Batch send failed:",o),this.shouldRetry(r.status,n)?this.retryRequest(e,t,n):{success:!1,error:o,endpoint:e}}}catch(s){return i.error("Fetch error:",s),this.shouldRetry(0,n)?this.retryRequest(e,t,n):{success:!1,error:s,endpoint:e}}}shouldRetry(e,t){return!!this.config.retryFailedRequests&&(!(t>=this.config.maxRetries)&&(0===e||(e>=500||429===e)))}async retryRequest(e,t,n){const s=1e3*Math.pow(this.config.retryBackoffMultiplier,n);return i.info(`Retrying request in ${s}ms (attempt ${n+1})`),await new Promise(e=>setTimeout(e,s)),this.sendViaFetch(e,t,n+1)}getActiveCell(){return this.activeCell}getRegionLatencies(){return new Map(this.regionLatencyMap)}destroy(){this.healthCheckInterval&&(clearInterval(this.healthCheckInterval),this.healthCheckInterval=null)}}const c="aegis_";class d{constructor(e={}){this.options=e,this.useLocalStorage=this.isLocalStorageAvailable()}isLocalStorageAvailable(){try{const e="__aegis_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}set(e,t,n=365){const i=c+e;if(this.useLocalStorage)try{const e={value:t,expiry:Date.now()+24*n*60*60*1e3};localStorage.setItem(i,JSON.stringify(e))}catch(s){console.warn("[Aegis Storage] localStorage.setItem failed:",s)}this.setCookie(i,t,n)}get(e){const t=c+e;if(this.useLocalStorage)try{const e=localStorage.getItem(t);if(e){const n=JSON.parse(e);if(Date.now()<n.expiry)return n.value;localStorage.removeItem(t)}}catch(n){console.warn("[Aegis Storage] localStorage.getItem failed:",n)}return this.getCookie(t)}remove(e){const t=c+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch(n){console.warn("[Aegis Storage] localStorage.removeItem failed:",n)}this.deleteCookie(t)}clear(){if(this.useLocalStorage)try{Object.keys(localStorage).forEach(e=>{e.startsWith(c)&&localStorage.removeItem(e)})}catch(e){console.warn("[Aegis Storage] localStorage.clear failed:",e)}document.cookie.split(";").forEach(e=>{const t=e.split("=")[0].trim();t.startsWith(c)&&this.deleteCookie(t)})}setCookie(e,t,n){try{const i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3);let s=`${e}=${t};${`expires=${i.toUTCString()}`};path=/`;if(this.options.secureCookie&&"https:"===window.location.protocol&&(s+=";Secure"),s+=";SameSite=Lax",this.options.cookieDomain)s+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(s+=`;domain=${e}`)}document.cookie=s}catch(i){console.warn("[Aegis Storage] setCookie failed:",i)}}getCookie(e){try{const t=e+"=",n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(t))return i.substring(t.length,i.length)}}catch(t){console.warn("[Aegis Storage] getCookie failed:",t)}return null}deleteCookie(e){try{let t=`${e}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;if(this.options.cookieDomain)t+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(t+=`;domain=${e}`)}document.cookie=t}catch(t){console.warn("[Aegis Storage] deleteCookie failed:",t)}}getRootDomain(){try{const e=window.location.hostname;if(/^(\d{1,3}\.){3}\d{1,3}$/.test(e))return null;if("localhost"===e)return null;const t=e.split(".");return t.length<=2?`.${e}`:`.${t.slice(-2).join(".")}`}catch(e){return console.warn("[Aegis Storage] getRootDomain failed:",e),null}}}function l(e,t){const n=e.capture_utm?function(e){try{const t=e?new URL(e).searchParams:new URLSearchParams(window.location.search),n={};return["source","medium","campaign","term","content","name"].forEach(e=>{const i=t.get(`utm_${e}`);i&&(n[e]=i)}),n}catch(t){return console.warn("[Aegis URL Parser] parseUTMParameters failed:",t),{}}}():void 0,i=function(){const e=navigator.userAgent;if(/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e))return{type:"tablet"};if(/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e))return{type:"mobile"};return{type:"desktop"}}(),s=function(){const e=navigator.userAgent;if(/Windows NT 10/i.test(e))return{name:"Windows",version:"10"};if(/Windows NT 6.3/i.test(e))return{name:"Windows",version:"8.1"};if(/Windows NT 6.2/i.test(e))return{name:"Windows",version:"8"};if(/Windows NT 6.1/i.test(e))return{name:"Windows",version:"7"};if(/Windows/i.test(e))return{name:"Windows",version:"Unknown"};if(/Mac OS X (\d+)[._](\d+)/.test(e)){const t=e.match(/Mac OS X (\d+)[._](\d+)/);return{name:"macOS",version:`${t[1]}.${t[2]}`}}if(/Mac/i.test(e))return{name:"macOS",version:"Unknown"};if(/Android (\d+\.\d+)/.test(e)){return{name:"Android",version:e.match(/Android (\d+\.\d+)/)[1]}}if(/Android/i.test(e))return{name:"Android",version:"Unknown"};if(/iPhone OS (\d+)_(\d+)/.test(e)){const t=e.match(/iPhone OS (\d+)_(\d+)/);return{name:"iOS",version:`${t[1]}.${t[2]}`}}if(/iPad.*OS (\d+)_(\d+)/.test(e)){const t=e.match(/iPad.*OS (\d+)_(\d+)/);return{name:"iOS",version:`${t[1]}.${t[2]}`}}return/iPhone|iPad/i.test(e)?{name:"iOS",version:"Unknown"}:/Linux/i.test(e)?{name:"Linux",version:"Unknown"}:{name:"Unknown",version:"Unknown"}}(),o=function(){const e=navigator.userAgent;if(/Edg\/(\d+\.\d+)/.test(e)){return{name:"Edge",version:e.match(/Edg\/(\d+\.\d+)/)[1]}}if(/Chrome\/(\d+\.\d+)/.test(e)&&!/Edg/.test(e)){return{name:"Chrome",version:e.match(/Chrome\/(\d+\.\d+)/)[1]}}if(/Firefox\/(\d+\.\d+)/.test(e)){return{name:"Firefox",version:e.match(/Firefox\/(\d+\.\d+)/)[1]}}if(/Safari\/(\d+\.\d+)/.test(e)&&!/Chrome/.test(e)){const t=e.match(/Version\/(\d+\.\d+)/);return{name:"Safari",version:t?t[1]:"Unknown"}}if(/MSIE (\d+\.\d+)/.test(e)||/Trident\//.test(e)){const t=e.match(/MSIE (\d+\.\d+)/)||e.match(/rv:(\d+\.\d+)/);return{name:"Internet Explorer",version:t?t[1]:"Unknown"}}return{name:"Unknown",version:"Unknown"}}(),r=function(){try{const e=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(e)return{effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt}}catch(e){console.warn("[Aegis Device] detectNetworkInfo failed:",e)}return}(),a=null==t?void 0:t.getAdClickIDs(),c=null==t?void 0:t.getLandingPage();return{library:{name:"@active-reach/web-sdk",version:"1.0.0"},page:{path:window.location.pathname,referrer:e.capture_referrer?document.referrer:"",search:window.location.search,title:document.title,url:window.location.href,hash:window.location.hash},userAgent:navigator.userAgent,locale:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,screen:{width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio||1},viewport:{width:window.innerWidth,height:window.innerHeight},...n&&Object.keys(n).length>0&&{campaign:n},...a&&Object.keys(a).length>0&&{adClickIDs:a},...c&&{landingPage:c},...r&&{network:r},...i&&{device:i},...s&&{os:s},...o&&{browser:o},...e.active_cell&&{cell:{region:e.active_cell.region,endpoint:e.active_cell.url}}}}class h{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.name)?i.warn(`Plugin "${e.name}" already registered, skipping`):(this.plugins.set(e.name,e),i.info(`Plugin registered: ${e.name} v${e.version}`))}unregister(e){const t=this.plugins.get(e);if(t){if(t.destroy)try{t.destroy()}catch(n){i.error(`Error destroying plugin "${e}":`,n)}this.plugins.delete(e),i.info(`Plugin unregistered: ${e}`)}else i.warn(`Plugin "${e}" not found`)}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}async executeHook(e,...t){for(const o of this.plugins.values()){const r=o[e];if("function"==typeof r)try{const e=await r.apply(o,t);if(void 0!==e)return e}catch(n){if(i.error(`Error executing ${String(e)} in plugin "${o.name}":`,n),o.onError)try{o.onError(n,{hookName:e,args:t})}catch(s){i.error(`Error in onError handler for plugin "${o.name}":`,s)}}}}async executeHookChain(e,t,...n){let s=t;for(const a of this.plugins.values()){const t=a[e];if("function"==typeof t)try{const e=await t.apply(a,[s,...n]);null!=e&&(s=e)}catch(o){if(i.error(`Error executing ${String(e)} in plugin "${a.name}":`,o),a.onError)try{a.onError(o,{hookName:e,value:s,additionalArgs:n})}catch(r){i.error(`Error in onError handler for plugin "${a.name}":`,r)}}}return s}async executeHookParallel(e,...t){const n=[];for(const s of this.plugins.values()){const o=s[e];if("function"==typeof o){const r=(async()=>{try{return await o.apply(s,t)}catch(n){if(i.error(`Error executing ${String(e)} in plugin "${s.name}":`,n),s.onError)try{s.onError(n,{hookName:e,args:t})}catch(r){i.error(`Error in onError handler for plugin "${s.name}":`,r)}return}})();n.push(r)}}return(await Promise.all(n)).filter(e=>void 0!==e)}clear(){for(const t of this.plugins.values())if(t.destroy)try{t.destroy()}catch(e){i.error(`Error destroying plugin "${t.name}":`,e)}this.plugins.clear(),i.info("All plugins cleared")}}class p{constructor(e,t={}){this.listeners=[],this.storage=e,this.config={defaultConsent:t.defaultConsent||{},waitForConsent:t.waitForConsent??!1,consentStorageKey:t.consentStorageKey||"aegis_consent"},this.preferences=this.loadPreferences()}loadPreferences(){const e=this.storage.get(this.config.consentStorageKey);if(e)try{const t=JSON.parse(e);return i.info("Loaded consent preferences:",t),this.mergeWithDefaults(t)}catch(t){i.warn("Failed to parse consent preferences:",t)}return this.getDefaultPreferences()}getDefaultPreferences(){return{analytics:this.config.defaultConsent.analytics??!1,marketing:this.config.defaultConsent.marketing??!1,functional:this.config.defaultConsent.functional??!0,necessary:!0}}mergeWithDefaults(e){return{necessary:!0,analytics:e.analytics??this.config.defaultConsent.analytics??!1,marketing:e.marketing??this.config.defaultConsent.marketing??!1,functional:e.functional??this.config.defaultConsent.functional??!0}}savePreferences(){try{this.storage.set(this.config.consentStorageKey,JSON.stringify(this.preferences),365),i.info("Saved consent preferences:",this.preferences)}catch(e){i.error("Failed to save consent preferences:",e)}}setConsent(e){const t={...this.preferences,...e};t.necessary=!0,this.preferences=t,this.savePreferences(),this.notifyListeners(),i.info("Consent updated:",this.preferences)}grantAll(){this.setConsent({analytics:!0,marketing:!0,functional:!0,necessary:!0})}denyAll(){this.setConsent({analytics:!1,marketing:!1,functional:!1,necessary:!0})}hasConsent(e){return this.preferences[e]}getPreferences(){return{...this.preferences}}getStatus(e){if(this.hasConsent(e))return"granted";return!this.storage.get(this.config.consentStorageKey)&&this.config.waitForConsent?"pending":"denied"}isAnalyticsEnabled(){return this.hasConsent("analytics")}isMarketingEnabled(){return this.hasConsent("marketing")}onChange(e){return this.listeners.push(e),()=>{const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}}notifyListeners(){this.listeners.forEach(e=>{try{e(this.getPreferences())}catch(t){i.error("Consent listener error:",t)}})}reset(){this.storage.remove(this.config.consentStorageKey),this.preferences=this.getDefaultPreferences(),this.notifyListeners(),i.info("Consent preferences reset")}integrateOneTrust(){if("undefined"==typeof window)return;if(!window.OneTrust)return void i.warn("OneTrust not detected");const e=()=>{const e=window.OnetrustActiveGroups||"";this.setConsent({necessary:!0,functional:e.includes("C0003"),analytics:e.includes("C0002"),marketing:e.includes("C0004")}),i.info("Synced with OneTrust consent")};if(window.OptanonWrapper){const t=window.OptanonWrapper;window.OptanonWrapper=function(){t(),e()}}else window.OptanonWrapper=e;e()}integrateCookiebot(){if("undefined"==typeof window)return;const e=window.Cookiebot;if(!e)return void i.warn("Cookiebot not detected");const t=()=>{const t=e.consent||{};this.setConsent({necessary:!0,functional:t.preferences||!1,analytics:t.statistics||!1,marketing:t.marketing||!1}),i.info("Synced with Cookiebot consent")};window.addEventListener("CookiebotOnAccept",t),window.addEventListener("CookiebotOnDecline",t),e.consent&&t()}integrateGoogleConsentMode(){if("undefined"==typeof window)return;const e=window.gtag;if(!e)return void i.warn("Google Tag Manager not detected");const t=()=>{e("consent","update",{ad_storage:this.preferences.marketing?"granted":"denied",analytics_storage:this.preferences.analytics?"granted":"denied",ad_user_data:this.preferences.marketing?"granted":"denied",ad_personalization:this.preferences.marketing?"granted":"denied",functionality_storage:this.preferences.functional?"granted":"denied",personalization_storage:this.preferences.functional?"granted":"denied",security_storage:"granted"}),i.info("Updated Google Consent Mode")};this.onChange(t),t()}}const u="_fbp",g="_fbc";function m(e){if("undefined"==typeof document)return null;try{const t=`${e}=`,n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length))}}catch{}return null}function f(e,t,n){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const i=new Date(Date.now()+24*n*60*60*1e3).toUTCString(),s=function(){if("undefined"==typeof window)return null;const e=window.location.hostname;if(!e||"localhost"===e)return null;if(/^\d+\.\d+\.\d+\.\d+$/.test(e))return null;const t=e.split(".");return t.length<2?null:"."+t.slice(-2).join(".")}(),o="https:"===window.location.protocol;let r=`${e}=${encodeURIComponent(t)};expires=${i};path=/;SameSite=Lax`;o&&(r+=";Secure"),s&&(r+=`;domain=${s}`),document.cookie=r}catch{}}function y(){if("undefined"==typeof window)return 1;const e=window.location.hostname;if(!e||"localhost"===e||/^\d+\.\d+\.\d+\.\d+$/.test(e))return 1;const t=e.split(".");return Math.max(1,t.length-1)}function x(){const e=m(u);if(e)return e;const t=`fb.${y()}.${Date.now()}.${Math.floor(1e10*Math.random()).toString().padStart(10,"0")}`;return f(u,t,90),t}function b(){const e=m(g);if(e)return e;const t=v();if(!t)return null;const n=`fb.${y()}.${Date.now()}.${t}`;return f(g,n,90),n}function v(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get("fbclid")}catch{return null}}function w(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function _(e){return e.map(e=>({product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency,category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label,position:e.position}))}class C{constructor(e){this.aegis=e}productViewed(e){this.aegis.track("product_viewed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label,image_url:e.image_url,url:e.url})}productListViewed(e){this.aegis.track("product_list_viewed",{list_id:e.list_id,list_name:e.list_name,category:e.category,products:_(e.products)})}productClicked(e,t){this.aegis.track("product_clicked",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}productImpressed(e,t){this.aegis.track("product_impression",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}categoryFiltered(e,t){this.aegis.track("category_filtered",{category:e,previous_category:null==t?void 0:t.previous_category,result_count:null==t?void 0:t.result_count})}searchPerformed(e){this.aegis.track("search_performed",{query:e.query,results_count:e.results_count,filters:e.filters})}addToCart(e){this.aegis.track("cart_item_added",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label})}removeFromCart(e){this.aegis.track("cart_item_removed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",variant_id:e.variant_id})}cartViewed(e){this.aegis.track("cart_viewed",{cart_id:e.cart_id,value:e.value,currency:e.currency??"INR",num_items:w(e.products),products:_(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:w(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:_(e.products)})}checkoutStep(e,t){this.aegis.track("checkout_step",{step:e,...t})}orderCompleted(e){this.aegis.track("order_completed",{order_id:e.order_id,value:e.value,revenue:e.revenue??e.value,currency:e.currency??"INR",num_items:w(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:_(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?_(n):void 0})}couponApplied(e){this.aegis.track("coupon_applied",{...e})}couponRemoved(e){this.aegis.track("coupon_removed",{...e})}wishlistItemAdded(e){this.aegis.track("wishlist_item_added",{wishlist_id:e.wishlist_id,wishlist_name:e.wishlist_name,product_id:e.product.product_id,sku:e.product.sku??e.product.product_id,name:e.product.name,price:e.product.price,variant_id:e.product.variant_id})}promotionViewed(e){this.aegis.track("promotion_viewed",{...e})}promotionClicked(e){this.aegis.track("promotion_clicked",{...e})}}class k{constructor(e={}){this.droppedThisWindow=0,this.firstDroppedName=null,this.windowFlushTimer=null,this.capacity=Math.max(1,e.burstCapacity??100),this.refillPerSecond=Math.max(1,e.refillPerSecond??20),this.windowMs=e.dropCoalesceWindowMs??1e3,this.onDropBatch=e.onDropBatch,this.tokens=this.capacity,this.lastRefillMs=Date.now()}tryConsume(e){return this.refill(),this.tokens>=1?(this.tokens-=1,!0):(this.droppedThisWindow+=1,null===this.firstDroppedName&&(this.firstDroppedName=e,i.warn(`[Aegis] Rate limit reached — dropping event "${e}" and any further events for ${this.windowMs}ms. Burst=${this.capacity}, refill=${this.refillPerSecond}/s.`)),this.windowFlushTimer||(this.windowFlushTimer=setTimeout(()=>this.flushWindow(),this.windowMs)),!1)}getAvailableTokens(){return this.refill(),Math.floor(this.tokens)}destroy(){this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.flushWindow()}refill(){const e=Date.now(),t=(e-this.lastRefillMs)/1e3;if(t<=0)return;const n=t*this.refillPerSecond;this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefillMs=e}flushWindow(){if(this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.droppedThisWindow>0&&this.onDropBatch)try{this.onDropBatch(this.droppedThisWindow,this.firstDroppedName)}catch(e){i.warn("[Aegis] RateLimiter.onDropBatch threw:",e)}this.droppedThisWindow=0,this.firstDroppedName=null}}const S=3432918353,E=461845907;function I(e,t=0){return function(e,t=0){const n=e.length,i=Math.floor(n/4);let s=t>>>0;for(let c=0;c<i;c++){const t=4*c;let n=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;n=Math.imul(n,S),n=n<<15|n>>>17,n=Math.imul(n,E),s^=n,s=s<<13|s>>>19,s=Math.imul(s,5)+3864292196>>>0}const o=4*i;let r=0;const a=n-o;3===a&&(r^=e[o+2]<<16);a>=2&&(r^=e[o+1]<<8);a>=1&&(r^=e[o],r=Math.imul(r,S),r=r<<15|r>>>17,r=Math.imul(r,E),s^=r);return s^=n,s^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}((new TextEncoder).encode(e),t)}class T{constructor(e,t){if(this.params=t,t.m&t.m-1)throw new Error(`Bloom filter m must be a power of 2, got ${t.m}`);if(e.length!==t.m>>3)throw new Error(`Bloom filter buffer size mismatch: expected ${t.m>>3} bytes, got ${e.length}`);this.buf=e,this.mask=t.m-1}static fromBase64(e,t){const n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const t=globalThis.Buffer;if(t&&"function"==typeof t.from){const n=t.from(e,"base64");return new Uint8Array(n)}throw new Error("No base64 decoder available (neither atob nor Buffer)")}(e);return new T(n,t)}has(e){const t=I(e,this.params.seedA),n=I(e,this.params.seedB);for(let i=0;i<this.params.k;i++){const e=t+Math.imul(i,n)>>>0&this.mask;if(0===(this.buf[e>>3]&1<<(7&e)))return!1}return!0}}class z{constructor(){this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,this.localNovelNames=new Set,this.droppedSinceLastReport=new Map,this.reportWindowStart=Date.now(),this.hasWarnedThisSession=!1}ingestHint(e){if(!e||"mmh3_x86_32_km"!==e.bloom_algo)return this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,void this.localNovelNames.clear();try{this.bloom=T.fromBase64(e.bloom_b64,{m:e.m,k:e.k,seedA:e.seed_a,seedB:e.seed_b})}catch{this.bloom=null}this.remainingNewNames=e.remaining_new_names??1/0,this.graceActive=!0===e.grace_active,this.localNovelNames.clear()}shouldSend(e){if(!this.bloom)return!0;if(this.graceActive)return!0;if(this.bloom.has(e))return!0;if(this.localNovelNames.has(e))return!0;if(this.remainingNewNames>0)return this.localNovelNames.add(e),this.remainingNewNames-=1,!0;const t=this.droppedSinceLastReport.get(e)??0;var n;return this.droppedSinceLastReport.set(e,t+1),this.hasWarnedThisSession||(this.hasWarnedThisSession=!0,n=`[aegis] Event-name cap reached — "${e}" dropped locally. Upgrade your plan or remove dynamically-generated event names.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(n)),!1}drainDropReport(){if(0===this.droppedSinceLastReport.size)return null;const e={};let t=0;for(const[i,s]of this.droppedSinceLastReport)e[i]=s,t+=s;const n=this.reportWindowStart;return this.droppedSinceLastReport.clear(),this.reportWindowStart=Date.now(),{events:e,total:t,since:n}}_debugState(){return{hasBloom:null!==this.bloom,remaining:this.remainingNewNames,localNovel:this.localNovelNames.size,graceActive:this.graceActive}}}const A=["system.","user.","loyalty.","review.","cart.","checkout.","product.","pos.","bill.","feedback.","chat.","delivery.","event.","$","_"],$=/(.)([A-Z][a-z]+)/g,D=/([a-z0-9])([A-Z])/g,L=/[\s\-.]+/g,M=/_+/g,P=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/,O=new Set(["at","on","date","time","timestamp","dob","birthday","joined","expired","expires","created","updated","started","ended"]);function F(e){if(!e)return null;return e.replace($,"$1_$2").replace(D,"$1_$2").replace(L,"_").toLowerCase().replace(M,"_").replace(/^_+|_+$/g,"")||null}function N(e){const t=e.toLowerCase();for(const n of A)if(t.startsWith(n))return n;return null}function R(e){for(const t of e.toLowerCase().split(/[_\-.\s]+/))if(O.has(t))return!0;return!1}function U(e){if("number"==typeof e&&Number.isFinite(e))return e<1e11?Math.floor(1e3*e):Math.floor(e);if("string"==typeof e&&e){const t=e.trim();if(P.test(t)){const e=Date.parse(t);if(!Number.isNaN(e))return e}const n=Number(t);if(Number.isFinite(n))return n<1e11?Math.floor(1e3*n):Math.floor(n)}return null}const B=class e{constructor(){this.warnCounts=new Map}process(e,t){const n={},i=[];if(!e||"object"!=typeof e)return{sanitized:n,drops:i};for(const s of Object.keys(e)){const t=N(s);if(null!==t){i.push({originalKey:s,verdict:"reserved_prefix",reason:`key uses reserved namespace ${JSON.stringify(t)}`});continue}const o=F(s);if(null===o){i.push({originalKey:s,verdict:"bad_key_format",reason:"key reduced to empty after normalization"});continue}if(null!==N(o)){i.push({originalKey:s,verdict:"reserved_prefix",reason:`normalized key ${JSON.stringify(o)} still uses a reserved namespace`});continue}let r=e[s];if("string"==typeof r){if(r.length>1e4){i.push({originalKey:s,verdict:"value_too_long",reason:`value length ${r.length} exceeds hard cap 10000`});continue}r.length>512&&(i.push({originalKey:s,verdict:"value_too_long",reason:`value truncated from ${r.length} to 512 chars`}),r=r.slice(0,512))}if(R(o)&&"string"==typeof r){const e=U(r);if(null===e){i.push({originalKey:s,verdict:"bad_date_format",reason:`value ${JSON.stringify(r)} on date-keyed field ${JSON.stringify(o)} didn't parse as ISO-8601 / epoch`});continue}r=e}n[o]=r}for(const s of i)this.maybeWarn(t??null,s);return{sanitized:n,drops:i}}maybeWarn(t,n){const i=t??"__no_workspace__";let s=this.warnCounts.get(i);s||(s=new Map,this.warnCounts.set(i,s));const o=s.get(n.verdict)??0;var r;o>=e.WARN_CAP||(s.set(n.verdict,o+1),r=`[Aegis SDK] trait ${n.verdict}: ${n.reason} (original key: ${JSON.stringify(n.originalKey)}). Backend will reject; fix the SDK call to silence this warning.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(r))}};B.WARN_CAP=3;let W=B;class j{constructor(){this.config=null,this.session=null,this.queue=null,this.transport=null,this.plugins=new h,this.initPromise=null,this.consent=null,this._ecommerce=null,this.rateLimiter=null,this.nameGovernor=new z,this.traitGovernor=new W,this._lastPageUrl=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._lastEventIds=new Map}async init(e,t){return this.initPromise||(this.initPromise=this._init(e,t)),this.initPromise}async _init(e,t){var n;(null==(n=this.config)?void 0:n.initialized)?i.warn("SDK already initialized"):this.shouldRespectDNT(t)?i.info("Do Not Track is enabled, SDK disabled"):!function(){const e=navigator.userAgent.toLowerCase();return["bot","crawl","spider","slurp","mediapartners","googlebot","bingbot","yahoo","duckduckbot","baiduspider","yandex","facebookexternalhit","linkedinbot","twitterbot","slackbot","telegrambot","whatsapp","pingdom","uptimerobot"].some(t=>e.includes(t))}()?(this.config=this.buildConfig(e,t),this.config.debug&&i.enable(),i.info("Initializing Aegis SDK...",this.config),this.storage=new d({cookieDomain:this.config.cookie_domain,secureCookie:this.config.secure_cookie,crossDomain:this.config.cross_domain_tracking}),this.identity=new s(this.storage),this.consent=new p(this.storage,{defaultConsent:this.config.default_consent,waitForConsent:this.config.wait_for_consent}),this.config.integrate_onetrust&&this.consent.integrateOneTrust(),this.config.integrate_cookiebot&&this.consent.integrateCookiebot(),this.config.integrate_google_consent_mode&&this.consent.integrateGoogleConsentMode(),this.session=new o(this.storage,this.config.session_timeout),this.captureAdClickIDsOnInit(),this.transport=new a({writeKey:this.config.write_key,apiHost:this.config.api_host,cellEndpoints:this.config.cell_endpoints,preferredRegion:this.config.preferred_region,autoRegionDetection:this.config.auto_region_detection,requestTimeout:this.config.request_timeout,retryFailedRequests:this.config.retry_failed_requests,maxRetries:this.config.max_retries,retryBackoffMultiplier:this.config.retry_backoff_multiplier},this.storage),this.config.active_cell=this.transport.getActiveCell(),this.queue=new r({batchSize:this.config.batch_size,batchInterval:this.config.batch_interval,enableOfflineMode:this.config.enable_offline_mode,maxOfflineEvents:this.config.max_offline_events},this.transport,this.storage),this.rateLimiter=new k({burstCapacity:this.config.rate_limit_burst,refillPerSecond:this.config.rate_limit_per_second,onDropBatch:(e,t)=>this.emitRateLimitMeta(e,t)}),await this.initializePlugins(),this.config.auto_page_view&&(this.page(),this.startSPATracking()),i.info("Aegis SDK initialized successfully")):i.info("Bot detected, SDK disabled")}startSPATracking(){this._lastPageUrl=window.location.href;const e=()=>{const e=window.location.href;e!==this._lastPageUrl&&(this._lastPageUrl=e,setTimeout(()=>{this.page()},50))};this._popstateHandler=e,window.addEventListener("popstate",this._popstateHandler),this._originalPushState=history.pushState.bind(history),this._originalReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this._originalPushState(...t),e()},history.replaceState=(...t)=>{this._originalReplaceState(...t),e()}}stopSPATracking(){this._popstateHandler&&(window.removeEventListener("popstate",this._popstateHandler),this._popstateHandler=null),this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null)}buildConfig(t,n){return{...e,...n,write_key:t,initialized:!0}}shouldRespectDNT(e){if(!(!1!==(null==e?void 0:e.respect_dnt)))return!1;const t=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===t||"yes"===t}captureAdClickIDsOnInit(){if(!this.session)return;const e=function(e){try{const t=e?new URL(e).searchParams:new URLSearchParams(window.location.search),n={};return["gclid","fbclid","msclkid","ctwa_clid","ttclid","li_fat_id"].forEach(e=>{const i=t.get(e);i&&(n[e]=i)}),n}catch(t){return console.warn("[Aegis URL Parser] parseAdClickIDs failed:",t),{}}}();(function(e){return Object.keys(e).length>0})(e)&&(this.session.setAdClickIDs(e,window.location.href),i.info("Ad click IDs captured on page load:",e))}async initializePlugins(){if(this.config){for(const e of this.config.plugins)i.debug(`Initializing plugin: ${e}`);await this.plugins.executeHook("init",this.config)}}use(e){var t;this.plugins.register(e),(null==(t=this.config)?void 0:t.initialized)&&e.init&&Promise.resolve(e.init(this.config)).catch(t=>{i.error(`Failed to initialize plugin "${e.name}":`,t)})}track(e,t){if(!this.assertInitialized())return;const i=n(),s={type:"track",event:e,properties:t||{},messageId:i,timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this._lastEventIds.set(e,i),this.captureEvent(s)}identify(e,t){if(!this.assertInitialized())return;const i=this.config.workspace_id||null,{sanitized:s}=this.traitGovernor.process(t,i);this.identity.setUserId(e,s);const o={type:"identify",traits:s,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this.captureEvent(o)}page(e,t){if(!this.assertInitialized())return;const i={type:"page",name:e||document.title,properties:t||{},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.config.workspace_id||void 0,context:l(this.config,this.session)};this.captureEvent(i)}group(e,t){if(!this.assertInitialized())return;const i=this.config.workspace_id||null,{sanitized:s}=this.traitGovernor.process(t,i),o={type:"group",groupId:e,traits:s,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};this.captureEvent(o)}alias(e){if(!this.assertInitialized())return;const{previousId:t}=this.identity.alias(e),i={type:"alias",previousId:t,messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};this.captureEvent(i)}async captureEvent(e){var t;if((null==(t=this.config)?void 0:t.enable_consent_mode)&&this.consent&&("track"===e.type||"page"===e.type)&&!this.consent.hasConsent("analytics"))return void i.debug("Event blocked: analytics consent not granted");if("track"===e.type){const t=e;if(!("string"==typeof t.event&&t.event.startsWith("aegis.client."))&&!this.nameGovernor.shouldSend(t.event))return}if(this.rateLimiter){const t="track"===e.type&&e.event?e.event:e.type;if(!("track"===e.type&&"string"==typeof e.event&&e.event.startsWith("aegis.client."))&&!this.rateLimiter.tryConsume(t))return}const n=e.context,s=e.properties;if((null==n?void 0:n.campaign)&&s&&!s.campaign_id){const e=n.campaign;e.campaign&&(s.campaign_id=e.campaign),e.source&&(s.campaign_source=e.source),e.medium&&(s.campaign_medium=e.medium),e.content&&(s.campaign_content=e.content),e.term&&(s.campaign_term=e.term)}if((null==n?void 0:n.adClickIDs)&&s){const e=n.adClickIDs,t=e.gclid||e.fbclid||e.ctwa_clid||e.msclkid||e.ttclid;t&&!s.campaign_click_id&&(s.campaign_click_id=t)}if(s){const e={fbp:x(),fbc:b(),fbclid:v()};e.fbp&&!s.fbp&&(s.fbp=e.fbp),e.fbc&&!s.fbc&&(s.fbc=e.fbc),e.fbclid&&!s.fbclid&&(s.fbclid=e.fbclid)}i.debug("Capturing event:",e);const o=await this.plugins.executeHookChain("beforeEventCapture",e);o?(this.queue.push(o),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",o)):i.debug("Event cancelled by plugin")}emitRateLimitMeta(e,t){var i,s;if(!(null==(i=this.config)?void 0:i.initialized)||!this.session||!this.identity)return;const o={type:"track",event:"aegis.client.rate_limited",properties:{dropped_count:e,sample_event_name:t,burst_capacity:this.config.rate_limit_burst,refill_per_second:this.config.rate_limit_per_second},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};null==(s=this.queue)||s.push(o)}reset(){this.assertInitialized()&&(this.identity.reset(),i.info("User identity reset"))}ingestGovernanceHint(e){this.nameGovernor.ingestHint(e??null),i.debug("Governance hint ingested",e?{k:e.k,m:e.m,remaining:e.remaining_new_names}:"disabled")}emitGovernanceDropMeta(){var e,t;if(!(null==(e=this.config)?void 0:e.initialized)||!this.session||!this.identity)return;const i=this.nameGovernor.drainDropReport();if(!i)return;const s={type:"track",event:"aegis.client.name_governor_dropped",properties:{dropped_count:i.total,distinct_names:Object.keys(i.events).length,sample_names:Object.entries(i.events).sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({name:e,count:t})),window_start:i.since,window_end:Date.now()},messageId:n(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:l(this.config,this.session)};null==(t=this.queue)||t.push(s)}async flush(){this.assertInitialized()&&(this.emitGovernanceDropMeta(),await this.queue.flush())}getAnonymousId(){return this.identity?this.identity.getAnonymousId():null}getUserId(){return this.identity?this.identity.getUserId():null}getSessionId(){return this.session?this.session.getSessionId():null}lastEventId(e){return this._lastEventIds.get(e)??null}debug(e=!0){e?i.enable():i.disable(),this.config&&(this.config.debug=e)}setCell(e){if(!this.config)return void i.warn("SDK not initialized");const t=this.config.cell_endpoints.find(t=>t.region===e.region);t?Object.assign(t,e):this.config.cell_endpoints.push(e),i.info("Cell endpoint configured:",e)}getCellInfo(){return this.transport?{activeCell:this.transport.getActiveCell(),latencies:this.transport.getRegionLatencies()}:null}setConsent(e){this.consent?(this.consent.setConsent(e),i.info("Consent preferences updated")):i.warn("Consent manager not initialized")}grantConsent(e){this.consent?e?this.consent.setConsent({[e]:!0}):this.consent.grantAll():i.warn("Consent manager not initialized")}denyConsent(e){this.consent?e?this.consent.setConsent({[e]:!1}):this.consent.denyAll():i.warn("Consent manager not initialized")}hasConsent(e){return!this.consent||this.consent.hasConsent(e)}getConsentPreferences(){return this.consent?this.consent.getPreferences():null}onConsentChange(e){return this.consent?this.consent.onChange(e):(i.warn("Consent manager not initialized"),()=>{})}assertInitialized(){var e;return!!(null==(e=this.config)?void 0:e.initialized)||(i.warn("SDK not initialized. Call aegis.init() first."),!1)}get ecommerce(){return this._ecommerce||(this._ecommerce=new C(this)),this._ecommerce}destroy(){this.stopSPATracking(),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.rateLimiter&&(this.rateLimiter.destroy(),this.rateLimiter=null),this.plugins.clear(),i.info("SDK destroyed")}}function V(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c=(Array.isArray(a.cards)?a.cards:[]).slice(0,10);if(0===c.length)return void o("carousel_cards rendered with zero cards — skipping","warn");const d=Number(a.autoplay_ms)||0,l=!1!==a.loop;r();const h=s(t.background_color||"#ffffff"),p=s(t.text_color||"#0f172a"),u=document.createElement("div");u.className="aegis-in-app-carousel-overlay",u.setAttribute("data-campaign-id",t.id),u.style.cssText='\n position: fixed; left: 0; right: 0; bottom: 0;\n z-index: 99999; padding: 12px 12px 20px;\n background: rgba(0,0,0,0.12); backdrop-filter: blur(8px);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n ';const g=document.createElement("div");g.style.cssText=`\n background: ${h}; color: ${p}; border-radius: 16px;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08); padding: 16px;\n max-width: 520px; margin: 0 auto; position: relative;\n `;const m=document.createElement("div");m.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 12px;";const f=document.createElement("div"),y=document.createElement("div");y.textContent=t.title,y.style.cssText="font-weight: 700; font-size: 15px; margin-bottom: 2px;";const x=document.createElement("div");x.textContent=t.body,x.style.cssText="font-size: 13px; opacity: 0.75;",f.appendChild(y),f.appendChild(x),m.appendChild(f);const b=document.createElement("button");b.textContent="✕",b.setAttribute("aria-label","Close"),b.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; opacity: 0.6; padding: 2px 6px;\n ",b.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),m.appendChild(b),g.appendChild(m);const v=document.createElement("div");v.style.cssText="\n display: flex; gap: 10px; overflow-x: auto; scroll-snap-type: x mandatory;\n scrollbar-width: none; -ms-overflow-style: none; padding-bottom: 4px;\n ",v.style.msOverflowStyle="none",v.addEventListener("wheel",e=>{Math.abs(e.deltaX)<Math.abs(e.deltaY)||(v.scrollLeft+=e.deltaX)}),c.forEach((e,s)=>{const o=document.createElement("div");if(o.setAttribute("data-card-index",String(s)),o.style.cssText=`\n flex: 0 0 auto; width: 140px; scroll-snap-align: start;\n background: ${p}0a; border-radius: 12px; padding: 10px;\n display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",o.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",o.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",o.appendChild(t)}if(e.cta_text&&e.cta_url){const s=document.createElement("button");s.textContent=e.cta_text,s.style.cssText=`\n margin-top: auto; background: ${p}; color: ${h};\n border: none; padding: 6px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const r=s=>{s.stopPropagation(),n(t.id,"clicked");const o=i(e.cta_url);o&&(window.location.href=o)};s.addEventListener("click",r),o.appendChild(s),o.addEventListener("click",r)}v.appendChild(o)}),g.appendChild(v);const w=document.createElement("div");w.style.cssText="display: flex; justify-content: center; gap: 6px; margin-top: 10px;";const _=[];c.forEach(()=>{const e=document.createElement("span");e.style.cssText=`\n width: 6px; height: 6px; border-radius: 999px; background: ${p};\n opacity: 0.25; transition: opacity 0.2s;\n `,_.push(e),w.appendChild(e)}),g.appendChild(w);const C=e=>{_.forEach((t,n)=>t.style.opacity=n===e?"0.9":"0.25")};C(0);let k=0;const S=v.querySelectorAll("[data-card-index]");let E=null;d>0&&c.length>1&&(E=setInterval(()=>{const e=k+1;e>=c.length&&!l?E&&clearInterval(E):(e=>{k=(e%c.length+c.length)%c.length;const t=S[k];t&&(t.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"}),C(k))})(e)},d)),u.addEventListener("remove",()=>{E&&clearInterval(E)}),v.addEventListener("scroll",()=>{const e=Math.round(v.scrollLeft/150);e!==k&&e>=0&&e<c.length&&(k=e,C(k))}),u.appendChild(g),document.body.appendChild(u)}const H="aegis_sticky_dismissed:";function q(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:s,addAnimationStyles:o}=e,r=t.interactive_config||{},a=r.progress_goal_type||"cart_total",c=Number(r.progress_threshold);if(!(c>0))return void s("progress_bar requires a positive progress_threshold — skipping","warn");const d=r.progress_reward_text||t.body||"Unlocked!",l="sse"===r.progress_source?"sse":"client";o();const h=i(t.background_color||"#f8fafc"),p=i(t.text_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-progress-bar",u.setAttribute("data-campaign-id",t.id),u.style.cssText=`\n position: fixed; left: 12px; right: 12px; bottom: 12px;\n max-width: 540px; margin: 0 auto;\n background: ${h}; color: #0f172a; border-radius: 12px;\n padding: 10px 14px; z-index: 999997;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `;const g=document.createElement("div");g.style.cssText="display: flex; justify-content: space-between; font-size: 13px; font-weight: 600; margin-bottom: 6px;";const m=document.createElement("span");m.textContent=t.title,g.appendChild(m);const f=document.createElement("span");f.style.cssText="opacity: 0.7; font-weight: 500;",g.appendChild(f),u.appendChild(g);const y=document.createElement("div");y.style.cssText=`\n height: 8px; border-radius: 999px; background: ${p}22;\n overflow: hidden;\n `;const x=document.createElement("div");x.style.cssText=`\n height: 100%; border-radius: 999px; background: ${p};\n width: 0%; transition: width 0.4s cubic-bezier(.4,0,.2,1);\n `,y.appendChild(x),u.appendChild(y);const b=document.createElement("div");b.style.cssText="font-size: 11.5px; opacity: 0.65; margin-top: 6px;",u.appendChild(b);let v=!1;const w=()=>{const e=(()=>{var e,n;if("sse"===l){const e=window.__aegisProgressSSE;return e&&"number"==typeof e[t.id]?e[t.id]:0}try{if("cart_total"===a||"items_in_cart"===a){const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=parseFloat(String(t.Shopify.checkout.total_price||0));return"cart_total"===a?e:0}if(t.aegis_cart)return"items_in_cart"===a?Array.isArray(t.aegis_cart.cart_items)?t.aegis_cart.cart_items.length:0:Number(t.aegis_cart.cart_total||0);try{const e=null==(n=window.localStorage)?void 0:n.getItem("mage-cache-storage");if(e){const t=JSON.parse(e).cart;if(t)return"cart_total"===a?Number(t.subtotalAmount||0):Array.isArray(t.items)?t.items.length:0}}catch{}}return 0}catch{return 0}})(),i=Math.max(0,Math.min(100,e/c*100));if(x.style.width=`${i}%`,f.textContent=`${e.toFixed(0)} / ${c.toFixed(0)}`,i>=100)b.textContent=d,v||(v=!0,n(t.id,"clicked"));else{const t=Math.max(0,c-e);b.textContent=`Add ${t.toFixed(0)} more to unlock: ${d}`}};w();const _=setInterval(w,1e3),C=()=>clearInterval(_);window.addEventListener("beforeunload",C,{once:!0}),u.addEventListener("remove",C),document.body.appendChild(u)}const K="aegis_coachmark_progress:";function X(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(K+e,String(t))}catch{}}function Q(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:s,addAnimationStyles:o}=e,r=t.interactive_config||{},a=r.resume_key;if(!a)return void s("coachmark_tour requires interactive_config.resume_key — skipping","warn");const c=Array.isArray(r.steps)?r.steps:[];if(0===c.length)return void s("coachmark_tour has no steps — skipping","warn");const d=!1!==r.allow_skip,l=!1!==r.show_progress_dots;o();const h=i(t.background_color||"#0f172a"),p=i(t.text_color||"#ffffff");let u=function(e){try{if("undefined"==typeof localStorage)return 0;const t=localStorage.getItem(K+e),n=t?parseInt(t,10):0;return Number.isFinite(n)&&n>=0?n:0}catch{return 0}}(a);if(u>=c.length)return void s(`coachmark_tour ${a} already complete — not re-showing`);n(t.id,"impression");let g=null,m=null,f=null;const y=()=>{null==g||g.remove(),null==m||m.remove(),null==f||f.remove(),g=null,m=null,f=null},x=e=>{y(),e.skipped?n(t.id,"dismissed"):n(t.id,"clicked"),X(a,c.length)},b=e=>{y();const n=c[e];if(!n)return void x({skipped:!1});X(a,e);const i=n.anchor_web;let o=null;if(i)try{o=document.querySelector(i)}catch{o=null}if(!o)return s(`coachmark step ${e} — selector '${i}' not found; advancing`,"warn"),void b(e+1);const r=o.getBoundingClientRect();f=document.createElement("div"),f.style.cssText=`\n position: fixed;\n top: ${r.top-6}px; left: ${r.left-6}px;\n width: ${r.width+12}px; height: ${r.height+12}px;\n border-radius: 10px; z-index: 999998;\n box-shadow: 0 0 0 2px ${p}, 0 0 0 9999px rgba(0,0,0,0.4);\n pointer-events: none;\n transition: all 0.2s ease;\n `,document.body.appendChild(f);const u=n.placement||"bottom";m=document.createElement("div"),m.setAttribute("data-campaign-id",t.id),m.style.cssText=`\n position: fixed; z-index: 999999;\n background: ${h}; color: ${p};\n padding: 12px 14px; border-radius: 12px;\n max-width: 260px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.25);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.2s ease;\n `;const g=document.createElement("div");g.textContent=n.title,g.style.cssText="font-weight: 700; font-size: 13px; margin-bottom: 4px;",m.appendChild(g);const v=document.createElement("div");v.textContent=n.body,v.style.cssText="font-size: 12.5px; line-height: 1.4; opacity: 0.9;",m.appendChild(v);const w=document.createElement("div");if(w.style.cssText="display: flex; align-items: center; justify-content: space-between; margin-top: 10px; gap: 8px;",l){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px;",c.forEach((n,i)=>{const s=document.createElement("span");s.style.cssText=`\n width: 5px; height: 5px; border-radius: 999px;\n background: ${p}; opacity: ${i===e?"0.95":"0.3"};\n `,t.appendChild(s)}),w.appendChild(t)}else w.appendChild(document.createElement("span"));const _=document.createElement("div");if(_.style.cssText="display: flex; gap: 6px;",d&&e<c.length-1){const e=document.createElement("button");e.textContent="Skip",e.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",e.addEventListener("click",()=>x({skipped:!0})),_.appendChild(e)}const C=document.createElement("button"),k=e===c.length-1;C.textContent=n.cta_text||(k?"Done":"Next"),C.style.cssText=`\n background: ${p}; color: ${h};\n border: none; padding: 6px 12px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer;\n `,C.addEventListener("click",()=>{k?x({skipped:!1}):b(e+1)}),_.appendChild(C),w.appendChild(_),m.appendChild(w),document.body.appendChild(m);const S=m.getBoundingClientRect();let E=r.bottom+12,I=r.left;"top"===u?E=r.top-S.height-12:"left"===u?(E=r.top,I=r.left-S.width-12):"right"===u&&(E=r.top,I=r.right+12),E=Math.max(8,Math.min(window.innerHeight-S.height-8,E)),I=Math.max(8,Math.min(window.innerWidth-S.width-8,I)),m.style.top=`${E}px`,m.style.left=`${I}px`};b(u),window.aegisResetTour=e=>function(e){try{"undefined"!=typeof localStorage&&localStorage.removeItem(K+e)}catch{}}(e)}const J=class e{constructor(e){this.campaigns=[],this.displayedCampaigns=new Set,this.suppressedUntil=new Map,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.hooks=new Map,this.ready=new Promise(e=>{this.readyResolve=e}),this.filledSlots=new WeakSet,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new d).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.propertyId=e.propertyId,this.debugMode=e.debugMode||!1,this.enableSSE=!0===e.enableSSE,this.onInteractiveCampaign=e.onInteractiveCampaign}emit(e,t){const n=this.hooks.get(e);if(!n||0===n.size)return!0;let i=!0;for(const o of n)try{!1===o(t)&&(i=!1)}catch(s){this.emitError(s,{event:e})}return i}emitError(e,t){const n=this.hooks.get("error");if(n&&0!==n.size)for(const i of n)try{i({message:e instanceof Error?e.message:String(e),error:e,context:t??{}})}catch{}else this.log(`Aegis SDK error: ${e instanceof Error?e.message:String(e)}`,"error")}register(e,t){return this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add(t),()=>{var n;null==(n=this.hooks.get(e))||n.delete(t)}}on(e,t){return this.register(e,t)}onCampaignsLoaded(e){return this.register("campaigns-loaded",e)}onCampaignWillShow(e){return this.register("campaign-will-show",e)}onCampaignShown(e){return this.register("campaign-shown",e)}onCampaignClick(e){return this.register("campaign-click",e)}onCampaignDismiss(e){return this.register("campaign-dismiss",e)}onError(e){return this.register("error",e)}async initialize(){this.isInitialized?this.log("AegisInApp already initialized"):("undefined"!=typeof localStorage&&localStorage.setItem("aegis_returning_user","1"),await this.refreshCampaigns(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisInApp initialized successfully"))}updateUserId(e){this.userId=e,this.refreshCampaigns()}updateContactId(e){this.contactId=e,this.disconnectSSE(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.refreshCampaigns()}notifyConversion(t){if(!t)return void this.log("notifyConversion called with empty goalName; ignored","warn");const n=Date.now();if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(`${e.CONVERSION_STORAGE_PREFIX}${t}`,JSON.stringify({ts:n}))}catch{}this.applySuppressionFromCampaigns(n),this.log(`notifyConversion: ${t} — suppressing ${this.suppressedUntil.size} armed campaigns`)}applySuppressionFromCampaigns(e){var t,n;for(const i of this.campaigns){const s=null==(t=i.frequency)?void 0:t.suppress_after_conversion_seconds;if("number"!=typeof s||s<=0)continue;const o=(null==(n=i.frequency)?void 0:n.scope)??"session";"session"!==o&&this.log(`applySuppressionFromCampaigns: scope=${o} not implemented; degrading to session for campaign ${i.id}`,"warn");const r=e+1e3*s,a=this.suppressedUntil.get(i.id);(void 0===a||a<r)&&this.suppressedUntil.set(i.id,r)}}rehydrateSuppressionFromStorage(){if("undefined"==typeof sessionStorage)return;let t=null;try{for(let n=0;n<sessionStorage.length;n++){const i=sessionStorage.key(n);if(!i||!i.startsWith(e.CONVERSION_STORAGE_PREFIX))continue;const s=sessionStorage.getItem(i);if(!s)continue;const o=JSON.parse(s);"number"==typeof o.ts&&(t=null===t?o.ts:Math.min(t,o.ts))}}catch{return}null!==t&&this.applySuppressionFromCampaigns(t)}isSuppressed(e){const t=this.suppressedUntil.get(e);return void 0!==t&&(!(Date.now()>=t)||(this.suppressedUntil.delete(e),!1))}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID","warn");const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("in_app_campaign_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received in-app campaign update: ${t.campaign_id}`),this.refreshCampaigns()}catch(t){this.log(`Error parsing SSE event: ${t}`,"error")}}),this.eventSource.addEventListener("heartbeat",()=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",()=>{var e;this.log("SSE connection error","error"),(null==(e=this.eventSource)?void 0:e.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up","warn");this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}async refreshCampaigns(){try{const e=new URLSearchParams({device_type:this.detectDeviceType(),page_url:"undefined"!=typeof window?window.location.pathname:"/"});e.set("is_new_user",this.isNewUser()?"true":"false");const t=`${this.apiHost}/v1/in-app/active?${e.toString()}`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId),this.propertyId&&(n["X-Property-Id"]=this.propertyId);const i=this.getABAssignments();Object.keys(i).length>0&&(n["X-AB-Assignments"]=btoa(JSON.stringify(i)));const s=await fetch(t,{method:"GET",headers:n,credentials:"include"});if(!s.ok)throw new Error(`Failed to fetch campaigns: ${s.status}`);const o=await s.json();this.campaigns=Array.isArray(o)?o:[],this.processABAssignments(this.campaigns),this.rehydrateSuppressionFromStorage(),this.log(`Fetched ${this.campaigns.length} campaigns`),this.emit("campaigns-loaded",this.campaigns),this.readyResolve(),this.tryDisplayNextCampaign(),this.renderIntoSlots(),this.renderTokenAnchors()}catch(e){this.emitError(e,{stage:"refresh-campaigns"}),this.log(`Error refreshing campaigns: ${e}`,"error")}}detectDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/Mobi|Android/i.test(e)?"mobile":/iPad|Tablet/i.test(e)?"tablet":"desktop"}isNewUser(){return"undefined"==typeof localStorage||!localStorage.getItem("aegis_returning_user")}getABAssignments(){if("undefined"==typeof localStorage)return{};try{return JSON.parse(localStorage.getItem("aegis_ab_assignments")||"{}")}catch{return{}}}processABAssignments(e){if("undefined"==typeof localStorage)return;const t=this.getABAssignments();for(const n of e)n.assigned_variant_id&&(t[n.id]=n.assigned_variant_id);localStorage.setItem("aegis_ab_assignments",JSON.stringify(t))}getVariantId(e){return this.getABAssignments()[e]??void 0}tryDisplayNextCampaign(){const e=this.campaigns.find(e=>!this.displayedCampaigns.has(e.id)&&!e.client_trigger&&!this.isSuppressed(e.id));e&&this.displayCampaign(e)}renderIntoSlots(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-slot]");if(0===e.length)return;const t=new Map;for(const n of this.campaigns){const e=n.delivery_modes,i=n.widget_category;e&&e.includes("embedded_card")&&(i&&(t.has(i)||t.set(i,n)))}0!==t.size&&e.forEach(e=>{if(this.filledSlots.has(e))return;const n=e.getAttribute("data-aegis-slot");if(!n)return;const i=t.get(n);i&&(this.renderCampaignIntoSlot(i,e),this.filledSlots.add(e))})}renderTokenAnchors(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-token-data]");0!==e.length&&e.forEach(e=>{if(this.filledSlots.has(e))return;const t=e.getAttribute("data-aegis-token-data");if(!t)return;let n=null;try{n=JSON.parse(t)}catch(i){return this.log(`data-aegis-token-data: invalid JSON, skipping anchor (${i})`,"warn"),void this.filledSlots.add(e)}if(!n||!n.campaign||!n.campaign.id)return this.log("data-aegis-token-data: missing `campaign` in payload, skipping","warn"),void this.filledSlots.add(e);this.renderCampaignIntoSlot(n.campaign,e,{submitUrl:n.submit_url}),this.filledSlots.add(e)})}renderCampaignIntoSlot(e,t,n){if(!this.emit("campaign-will-show",e))return void this.log(`slot campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id),this.addAnimationStyles();const i=e.interactive_config||{},s=this.sanitizeColor(e.background_color||"#4169e1"),o=this.sanitizeColor(e.text_color||"#ffffff"),r=null==n?void 0:n.submitUrl;let a=!1;switch(e.sub_type){case"star_rating":a=this.renderStarRatingSlot(e,i,s,o,t,r);break;case"nps_survey":a=this.renderNPSSurveySlot(e,i,s,o,t,r);break;default:return this.log(`slot mode not yet supported for sub_type: ${e.sub_type??e.type}`,"warn"),void this.displayedCampaigns.delete(e.id)}a&&(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))}renderStarRatingSlot(e,t,n,i,s,o){const r=this._wrapInSlotCard("aegis-in-app-rating-card",e.id,n,i);return r.appendChild(this._buildStarRatingBody(e,t,i,"slot",o)),s.appendChild(r),!0}renderNPSSurveySlot(e,t,n,i,s,o){const r=this._wrapInSlotCard("aegis-in-app-nps-card",e.id,n,i);return r.appendChild(this._buildNPSSurveyBody(e,t,i,"slot",o)),s.appendChild(r),!0}_submitTokenResponse(e,t){e&&fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({response:t}),keepalive:!0}).catch(e=>{this.log(`token submit failed: ${e}`,"warn")})}_wrapInSlotCard(e,t,n,i){const s=document.createElement("div");return s.className=e,s.setAttribute("data-campaign-id",t),s.style.cssText=`\n width: 100%; border-radius: 12px; overflow: hidden;\n background: ${n}; color: ${i};\n box-shadow: 0 4px 12px rgba(0,0,0,0.06);\n `,s}_buildStarRatingBody(e,t,n,i,s){const o="overlay"===i,r=o?"24px":"20px",a=o?"18px":"16px",c=o?"700":"600",d=o?"16px":"12px",l=o?"32px":"28px",h=o?"16px":"0",p=o?"1.2":"1.15",u=document.createElement("div");u.style.cssText=`padding: ${r}; text-align: center;`;const g=document.createElement("div");g.style.cssText=`font-size: ${a}; font-weight: ${c}; margin-bottom: ${d};`,g.textContent=e.title||"Rate your experience",u.appendChild(g);const m=document.createElement("div");m.style.cssText="display: flex; gap: 8px; justify-content: center;"+("0"!==h?` margin-bottom: ${h};`:"");const f=t.rating_scale||5;for(let y=1;y<=f;y++){const t=document.createElement("span");t.style.cssText=`font-size: ${l}; cursor: pointer; transition: transform 0.1s; user-select: none;`+(n?` color: ${n};`:""),t.textContent="☆";const i=y;t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"star_rating",value:i})}),t.addEventListener("mouseenter",()=>{t.style.transform=`scale(${p})`}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),m.appendChild(t)}return u.appendChild(m),u}_buildNPSSurveyBody(e,t,n,i,s){const o="overlay"===i,r=o?"24px":"20px",a=document.createElement("div");a.style.cssText=`padding: ${r};`+(o?" text-align: center;":"");const c=document.createElement("div");if(c.style.cssText=`font-size: 16px; font-weight: ${o?"700":"600"}; margin-bottom: ${o?"16px":"12px"}; text-align: center;`,c.textContent=t.nps_question||e.title||"How likely are you to recommend us?",a.appendChild(c),o){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;";for(let a=0;a<=10;a++){const i=document.createElement("span");i.style.cssText=`\n width: 28px; height: 28px; border-radius: 6px; display: flex;\n align-items: center; justify-content: center; font-size: 11px;\n font-weight: 600; cursor: pointer; background: ${n}33; color: ${n};\n transition: transform 0.1s;\n `,i.textContent=String(a);const o=a;i.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"nps_survey",value:o})}),t.appendChild(i)}a.appendChild(t);const i=document.createElement("div");i.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const o=document.createElement("span");o.textContent="Not likely";const r=document.createElement("span");return r.textContent="Very likely",i.appendChild(o),i.appendChild(r),a.appendChild(i),a}const d=document.createElement("div");d.style.cssText="display: grid; grid-template-columns: repeat(11, 1fr); gap: 4px;";for(let l=0;l<=10;l++){const t=document.createElement("button");t.style.cssText=`\n padding: 8px 0; border-radius: 6px; border: 1px solid ${n}33;\n background: transparent; color: ${n}; font-size: 13px; font-weight: 600;\n cursor: pointer; transition: background 0.15s;\n `,t.textContent=String(l);const i=l;t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),s&&this._submitTokenResponse(s,{sub_type:"nps_survey",value:i})}),d.appendChild(t)}return a.appendChild(d),a}onClientEvent(e,t={}){for(const n of this.campaigns)this.displayedCampaigns.has(n.id)||n.client_trigger&&(this.isSuppressed(n.id)||this.matchesClientTrigger(n.client_trigger,e,t)&&this.displayCampaign(n))}matchesClientTrigger(e,t,n){var i;const s=e.config||{};switch(e.type){case"custom_event":return"string"==typeof s.event&&s.event===t;case"product_match":{if("product_viewed"!==t&&"product_view"!==t)return!1;const e=s.product_id,o=Array.isArray(e)?e:"string"==typeof e?[e]:[];if(0===o.length)return!1;const r=String(n.product_id??n.productId??(null==(i=n.product)?void 0:i.id)??"");return o.includes(r)}default:return!1}}displayCampaign(e){if(!this.emit("campaign-will-show",e))return void this.log(`campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id);const t=new Set(["spin_wheel","scratch_card","nps_survey","quiz","countdown_offer","star_rating","quick_poll"]);if(e.sub_type&&t.has(e.sub_type))return this.renderInteractive(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);switch(e.type){case"modal":this.renderModal(e);break;case"banner":this.renderBanner(e);break;case"full_screen":this.renderFullScreen(e);break;case"half_interstitial":this.renderHalfInterstitial(e);break;case"alert":this.renderAlert(e);break;case"pip":this.renderPIP(e);break;case"tooltip":this.renderTooltip(e);break;case"carousel_cards":return V(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"sticky_bar":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c="top"===a.sticky_position?"top":"bottom",d=!1!==a.sticky_dismissible,l=Number(a.sticky_auto_hide_ms)||0;try{if("undefined"!=typeof localStorage&&localStorage.getItem(H+t.id))return void o(`sticky_bar ${t.id} suppressed — user dismissed earlier`)}catch{}r();const h=s(a.sticky_bg_color||t.background_color||"#4169e1"),p=s(t.text_color||"#ffffff"),u=document.createElement("div");u.className="aegis-in-app-sticky-bar",u.setAttribute("data-campaign-id",t.id);const g="top"===c?"top: 0; left: 0; right: 0; animation: aegisSlideDown 0.3s ease-out;":"bottom: 0; left: 0; right: 0; animation: aegisSlideInFromBottom 0.3s ease-out;";u.style.cssText=`\n position: fixed; ${g}\n background: ${h}; color: ${p};\n padding: 10px 14px; z-index: 999998;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex; align-items: center; gap: 12px; justify-content: center;\n box-shadow: 0 ${"top"===c?"2px":"-2px"} 8px rgba(0,0,0,0.08);\n `;const m=document.createElement("div");m.style.cssText="flex: 0 1 auto; font-size: 13px; font-weight: 500; text-align: center;";const f=document.createElement("strong");if(f.textContent=t.title,f.style.cssText="margin-right: 6px; font-weight: 700;",m.appendChild(f),m.appendChild(document.createTextNode(t.body)),u.appendChild(m),t.action_url&&t.button_text){const e=document.createElement("button");e.textContent=t.button_text,e.style.cssText=`\n background: ${p}; color: ${h};\n border: none; padding: 6px 14px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer; white-space: nowrap;\n `,e.addEventListener("click",()=>{n(t.id,"clicked");const e=i(t.action_url);e&&(window.location.href=e)}),u.appendChild(e)}let y=null;const x=e=>{if(y&&clearTimeout(y),e)try{"undefined"!=typeof localStorage&&localStorage.setItem(H+t.id,"1")}catch{}u.remove()};if(d){const e=document.createElement("button");e.textContent="✕",e.setAttribute("aria-label","Dismiss"),e.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; padding: 0 4px; opacity: 0.75;\n ",e.addEventListener("click",()=>{n(t.id,"dismissed"),x(!0)}),u.appendChild(e)}l>0&&(y=setTimeout(()=>x(!1),l)),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"progress_bar":return q(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"coachmark_tour":return Q(this.buildRenderContext(e)),void this.emit("campaign-shown",e);case"product_recommendation":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:s,log:o,addAnimationStyles:r}=e,a=t.interactive_config||{},c=(Array.isArray(a.cards)?a.cards:[]).slice(0,24);if(0===c.length)return void o("product_recommendation rendered with zero products — skipping","warn");const d=a.rec_layout||"grid",l=a.rec_cta_text||"Shop now";r();const h=s(t.background_color||"#ffffff"),p=s(t.text_color||"#0f172a"),u=s("#4169e1"),g=document.createElement("div");g.className="aegis-in-app-product-rec",g.setAttribute("data-campaign-id",t.id),g.style.cssText="\n position: fixed; inset: 0;\n background: rgba(15,23,42,0.55); backdrop-filter: blur(4px);\n display: flex; align-items: flex-end; justify-content: center;\n z-index: 99999; animation: aegisFadeIn 0.25s ease;\n ";const m=document.createElement("div");m.style.cssText=`\n background: ${h}; color: ${p};\n max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;\n border-radius: 20px 20px 0 0;\n padding: 18px 16px 22px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n box-shadow: 0 -12px 30px rgba(0,0,0,0.12);\n `;const f=document.createElement("div");f.style.cssText=`\n width: 36px; height: 4px; border-radius: 999px; background: ${p}1f;\n margin: 0 auto 12px;\n `,m.appendChild(f);const y=document.createElement("div");y.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;";const x=document.createElement("div"),b=document.createElement("div");b.textContent=t.title,b.style.cssText="font-weight: 700; font-size: 16px; margin-bottom: 2px;";const v=document.createElement("div");v.textContent=t.body,v.style.cssText="font-size: 13px; opacity: 0.7; line-height: 1.4;",x.appendChild(b),x.appendChild(v),y.appendChild(x);const w=document.createElement("button");w.textContent="✕",w.setAttribute("aria-label","Close"),w.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 18px; cursor: pointer; padding: 4px 8px; opacity: 0.7;\n ",w.addEventListener("click",()=>{n(t.id,"dismissed"),g.remove()}),y.appendChild(w),m.appendChild(y);const _=document.createElement("div");_.style.cssText="row"===d||"carousel"===d?"\n display: flex; gap: 10px; overflow-x: auto;\n scroll-snap-type: x mandatory; padding: 14px 0 4px;\n ":"\n display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;\n padding-top: 14px;\n ",c.forEach(e=>{const s=document.createElement("div"),o="row"===d||"carousel"===d;if(s.style.cssText=`\n background: ${p}08; border-radius: 12px;\n padding: 10px; display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n ${o?"flex: 0 0 150px; scroll-snap-align: start;":""}\n transition: transform 0.15s ease;\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; aspect-ratio: 1 / 1; border-radius: 8px; object-fit: cover;",s.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",s.appendChild(t)}const r=e.metadata&&"object"==typeof e.metadata?e.metadata.price:void 0;if(void 0!==r){const e=document.createElement("div");e.textContent=String(r),e.style.cssText=`color: ${u}; font-weight: 700; font-size: 13px;`,s.appendChild(e)}else if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",s.appendChild(t)}const a=document.createElement("button");a.textContent=e.cta_text||l,a.style.cssText=`\n margin-top: auto;\n background: ${u}; color: #fff;\n border: none; padding: 7px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const c=s=>{if(s.stopPropagation(),n(t.id,"clicked"),e.cta_url){const t=i(e.cta_url);t&&(window.location.href=t)}};a.addEventListener("click",c),s.appendChild(a),e.cta_url&&s.addEventListener("click",c),_.appendChild(s)}),m.appendChild(_),g.appendChild(m),g.addEventListener("click",e=>{e.target===g&&(n(t.id,"dismissed"),g.remove())}),document.body.appendChild(g)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e)}this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)}buildRenderContext(e){return{campaign:e,trackEvent:(e,t)=>{this.trackEvent(e,t)},sanitizeUrl:e=>this.sanitizeUrl(e),sanitizeColor:e=>this.sanitizeColor(e),log:(e,t)=>this.log(e,t),addAnimationStyles:()=>this.addAnimationStyles()}}renderInteractive(e){const t=e.interactive_config||{},n=this.sanitizeColor(e.background_color||"#4169e1"),i=this.sanitizeColor(e.text_color||"#ffffff");switch(e.sub_type){case"nps_survey":this.renderNPSSurvey(e,t,n,i);break;case"countdown_offer":this.renderCountdownOffer(e,t,n,i);break;case"star_rating":this.renderStarRating(e,t,n,i);break;case"quick_poll":this.renderQuickPoll(e,t,n,i);break;case"quiz":this.renderQuiz(e,t,n,i);break;case"spin_wheel":case"scratch_card":this.onInteractiveCampaign?this.onInteractiveCampaign(e):this.log(`${e.sub_type} campaign received but no onInteractiveCampaign handler wired — install via AegisMessageRuntime`,"warn");break;default:this.log(`Unknown interactive sub_type: ${e.sub_type}`,"warn"),this.renderModal(e)}}renderNPSSurvey(e,t,n,i){const s=this.createOverlay("aegis-in-app-nps-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 360px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=this._buildNPSSurveyBody(e,t,i,"overlay");this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderCountdownOffer(e,t,n,i){const s=this.createOverlay("aegis-in-app-countdown-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 20px; font-weight: 700; margin-bottom: 8px;",a.textContent=e.title||"Flash Sale",r.appendChild(a);const c=document.createElement("div");c.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 12px;",c.textContent=t.countdown_label||"Sale ends in:",r.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 8px; justify-content: center; margin-bottom: 16px;";const l=`padding: 8px 12px; border-radius: 8px; font-size: 24px; font-weight: 700; font-family: monospace; background: ${i}22;`;for(const p of["00",":","00",":","00"]){const e=document.createElement("span");e.style.cssText=":"===p?"font-size: 24px; font-weight: 700; align-self: center;":l,e.textContent=p,d.appendChild(e)}r.appendChild(d);const h=t.countdown_target;if(h){const e=new Date(h).getTime(),t=()=>{const n=Math.max(0,e-Date.now()),i=String(Math.floor(n/36e5)).padStart(2,"0"),s=String(Math.floor(n%36e5/6e4)).padStart(2,"0"),o=String(Math.floor(n%6e4/1e3)).padStart(2,"0"),r=d.querySelectorAll("span");r.length>=5&&(r[0].textContent=i,r[2].textContent=s,r[4].textContent=o),n>0&&requestAnimationFrame(t)};t()}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 14px; opacity: 0.85; margin-bottom: 16px;",t.textContent=e.body,r.appendChild(t)}if(e.button_text){const t=this.createCTAButton(e,n,i);r.appendChild(t)}this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderStarRating(e,t,n,i){const s=this.createOverlay("aegis-in-app-rating-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=this._buildStarRatingBody(e,t,i,"overlay");this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderQuickPoll(e,t,n,i){const s=this.createOverlay("aegis-in-app-poll-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 320px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",a.textContent=e.title||"Quick question",r.appendChild(a);const c=t.poll_options||[],d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;";for(const l of c){const t=document.createElement("button");t.style.cssText=`\n padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33;\n background: transparent; color: ${i}; font-size: 14px; cursor: pointer;\n text-align: left; transition: background 0.15s;\n `,t.textContent=l,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),d.appendChild(t)}r.appendChild(d),this.addCloseButton(r,s,e.id),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}renderQuiz(e,t,n,i){const s=this.createOverlay("aegis-in-app-quiz-overlay"),o=document.createElement("div");o.style.cssText=`\n max-width: 360px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 20px 60px rgba(0,0,0,0.15);\n `;const r=document.createElement("div");r.style.cssText="padding: 24px; text-align: center;";const a=document.createElement("div");a.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",a.textContent=e.title||"Quiz",r.appendChild(a);const c=t.questions||[];let d=0;const l=()=>{for(;r.childNodes.length>1;)r.removeChild(r.lastChild);if(d>=c.length){const n=document.createElement("div");return n.style.cssText="font-size: 16px; margin: 16px 0;",n.textContent=t.thank_you_message||"Thanks for completing the quiz!",r.appendChild(n),this.trackEvent(e.id,"clicked"),void this.addCloseButton(r,s,e.id)}const n=c[d],o=document.createElement("div");o.style.cssText="font-size: 12px; opacity: 0.6; margin-bottom: 12px;",o.textContent=`Question ${d+1} of ${c.length}`,r.appendChild(o);const a=document.createElement("div");a.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 16px;",a.textContent=n.question,r.appendChild(a);const h=document.createElement("div");h.style.cssText="display: flex; flex-direction: column; gap: 8px;";for(const e of n.options){const t=document.createElement("button");t.style.cssText=`\n padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33;\n background: transparent; color: ${i}; font-size: 14px; cursor: pointer;\n text-align: left; transition: background 0.15s;\n `,t.textContent=e,t.addEventListener("click",()=>{d++,l()}),h.appendChild(t)}r.appendChild(h),this.addCloseButton(r,s,e.id)};l(),o.appendChild(r),s.appendChild(o),this.addAnimationStyles(),document.body.appendChild(s)}createOverlay(e){const t=document.createElement("div");return t.className=e,t.style.cssText="\n position: fixed; top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.5); display: flex; align-items: center;\n justify-content: center; z-index: 99999; animation: aegisFadeIn 0.3s ease;\n ",t}createCTAButton(e,t,n){const i=document.createElement("button");return i.style.cssText=`\n display: inline-block; padding: 10px 28px; border-radius: 999px;\n font-size: 14px; font-weight: 600; cursor: pointer; border: none;\n background: ${n}; color: ${t}; transition: transform 0.15s;\n `,i.textContent=e.button_text||"OK",i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&window.open(t,"_blank")}}),i}addCloseButton(e,t,n){const i=document.createElement("div");i.style.cssText="margin-top: 12px; font-size: 12px; opacity: 0.6; cursor: pointer;",i.textContent="Close",i.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(i)}navigateToCampaignAction(e,t,n="cta"){if("undefined"==typeof window)return;let i=!1;const s={campaign:e,action_url:t,button_id:n,preventDefault:()=>{i=!0,s.defaultPrevented=!0},defaultPrevented:!1},o=this.emit("campaign-click",s),r=new CustomEvent("aegis:campaign-click",{detail:{campaign_id:e.id,campaign_type:e.type,action_url:t,button_id:n},cancelable:!0}),a=window.dispatchEvent(r);!o||i||!a||r.defaultPrevented||(window.location.href=t)}renderBanner(e){const t=document.createElement("div");t.className="aegis-in-app-banner",t.setAttribute("data-campaign-id",e.id),t.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n padding: 16px;\n z-index: 999999;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n display: flex;\n align-items: center;\n justify-content: space-between;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideDown 0.3s ease-out;\n `;const n=document.createElement("div");if(n.style.cssText="flex: 1; display: flex; align-items: center; gap: 12px;",e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 40px; height: 40px; border-radius: 4px; object-fit: cover;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="flex: 1;";const s=document.createElement("div");s.textContent=e.title,s.style.cssText="font-weight: 600; font-size: 14px; margin-bottom: 4px;",i.appendChild(s);const o=document.createElement("div");o.textContent=e.body,o.style.cssText="font-size: 13px; opacity: 0.9;",i.appendChild(o),n.appendChild(i);const r=document.createElement("div");if(r.style.cssText="display: flex; align-items: center; gap: 12px; margin-left: 16px;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n border: none;\n padding: 8px 16px;\n border-radius: 4px;\n font-weight: 600;\n cursor: pointer;\n font-size: 13px;\n white-space: nowrap;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeBanner(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="✕",a.setAttribute("aria-label","Close"),a.style.cssText="\n background: transparent;\n border: none;\n color: inherit;\n font-size: 20px;\n cursor: pointer;\n padding: 0;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.7;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),r.appendChild(a),t.appendChild(n),t.appendChild(r),this.addAnimationStyles(),document.body.appendChild(t)}renderModal(e){const t=document.createElement("div");t.className="aegis-in-app-modal-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");if(n.className="aegis-in-app-modal",n.style.cssText='\n background: white;\n border-radius: 8px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow: auto;\n box-shadow: 0 10px 40px rgba(0,0,0,0.2);\n animation: aegisScaleIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 100%; height: 200px; object-fit: cover; border-radius: 8px 8px 0 0;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="padding: 24px;";const s=document.createElement("h2");s.textContent=e.title,s.style.cssText="margin: 0 0 12px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=e.body,o.style.cssText="margin: 0 0 20px 0; font-size: 15px; line-height: 1.5; color: #4a4a4a;",i.appendChild(o);const r=document.createElement("div");if(r.style.cssText="display: flex; gap: 12px; justify-content: flex-end;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n border: none;\n padding: 10px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="Close",a.style.cssText="\n background: transparent;\n border: 1px solid #d0d0d0;\n color: #4a4a4a;\n padding: 10px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),r.appendChild(a),i.appendChild(r),n.appendChild(i),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderFullScreen(e){const t=document.createElement("div");if(t.className="aegis-in-app-fullscreen-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: ${this.sanitizeColor(e.background_color||"#ffffff")};\n color: ${this.sanitizeColor(e.text_color||"#1a1a1a")};\n z-index: 1000001;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: 40px 20px;\n animation: aegisFadeIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow-y: auto;\n `,e.image_url){const n=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(n.src=i,n.alt="",n.style.cssText="max-width: 100%; max-height: 40vh; object-fit: contain; margin-bottom: 32px;",t.appendChild(n))}const n=document.createElement("div");n.style.cssText="max-width: 600px; text-align: center;";const i=document.createElement("h1");i.textContent=e.title,i.style.cssText="margin: 0 0 16px 0; font-size: 32px; font-weight: 700;",n.appendChild(i);const s=document.createElement("p");if(s.textContent=e.body,s.style.cssText="margin: 0 0 32px 0; font-size: 18px; line-height: 1.6; opacity: 0.9;",n.appendChild(s),e.action_url&&e.button_text){const i=document.createElement("button");i.textContent=e.button_text,i.style.cssText=`\n background: ${this.sanitizeColor(e.text_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.background_color||"#ffffff")};\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 18px;\n cursor: pointer;\n margin-bottom: 16px;\n `,i.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),n.appendChild(i)}t.appendChild(n);const o=document.createElement("button");o.textContent="✕",o.setAttribute("aria-label","Close"),o.style.cssText="\n position: absolute;\n top: 20px;\n right: 20px;\n background: transparent;\n border: none;\n color: inherit;\n font-size: 32px;\n cursor: pointer;\n padding: 0;\n width: 48px;\n height: 48px;\n display: flex;\n align-items: center;\n justify-content: center;\n opacity: 0.6;\n ",o.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),t.appendChild(o),this.addAnimationStyles(),document.body.appendChild(t)}renderHalfInterstitial(e){const t=document.createElement("div");t.className="aegis-in-app-half-interstitial-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.5);\n z-index: 1000000;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");if(n.className="aegis-in-app-half-interstitial",n.style.cssText='\n background: white;\n border-radius: 16px 16px 0 0;\n width: 100%;\n max-width: 600px;\n max-height: 60vh;\n overflow: auto;\n box-shadow: 0 -4px 20px rgba(0,0,0,0.2);\n animation: aegisSlideUp 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.image_url){const t=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(t.src=i,t.alt="",t.style.cssText="width: 100%; height: 200px; object-fit: cover;",n.appendChild(t))}const i=document.createElement("div");i.style.cssText="padding: 32px 24px;";const s=document.createElement("h2");s.textContent=e.title,s.style.cssText="margin: 0 0 12px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");if(o.textContent=e.body,o.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5; color: #4a4a4a;",i.appendChild(o),e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText=`\n background: ${this.sanitizeColor(e.background_color||"#1a73e8")};\n color: ${this.sanitizeColor(e.text_color||"#ffffff")};\n border: none;\n padding: 14px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),i.appendChild(n)}n.appendChild(i);const r=document.createElement("button");r.textContent="✕",r.setAttribute("aria-label","Close"),r.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: rgba(255,255,255,0.9);\n border: none;\n color: #333;\n font-size: 24px;\n cursor: pointer;\n width: 36px;\n height: 36px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n box-shadow: 0 2px 8px rgba(0,0,0,0.2);\n ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),n.style.position="relative",n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderAlert(e){const t=document.createElement("div");t.className="aegis-in-app-alert-overlay",t.setAttribute("data-campaign-id",e.id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.6);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.2s ease-out;\n ";const n=document.createElement("div");n.className="aegis-in-app-alert",n.style.cssText='\n background: white;\n border-radius: 12px;\n max-width: 320px;\n width: 85%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n animation: aegisScaleIn 0.2s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow: hidden;\n ';const i=document.createElement("div");i.style.cssText="padding: 24px 20px; text-align: center;";const s=document.createElement("h3");s.textContent=e.title,s.style.cssText="margin: 0 0 8px 0; font-size: 18px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=e.body,o.style.cssText="margin: 0; font-size: 14px; line-height: 1.4; color: #666;",i.appendChild(o),n.appendChild(i);const r=document.createElement("div");if(r.style.cssText="display: flex; border-top: 1px solid #e0e0e0;",e.action_url&&e.button_text){const n=document.createElement("button");n.textContent=e.button_text,n.style.cssText="\n flex: 1;\n background: transparent;\n border: none;\n border-right: 1px solid #e0e0e0;\n color: #1a73e8;\n padding: 14px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n ",n.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n),this.removeModal(t)}),r.appendChild(n)}const a=document.createElement("button");a.textContent="Cancel",a.style.cssText="\n flex: 1;\n background: transparent;\n border: none;\n color: #666;\n padding: 14px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),r.appendChild(a),n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderPIP(e){const t=document.createElement("div");if(t.className="aegis-in-app-pip",t.setAttribute("data-campaign-id",e.id),t.style.cssText='\n position: fixed;\n bottom: 20px;\n right: 20px;\n width: 320px;\n background: black;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 8px 24px rgba(0,0,0,0.3);\n z-index: 999999;\n animation: aegisSlideUp 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',e.video_url){const n=document.createElement("video"),i=this.sanitizeUrl(e.video_url);i&&(n.src=i,n.controls=!0,n.autoplay=!0,n.muted=!0,n.style.cssText="width: 100%; display: block;",t.appendChild(n))}else if(e.image_url){const n=document.createElement("img"),i=this.sanitizeUrl(e.image_url);i&&(n.src=i,n.alt="",n.style.cssText="width: 100%; display: block;",t.appendChild(n))}const n=document.createElement("div");n.style.cssText="\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0,0,0,0.9), transparent);\n padding: 40px 16px 16px;\n color: white;\n ";const i=document.createElement("div");i.textContent=e.title,i.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 4px;",n.appendChild(i);const s=document.createElement("div");s.textContent=e.body,s.style.cssText="font-size: 12px; opacity: 0.9;",n.appendChild(s),t.appendChild(n);const o=document.createElement("button");o.textContent="✕",o.setAttribute("aria-label","Close"),o.style.cssText="\n position: absolute;\n top: 8px;\n right: 8px;\n background: rgba(0,0,0,0.6);\n border: none;\n color: white;\n font-size: 18px;\n cursor: pointer;\n width: 28px;\n height: 28px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n ",o.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),t.style.animation="aegisSlideDown 0.3s ease-out",setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},300)}),t.appendChild(o),e.action_url&&(t.style.cursor="pointer",t.addEventListener("click",t=>{if(t.target!==o){this.trackEvent(e.id,"clicked");const t=this.sanitizeUrl(e.action_url);t&&window.open(t,"_blank")}})),this.addAnimationStyles(),document.body.appendChild(t)}removeBanner(e){e.style.animation="aegisSlideUp 0.3s ease-out",setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},300)}removeModal(e){e.style.animation="aegisFadeOut 0.3s ease-out",setTimeout(()=>{e.parentNode&&e.parentNode.removeChild(e)},300)}renderTooltip(e){const t=e.interactive_config||{},n=t.tooltip_anchor_selector||"[data-aegis-tooltip]",i=t.tooltip_position||"bottom",s=document.querySelector(n);if(!s)return void this.log(`Tooltip anchor not found: ${n}`,"warn");const o=this.sanitizeColor(e.background_color||"#1a1a1a"),r=this.sanitizeColor(e.text_color||"#ffffff"),a=document.createElement("div");a.className="aegis-in-app-tooltip",a.setAttribute("data-campaign-id",e.id),a.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${o}; color: ${r}; border-radius: 10px; padding: 14px 16px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.18); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.2s ease-out; pointer-events: auto;\n `;const c=document.createElement("div");c.className="aegis-tooltip-arrow",c.style.cssText=`\n position: absolute; width: 10px; height: 10px; background: ${o};\n transform: rotate(45deg);\n `;const d=document.createElement("button");d.textContent="×",d.style.cssText=`\n position: absolute; top: 6px; right: 8px; background: none; border: none;\n color: ${r}; opacity: 0.6; font-size: 16px; cursor: pointer; padding: 0; line-height: 1;\n `;const l=()=>{a.style.animation="aegisFadeOut 0.2s ease-out",setTimeout(()=>{var e;null==(e=a.parentNode)||e.removeChild(a)},200),this.trackEvent(e.id,"dismissed")};if(d.addEventListener("click",e=>{e.stopPropagation(),l()}),e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-size: 13px; font-weight: 700; margin-bottom: 4px; padding-right: 16px;",a.appendChild(t)}const h=document.createElement("div");if(h.textContent=e.body,h.style.cssText="font-size: 12px; line-height: 1.4; opacity: 0.9;",a.appendChild(h),e.button_text&&e.action_url){const t=document.createElement("a");t.textContent=e.button_text,t.href=e.action_url,t.style.cssText=`\n display: inline-block; margin-top: 8px; font-size: 12px; font-weight: 600;\n color: ${r}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),a.appendChild(t)}a.appendChild(d),a.appendChild(c),document.body.appendChild(a);const p=s.getBoundingClientRect(),u=a.getBoundingClientRect(),g=window.scrollX,m=window.scrollY;let f=0,y=0,x="",b="",v="",w="";switch(i){case"top":f=p.top+m-u.height-10,y=p.left+g+(p.width-u.width)/2,v="-5px",b=u.width/2-5+"px";break;case"left":f=p.top+m+(p.height-u.height)/2,y=p.left+g-u.width-10,w="-5px",x=u.height/2-5+"px";break;case"right":f=p.top+m+(p.height-u.height)/2,y=p.right+g+10,b="-5px",x=u.height/2-5+"px";break;default:f=p.bottom+m+10,y=p.left+g+(p.width-u.width)/2,x="-5px",b=u.width/2-5+"px"}y=Math.max(8,Math.min(y,window.innerWidth+g-u.width-8)),f=Math.max(8,f),a.style.top=`${f}px`,a.style.left=`${y}px`,c.style.top=x||"",c.style.left=b||"",c.style.bottom=v||"",c.style.right=w||"";const _=e=>{a.contains(e.target)||s.contains(e.target)||(document.removeEventListener("click",_),l())};setTimeout(()=>document.addEventListener("click",_),100)}addAnimationStyles(){if(document.getElementById("aegis-in-app-styles"))return;const e=document.createElement("style");e.id="aegis-in-app-styles",e.textContent="\n @keyframes aegisSlideDown {\n from { transform: translateY(-100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisSlideUp {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(-100%); opacity: 0; }\n }\n \n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.9); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n\n /* Bottom-anchored slide IN (opposite of aegisSlideUp which slides OUT).\n Used by the preload-first renderers: sticky_bar (bottom),\n progress_bar, carousel_cards, product_recommendation. */\n @keyframes aegisSlideInFromBottom {\n from { transform: translateY(100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n ",document.head.appendChild(e)}sanitizeUrl(e){try{const t=new URL(e,window.location.origin);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked unsafe URL: ${e}`,"error"),null):t.href}catch(t){return this.log(`Invalid URL: ${e}`,"error"),null}}sanitizeColor(e){if(/^#[0-9A-Fa-f]{3,6}$/.test(e))return e;if(/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/.test(e))return e;if(/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/.test(e))return e;return["white","black","red","green","blue","yellow","orange","purple","pink","gray","transparent"].includes(e.toLowerCase())?e:"#000000"}async trackEvent(e,t){if("dismissed"===t){const t=this.campaigns.find(t=>t.id===e);t&&this.emit("campaign-dismiss",{campaign:t,source:"close_button"})}try{const n=`${this.apiHost}/v1/in_app/events`,i=`inapp_${e}_${t}_${Date.now()}`,s={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey};this.organizationId&&(s["X-Organization-ID"]=this.organizationId),this.userId&&(s["X-User-ID"]=this.userId),this.contactId&&(s["X-Contact-ID"]=this.contactId);const o={campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,anonymous_id:this.userId,platform:"web",metadata:{property_id:this.propertyId,variant_id:this.getVariantId(e)??void 0},idempotency_key:i};fetch(n,{method:"POST",headers:s,body:JSON.stringify(o),credentials:"include"}).catch(e=>{this.log(`Error tracking event: ${e}`,"error")}),this.log(`Tracked ${t} event for campaign ${e}`)}catch(n){this.log(`Error tracking event: ${n}`,"error")}}log(e,t="log"){this.debugMode&&console[t](`[AegisInApp] ${e}`)}destroy(e){if(this.disconnectSSE(),"undefined"!=typeof document){document.querySelectorAll(".aegis-in-app-banner, .aegis-in-app-modal-overlay, .aegis-in-app-fullscreen-overlay, .aegis-in-app-half-interstitial-overlay, .aegis-in-app-alert-overlay, .aegis-in-app-pip, .aegis-in-app-nps-overlay, .aegis-in-app-countdown-overlay, .aegis-in-app-rating-overlay, .aegis-in-app-poll-overlay, .aegis-in-app-quiz-overlay, .aegis-in-app-rating-card, .aegis-in-app-nps-card").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const e=document.getElementById("aegis-in-app-styles");e&&e.parentNode&&e.parentNode.removeChild(e)}(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}};J.CONVERSION_STORAGE_PREFIX="aegis_conv_";let G=J;class Y{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.isDestroyed=!1,this.prefetchWidgetConfigs={},this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new d).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.triggerEngine=e.triggerEngine,this.ownsTriggerEngine=!0===e.ownsTriggerEngine,this.enablePrefetch=!1!==e.enablePrefetch,this.cssCustomization=e.cssCustomization||{},this.onEvent=e.onEvent,this.sourcePlatform=e.sourcePlatform}updateCSSCustomization(e){this.cssCustomization={...this.cssCustomization,...e},this.log("CSS customization updated")}async updateContactId(e){this.contactId!==e&&(this.contactId=e,this.log(`Contact ID updated → ${e??"(cleared)"}`),this.isInitialized&&!this.isDestroyed&&this.enablePrefetch&&e&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()))}renderInteractiveCampaign(e){if(this.isDestroyed)return;if("undefined"==typeof document)return;const t=e.sub_type;if("spin_wheel"!==t&&"scratch_card"!==t)return void this.log(`renderInteractiveCampaign: unsupported sub_type "${t}"`,!0);const n={widget_id:e.id,widget_type:t,name:e.title,config:e.interactive_config??{},priority:e.priority??0};this.renderedWidgets.has(n.widget_id)||(this.renderedWidgets.add(n.widget_id),"spin_wheel"===t?this.renderSpinWheel(n):this.renderScratchCard(n))}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.triggerEngine&&this.ownsTriggerEngine&&this.triggerEngine.stop(),"undefined"!=typeof document){const e=document.getElementById("aegis-widget-animations");null==e||e.remove(),document.querySelectorAll("[data-aegis-widget-root]").forEach(e=>{e.remove()})}this.renderedWidgets.clear(),this.widgets=[],this.isInitialized=!1,this.log("AegisWidgets destroyed"),this.emitEvent("destroyed",{})}}emitEvent(e,t){if(this.onEvent)try{this.onEvent(e,t)}catch(n){this.log(`Error in event callback: ${n}`,!0)}}async initialize(){this.isInitialized?this.log("AegisWidgets already initialized"):(this.enablePrefetch&&this.contactId&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()),await this.fetchWidgets(),this.renderImmediateWidgets(),this.setupTriggerListeners(),this.setupExitIntentWithPrefetch(),this.isInitialized=!0,this.log("AegisWidgets initialized successfully"))}setCartData(e){this.cartData=e,this.log(`Cart data updated: ${e.cart_items.length} items, total: ${e.cart_currency} ${e.cart_total}`)}detectPlatformCart(){const e=this.normalizeShopifyCart();if(e)return this.log("Detected Shopify cart via browser globals"),e;const t=this.normalizeWooCart();if(t)return this.log("Detected WooCommerce cart via injected data"),t;const n=this.normalizeMagentoCart();return n?(this.log("Detected Magento cart via localStorage"),n):this.cartData?(this.log("Using manually set cart data"),this.cartData):null}normalizeShopifyCart(){var e;try{if("undefined"==typeof window)return null;const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=t.Shopify.checkout;return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:parseFloat(e.total_price)||0,cart_currency:e.currency||"USD",cart_items:(e.line_items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.title||e.product_title,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}const n=document.getElementById("cart-json");if(null==n?void 0:n.textContent){const e=JSON.parse(n.textContent);return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:(e.total_price||0)/100,cart_currency:e.currency||"USD",cart_items:(e.items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.product_title||e.title,quantity:e.quantity||1,price:(e.price||0)/100}))}}return null}catch(t){return this.log(`Error detecting Shopify cart: ${t}`,!0),null}}normalizeWooCart(){try{if("undefined"==typeof window)return null;const e=window;if(e.aegis_cart){const t=e.aegis_cart;return{cart_id:t.cart_id||`woo_${Date.now()}`,cart_total:parseFloat(t.cart_total)||0,cart_currency:t.cart_currency||"USD",cart_items:(t.cart_items||[]).map(e=>({product_id:String(e.product_id),product_name:e.product_name,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}return null}catch(e){return this.log(`Error detecting WooCommerce cart: ${e}`,!0),null}}normalizeMagentoCart(){try{if("undefined"==typeof window||!window.localStorage)return null;const e=localStorage.getItem("mage-cache-storage");if(!e)return null;const t=JSON.parse(e);if(!(null==t?void 0:t.cart))return null;const n=t.cart;return{cart_id:n.quote_id||n.id||`magento_${Date.now()}`,cart_total:parseFloat(n.subtotalAmount||n.subtotal||0),cart_currency:n.currencyCode||"USD",cart_items:(n.items||[]).map(e=>({product_id:String(e.item_id||e.product_id),product_name:e.product_name||e.name,quantity:e.qty||1,price:parseFloat(e.product_price_value||e.price||0)}))}}catch(e){return this.log(`Error detecting Magento cart: ${e}`,!0),null}}preloadWidgetAssets(){try{const e=this.prefetchWidgetConfigs.exit_intent;if(null==e?void 0:e.enabled){const t=e.image_url;if(t){(new Image).src=t,this.log(`Preloading exit intent image: ${t}`)}}const t=this.prefetchWidgetConfigs.spin_wheel;if(null==t?void 0:t.enabled){const e=t.image_url;if(e){(new Image).src=e,this.log(`Preloading spin wheel image: ${e}`)}}}catch(e){this.log(`Error preloading widget assets: ${e}`,!0)}}async fetchPrefetchConfigs(){try{const e=performance.now(),t=`${this.apiHost}/v1/widgets/config/prefetch`,n={"X-Aegis-Write-Key":this.writeKey};this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n,credentials:"include"});if(!i.ok)throw new Error(`Failed to fetch prefetch configs: ${i.status}`);this.prefetchWidgetConfigs=await i.json();const s=performance.now()-e;this.log(`Fetched prefetch widget configs in ${s.toFixed(2)}ms`)}catch(e){this.log(`Error fetching prefetch configs: ${e}`,!0)}}async fetchWidgets(){try{const e=`${this.apiHost}/v1/widgets/config`,t={"X-Aegis-Write-Key":this.writeKey,"X-Device-Platform":"web","X-Device-Type":this.getDeviceType()};this.userId&&(t["X-User-ID"]=this.userId),this.contactId&&(t["X-Contact-ID"]=this.contactId),this.organizationId&&(t["X-Organization-ID"]=this.organizationId),this.sourcePlatform&&(t["X-Source-Platform"]=this.sourcePlatform);const n=await fetch(e,{headers:t,credentials:"include"});if(!n.ok)throw new Error(`Failed to fetch widgets: ${n.status}`);this.widgets=await n.json(),this.log(`Fetched ${this.widgets.length} widgets`)}catch(e){this.log(`Error fetching widgets: ${e}`,!0)}}renderImmediateWidgets(){this.widgets.filter(e=>!e.trigger_rules||"immediate"===e.trigger_rules.type).forEach(e=>this.renderWidget(e))}setupTriggerListeners(){this.triggerEngine?this.widgets.forEach(e=>{if(!e.trigger_rules)return;const{type:t,config:n}=e.trigger_rules;switch(t){case"exit_intent":this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"scroll_depth":const t=(null==n?void 0:n.depth_percent)||50;this.triggerEngine.registerScrollDepth(t),this.triggerEngine.on(`scroll_depth_${t}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"time_on_page":const i=(null==n?void 0:n.seconds)||30;this.triggerEngine.registerTimeOnPage(i),this.triggerEngine.on(`time_on_page_${i}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)})}}):this.log("TriggerEngine not provided, skipping trigger-based widgets")}setupExitIntentWithPrefetch(){if(!this.enablePrefetch||!this.triggerEngine)return;const e=this.prefetchWidgetConfigs.spin_wheel,t=this.prefetchWidgetConfigs.exit_intent;if(e&&e.enabled){const n=this.isMobileDevice(),i=(null==t?void 0:t.mobile_triggers)||{},s=()=>{const t=`prefetch_spin_wheel_${Date.now()}`;if(this.renderedWidgets.has(t))return;this.renderedWidgets.add(t);const n=this.detectPlatformCart();"cart_recovery"===e.type&&n?(this.cartData=n,this.renderSpinWheelWidget(t,e),this.sendCartAbandonmentBeacon()):"lead_gen"===e.type&&this.renderSpinWheelWidget(t,e)};if(n){!1!==i.scroll_velocity&&(this.triggerEngine.registerScrollVelocity({threshold:i.scroll_threshold||.5,minScrollPosition:i.scroll_min_position||100,cooldown:i.scroll_cooldown||5e3}),this.triggerEngine.on("mobile_exit_intent",s),this.log("Registered mobile scroll velocity trigger for spin wheel"));if(!1!==i.idle_timer){const e=i.idle_seconds||15;this.triggerEngine.registerInactivity(e),this.triggerEngine.on(`inactivity_${e}`,s),this.log(`Registered mobile idle timer trigger for spin wheel: ${e}s`)}if(!1!==i.visibility_change){const e=this.detectPlatformCart();e&&e.cart_items&&e.cart_items.length>0&&(this.triggerEngine.registerVisibilityChange(),this.triggerEngine.on("visibility_hidden",s),this.log("Registered mobile visibility change trigger for spin wheel (cart detected)"))}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",s),this.log("Registered mobile back button trigger for spin wheel")),this.log(`Setup mobile spin wheel: type=${e.type}, priority=${e.priority}`)}else this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",s),this.log(`Setup desktop spin wheel exit intent: type=${e.type}, priority=${e.priority}`);return}if(!t||!t.enabled)return void this.log("No exit intent config found in prefetch");const n=this.isMobileDevice(),i=t.mobile_triggers||{},s=()=>{const e=`prefetch_exit_intent_${Date.now()}`;if(this.renderedWidgets.has(e))return;this.renderedWidgets.add(e);const n=this.detectPlatformCart();"cart_recovery"===t.type&&n?(this.cartData=n,this.renderCartRecoveryPopup(e,t),this.sendCartAbandonmentBeacon()):"lead_gen"===t.type?this.renderLeadGenPopup(e,t):this.log("Unknown exit intent type or missing cart data")};if(n){!1!==i.scroll_velocity&&(this.triggerEngine.registerScrollVelocity({threshold:i.scroll_threshold||.5,minScrollPosition:i.scroll_min_position||100,cooldown:i.scroll_cooldown||5e3}),this.triggerEngine.on("mobile_exit_intent",s),this.log("Registered mobile scroll velocity trigger"));if(!1!==i.idle_timer){const e=i.idle_seconds||15;this.triggerEngine.registerInactivity(e),this.triggerEngine.on(`inactivity_${e}`,s),this.log(`Registered mobile idle timer trigger: ${e}s`)}if(!1!==i.visibility_change){const e=this.detectPlatformCart();e&&e.cart_items&&e.cart_items.length>0?(this.triggerEngine.registerVisibilityChange(),this.triggerEngine.on("visibility_hidden",s),this.log("Registered mobile visibility change trigger (cart detected)")):this.log("Skipped visibility change trigger (no cart items)")}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",s),this.log("Registered mobile back button trigger (aggressive mode)")),this.log(`Setup mobile exit intent: type=${t.type}, priority=${t.priority}`)}else this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",s),this.log(`Setup desktop exit intent: type=${t.type}, priority=${t.priority}`)}sendCartAbandonmentBeacon(){if(!this.cartData)return void this.log("No cart data available for beacon",!0);const e={organization_id:this.organizationId||"default",contact_id:this.contactId,cart_id:this.cartData.cart_id,cart_total:this.cartData.cart_total,cart_currency:this.cartData.cart_currency,cart_items:this.cartData.cart_items,user_email:this.userId,abandoned_at:(new Date).toISOString(),page_url:window.location.href,referrer:document.referrer},t=`${this.apiHost}/v1/widgets/beacon/cart-abandoned`;if(navigator.sendBeacon){const n=new Blob([JSON.stringify(e)],{type:"application/json"});navigator.sendBeacon(t,n)?this.log("Cart abandonment beacon sent successfully"):this.log("Failed to send cart abandonment beacon",!0)}else fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(e),keepalive:!0,credentials:"include"}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!this.isDestroyed&&!this.renderedWidgets.has(e.widget_id)){switch(this.renderedWidgets.add(e.widget_id),e.widget_type){case"chat_bubble":this.renderChatBubble(e);break;case"spin_wheel":this.renderSpinWheel(e);break;case"scratch_card":this.renderScratchCard(e);break;case"toast":this.renderToast(e);break;case"feedback_form":this.renderFeedbackForm(e);break;case"exit_intent_popup":this.renderExitIntentPopup(e);break;default:this.log(`Unknown widget type: ${e.widget_type}`,!0)}this.trackEvent(e.widget_id,"show")}}renderChatBubble(e){const{text:t,icon_url:n,link_url:i,background_color:s,text_color:o}=e.config,r=e.position||"bottom_right",a=document.createElement("div");a.className="aegis-chat-bubble",a.setAttribute("data-widget-id",e.widget_id);const c={bottom_right:"bottom: 20px; right: 20px;",bottom_left:"bottom: 20px; left: 20px;",top_right:"top: 20px; right: 20px;",top_left:"top: 20px; left: 20px;"};if(a.style.cssText=`\n position: fixed;\n ${c[r]||c.bottom_right}\n background: ${this.sanitizeColor(s||"#25D366")};\n color: ${this.sanitizeColor(o||"#ffffff")};\n padding: 16px 24px;\n border-radius: 50px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n cursor: pointer;\n z-index: 999999;\n display: flex;\n align-items: center;\n gap: 12px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n font-weight: 600;\n font-size: 14px;\n animation: aegisBubbleIn 0.3s ease-out;\n `,n){const e=document.createElement("img"),t=this.sanitizeUrl(n);t&&(e.src=t,e.alt="",e.style.cssText="width: 24px; height: 24px;",a.appendChild(e))}const d=document.createElement("span");d.textContent=t||"Chat with us",a.appendChild(d),a.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(i);t&&window.open(t,"_blank")}),this.addAnimationStyles(),a.setAttribute("data-aegis-widget-root",""),document.body.appendChild(a)}renderSpinWheel(e){const t=document.createElement("div");t.className="aegis-gamification-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");n.className="aegis-spin-wheel-modal",n.style.cssText='\n background: white;\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ';const i=document.createElement("h2");i.textContent=e.config.title||"Spin to Win!",i.style.cssText="margin: 0 0 16px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",n.appendChild(i);const s=document.createElement("p");s.textContent=e.config.description||"Try your luck and win exclusive prizes!",s.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(s);const o=Array.isArray(e.config.segments)?e.config.segments:[{label:"Prize 1",color:"#ff6b6b"},{label:"Prize 2",color:"#feca57"},{label:"Prize 3",color:"#48dbfb"},{label:"Prize 4",color:"#ff6348"}],r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg");a.setAttribute("viewBox","-160 -160 320 320"),a.setAttribute("width","300"),a.setAttribute("height","300"),a.style.cssText="margin: 0 auto 24px; display: block;";const c=o.length,d=2*Math.PI/c,l=140;for(let u=0;u<c;u++){const e=u*d-Math.PI/2,t=e+d,n=Math.cos(e)*l,i=Math.sin(e)*l,s=Math.cos(t)*l,c=Math.sin(t)*l,h=d>Math.PI?1:0,p=document.createElementNS(r,"path");p.setAttribute("d",`M 0 0 L ${n.toFixed(2)} ${i.toFixed(2)} A 140 140 0 ${h} 1 ${s.toFixed(2)} ${c.toFixed(2)} Z`),p.setAttribute("fill",this.sanitizeColor(o[u].color||"#cccccc")),p.setAttribute("stroke","#ffffff"),p.setAttribute("stroke-width","2"),a.appendChild(p);const g=e+d/2,m=Math.cos(g)*l*.65,f=Math.sin(g)*l*.65,y=document.createElementNS(r,"text");y.setAttribute("x",m.toFixed(2)),y.setAttribute("y",f.toFixed(2)),y.setAttribute("fill","#ffffff"),y.setAttribute("font-size","13"),y.setAttribute("font-weight","600"),y.setAttribute("text-anchor","middle"),y.setAttribute("dominant-baseline","middle"),y.textContent=o[u].label||`#${u+1}`,a.appendChild(y)}n.appendChild(a);const h=document.createElement("button");h.textContent="SPIN NOW!",h.style.cssText="\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n margin-bottom: 16px;\n ",h.addEventListener("click",async()=>{h.disabled=!0,h.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);a.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),h.disabled=!1,h.textContent="TRY AGAIN"}}),n.appendChild(h);const p=document.createElement("button");p.textContent="×",p.setAttribute("aria-label","Close"),p.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",p.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(p),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderSpinWheelWidget(e,t){if(this.isDestroyed)return;const n=this.detectPlatformCart();if("cart_recovery"===t.type&&!n)return void this.log("Spin wheel requires cart, but none detected");n&&(this.cartData=n);const i=this.cssCustomization.spinWheel||{},s=i.accentColor||t.accent_color||"#FF6B6B",o=i.backgroundColor||t.background_color||"#FFFFFF",r=i.textColor||t.text_color||"#333333",a=i.buttonColor||t.button_color||s,c=i.wheelColors||["#FF6B6B","#4ECDC4","#FFE66D","#95E1D3"],d=document.createElement("div");d.className="aegis-spin-wheel-overlay",d.setAttribute("data-widget-id",e),d.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.7);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 999999;\n animation: aegisFadeIn 0.3s ease;\n ";const l=document.createElement("div");l.className="aegis-spin-wheel-modal",l.style.cssText=`\n background: ${this.sanitizeColor(o)};\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 20px 60px rgba(0,0,0,0.3);\n position: relative;\n animation: aegisScaleIn 0.4s ease;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `;const h=document.createElement("button");h.innerHTML="✕",h.className="aegis-spin-wheel-close",h.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: none;\n border: none;\n font-size: 24px;\n cursor: pointer;\n color: #999;\n ",h.onclick=()=>{this.trackEvent(e,"dismiss",{type:"spin_wheel"}),document.body.removeChild(d),this.renderedWidgets.delete(e)},l.appendChild(h);const p=document.createElement("h2");if(p.textContent=this.interpolateCartVariables(t.title||"Spin to Win!"),p.style.cssText=`\n margin: 0 0 16px 0;\n font-size: 28px;\n font-weight: bold;\n text-align: center;\n color: ${this.sanitizeColor(r)};\n `,l.appendChild(p),n){const e=document.createElement("p");e.textContent=`Complete your ${n.cart_currency} ${n.cart_total.toFixed(2)} order and save!`,e.style.cssText="\n margin: 0 0 24px 0;\n font-size: 16px;\n text-align: center;\n color: #666;\n ",l.appendChild(e)}const u=document.createElement("div");u.className="aegis-wheel-container",u.style.cssText=`\n width: 300px;\n height: 300px;\n margin: 0 auto 24px auto;\n background: conic-gradient(\n from 0deg,\n ${c[0]} 0deg 90deg,\n ${c[1]} 90deg 180deg,\n ${c[2]} 180deg 270deg,\n ${c[3]} 270deg 360deg\n );\n border-radius: 50%;\n position: relative;\n display: flex;\n align-items: center;\n justify-content: center;\n `;const g=document.createElement("form");g.className="aegis-spin-form",g.style.cssText="display: block;";const m=document.createElement("input");m.type="tel",m.placeholder="Enter your phone number",m.required=!0,m.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(m);const f=document.createElement("input");f.type="email",f.placeholder="Enter your email (optional)",f.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(f);const y=document.createElement("input");y.type="text",y.placeholder="Enter your name (optional)",y.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 12px;\n box-sizing: border-box;\n ",g.appendChild(y);const x=document.createElement("button");x.type="submit",x.textContent="Spin the Wheel!",x.style.cssText=`\n width: 100%;\n padding: 14px;\n background: ${this.sanitizeColor(a)};\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 700;\n cursor: pointer;\n `,g.appendChild(x);const b=document.createElement("div");b.className="aegis-spin-error",b.style.cssText="\n color: #d32f2f;\n font-size: 14px;\n margin-top: 12px;\n text-align: center;\n display: none;\n ",g.appendChild(b),g.addEventListener("submit",async t=>{t.preventDefault();const i=m.value.trim(),s=f.value.trim(),o=y.value.trim();return this.validatePhone(i)?s&&!this.validateEmail(s)?(b.textContent="Please enter a valid email address",void(b.style.display="block")):(b.style.display="none",x.disabled=!0,x.textContent="Spinning...",u.style.animation="aegisSpin 2s ease-out",void setTimeout(async()=>{try{const t=await this.submitSpinWheel({phone:i,email:s,name:o,cart:n,widgetId:e});this.showSpinWheelPrize(l,t),this.trackEvent(e,"submit",{type:"spin_wheel",prize_label:t.prize_label,has_email:!!s})}catch(t){this.log(`Error submitting spin wheel: ${t}`,!0),b.textContent="Failed to submit. Please try again.",b.style.display="block",x.disabled=!1,x.textContent="Spin the Wheel!",u.style.animation=""}},2e3)):(b.textContent="Please enter a valid phone number (e.g., +1234567890)",void(b.style.display="block"))}),l.appendChild(u),l.appendChild(g),d.appendChild(l),this.addAnimationStyles(),d.setAttribute("data-aegis-widget-root",""),document.body.appendChild(d),this.trackEvent(e,"show",{type:"spin_wheel"})}validatePhone(e){return/^\+?[1-9]\d{1,14}$/.test(e.replace(/[\s()-]/g,""))}validateEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}async submitSpinWheel(e){var t,n,i,s,o;const r=`${this.apiHost}/v1/widgets/spin-wheel/submit`,a={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.organizationId&&(a["X-Organization-ID"]=this.organizationId);const c=this.detectGeoRegion(),d=this.getDeviceType(),l=this.getUTMParams(),h={phone:e.phone.replace(/[\s()-]/g,""),email:e.email||void 0,name:e.name||void 0,cart_id:(null==(t=e.cart)?void 0:t.cart_id)||`web_${Date.now()}`,cart_token:null==(n=e.cart)?void 0:n.cart_id,cart_total:(null==(i=e.cart)?void 0:i.cart_total)||0,cart_currency:(null==(s=e.cart)?void 0:s.cart_currency)||"USD",cart_items:(null==(o=e.cart)?void 0:o.cart_items)||[],cart_url:window.location.href,platform:"web",geo_region:c,device_type:d,session_id:this.getSessionId()||void 0,anonymous_id:this.getAnonymousId()||void 0,utm_source:l.utm_source,utm_medium:l.utm_medium,utm_campaign:l.utm_campaign},p=await fetch(r,{method:"POST",headers:a,body:JSON.stringify(h),credentials:"include"});if(!p.ok){const e=await p.text();throw new Error(`Failed to submit spin wheel: ${p.status} - ${e}`)}return await p.json()}showSpinWheelPrize(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const s=document.createElement("h2");s.textContent="Congratulations!",s.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(s);const o=document.createElement("p");if(o.textContent=t.prize_label,o.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(o),t.coupon_code){const e=document.createElement("div");e.style.cssText="\n background: #f5f5f5;\n padding: 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 2px dashed #1a73e8;\n ";const i=document.createElement("div");i.textContent="Your coupon code:",i.style.cssText="font-size: 12px; color: #666; margin-bottom: 8px;",e.appendChild(i);const s=document.createElement("div");s.textContent=t.coupon_code,s.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(s),n.appendChild(e)}const r=document.createElement("p");r.textContent="Check your WhatsApp/SMS for your discount code and cart link!",r.style.cssText="margin: 0 0 20px 0; font-size: 14px; color: #666;",n.appendChild(r);const a=document.createElement("button");a.textContent="Close",a.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",a.addEventListener("click",()=>{const t=e.parentElement;t&&document.body.contains(t)&&document.body.removeChild(t)}),n.appendChild(a),e.appendChild(n)}detectGeoRegion(){const e=Intl.DateTimeFormat().resolvedOptions().timeZone;return e.includes("America")?"north_america":e.includes("Europe")?"europe":e.includes("Asia/Kolkata")||e.includes("Asia/Calcutta")?"india":e.includes("Asia/Singapore")||e.includes("Asia/Bangkok")||e.includes("Asia/Jakarta")?"southeast_asia":e.includes("Asia/Dubai")||e.includes("Asia/Riyadh")?"middle_east":e.includes("America")&&(e.includes("Sao_Paulo")||e.includes("Buenos_Aires"))?"latin_america":e.includes("Australia")||e.includes("Pacific/Auckland")?"oceania":"north_america"}getUTMParams(){const e=new URLSearchParams(window.location.search);return{utm_source:e.get("utm_source")||void 0,utm_medium:e.get("utm_medium")||void 0,utm_campaign:e.get("utm_campaign")||void 0}}getSessionId(){return sessionStorage.getItem("aegis_session_id")}getAnonymousId(){return localStorage.getItem("aegis_anonymous_id")}renderScratchCard(e){const t=document.createElement("div");t.className="aegis-gamification-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const n=document.createElement("div");n.className="aegis-scratch-card-modal",n.style.cssText='\n background: white;\n border-radius: 16px;\n padding: 32px;\n max-width: 500px;\n width: 90%;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ';const i=document.createElement("h2");i.textContent=e.config.title||"Scratch & Win!",i.style.cssText="margin: 0 0 16px 0; font-size: 24px; font-weight: 700; color: #1a1a1a;",n.appendChild(i);const s=document.createElement("p");s.textContent=e.config.description||"Scratch to reveal your prize!",s.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(s);const o=document.createElement("canvas");o.width=300,o.height=200,o.style.cssText="\n border-radius: 8px;\n cursor: pointer;\n margin: 0 auto 24px;\n display: block;\n box-shadow: 0 4px 12px rgba(0,0,0,0.1);\n ",n.appendChild(o);const r=o.getContext("2d");if(r){r.fillStyle="#c0c0c0",r.fillRect(0,0,o.width,o.height),r.fillStyle="#888",r.font="20px Arial",r.textAlign="center",r.fillText("Scratch here!",o.width/2,o.height/2);let e=!1;const t=(e,t)=>{r.globalCompositeOperation="destination-out",r.beginPath(),r.arc(e,t,20,0,2*Math.PI),r.fill()};o.addEventListener("mousedown",()=>{e=!0}),o.addEventListener("mouseup",()=>{e=!1}),o.addEventListener("mousemove",n=>{if(e){const e=o.getBoundingClientRect();t(n.clientX-e.left,n.clientY-e.top)}})}const a=document.createElement("button");a.textContent="REVEAL PRIZE",a.style.cssText="\n background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);\n color: white;\n border: none;\n padding: 16px 48px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n ",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="REVEALING...";try{const t=await this.generatePrize(e.config.config_id);this.showPrizeResult(n,t)}catch(t){this.log(`Error generating prize: ${t}`,!0),a.disabled=!1,a.textContent="TRY AGAIN"}}),n.appendChild(a),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderToast(e){const{message:t,icon:n,duration:i}=e.config,s=e.position||"bottom_left",o=document.createElement("div");o.className="aegis-toast",o.setAttribute("data-widget-id",e.widget_id);const r={bottom_left:"bottom: 20px; left: 20px;",bottom_right:"bottom: 20px; right: 20px;",top_left:"top: 20px; left: 20px;",top_right:"top: 20px; right: 20px;"};if(o.style.cssText=`\n position: fixed;\n ${r[s]||r.bottom_left}\n background: white;\n padding: 16px 20px;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0,0,0,0.15);\n z-index: 999998;\n display: flex;\n align-items: center;\n gap: 12px;\n max-width: 350px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisToastIn 0.3s ease-out;\n `,n){const e=document.createElement("div");e.textContent=n,e.style.cssText="font-size: 20px;",o.appendChild(e)}const a=document.createElement("div");a.textContent=t||"Someone just made a purchase!",a.style.cssText="flex: 1; font-size: 13px; color: #333;",o.appendChild(a),this.addAnimationStyles(),o.setAttribute("data-aegis-widget-root",""),document.body.appendChild(o),setTimeout(()=>{o.style.animation="aegisToastOut 0.3s ease-out",setTimeout(()=>{document.body.contains(o)&&document.body.removeChild(o),this.renderedWidgets.delete(e.widget_id)},300)},i||5e3)}renderFeedbackForm(e){const t=document.createElement("div");t.className="aegis-feedback-overlay",t.setAttribute("data-widget-id",e.widget_id),t.style.cssText='\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 400px;\n background: white;\n box-shadow: -4px 0 20px rgba(0,0,0,0.15);\n z-index: 1000000;\n padding: 32px;\n overflow-y: auto;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInRight 0.3s ease-out;\n ';const n=document.createElement("h2");n.textContent=e.config.title||"We value your feedback!",n.style.cssText="margin: 0 0 8px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",t.appendChild(n);const i=document.createElement("p");i.textContent=e.config.description||"Help us improve your experience.",i.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",t.appendChild(i);const s=document.createElement("form"),o=document.createElement("label");o.textContent="How likely are you to recommend us? (0-10)",o.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(o);const r=document.createElement("input");r.type="number",r.min="0",r.max="10",r.style.cssText="\n width: 100%;\n padding: 12px;\n border: 1px solid #ddd;\n border-radius: 6px;\n font-size: 14px;\n margin-bottom: 16px;\n ",s.appendChild(r);const a=document.createElement("label");a.textContent="Tell us more (optional)",a.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(a);const c=document.createElement("textarea");c.rows=4,c.style.cssText="\n width: 100%;\n padding: 12px;\n border: 1px solid #ddd;\n border-radius: 6px;\n font-size: 14px;\n resize: vertical;\n margin-bottom: 16px;\n font-family: inherit;\n ",s.appendChild(c);const d=document.createElement("button");d.type="submit",d.textContent="Submit Feedback",d.style.cssText="\n width: 100%;\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px;\n border-radius: 6px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",s.appendChild(d),s.addEventListener("submit",async n=>{n.preventDefault(),d.disabled=!0,d.textContent="Submitting...";try{await this.submitFeedback(e.widget_id,{score:parseInt(r.value),comment:c.value}),t.innerHTML='<div style="text-align: center; padding: 60px 20px;"><h3 style="margin: 0 0 12px 0; color: #1a73e8;">Thank you!</h3><p style="margin: 0; color: #666;">Your feedback helps us improve.</p></div>',setTimeout(()=>{document.body.removeChild(t)},2e3)}catch(i){this.log(`Error submitting feedback: ${i}`,!0),d.disabled=!1,d.textContent="Submit Feedback"}}),t.appendChild(s);const l=document.createElement("button");l.textContent="×",l.setAttribute("aria-label","Close"),l.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",l.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),t.appendChild(l),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:s,image_url:o}=e.config,r=document.createElement("div");r.className="aegis-exit-popup-overlay",r.setAttribute("data-widget-id",e.widget_id),r.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const a=document.createElement("div");if(a.className="aegis-exit-popup-modal",a.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n overflow: hidden;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n ',o){const e=document.createElement("img"),t=this.sanitizeUrl(o);t&&(e.src=t,e.alt="",e.style.cssText="width: 100%; height: 250px; object-fit: cover;",a.appendChild(e))}const c=document.createElement("div");c.style.cssText="padding: 32px;";const d=document.createElement("h2");d.textContent=t||"Wait! Don't leave yet!",d.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",c.appendChild(d);const l=document.createElement("p");if(l.textContent=n||"Get 10% off your first order!",l.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666; line-height: 1.5;",c.appendChild(l),i&&s){const t=document.createElement("button");t.textContent=i,t.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n ",t.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(s);t&&(window.location.href=t)}),c.appendChild(t)}a.appendChild(c);const h=document.createElement("button");h.textContent="×",h.setAttribute("aria-label","Close"),h.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: white;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #666;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n box-shadow: 0 2px 8px rgba(0,0,0,0.2);\n ",h.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(r),this.renderedWidgets.delete(e.widget_id)}),a.style.position="relative",a.appendChild(h),r.appendChild(a),this.addAnimationStyles(),r.setAttribute("data-aegis-widget-root",""),document.body.appendChild(r)}async generatePrize(e){const t=`${this.apiHost}/v1/widgets/gamification/generate-prize`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{method:"POST",headers:n,body:JSON.stringify({config_id:e}),credentials:"include"});if(!i.ok)throw new Error(`Failed to generate prize: ${i.status}`);return await i.json()}showPrizeResult(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const s=document.createElement("h2");s.textContent="Congratulations!",s.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(s);const o=document.createElement("p");if(o.textContent=t.prize_label,o.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(o),t.coupon_code){const e=document.createElement("div");e.style.cssText="\n background: #f5f5f5;\n padding: 16px;\n border-radius: 8px;\n margin-bottom: 20px;\n border: 2px dashed #1a73e8;\n ";const i=document.createElement("div");i.textContent="Your coupon code:",i.style.cssText="font-size: 12px; color: #666; margin-bottom: 8px;",e.appendChild(i);const s=document.createElement("div");s.textContent=t.coupon_code,s.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(s),n.appendChild(e)}const r=document.createElement("button");r.textContent="Close",r.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 12px 32px;\n border-radius: 8px;\n font-weight: 600;\n font-size: 14px;\n cursor: pointer;\n ",r.addEventListener("click",()=>{const t=e.parentElement;t&&document.body.contains(t)&&document.body.removeChild(t)}),n.appendChild(r),e.appendChild(n)}async submitFeedback(e,t){const n=`${this.apiHost}/v1/widgets/track-event`,i={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(i["X-User-ID"]=this.userId),this.contactId&&(i["X-Contact-ID"]=this.contactId),this.organizationId&&(i["X-Organization-ID"]=this.organizationId);const s=await fetch(n,{method:"POST",headers:i,body:JSON.stringify({widget_id:e,event_type:"submit",event_data:t}),credentials:"include"});if(!s.ok)throw new Error(`Failed to submit feedback: ${s.status}`)}async trackEvent(e,t,n){try{const i=`${this.apiHost}/v1/widgets/track-event`,s={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(s["X-User-ID"]=this.userId),this.contactId&&(s["X-Contact-ID"]=this.contactId),this.organizationId&&(s["X-Organization-ID"]=this.organizationId),await fetch(i,{method:"POST",headers:s,body:JSON.stringify({widget_id:e,event_type:t,event_data:n||{}}),credentials:"include"})}catch(i){this.log(`Error tracking widget event: ${i}`,!0)}}sanitizeUrl(e){if(!e)return null;try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked dangerous URL: ${e}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-F]{3,8}$/i.test(e)||/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/i.test(e)||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/i.test(e)?e:"#1a73e8"}getDeviceType(){const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"}isMobileDevice(){const e=this.getDeviceType();return"mobile"===e||"tablet"===e}addAnimationStyles(){if(document.getElementById("aegis-widget-animations"))return;const e=document.createElement("style");e.id="aegis-widget-animations",e.textContent="\n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.8); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n \n @keyframes aegisBubbleIn {\n from { transform: translateY(20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisToastIn {\n from { transform: translateX(-100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n \n @keyframes aegisToastOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(-100%); opacity: 0; }\n }\n \n @keyframes aegisSlideInRight {\n from { transform: translateX(100%); }\n to { transform: translateX(0); }\n }\n \n @keyframes aegisSpin {\n from { transform: rotate(0deg); }\n to { transform: rotate(1440deg); }\n }\n ",document.head.appendChild(e)}renderCartRecoveryPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-cart-recovery-modal",i.style.cssText=`\n background: ${this.sanitizeColor(t.background_color||"#FFFFFF")};\n color: ${this.sanitizeColor(t.text_color||"#333333")};\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n `;const s=document.createElement("h2"),o=this.interpolateCartVariables(t.title||"Complete Your Order");s.textContent=o,s.style.cssText=`margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: ${this.sanitizeColor(t.accent_color||"#FF6B00")};`,i.appendChild(s);const r=document.createElement("p"),a=this.interpolateCartVariables(t.message||"Your cart is waiting for you!");if(r.textContent=a,r.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5;",i.appendChild(r),t.show_cart_items&&this.cartData){const e=document.createElement("div");e.style.cssText="margin: 0 0 24px 0; padding: 16px; background: rgba(0,0,0,0.05); border-radius: 8px;";const t=document.createElement("div");t.textContent=`${this.cartData.cart_items.length} items in your cart`,t.style.cssText="font-weight: 600; margin-bottom: 12px;",e.appendChild(t),this.cartData.cart_items.slice(0,3).forEach(t=>{const n=document.createElement("div");n.textContent=`${t.quantity}× ${t.product_name||t.product_id}`,n.style.cssText="font-size: 14px; margin-bottom: 4px;",e.appendChild(n)}),i.appendChild(e)}if(t.discount_code){const e=document.createElement("div");e.style.cssText=`\n margin: 0 0 24px 0;\n padding: 16px;\n background: ${this.sanitizeColor(t.accent_color||"#FF6B00")};\n color: white;\n border-radius: 8px;\n text-align: center;\n font-weight: 700;\n font-size: 18px;\n `,e.textContent=`Use code: ${t.discount_code} for ${t.discount_percentage||10}% off!`,i.appendChild(e)}if(t.show_timer&&t.timer_minutes){const e=document.createElement("div");e.style.cssText="margin: 0 0 24px 0; text-align: center; font-size: 14px; color: #999;",e.textContent=`⏰ Offer expires in ${t.timer_minutes} minutes`,i.appendChild(e)}const c=document.createElement("button");c.textContent=t.cta_text||"Complete Checkout",c.style.cssText=`\n background: ${this.sanitizeColor(t.accent_color||"#FF6B00")};\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,c.addEventListener("click",()=>{this.trackEvent(e,"click",{type:"cart_recovery"});const n=this.sanitizeUrl(t.cta_url||"/checkout");n&&(window.location.href=n)}),i.appendChild(c);const d=document.createElement("button");d.textContent="×",d.setAttribute("aria-label","Close"),d.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",d.addEventListener("click",()=>{this.trackEvent(e,"dismiss",{type:"cart_recovery"}),document.body.removeChild(n),this.renderedWidgets.delete(e)}),i.appendChild(d),n.appendChild(i),this.addAnimationStyles(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-leadgen-modal",i.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 500px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n ';const s=document.createElement("h2");s.textContent=t.title||"Get 10% Off Your First Order!",s.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",i.appendChild(s);const o=document.createElement("p");o.textContent=t.message||"Subscribe to our newsletter and get an exclusive discount code.",o.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666;",i.appendChild(o);const r=document.createElement("form"),a=document.createElement("input");a.type="email",a.placeholder="Enter your email",a.required=!0,a.style.cssText="\n width: 100%;\n padding: 14px;\n border: 2px solid #ddd;\n border-radius: 8px;\n font-size: 16px;\n margin-bottom: 16px;\n box-sizing: border-box;\n ",r.appendChild(a);const c=document.createElement("button");c.type="submit",c.textContent="Get My Discount",c.style.cssText="\n width: 100%;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n padding: 16px 32px;\n border-radius: 8px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n ",r.appendChild(c),r.addEventListener("submit",async t=>{t.preventDefault(),c.disabled=!0,c.textContent="Submitting...";try{await this.trackEvent(e,"submit",{type:"lead_gen",email:a.value}),i.innerHTML='\n <div style="text-align: center; padding: 20px;">\n <div style="font-size: 48px; margin-bottom: 16px;">✅</div>\n <h3 style="margin: 0 0 12px 0; color: #1a73e8;">Thank You!</h3>\n <p style="margin: 0; color: #666;">Check your email for your discount code!</p>\n </div>\n ',setTimeout(()=>{document.body.removeChild(n)},2500)}catch(s){this.log(`Error submitting lead gen form: ${s}`,!0),c.disabled=!1,c.textContent="Get My Discount"}}),i.appendChild(r);const d=document.createElement("button");d.textContent="×",d.setAttribute("aria-label","Close"),d.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",d.addEventListener("click",()=>{this.trackEvent(e,"dismiss",{type:"lead_gen"}),document.body.removeChild(n),this.renderedWidgets.delete(e)}),i.appendChild(d),n.appendChild(i),this.addAnimationStyles(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"lead_gen"})}interpolateCartVariables(e){return this.cartData?e.replace(/\{\{cart_total\}\}/g,`${this.cartData.cart_currency} ${this.cartData.cart_total.toFixed(2)}`).replace(/\{\{cart_currency\}\}/g,this.cartData.cart_currency).replace(/\{\{cart_items_count\}\}/g,this.cartData.cart_items.length.toString()):e}log(e,t=!1){if(this.debugMode||t){console[t?"error":"log"](`[AegisWidgets] ${e}`)}}}class Z{constructor(){this.listeners=new Map,this.isStarted=!1,this.scrollDepthTargets=new Set,this.scrollDepthReached=new Set,this.timeOnPageTargets=new Map,this.exitIntentEnabled=!1,this.exitIntentFired=!1,this.inactivityTargets=new Map,this.lastActivityTime=Date.now(),this.scrollVelocityEnabled=!1,this.scrollVelocityFired=!1,this.scrollVelocityConfig={threshold:.5,minScrollPosition:100,cooldown:5e3},this.lastScrollY=0,this.lastScrollTime=Date.now(),this.visibilityChangeEnabled=!1,this.backButtonEnabled=!1,this.backButtonFired=!1,this.rageClickEnabled=!1,this.rageClickConfig={threshold:3,windowMs:1e3},this.rageClickBuffer=new Map,this.rageClickFiredInBurst=new Set,this.hoverEnabled=!1,this.hoverStartAt=new Map,this.hoverLastMs=new Map,this.hoverThresholds=new Map([["price",[1500]],["cta",[1500]]]),this.hoverThresholdsFired=new Map,this.hoverThresholdTimers=new Map,this.mouseVelEnabled=!1,this.mouseVelConfig={threshold:1.5,windowMs:400,cooldownMs:5e3},this.mouseSamples=[],this.mouseVelLast=0,this.mouseVelLastFiredAt=0,this.handleScroll=()=>{const e=window.pageYOffset||document.documentElement.scrollTop,t=document.documentElement.scrollHeight-window.innerHeight,n=t>0?e/t*100:0;for(const i of this.scrollDepthTargets)n>=i&&!this.scrollDepthReached.has(i)&&(this.scrollDepthReached.add(i),this.emit(`scroll_depth_${i}`,{depth_percent:i,actual_percent:n,scroll_top:e,scroll_height:t}))},this.handleExitIntent=e=>{this.exitIntentFired||e.clientY<10&&(this.exitIntentFired=!0,this.emit("exit_intent",{client_y:e.clientY,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleScrollVelocity=()=>{if(this.scrollVelocityFired)return;const e=window.scrollY||document.documentElement.scrollTop,t=Date.now(),n=t-this.lastScrollTime;if(n>100){const i=this.lastScrollY-e,s=Math.abs(i/n);i>0&&s>this.scrollVelocityConfig.threshold&&e>this.scrollVelocityConfig.minScrollPosition&&(this.scrollVelocityFired=!0,this.emit("mobile_exit_intent",{scroll_velocity:s,scroll_distance:i,current_position:e,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}),this.scrollVelocityCooldownTimer=window.setTimeout(()=>{this.scrollVelocityFired=!1},this.scrollVelocityConfig.cooldown)),this.lastScrollY=e,this.lastScrollTime=t}},this.handleVisibilityChange=()=>{document.hidden?this.emit("visibility_hidden",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}):this.emit("visibility_visible",{page_url:window.location.href})},this.handleBackButton=()=>{this.backButtonFired||(this.backButtonFired=!0,window.history.pushState(null,"",window.location.href),this.emit("back_button",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleActivity=()=>{this.lastActivityTime=Date.now()}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}registerScrollDepth(e){this.scrollDepthTargets.add(e)}registerTimeOnPage(e){if(!this.timeOnPageTargets.has(e)){const t=window.setTimeout(()=>{this.emit(`time_on_page_${e}`,{seconds:e,page_url:window.location.href}),this.timeOnPageTargets.delete(e)},1e3*e);this.timeOnPageTargets.set(e,t)}}registerExitIntent(){this.exitIntentEnabled=!0}registerInactivity(e){if(!this.inactivityTargets.has(e)){const t=window.setTimeout(()=>{const t=(Date.now()-this.lastActivityTime)/1e3;t>=e&&this.emit(`inactivity_${e}`,{idle_seconds:e,actual_idle_time:t}),this.inactivityTargets.delete(e)},1e3*e);this.inactivityTargets.set(e,t)}}registerScrollVelocity(e){this.scrollVelocityEnabled=!0,e&&(this.scrollVelocityConfig={threshold:e.threshold??this.scrollVelocityConfig.threshold,minScrollPosition:e.minScrollPosition??this.scrollVelocityConfig.minScrollPosition,cooldown:e.cooldown??this.scrollVelocityConfig.cooldown})}registerVisibilityChange(){this.visibilityChangeEnabled=!0}registerBackButton(){this.backButtonEnabled=!0}registerRageClick(e){this.rageClickEnabled=!0,e&&(this.rageClickConfig={threshold:e.threshold??this.rageClickConfig.threshold,windowMs:e.windowMs??this.rageClickConfig.windowMs})}noteClick(e,t=Date.now()){if(!this.rageClickEnabled)return 0;const n=this.rageClickBuffer.get(e)??[],i=t-this.rageClickConfig.windowMs;let s=0;for(;s<n.length&&n[s]<i;)s++;const o=0===s?n:n.slice(s);return o.push(t),this.rageClickBuffer.set(e,o),o.length<this.rageClickConfig.threshold&&this.rageClickFiredInBurst.delete(e),o.length>=this.rageClickConfig.threshold&&!this.rageClickFiredInBurst.has(e)&&(this.rageClickFiredInBurst.add(e),this.emit("rage_click",{intent:e,count:o.length,window_ms:this.rageClickConfig.windowMs})),o.length}getRageClickCount(e){if(!this.rageClickEnabled)return 0;const t=this.rageClickBuffer.get(e);if(!t)return 0;const n=Date.now()-this.rageClickConfig.windowMs;let i=0;for(const s of t)s>=n&&i++;return i}registerHoverDwell(e){if(this.hoverEnabled=!0,null==e?void 0:e.thresholdsByIntent)for(const[t,n]of Object.entries(e.thresholdsByIntent))n&&this.hoverThresholds.set(t,n)}noteHoverStart(e,t=Date.now()){if(!this.hoverEnabled)return;this.hoverStartAt.has(e)&&this.noteHoverEnd(e,t),this.hoverStartAt.set(e,t),this.hoverThresholdsFired.set(e,new Set);const n=this.hoverThresholds.get(e);if(n){const i=[];for(const s of n){const n=setTimeout(()=>{if(!this.hoverStartAt.has(e))return;const n=this.hoverThresholdsFired.get(e);(null==n?void 0:n.has(s))||(null==n||n.add(s),this.emit(`${e}_hover_dwell_${s}`,{intent:e,threshold_ms:s,actual_ms:Date.now()-t}))},s);i.push(n)}this.hoverThresholdTimers.set(e,i)}}noteHoverEnd(e,t=Date.now()){if(!this.hoverEnabled)return;const n=this.hoverStartAt.get(e);if(void 0===n)return;const i=Math.max(0,t-n);this.hoverLastMs.set(e,i),this.hoverStartAt.delete(e);const s=this.hoverThresholdTimers.get(e);if(s){for(const e of s)clearTimeout(e);this.hoverThresholdTimers.delete(e)}this.hoverThresholdsFired.delete(e)}registerMouseVelocityToTop(e){this.mouseVelEnabled=!0,e&&(this.mouseVelConfig={threshold:e.threshold??this.mouseVelConfig.threshold,windowMs:e.windowMs??this.mouseVelConfig.windowMs,cooldownMs:e.cooldownMs??this.mouseVelConfig.cooldownMs})}noteMousePosition(e,t,n=Date.now()){if(!this.mouseVelEnabled)return 0;const i=n-this.mouseVelConfig.windowMs;let s=0;for(;s<this.mouseSamples.length&&this.mouseSamples[s].ts<i;)s++;if(s>0&&(this.mouseSamples=this.mouseSamples.slice(s)),this.mouseSamples.push({x:e,y:t,ts:n}),this.mouseSamples.length<2)return this.mouseVelLast=0,0;const o=this.mouseSamples[0],r=this.mouseSamples[this.mouseSamples.length-1],a=r.ts-o.ts;if(a<=0)return this.mouseVelLast=0,0;const c=-(r.y-o.y)/a;this.mouseVelLast=c;const d=0===this.mouseVelLastFiredAt||n-this.mouseVelLastFiredAt>=this.mouseVelConfig.cooldownMs;return c>=this.mouseVelConfig.threshold&&d&&(this.mouseVelLastFiredAt=n,this.emit("mouse_velocity_to_top",{velocity:c,threshold:this.mouseVelConfig.threshold,window_ms:this.mouseVelConfig.windowMs,samples:this.mouseSamples.length})),c}getMouseVelocityToTop(){return this.mouseVelEnabled?this.mouseVelLast:0}getHoverMs(e){if(!this.hoverEnabled)return 0;const t=this.hoverStartAt.get(e);return void 0!==t?Math.max(0,Date.now()-t):this.hoverLastMs.get(e)??0}start(){this.isStarted||(this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollDepthTargets.size>0&&this.attachScrollListener(),this.exitIntentEnabled&&this.attachExitIntentListener(),this.scrollVelocityEnabled&&this.attachScrollVelocityListener(),this.visibilityChangeEnabled&&this.attachVisibilityChangeListener(),this.backButtonEnabled&&this.attachBackButtonListener(),this.attachActivityListeners(),this.startInactivityCheck(),this.isStarted=!0)}stop(){this.isStarted&&(this.removeScrollListener(),this.removeExitIntentListener(),this.removeScrollVelocityListener(),this.removeVisibilityChangeListener(),this.removeBackButtonListener(),this.removeActivityListeners(),this.timeOnPageTargets.forEach(e=>clearTimeout(e)),this.timeOnPageTargets.clear(),this.inactivityTargets.forEach(e=>clearTimeout(e)),this.inactivityTargets.clear(),this.inactivityCheckInterval&&(clearInterval(this.inactivityCheckInterval),this.inactivityCheckInterval=void 0),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0),this.isStarted=!1)}reset(){this.scrollDepthReached.clear(),this.exitIntentFired=!1,this.scrollVelocityFired=!1,this.backButtonFired=!1,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0)}attachScrollListener(){window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.handleScroll()}removeScrollListener(){window.removeEventListener("scroll",this.handleScroll)}attachExitIntentListener(){document.addEventListener("mouseleave",this.handleExitIntent)}removeExitIntentListener(){document.removeEventListener("mouseleave",this.handleExitIntent)}attachScrollVelocityListener(){window.addEventListener("scroll",this.handleScrollVelocity,{passive:!0})}removeScrollVelocityListener(){window.removeEventListener("scroll",this.handleScrollVelocity)}attachVisibilityChangeListener(){document.addEventListener("visibilitychange",this.handleVisibilityChange)}removeVisibilityChangeListener(){document.removeEventListener("visibilitychange",this.handleVisibilityChange)}attachBackButtonListener(){"undefined"!=typeof window&&window.history&&(window.history.pushState(null,"",window.location.href),window.addEventListener("popstate",this.handleBackButton))}removeBackButtonListener(){window.removeEventListener("popstate",this.handleBackButton)}attachActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.addEventListener(e,this.handleActivity,{passive:!0})})}removeActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.removeEventListener(e,this.handleActivity)})}startInactivityCheck(){this.inactivityCheckInterval=window.setInterval(()=>{const e=(Date.now()-this.lastActivityTime)/1e3;for(const[t]of this.inactivityTargets)if(e>=t){this.emit(`inactivity_${t}`,{idle_seconds:t,actual_idle_time:e});const n=this.inactivityTargets.get(t);n&&(clearTimeout(n),this.inactivityTargets.delete(t))}},1e3)}emit(e,t){const n={type:e,data:t,timestamp:Date.now()},i=this.listeners.get(e);i&&i.forEach(t=>{try{t(n)}catch(i){console.error(`Error in trigger callback for ${e}:`,i)}});const s=this.listeners.get("*");s&&s.forEach(e=>{try{e(n)}catch(t){console.error("Error in wildcard trigger callback:",t)}})}}const ee="aegis_fpc";class te extends Error{constructor(e,t){super(t),this.status=e,this.name="BootstrapError"}}const ne="aegis",ie=window[ne]||[],se=new j;if(Array.isArray(ie)){const e=ie._loadOptions;ie.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("function"==typeof se[t])try{se[t].apply(se,n)}catch(i){console.error(`[Aegis SDK] Error executing queued method "${t}":`,i)}else console.warn(`[Aegis SDK] Unknown method "${t}"`)}),(null==e?void 0:e.key)&&se.init(e.key,e.options).catch(e=>{console.error("[Aegis SDK] Initialization failed:",e)})}return window[ne]=se,window.Aegis=j,window.AegisMessageRuntime=class{constructor(e){this.initialized=!1;const t=e.triggerEngine??new Z,n=!e.triggerEngine;this.widgets=new Y({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,debugMode:e.debugMode,triggerEngine:t,ownsTriggerEngine:n,enablePrefetch:!1!==e.enableWidgetPrefetch,sourcePlatform:e.sourcePlatform}),this.inApp=new G({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,propertyId:e.propertyId,debugMode:e.debugMode,enableSSE:e.enableSSE,onInteractiveCampaign:e=>{this.widgets.renderInteractiveCampaign(e)}})}async initialize(){this.initialized||(this.initialized=!0,await Promise.all([this.inApp.initialize(),this.widgets.initialize()]))}async updateContactId(e){var t,n;null==(n=(t=this.inApp).updateContactId)||n.call(t,e),await this.widgets.updateContactId(e)}onClientEvent(e,t={}){var n,i;null==(i=(n=this.inApp).onClientEvent)||i.call(n,e,t)}notifyConversion(e){var t,n;null==(n=(t=this.inApp).notifyConversion)||n.call(t,e)}destroy(){var e,t;null==(t=(e=this.inApp).destroy)||t.call(e),this.widgets.destroy(),this.initialized=!1}getCampaigns(){return this.inApp.campaigns??[]}},window.AegisPlacementManager=class{constructor(e){this.placements=new Map,this.slots=new Map,this.renderedSlots=new Set,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId,this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.enableSSE=!1!==e.enableSSE}async initialize(){this.isInitialized?this.log("AegisPlacements already initialized"):(await this.refreshPlacements(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisPlacements initialized successfully"))}register(e,t){const n={placementId:e,...t};this.slots.set(e,n),this.log(`Registered placement slot: ${e}`);const i=this.placements.get(e);i?this.renderSlot(n,i):t.fallbackContent&&this.renderFallback(n)}unregister(e){this.slots.delete(e),this.renderedSlots.delete(e),this.log(`Unregistered placement slot: ${e}`)}async refreshPlacements(){try{const e=Array.from(this.slots.keys());if(0===e.length)return void this.log("No registered slots, skipping refresh");const t=`${this.apiHost}/v1/placements/content?placement_ids=${e.join(",")}`,n={"X-Aegis-Write-Key":this.writeKey,"X-Device-Type":this.getDeviceType(),"X-Platform":"web"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n});if(!i.ok)throw new Error(`Failed to fetch placements: ${i.status}`);const s=await i.json();this.placements.clear();for(const o of s.placements||[])this.placements.set(o.placement_id,o);this.renderAllSlots(),this.log(`Refreshed ${this.placements.size} placements`)}catch(e){this.log(`Error refreshing placements: ${e}`,!0)}}renderAllSlots(){for(const[e,t]of this.slots.entries()){const n=this.placements.get(e);n?this.renderSlot(t,n):t.fallbackContent&&this.renderFallback(t)}}renderSlot(e,t){try{if("dynamic_injection"===t.content_type)this.renderDynamicInjection(t);else{const n=document.getElementById(e.containerId);if(!n)return void this.log(`Container not found: ${e.containerId}`,!0);switch(n.innerHTML="",t.content_type){case"banner":this.renderBanner(n,t);break;case"card":this.renderCard(n,t);break;case"carousel":this.renderCarousel(n,t);break;case"video":this.renderVideo(n,t);break;case"html":this.renderHTML(n,t);break;default:return void this.log(`Unknown content type: ${t.content_type}`,!0)}}this.renderedSlots.has(e.placementId)||(this.trackEvent(t.placement_id,t.variant_id,"impression"),this.renderedSlots.add(e.placementId)),e.onRender&&e.onRender(t),this.log(`Rendered placement: ${t.placement_id} (${t.content_type})`)}catch(n){this.log(`Error rendering placement: ${n}`,!0),e.onError&&e.onError(n)}}renderBanner(e,t){const{title:n,body:i,image_url:s,cta_text:o,cta_url:r,background_color:a,text_color:c}=t.content,d=document.createElement("div");if(d.className="aegis-placement-banner",d.style.cssText=`\n background: ${this.sanitizeColor(a||"#1a73e8")};\n color: ${this.sanitizeColor(c||"#ffffff")};\n padding: 24px;\n border-radius: 8px;\n display: flex;\n align-items: center;\n gap: 16px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,s){const e=document.createElement("img"),t=this.sanitizeUrl(s);t&&(e.src=t,e.alt="",e.style.cssText="width: 80px; height: 80px; border-radius: 8px; object-fit: cover;",d.appendChild(e))}const l=document.createElement("div");if(l.style.cssText="flex: 1;",n){const e=document.createElement("div");e.textContent=n,e.style.cssText="font-size: 18px; font-weight: 600; margin-bottom: 8px;",l.appendChild(e)}if(i){const e=document.createElement("div");e.textContent=i,e.style.cssText="font-size: 14px; opacity: 0.9;",l.appendChild(e)}if(d.appendChild(l),o&&r){const e=document.createElement("button");e.textContent=o,e.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(a||"#1a73e8")};\n border: none;\n padding: 12px 24px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n white-space: nowrap;\n `,e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click");const e=this.sanitizeUrl(r);e&&(window.location.href=e)}),d.appendChild(e)}e.appendChild(d)}renderCard(e,t){const{title:n,body:i,image_url:s,cta_text:o,cta_url:r}=t.content,a=document.createElement("div");if(a.className="aegis-placement-card",a.style.cssText='\n background: white;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',s){const e=document.createElement("img"),t=this.sanitizeUrl(s);t&&(e.src=t,e.alt=n||"",e.style.cssText="width: 100%; height: 200px; object-fit: cover;",a.appendChild(e))}const c=document.createElement("div");if(c.style.cssText="padding: 20px;",n){const e=document.createElement("h3");e.textContent=n,e.style.cssText="margin: 0 0 12px 0; font-size: 20px; font-weight: 600; color: #1a1a1a;",c.appendChild(e)}if(i){const e=document.createElement("p");e.textContent=i,e.style.cssText="margin: 0 0 16px 0; font-size: 14px; color: #666; line-height: 1.5;",c.appendChild(e)}if(o&&r){const e=document.createElement("button");e.textContent=o,e.style.cssText="\n background: #1a73e8;\n color: white;\n border: none;\n padding: 10px 20px;\n border-radius: 6px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n ",e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click");const e=this.sanitizeUrl(r);e&&(window.location.href=e)}),c.appendChild(e)}a.appendChild(c),e.appendChild(a)}renderCarousel(e,t){const{items:n}=t.content;if(!Array.isArray(n)||0===n.length)return void this.log("Carousel items empty or invalid",!0);const i=document.createElement("div");i.className="aegis-placement-carousel",i.style.cssText="\n display: flex;\n gap: 16px;\n overflow-x: auto;\n padding: 8px 0;\n scroll-behavior: smooth;\n -webkit-overflow-scrolling: touch;\n ";for(const s of n){const e=document.createElement("div");if(e.style.cssText='\n flex: 0 0 250px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n overflow: hidden;\n cursor: pointer;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n ',s.image_url){const t=document.createElement("img"),n=this.sanitizeUrl(s.image_url);n&&(t.src=n,t.alt=s.title||"",t.style.cssText="width: 100%; height: 150px; object-fit: cover;",e.appendChild(t))}const o=document.createElement("div");if(o.style.cssText="padding: 12px;",s.title){const e=document.createElement("div");e.textContent=s.title,e.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 4px; color: #1a1a1a;",o.appendChild(e)}if(s.price){const e=document.createElement("div");e.textContent=s.price,e.style.cssText="font-size: 16px; font-weight: 700; color: #1a73e8;",o.appendChild(e)}e.appendChild(o),s.url&&e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{item_index:n.indexOf(s)});const e=this.sanitizeUrl(s.url);e&&(window.location.href=e)}),i.appendChild(e)}e.appendChild(i)}renderVideo(e,t){const{video_url:n,poster_url:i,autoplay:s,muted:o}=t.content;if(!n)return void this.log("Video URL missing",!0);const r=this.sanitizeUrl(n);if(!r)return void this.log("Invalid video URL",!0);const a=document.createElement("video");if(a.src=r,a.controls=!0,a.autoplay=s||!1,a.muted=o||!1,a.style.cssText="width: 100%; border-radius: 8px;",i){const e=this.sanitizeUrl(i);e&&(a.poster=e)}a.addEventListener("play",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{action:"video_play"})}),e.appendChild(a)}renderHTML(e,t){const{html:n}=t.content;if(!n)return void this.log("HTML content missing",!0);const i=document.createElement("div");i.className="aegis-placement-html",i.innerHTML=this.sanitizeHTML(n);i.querySelectorAll("a").forEach(e=>{e.addEventListener("click",()=>{this.trackEvent(t.placement_id,t.variant_id,"click")})}),e.appendChild(i)}renderDynamicInjection(e){const{html:t}=e.content,n=e.css_selector,i=e.injection_mode||"replace";if(!n)return void this.log("CSS selector missing for dynamic injection",!0);if(!t)return void this.log("HTML content missing for dynamic injection",!0);let s=null;try{s=document.querySelector(n)}catch(r){return void this.log(`Invalid CSS selector: ${n}`,!0)}if(!s)return void this.log(`Target element not found for selector: ${n}`,!0);const o=document.createElement("div");o.className="aegis-dynamic-injection",o.setAttribute("data-placement-id",e.placement_id),o.setAttribute("data-variant-id",e.variant_id),o.innerHTML=this.sanitizeHTML(t);switch(o.querySelectorAll("a").forEach(t=>{t.addEventListener("click",()=>{this.trackEvent(e.placement_id,e.variant_id,"click")})}),i){case"replace":s.innerHTML="",s.appendChild(o),this.log(`Replaced content in ${n}`,!1);break;case"append":s.appendChild(o),this.log(`Appended content to ${n}`,!1);break;case"prepend":s.insertBefore(o,s.firstChild),this.log(`Prepended content to ${n}`,!1);break;default:return void this.log(`Unknown injection mode: ${i}`,!0)}this.log(`Dynamically injected content for ${e.placement_id} into ${n} (${i})`)}renderFallback(e){if(!e.fallbackContent)return;const t=document.getElementById(e.containerId);t&&(t.innerHTML=e.fallbackContent,this.log(`Rendered fallback content for: ${e.placementId}`))}async trackEvent(e,t,n,i={}){try{const s=`${this.apiHost}/v1/placements/track`,o={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Device-Type":this.getDeviceType(),"X-Platform":"web"};this.userId&&(o["X-User-ID"]=this.userId),this.contactId&&(o["X-Contact-ID"]=this.contactId),this.organizationId&&(o["X-Organization-ID"]=this.organizationId);const r={placement_id:e,variant_id:t,event_type:n,metadata:{device_type:this.getDeviceType(),platform:"web",...i}};fetch(s,{method:"POST",headers:o,body:JSON.stringify(r)}).catch(e=>this.log(`Track event failed: ${e}`,!0)),this.log(`Tracked ${n}: ${e}`)}catch(s){this.log(`Error tracking event: ${s}`,!0)}}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID",!0);const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("placement_content_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received placement content update: ${t.placement_id}`),this.refreshPlacements()}catch(t){this.log(`Error parsing SSE event: ${t}`,!0)}}),this.eventSource.addEventListener("heartbeat",()=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",()=>{var e;this.log("SSE connection error",!0),(null==(e=this.eventSource)?void 0:e.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up",!0);this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}getDeviceType(){const e=window.innerWidth;return e<768?"mobile_web":e<1024?"tablet_web":"desktop_web"}sanitizeUrl(e){try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked unsafe URL protocol: ${t.protocol}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-Fa-f]{3,6}$/.test(e)||/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/.test(e)||["white","black","red","blue","green","yellow","transparent"].includes(e.toLowerCase())?e:(this.log(`Invalid color: ${e}`,!0),"#000000")}sanitizeHTML(e){const t=window.DOMPurify;if(null==t?void 0:t.sanitize)return t.sanitize(e,{ALLOWED_TAGS:["a","b","br","div","em","h1","h2","h3","h4","h5","h6","i","img","li","ol","p","span","strong","u","ul","table","thead","tbody","tr","th","td","blockquote","hr","figure","figcaption","picture","source","video","section","article"],ALLOWED_ATTR:["href","target","rel","src","alt","width","height","class","id","style","title","loading","srcset","sizes","type","media","controls","poster"],ALLOW_DATA_ATTR:!1});this.log('DOMPurify not found — falling back to built-in sanitizer. For full HTML placement support, add <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.4/purify.min.js"><\/script>',!1);const n=document.createElement("div");return n.textContent=e,n.innerHTML}log(e,t=!1){(this.debugMode||t)&&console[t?"error":"log"](`[AegisPlacements] ${e}`)}destroy(){this.disconnectSSE(),this.slots.clear(),this.placements.clear(),this.renderedSlots.clear(),this.isInitialized=!1,this.log("AegisPlacements destroyed")}},window.TriggerEngine=Z,window.aegisBootstrap=async function(e,t){const n={writeKey:t.writeKey};t.currentOrigin&&(n.currentOrigin=t.currentOrigin),t.firstPartyCookieId&&(n.firstPartyCookieId=t.firstPartyCookieId),t.attestationToken&&(n.attestationToken=t.attestationToken),t.userAgent&&(n.userAgent=t.userAgent);const i=`${e.replace(/\/$/,"")}/v1/sdk/bootstrap`,s=async()=>fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"omit"});let o=await s();if(o.status>=500&&(await new Promise(e=>setTimeout(e,750)),o=await s()),401===o.status)throw new te(401,"writeKey not recognized or revoked");if(403===o.status)throw new te(403,"Origin validation failed — this writeKey is bound to a different property");if(!o.ok)throw new te(o.status,`Bootstrap failed: HTTP ${o.status}`);const r=await o.json();return function(e){if("undefined"==typeof document)return;const t=new Date;t.setDate(t.getDate()+730),document.cookie=`${ee}=${encodeURIComponent(e)};expires=${t.toUTCString()};path=/;SameSite=Lax`;try{window.localStorage.setItem(ee,e)}catch{}}(r.firstPartyCookieId),r},se}();
2
2
  //# sourceMappingURL=aegis.min.js.map