@active-reach/web-sdk 1.1.0 → 1.2.1

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,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 a{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 r{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),a=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),a.ok){const t=await a.json();return i.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const s=await a.text(),o=new Error(`HTTP ${a.status}: ${s||a.statusText}`);return i.error("Batch send failed:",o),this.shouldRetry(a.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"}}(),a=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}(),r=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},...r&&Object.keys(r).length>0&&{adClickIDs:r},...c&&{landingPage:c},...a&&{network:a},...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 a=o[e];if("function"==typeof a)try{const e=await a.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 r of this.plugins.values()){const t=r[e];if("function"==typeof t)try{const e=await t.apply(r,[s,...n]);null!=e&&(s=e)}catch(o){if(i.error(`Error executing ${String(e)} in plugin "${r.name}":`,o),r.onError)try{r.onError(o,{hookName:e,value:s,additionalArgs:n})}catch(a){i.error(`Error in onError handler for plugin "${r.name}":`,a)}}}return s}async executeHookParallel(e,...t){const n=[];for(const s of this.plugins.values()){const o=s[e];if("function"==typeof o){const a=(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(a){i.error(`Error in onError handler for plugin "${s.name}":`,a)}return}})();n.push(a)}}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()}}function u(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function g(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 m{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:g(e.products)})}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:u(e.products),products:g(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:u(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:g(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:u(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:g(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?g(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 f{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}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 r({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 a({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),await this.initializePlugins(),this.config.auto_page_view&&this.page(),i.info("Aegis SDK initialized successfully")):i.info("Bot detected, SDK disabled")}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={type:"track",event:e,properties:t||{},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(i)}identify(e,t){if(!this.assertInitialized())return;this.identity.setUserId(e,t);const i={type:"identify",traits: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)}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(),context:l(this.config,this.session)};this.captureEvent(i)}group(e,t){if(!this.assertInitialized())return;const i={type:"group",groupId:e,traits:t||{},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(i)}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");i.debug("Capturing event:",e);const n=await this.plugins.executeHookChain("beforeEventCapture",e);n?(this.queue.push(n),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",n)):i.debug("Event cancelled by plugin")}reset(){this.assertInitialized()&&(this.identity.reset(),i.info("User identity reset"))}async flush(){this.assertInitialized()&&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}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 m(this)),this._ecommerce}destroy(){this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.plugins.clear(),i.info("SDK destroyed")}}const y="aegis",x=window[y]||[],b=new f;if(Array.isArray(x)){const e=x._loadOptions;x.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("function"==typeof b[t])try{b[t].apply(b,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)&&b.init(e.key,e.options).catch(e=>{console.error("[Aegis SDK] Initialization failed:",e)})}return window[y]=b,window.Aegis=f,window.AegisInAppManager=class{constructor(e){this.campaigns=[],this.displayedCampaigns=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("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()}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);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});if(!s.ok)throw new Error(`Failed to fetch campaigns: ${s.status}`);this.campaigns=await s.json(),this.processABAssignments(this.campaigns),this.log(`Fetched ${this.campaigns.length} campaigns`),this.tryDisplayNextCampaign()}catch(e){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&&this.displayCampaign(e)}displayCampaign(e){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),void this.trackEvent(e.id,"impression");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)}this.trackEvent(e.id,"impression")}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.log(`${e.sub_type} delegated to AegisWidgetManager`),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("aegis:render-widget",{detail:{campaign:e,sub_type:e.sub_type}}));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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",r.textContent=t.nps_question||"How likely are you to recommend us?",a.appendChild(r);const c=document.createElement("div");c.style.cssText="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;";for(let p=0;p<=10;p++){const t=document.createElement("span");t.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: ${i}33; color: ${i};\n transition: transform 0.1s;\n `,t.textContent=String(p),t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),c.appendChild(t)}a.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const l=document.createElement("span");l.textContent="Not likely";const h=document.createElement("span");h.textContent="Very likely",d.appendChild(l),d.appendChild(h),a.appendChild(d),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 20px; font-weight: 700; margin-bottom: 8px;",r.textContent=e.title||"Flash Sale",a.appendChild(r);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:",a.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)}a.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"),a=d.querySelectorAll("span");a.length>=5&&(a[0].textContent=i,a[2].textContent=s,a[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,a.appendChild(t)}if(e.button_text){const t=this.createCTAButton(e,n,i);a.appendChild(t)}this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 16px;",r.textContent=e.title||"Rate your experience",a.appendChild(r);const c=document.createElement("div");c.style.cssText="display: flex; gap: 8px; justify-content: center; margin-bottom: 16px;";const d=t.rating_scale||5;for(let l=1;l<=d;l++){const t=document.createElement("span");t.style.cssText="font-size: 32px; cursor: pointer; transition: transform 0.1s;",t.textContent="☆",t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),t.addEventListener("mouseenter",()=>{t.style.transform="scale(1.2)"}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),c.appendChild(t)}a.appendChild(c),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",r.textContent=e.title||"Quick question",a.appendChild(r);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)}a.appendChild(d),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",r.textContent=e.title||"Quiz",a.appendChild(r);const c=t.questions||[];let d=0;const l=()=>{for(;a.childNodes.length>1;)a.removeChild(a.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!",a.appendChild(n),this.trackEvent(e.id,"clicked"),void this.addCloseButton(a,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}`,a.appendChild(o);const r=document.createElement("div");r.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 16px;",r.textContent=n.question,a.appendChild(r);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)}a.appendChild(h),this.addCloseButton(a,s,e.id)};l(),o.appendChild(a),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)}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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeBanner(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="✕",r.setAttribute("aria-label","Close"),r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),a.appendChild(r),t.appendChild(n),t.appendChild(a),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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeModal(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="Close",r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),a.appendChild(r),i.appendChild(a),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&&(window.location.href=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&&(window.location.href=n),this.removeModal(t)}),i.appendChild(n)}n.appendChild(i);const a=document.createElement("button");a.textContent="✕",a.setAttribute("aria-label","Close"),a.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 ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),n.style.position="relative",n.appendChild(a),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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeModal(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="Cancel",r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),a.appendChild(r),n.appendChild(a),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"),a=this.sanitizeColor(e.text_color||"#ffffff"),r=document.createElement("div");r.className="aegis-in-app-tooltip",r.setAttribute("data-campaign-id",e.id),r.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${o}; color: ${a}; 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: ${a}; opacity: 0.6; font-size: 16px; cursor: pointer; padding: 0; line-height: 1;\n `;const l=()=>{r.style.animation="aegisFadeOut 0.2s ease-out",setTimeout(()=>{var e;null==(e=r.parentNode)||e.removeChild(r)},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;",r.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;",r.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: ${a}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),r.appendChild(t)}r.appendChild(d),r.appendChild(c),document.body.appendChild(r);const p=s.getBoundingClientRect(),u=r.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),r.style.top=`${f}px`,r.style.left=`${y}px`,c.style.top=x||"",c.style.left=b||"",c.style.bottom=v||"",c.style.right=w||"";const C=e=>{r.contains(e.target)||s.contains(e.target)||(document.removeEventListener("click",C),l())};setTimeout(()=>document.addEventListener("click",C),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 ",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){try{const n=`${this.apiHost}/api/v1/events`,i=(new Date).toISOString(),s=`inapp_${e}_${t}_${Date.now()}`,o={tenant_id:this.organizationId||"unknown",source:"in_app_sdk",external_event_id:s,event_type:`in_app.${t}`,timestamp:i,payload:{campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,platform:"web",variant_id:this.getVariantId(e)??void 0},trace_id:s,metadata:{write_key:this.writeKey}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(o)}).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){this.disconnectSSE(),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").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const t=document.getElementById("aegis-in-app-styles");t&&t.parentNode&&t.parentNode.removeChild(t),(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}},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:a,background_color:r,text_color:c}=t.content,d=document.createElement("div");if(d.className="aegis-placement-banner",d.style.cssText=`\n background: ${this.sanitizeColor(r||"#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&&a){const e=document.createElement("button");e.textContent=o,e.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(r||"#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(a);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:a}=t.content,r=document.createElement("div");if(r.className="aegis-placement-card",r.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;",r.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&&a){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(a);e&&(window.location.href=e)}),c.appendChild(e)}r.appendChild(c),e.appendChild(r)}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 a=this.sanitizeUrl(n);if(!a)return void this.log("Invalid video URL",!0);const r=document.createElement("video");if(r.src=a,r.controls=!0,r.autoplay=s||!1,r.muted=o||!1,r.style.cssText="width: 100%; border-radius: 8px;",i){const e=this.sanitizeUrl(i);e&&(r.poster=e)}r.addEventListener("play",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{action:"video_play"})}),e.appendChild(r)}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(a){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 a={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(a)}).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.AegisWidgetManager=class{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.prefetchWidgetConfigs={},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.triggerEngine=e.triggerEngine,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")}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});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});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}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!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,a=e.position||"bottom_right",r=document.createElement("div");r.className="aegis-chat-bubble",r.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(r.style.cssText=`\n position: fixed;\n ${c[a]||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;",r.appendChild(e))}const d=document.createElement("span");d.textContent=t||"Chat with us",r.appendChild(d),r.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(i);t&&window.open(t,"_blank")}),this.addAnimationStyles(),document.body.appendChild(r)}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=document.createElement("div");o.style.cssText="\n width: 300px;\n height: 300px;\n margin: 0 auto 24px;\n background: linear-gradient(45deg, #ff6b6b, #feca57, #48dbfb, #ff6348);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 48px;\n color: white;\n ",o.textContent="🎰",n.appendChild(o);const a=document.createElement("button");a.textContent="SPIN NOW!",a.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 ",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);o.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),a.disabled=!1,a.textContent="TRY AGAIN"}}),n.appendChild(a);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: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",r.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderSpinWheelWidget(e,t){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",a=i.textColor||t.text_color||"#333333",r=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(a)};\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(r)};\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(),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 a=`${this.apiHost}/v1/widgets/spin-wheel/submit`,r={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.organizationId&&(r["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(a,{method:"POST",headers:r,body:JSON.stringify(h)});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 a=document.createElement("p");a.textContent="Check your WhatsApp/SMS for your discount code and cart link!",a.style.cssText="margin: 0 0 20px 0; font-size: 14px; color: #666;",n.appendChild(a);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)}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 a=o.getContext("2d");if(a){a.fillStyle="#c0c0c0",a.fillRect(0,0,o.width,o.height),a.fillStyle="#888",a.font="20px Arial",a.textAlign="center",a.fillText("Scratch here!",o.width/2,o.height/2);let e=!1;const t=(e,t)=>{a.globalCompositeOperation="destination-out",a.beginPath(),a.arc(e,t,20,0,2*Math.PI),a.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 r=document.createElement("button");r.textContent="REVEAL PRIZE",r.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 ",r.addEventListener("click",async()=>{r.disabled=!0,r.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),r.disabled=!1,r.textContent="TRY AGAIN"}}),n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),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 a={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 ${a[s]||a.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 r=document.createElement("div");r.textContent=t||"Someone just made a purchase!",r.style.cssText="flex: 1; font-size: 13px; color: #333;",o.appendChild(r),this.addAnimationStyles(),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 a=document.createElement("input");a.type="number",a.min="0",a.max="10",a.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(a);const r=document.createElement("label");r.textContent="Tell us more (optional)",r.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(r);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(a.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(),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:s,image_url:o}=e.config,a=document.createElement("div");a.className="aegis-exit-popup-overlay",a.setAttribute("data-widget-id",e.widget_id),a.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 r=document.createElement("div");if(r.className="aegis-exit-popup-modal",r.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;",r.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)}r.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(a),this.renderedWidgets.delete(e.widget_id)}),r.style.position="relative",r.appendChild(h),a.appendChild(r),this.addAnimationStyles(),document.body.appendChild(a)}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})});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 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)}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})});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||{}})})}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){const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),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 a=document.createElement("p"),r=this.interpolateCartVariables(t.message||"Your cart is waiting for you!");if(a.textContent=r,a.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5;",i.appendChild(a),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(),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),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 a=document.createElement("form"),r=document.createElement("input");r.type="email",r.placeholder="Enter your email",r.required=!0,r.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 ",a.appendChild(r);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 ",a.appendChild(c),a.addEventListener("submit",async t=>{t.preventDefault(),c.disabled=!0,c.textContent="Submitting...";try{await this.trackEvent(e,"submit",{type:"lead_gen",email:r.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(a);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(),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}`)}}},window.TriggerEngine=class{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.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}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)}})}},b}();
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,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 a{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 r{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),a=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),a.ok){const t=await a.json();return i.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const s=await a.text(),o=new Error(`HTTP ${a.status}: ${s||a.statusText}`);return i.error("Batch send failed:",o),this.shouldRetry(a.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"}}(),a=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}(),r=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},...r&&Object.keys(r).length>0&&{adClickIDs:r},...c&&{landingPage:c},...a&&{network:a},...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 a=o[e];if("function"==typeof a)try{const e=await a.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 r of this.plugins.values()){const t=r[e];if("function"==typeof t)try{const e=await t.apply(r,[s,...n]);null!=e&&(s=e)}catch(o){if(i.error(`Error executing ${String(e)} in plugin "${r.name}":`,o),r.onError)try{r.onError(o,{hookName:e,value:s,additionalArgs:n})}catch(a){i.error(`Error in onError handler for plugin "${r.name}":`,a)}}}return s}async executeHookParallel(e,...t){const n=[];for(const s of this.plugins.values()){const o=s[e];if("function"==typeof o){const a=(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(a){i.error(`Error in onError handler for plugin "${s.name}":`,a)}return}})();n.push(a)}}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()}}function u(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function g(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 m{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:g(e.products)})}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:u(e.products),products:g(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:u(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:g(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:u(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:g(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?g(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 f{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._lastPageUrl=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null}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 r({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 a({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),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={type:"track",event:e,properties:t||{},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(i)}identify(e,t){if(!this.assertInitialized())return;this.identity.setUserId(e,t);const i={type:"identify",traits: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)}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(),context:l(this.config,this.session)};this.captureEvent(i)}group(e,t){if(!this.assertInitialized())return;const i={type:"group",groupId:e,traits:t||{},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(i)}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");i.debug("Capturing event:",e);const n=await this.plugins.executeHookChain("beforeEventCapture",e);n?(this.queue.push(n),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",n)):i.debug("Event cancelled by plugin")}reset(){this.assertInitialized()&&(this.identity.reset(),i.info("User identity reset"))}async flush(){this.assertInitialized()&&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}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 m(this)),this._ecommerce}destroy(){this.stopSPATracking(),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.plugins.clear(),i.info("SDK destroyed")}}const y="aegis",x=window[y]||[],b=new f;if(Array.isArray(x)){const e=x._loadOptions;x.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("function"==typeof b[t])try{b[t].apply(b,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)&&b.init(e.key,e.options).catch(e=>{console.error("[Aegis SDK] Initialization failed:",e)})}return window[y]=b,window.Aegis=f,window.AegisInAppManager=class{constructor(e){this.campaigns=[],this.displayedCampaigns=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("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()}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);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});if(!s.ok)throw new Error(`Failed to fetch campaigns: ${s.status}`);this.campaigns=await s.json(),this.processABAssignments(this.campaigns),this.log(`Fetched ${this.campaigns.length} campaigns`),this.tryDisplayNextCampaign()}catch(e){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&&this.displayCampaign(e)}displayCampaign(e){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),void this.trackEvent(e.id,"impression");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)}this.trackEvent(e.id,"impression")}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.log(`${e.sub_type} delegated to AegisWidgetManager`),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("aegis:render-widget",{detail:{campaign:e,sub_type:e.sub_type}}));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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",r.textContent=t.nps_question||"How likely are you to recommend us?",a.appendChild(r);const c=document.createElement("div");c.style.cssText="display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;";for(let p=0;p<=10;p++){const t=document.createElement("span");t.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: ${i}33; color: ${i};\n transition: transform 0.1s;\n `,t.textContent=String(p),t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),c.appendChild(t)}a.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const l=document.createElement("span");l.textContent="Not likely";const h=document.createElement("span");h.textContent="Very likely",d.appendChild(l),d.appendChild(h),a.appendChild(d),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 20px; font-weight: 700; margin-bottom: 8px;",r.textContent=e.title||"Flash Sale",a.appendChild(r);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:",a.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)}a.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"),a=d.querySelectorAll("span");a.length>=5&&(a[0].textContent=i,a[2].textContent=s,a[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,a.appendChild(t)}if(e.button_text){const t=this.createCTAButton(e,n,i);a.appendChild(t)}this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 16px;",r.textContent=e.title||"Rate your experience",a.appendChild(r);const c=document.createElement("div");c.style.cssText="display: flex; gap: 8px; justify-content: center; margin-bottom: 16px;";const d=t.rating_scale||5;for(let l=1;l<=d;l++){const t=document.createElement("span");t.style.cssText="font-size: 32px; cursor: pointer; transition: transform 0.1s;",t.textContent="☆",t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),t.addEventListener("mouseenter",()=>{t.style.transform="scale(1.2)"}),t.addEventListener("mouseleave",()=>{t.style.transform="scale(1)"}),c.appendChild(t)}a.appendChild(c),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 16px;",r.textContent=e.title||"Quick question",a.appendChild(r);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)}a.appendChild(d),this.addCloseButton(a,s,e.id),o.appendChild(a),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 a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",r.textContent=e.title||"Quiz",a.appendChild(r);const c=t.questions||[];let d=0;const l=()=>{for(;a.childNodes.length>1;)a.removeChild(a.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!",a.appendChild(n),this.trackEvent(e.id,"clicked"),void this.addCloseButton(a,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}`,a.appendChild(o);const r=document.createElement("div");r.style.cssText="font-size: 14px; font-weight: 600; margin-bottom: 16px;",r.textContent=n.question,a.appendChild(r);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)}a.appendChild(h),this.addCloseButton(a,s,e.id)};l(),o.appendChild(a),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)}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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeBanner(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="✕",r.setAttribute("aria-label","Close"),r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),a.appendChild(r),t.appendChild(n),t.appendChild(a),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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeModal(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="Close",r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),a.appendChild(r),i.appendChild(a),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&&(window.location.href=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&&(window.location.href=n),this.removeModal(t)}),i.appendChild(n)}n.appendChild(i);const a=document.createElement("button");a.textContent="✕",a.setAttribute("aria-label","Close"),a.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 ",a.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),n.style.position="relative",n.appendChild(a),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 a=document.createElement("div");if(a.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&&(window.location.href=n),this.removeModal(t)}),a.appendChild(n)}const r=document.createElement("button");r.textContent="Cancel",r.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 ",r.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(t)}),a.appendChild(r),n.appendChild(a),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"),a=this.sanitizeColor(e.text_color||"#ffffff"),r=document.createElement("div");r.className="aegis-in-app-tooltip",r.setAttribute("data-campaign-id",e.id),r.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${o}; color: ${a}; 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: ${a}; opacity: 0.6; font-size: 16px; cursor: pointer; padding: 0; line-height: 1;\n `;const l=()=>{r.style.animation="aegisFadeOut 0.2s ease-out",setTimeout(()=>{var e;null==(e=r.parentNode)||e.removeChild(r)},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;",r.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;",r.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: ${a}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),r.appendChild(t)}r.appendChild(d),r.appendChild(c),document.body.appendChild(r);const p=s.getBoundingClientRect(),u=r.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),r.style.top=`${f}px`,r.style.left=`${y}px`,c.style.top=x||"",c.style.left=b||"",c.style.bottom=v||"",c.style.right=w||"";const C=e=>{r.contains(e.target)||s.contains(e.target)||(document.removeEventListener("click",C),l())};setTimeout(()=>document.addEventListener("click",C),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 ",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){try{const n=`${this.apiHost}/api/v1/events`,i=(new Date).toISOString(),s=`inapp_${e}_${t}_${Date.now()}`,o={tenant_id:this.organizationId||"unknown",source:"in_app_sdk",external_event_id:s,event_type:`in_app.${t}`,timestamp:i,payload:{campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,platform:"web",variant_id:this.getVariantId(e)??void 0},trace_id:s,metadata:{write_key:this.writeKey}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(o)}).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){this.disconnectSSE(),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").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const t=document.getElementById("aegis-in-app-styles");t&&t.parentNode&&t.parentNode.removeChild(t),(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}},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:a,background_color:r,text_color:c}=t.content,d=document.createElement("div");if(d.className="aegis-placement-banner",d.style.cssText=`\n background: ${this.sanitizeColor(r||"#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&&a){const e=document.createElement("button");e.textContent=o,e.style.cssText=`\n background: white;\n color: ${this.sanitizeColor(r||"#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(a);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:a}=t.content,r=document.createElement("div");if(r.className="aegis-placement-card",r.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;",r.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&&a){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(a);e&&(window.location.href=e)}),c.appendChild(e)}r.appendChild(c),e.appendChild(r)}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 a=this.sanitizeUrl(n);if(!a)return void this.log("Invalid video URL",!0);const r=document.createElement("video");if(r.src=a,r.controls=!0,r.autoplay=s||!1,r.muted=o||!1,r.style.cssText="width: 100%; border-radius: 8px;",i){const e=this.sanitizeUrl(i);e&&(r.poster=e)}r.addEventListener("play",()=>{this.trackEvent(t.placement_id,t.variant_id,"click",{action:"video_play"})}),e.appendChild(r)}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(a){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 a={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(a)}).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.AegisWidgetManager=class{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.prefetchWidgetConfigs={},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.triggerEngine=e.triggerEngine,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")}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});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});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}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!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,a=e.position||"bottom_right",r=document.createElement("div");r.className="aegis-chat-bubble",r.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(r.style.cssText=`\n position: fixed;\n ${c[a]||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;",r.appendChild(e))}const d=document.createElement("span");d.textContent=t||"Chat with us",r.appendChild(d),r.addEventListener("click",()=>{this.trackEvent(e.widget_id,"click");const t=this.sanitizeUrl(i);t&&window.open(t,"_blank")}),this.addAnimationStyles(),document.body.appendChild(r)}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=document.createElement("div");o.style.cssText="\n width: 300px;\n height: 300px;\n margin: 0 auto 24px;\n background: linear-gradient(45deg, #ff6b6b, #feca57, #48dbfb, #ff6348);\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 48px;\n color: white;\n ",o.textContent="🎰",n.appendChild(o);const a=document.createElement("button");a.textContent="SPIN NOW!",a.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 ",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);o.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),a.disabled=!1,a.textContent="TRY AGAIN"}}),n.appendChild(a);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: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",r.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),document.body.appendChild(t)}renderSpinWheelWidget(e,t){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",a=i.textColor||t.text_color||"#333333",r=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(a)};\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(r)};\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(),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 a=`${this.apiHost}/v1/widgets/spin-wheel/submit`,r={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.organizationId&&(r["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(a,{method:"POST",headers:r,body:JSON.stringify(h)});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 a=document.createElement("p");a.textContent="Check your WhatsApp/SMS for your discount code and cart link!",a.style.cssText="margin: 0 0 20px 0; font-size: 14px; color: #666;",n.appendChild(a);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)}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 a=o.getContext("2d");if(a){a.fillStyle="#c0c0c0",a.fillRect(0,0,o.width,o.height),a.fillStyle="#888",a.font="20px Arial",a.textAlign="center",a.fillText("Scratch here!",o.width/2,o.height/2);let e=!1;const t=(e,t)=>{a.globalCompositeOperation="destination-out",a.beginPath(),a.arc(e,t,20,0,2*Math.PI),a.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 r=document.createElement("button");r.textContent="REVEAL PRIZE",r.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 ",r.addEventListener("click",async()=>{r.disabled=!0,r.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),r.disabled=!1,r.textContent="TRY AGAIN"}}),n.appendChild(r),t.appendChild(n),this.addAnimationStyles(),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 a={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 ${a[s]||a.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 r=document.createElement("div");r.textContent=t||"Someone just made a purchase!",r.style.cssText="flex: 1; font-size: 13px; color: #333;",o.appendChild(r),this.addAnimationStyles(),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 a=document.createElement("input");a.type="number",a.min="0",a.max="10",a.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(a);const r=document.createElement("label");r.textContent="Tell us more (optional)",r.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",s.appendChild(r);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(a.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(),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:s,image_url:o}=e.config,a=document.createElement("div");a.className="aegis-exit-popup-overlay",a.setAttribute("data-widget-id",e.widget_id),a.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 r=document.createElement("div");if(r.className="aegis-exit-popup-modal",r.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;",r.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)}r.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(a),this.renderedWidgets.delete(e.widget_id)}),r.style.position="relative",r.appendChild(h),a.appendChild(r),this.addAnimationStyles(),document.body.appendChild(a)}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})});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 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)}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})});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||{}})})}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){const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),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 a=document.createElement("p"),r=this.interpolateCartVariables(t.message||"Your cart is waiting for you!");if(a.textContent=r,a.style.cssText="margin: 0 0 24px 0; font-size: 16px; line-height: 1.5;",i.appendChild(a),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(),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),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 a=document.createElement("form"),r=document.createElement("input");r.type="email",r.placeholder="Enter your email",r.required=!0,r.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 ",a.appendChild(r);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 ",a.appendChild(c),a.addEventListener("submit",async t=>{t.preventDefault(),c.disabled=!0,c.textContent="Submitting...";try{await this.trackEvent(e,"submit",{type:"lead_gen",email:r.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(a);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(),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}`)}}},window.TriggerEngine=class{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.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}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)}})}},b}();
2
2
  //# sourceMappingURL=aegis.min.js.map