@active-reach/web-sdk 1.20.0 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aegis.min.js +1 -1
- package/dist/aegis.min.js.map +1 -1
- package/dist/cdn.d.ts.map +1 -1
- package/dist/chat/AegisChat.d.ts +24 -0
- package/dist/chat/AegisChat.d.ts.map +1 -1
- package/dist/chat/index.d.ts +1 -1
- package/dist/chat/index.d.ts.map +1 -1
- package/dist/inapp/AegisInAppManager.d.ts +17 -1
- package/dist/inapp/AegisInAppManager.d.ts.map +1 -1
- package/dist/inapp/renderPreview.d.ts +16 -1
- package/dist/inapp/renderPreview.d.ts.map +1 -1
- package/dist/inapp/renderers/active-web-chat.d.ts +7 -0
- package/dist/inapp/renderers/active-web-chat.d.ts.map +1 -1
- package/dist/inapp/renderers/hero.d.ts +23 -0
- package/dist/inapp/renderers/hero.d.ts.map +1 -0
- package/dist/inapp/renderers/index.d.ts +1 -0
- package/dist/inapp/renderers/index.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +582 -126
- package/dist/index.js.map +1 -1
- package/dist/runtime/AegisMessageRuntime.d.ts +1 -1
- package/dist/runtime/AegisMessageRuntime.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/aegis.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Aegis=function(){"use strict";var e;const t={workspace_id:null,batch_size:10,batch_interval:1e3,capture_utm:!0,capture_referrer:!0,auto_page_view:!1,session_timeout:30,debug:!1,respect_dnt:!0,cross_domain_tracking:!1,secure_cookie:!0,enable_offline_mode:!0,max_offline_events:100,retry_failed_requests:!0,max_retries:3,retry_backoff_multiplier:2,request_timeout:5e3,rate_limit_burst:100,rate_limit_per_second:20,auto_region_detection:!0,wait_for_consent:!1,enable_consent_mode:!1,integrate_onetrust:!1,integrate_cookiebot:!1,integrate_google_consent_mode:!1,default_consent:{analytics:!1,marketing:!1,functional:!0},initialized:!1,api_host:null,cell_endpoints:[],preferred_region:null,cookie_domain:null,plugins:[],active_cell:null};function n(){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 i(){return`msg_${Date.now()}_${n().slice(0,8)}`}const o=new class{constructor(){this.enabled=!1,this.prefix="[Active Reach 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?o.debug("Loaded existing anonymous ID:",e):(e=n(),this.storage.set("anon_id",e,365),o.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,o.debug("Loaded user ID:",e)),t)try{this.traits=JSON.parse(t),o.debug("Loaded user traits:",this.traits)}catch(n){o.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),o.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),o.debug("User traits updated:",this.traits)}getTraits(){return{...this.traits}}reset(){this.userId=null,this.traits={},this.anonymousId=n(),this.storage.remove("user_id"),this.storage.remove("user_traits"),this.storage.set("anon_id",this.anonymousId,365),o.info("Identity reset, new anonymous ID:",this.anonymousId)}alias(e){const t=this.userId||this.anonymousId;return this.setUserId(e),o.info("User aliased:",{previousId:t,newUserId:e}),{previousId:t,newUserId:e}}getState(){return{anonymousId:this.anonymousId,userId:this.userId,traits:this.getTraits()}}}class a{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,o.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:(o.debug("Session expired, creating new session"),this.storage.remove("session"),null)}catch(t){return o.warn("Failed to parse session data:",t),this.storage.remove("session"),null}}createNewSession(){const e=`sess_${Date.now()}_${n().slice(0,8)}`;return this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.eventCount=0,this.sessionId=e,this.persistSession(),o.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?(o.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&&(o.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(),o.info("Ad click IDs stored in session:",this.adClickIDs))}getAdClickIDs(){return this.adClickIDs}getLandingPage(){return this.landingPage}destroy(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null)}}class r{constructor(e,t,n){this.buffer=[],this.flushInterval=null,this.isFlushing=!1,this.offlineQueue=[],this.isOnline=navigator.onLine,this.config=e,this.transport=t,this.storage=n,e.enableOfflineMode&&(this.loadOfflineQueue(),this.setupOnlineListener()),this.startFlushTimer(),this.setupUnloadHandlers()}loadOfflineQueue(){const e=this.storage.get("offline_queue");if(e)try{const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.offlineQueue=t.slice(0,this.config.maxOfflineEvents),o.info(`Loaded ${this.offlineQueue.length} offline events`),this.isOnline&&this.flushOfflineQueue())}catch(t){o.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),o.debug(`Saved ${this.offlineQueue.length} events to offline queue`)}catch(e){o.warn("Failed to save offline queue:",e)}else this.storage.remove("offline_queue")}setupOnlineListener(){window.addEventListener("online",()=>{o.info("Connection restored"),this.isOnline=!0,this.flushOfflineQueue(),this.flush()}),window.addEventListener("offline",()=>{o.warn("Connection lost, entering offline mode"),this.isOnline=!1})}async flushOfflineQueue(){if(0===this.offlineQueue.length)return;o.info(`Flushing ${this.offlineQueue.length} offline events`);const e=[...this.offlineQueue];this.offlineQueue=[],this.storage.remove("offline_queue");(await this.transport.send(e)).success?o.info("Offline events sent successfully"):(o.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),o.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&&(o.warn("Offline queue full, dropping oldest event"),this.offlineQueue.shift()),this.offlineQueue.push(e),this.saveOfflineQueue(),o.debug("Event added to offline queue")}async flush(){if(this.isFlushing)return void o.debug("Flush already in progress, skipping");if(0===this.buffer.length)return;this.isFlushing=!0;const e=[...this.buffer];this.buffer=[],o.info(`Flushing ${e.length} events`);try{const t=await this.transport.send(e);t.success?o.info("Events sent successfully"):(o.error("Failed to send events:",t.error),this.config.enableOfflineMode?(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),o.info("Events saved to offline queue")):(this.buffer.unshift(...e),o.warn("Events re-queued for retry")))}catch(t){o.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),o.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(),o.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"),o.info("Queue cleared")}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}class c{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,o.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 o.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(o.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 o.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 o.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 i=n[0].cell;this.activeCell=i,this.saveCachedCell(i),o.info("Optimal cell selected:",{region:i.region,latency:n[0].latency})}async measureLatency(e){const t=performance.now();try{const n=new AbortController,i=setTimeout(()=>n.abort(),2e3),o=await fetch(`${e.url}/health`,{method:"GET",signal:n.signal});return clearTimeout(i),o.ok?performance.now()-t:1/0}catch(n){return o.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]),o.info("Cell selected by priority:",e[0])):o.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&&(o.warn("Active cell unhealthy, selecting new cell"),await this.selectOptimalCell()),o.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(o.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)?(o.debug("Batch sent via Beacon"),{success:!0,endpoint:e}):(o.warn("Beacon send failed, falling back to fetch"),this.sendViaFetch(e,t))}catch(n){return o.error("Beacon send error:",n),{success:!1,error:n,endpoint:e}}}async sendViaFetch(e,t,n=1){try{const i=new AbortController,s=setTimeout(()=>i.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:i.signal});if(clearTimeout(s),a.ok){const t=await a.json();return o.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const i=await a.text(),s=new Error(`HTTP ${a.status}: ${i||a.statusText}`);return o.error("Batch send failed:",s),this.shouldRetry(a.status,n)?this.retryRequest(e,t,n):{success:!1,error:s,endpoint:e}}}catch(i){return o.error("Fetch error:",i),this.shouldRetry(0,n)?this.retryRequest(e,t,n):{success:!1,error:i,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 i=1e3*Math.pow(this.config.retryBackoffMultiplier,n);return o.info(`Retrying request in ${i}ms (attempt ${n+1})`),await new Promise(e=>setTimeout(e,i)),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 d="aegis_";class l{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=d+e;if(this.useLocalStorage)try{const e={value:t,expiry:Date.now()+24*n*60*60*1e3};localStorage.setItem(i,JSON.stringify(e))}catch(o){console.warn("[Active Reach Storage] localStorage.setItem failed:",o)}this.setCookie(i,t,n)}get(e){const t=d+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("[Active Reach Storage] localStorage.getItem failed:",n)}return this.getCookie(t)}remove(e){const t=d+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch(n){console.warn("[Active Reach Storage] localStorage.removeItem failed:",n)}this.deleteCookie(t)}clear(){if(this.useLocalStorage)try{Object.keys(localStorage).forEach(e=>{e.startsWith(d)&&localStorage.removeItem(e)})}catch(e){console.warn("[Active Reach Storage] localStorage.clear failed:",e)}document.cookie.split(";").forEach(e=>{const t=e.split("=")[0].trim();t.startsWith(d)&&this.deleteCookie(t)})}setCookie(e,t,n){try{const i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3);let o=`${e}=${t};${`expires=${i.toUTCString()}`};path=/`;if(this.options.secureCookie&&"https:"===window.location.protocol&&(o+=";Secure"),o+=";SameSite=Lax",this.options.cookieDomain)o+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(o+=`;domain=${e}`)}document.cookie=o}catch(i){console.warn("[Active Reach 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("[Active Reach 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("[Active Reach 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("[Active Reach Storage] getRootDomain failed:",e),null}}}function p(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("[Active Reach 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"}}(),o=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"}}(),s=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("[Active Reach 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},...o&&{os:o},...s&&{browser:s},...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)?o.warn(`Plugin "${e.name}" already registered, skipping`):(this.plugins.set(e.name,e),o.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){o.error(`Error destroying plugin "${e}":`,n)}this.plugins.delete(e),o.info(`Plugin unregistered: ${e}`)}else o.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 s of this.plugins.values()){const a=s[e];if("function"==typeof a)try{const e=await a.apply(s,t);if(void 0!==e)return e}catch(n){if(o.error(`Error executing ${String(e)} in plugin "${s.name}":`,n),s.onError)try{s.onError(n,{hookName:e,args:t})}catch(i){o.error(`Error in onError handler for plugin "${s.name}":`,i)}}}}async executeHookChain(e,t,...n){let i=t;for(const r of this.plugins.values()){const t=r[e];if("function"==typeof t)try{const e=await t.apply(r,[i,...n]);null!=e&&(i=e)}catch(s){if(o.error(`Error executing ${String(e)} in plugin "${r.name}":`,s),r.onError)try{r.onError(s,{hookName:e,value:i,additionalArgs:n})}catch(a){o.error(`Error in onError handler for plugin "${r.name}":`,a)}}}return i}async executeHookParallel(e,...t){const n=[];for(const i of this.plugins.values()){const s=i[e];if("function"==typeof s){const a=(async()=>{try{return await s.apply(i,t)}catch(n){if(o.error(`Error executing ${String(e)} in plugin "${i.name}":`,n),i.onError)try{i.onError(n,{hookName:e,args:t})}catch(a){o.error(`Error in onError handler for plugin "${i.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){o.error(`Error destroying plugin "${t.name}":`,e)}this.plugins.clear(),o.info("All plugins cleared")}}class u{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 o.info("Loaded consent preferences:",t),this.mergeWithDefaults(t)}catch(t){o.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),o.info("Saved consent preferences:",this.preferences)}catch(e){o.error("Failed to save consent preferences:",e)}}setConsent(e){const t={...this.preferences,...e};t.necessary=!0,this.preferences=t,this.savePreferences(),this.notifyListeners(),o.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){o.error("Consent listener error:",t)}})}reset(){this.storage.remove(this.config.consentStorageKey),this.preferences=this.getDefaultPreferences(),this.notifyListeners(),o.info("Consent preferences reset")}integrateOneTrust(){if("undefined"==typeof window)return;if(!window.OneTrust)return void o.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")}),o.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 o.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}),o.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 o.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"}),o.info("Updated Google Consent Mode")};this.onChange(t),t()}}const g="_fbp",m="_fbc";function f(e){if("undefined"==typeof document)return null;try{const t=`${e}=`,n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length))}}catch{}return null}function x(e,t,n){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const i=new Date(Date.now()+24*n*60*60*1e3).toUTCString(),o=function(){if("undefined"==typeof window)return null;const e=window.location.hostname;if(!e||"localhost"===e)return null;if(/^\d+\.\d+\.\d+\.\d+$/.test(e))return null;const t=e.split(".");return t.length<2?null:"."+t.slice(-2).join(".")}(),s="https:"===window.location.protocol;let a=`${e}=${encodeURIComponent(t)};expires=${i};path=/;SameSite=Lax`;s&&(a+=";Secure"),o&&(a+=`;domain=${o}`),document.cookie=a}catch{}}function y(){if("undefined"==typeof window)return 1;const e=window.location.hostname;if(!e||"localhost"===e||/^\d+\.\d+\.\d+\.\d+$/.test(e))return 1;const t=e.split(".");return Math.max(1,t.length-1)}function b(){const e=f(g);if(e)return e;const t=`fb.${y()}.${Date.now()}.${Math.floor(1e10*Math.random()).toString().padStart(10,"0")}`;return x(g,t,90),t}function v(){const e=f(m);if(e)return e;const t=w();if(!t)return null;const n=`fb.${y()}.${Date.now()}.${t}`;return x(m,n,90),n}function w(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get("fbclid")}catch{return null}}function _(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function C(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 k{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:C(e.products)})}productClicked(e,t){this.aegis.track("product_clicked",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}productImpressed(e,t){this.aegis.track("product_impression",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}categoryFiltered(e,t){this.aegis.track("category_filtered",{category:e,previous_category:null==t?void 0:t.previous_category,result_count:null==t?void 0:t.result_count})}searchPerformed(e){this.aegis.track("search_performed",{query:e.query,results_count:e.results_count,filters:e.filters})}addToCart(e){this.aegis.track("cart_item_added",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label})}removeFromCart(e){this.aegis.track("cart_item_removed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",variant_id:e.variant_id})}cartViewed(e){this.aegis.track("cart_viewed",{cart_id:e.cart_id,value:e.value,currency:e.currency??"INR",num_items:_(e.products),products:C(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:_(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:C(e.products)})}checkoutStep(e,t){this.aegis.track("checkout_step",{step:e,...t})}checkoutOption(e){this.aegis.track("checkout_option",{...e})}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:_(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:C(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?C(n):void 0})}orderShipped(e,t){this.aegis.track("order_shipped",{order_id:e,carrier:null==t?void 0:t.carrier,tracking_code:null==t?void 0:t.tracking_code,tracking_url:null==t?void 0:t.tracking_url})}couponApplied(e){this.aegis.track("coupon_applied",{...e})}couponRemoved(e){this.aegis.track("coupon_removed",{...e})}couponDenied(e,t){this.aegis.track("coupon_denied",{...e,reason:t})}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})}productRemovedFromWishlist(e){this.aegis.track("wishlist_item_removed",{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})}productWaitlisted(e){this.aegis.track("product_waitlisted",{product_id:e.product.product_id,sku:e.product.sku??e.product.product_id,variant_id:e.product.variant_id,name:e.product.name,price:e.product.price,channels:e.channels})}promotionViewed(e){this.aegis.track("promotion_viewed",{...e})}promotionClicked(e){this.aegis.track("promotion_clicked",{...e})}}class E{constructor(e={}){this.droppedThisWindow=0,this.firstDroppedName=null,this.windowFlushTimer=null,this.capacity=Math.max(1,e.burstCapacity??100),this.refillPerSecond=Math.max(1,e.refillPerSecond??20),this.windowMs=e.dropCoalesceWindowMs??1e3,this.onDropBatch=e.onDropBatch,this.tokens=this.capacity,this.lastRefillMs=Date.now()}tryConsume(e){return this.refill(),this.tokens>=1?(this.tokens-=1,!0):(this.droppedThisWindow+=1,null===this.firstDroppedName&&(this.firstDroppedName=e,o.warn(`[Aegis] Rate limit reached — dropping event "${e}" and any further events for ${this.windowMs}ms. Burst=${this.capacity}, refill=${this.refillPerSecond}/s.`)),this.windowFlushTimer||(this.windowFlushTimer=setTimeout(()=>this.flushWindow(),this.windowMs)),!1)}getAvailableTokens(){return this.refill(),Math.floor(this.tokens)}destroy(){this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.flushWindow()}refill(){const e=Date.now(),t=(e-this.lastRefillMs)/1e3;if(t<=0)return;const n=t*this.refillPerSecond;this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefillMs=e}flushWindow(){if(this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.droppedThisWindow>0&&this.onDropBatch)try{this.onDropBatch(this.droppedThisWindow,this.firstDroppedName)}catch(e){o.warn("[Active Reach] RateLimiter.onDropBatch threw:",e)}this.droppedThisWindow=0,this.firstDroppedName=null}}const S=3432918353,T=461845907;function $(e,t=0){return function(e,t=0){const n=e.length,i=Math.floor(n/4);let o=t>>>0;for(let c=0;c<i;c++){const t=4*c;let n=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;n=Math.imul(n,S),n=n<<15|n>>>17,n=Math.imul(n,T),o^=n,o=o<<13|o>>>19,o=Math.imul(o,5)+3864292196>>>0}const s=4*i;let a=0;const r=n-s;3===r&&(a^=e[s+2]<<16);r>=2&&(a^=e[s+1]<<8);r>=1&&(a^=e[s],a=Math.imul(a,S),a=a<<15|a>>>17,a=Math.imul(a,T),o^=a);return o^=n,o^=o>>>16,o=Math.imul(o,2246822507),o^=o>>>13,o=Math.imul(o,3266489909),o^=o>>>16,o>>>0}((new TextEncoder).encode(e),t)}class I{constructor(e,t){if(this.params=t,t.m&t.m-1)throw new Error(`Bloom filter m must be a power of 2, got ${t.m}`);if(e.length!==t.m>>3)throw new Error(`Bloom filter buffer size mismatch: expected ${t.m>>3} bytes, got ${e.length}`);this.buf=e,this.mask=t.m-1}static fromBase64(e,t){const n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const t=globalThis.Buffer;if(t&&"function"==typeof t.from){const n=t.from(e,"base64");return new Uint8Array(n)}throw new Error("No base64 decoder available (neither atob nor Buffer)")}(e);return new I(n,t)}has(e){const t=$(e,this.params.seedA),n=$(e,this.params.seedB);for(let i=0;i<this.params.k;i++){const e=t+Math.imul(i,n)>>>0&this.mask;if(0===(this.buf[e>>3]&1<<(7&e)))return!1}return!0}}class z{constructor(){this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,this.localNovelNames=new Set,this.droppedSinceLastReport=new Map,this.reportWindowStart=Date.now(),this.hasWarnedThisSession=!1}ingestHint(e){if(!e||"mmh3_x86_32_km"!==e.bloom_algo)return this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,void this.localNovelNames.clear();try{this.bloom=I.fromBase64(e.bloom_b64,{m:e.m,k:e.k,seedA:e.seed_a,seedB:e.seed_b})}catch{this.bloom=null}this.remainingNewNames=e.remaining_new_names??1/0,this.graceActive=!0===e.grace_active,this.localNovelNames.clear()}shouldSend(e){if(!this.bloom)return!0;if(this.graceActive)return!0;if(this.bloom.has(e))return!0;if(this.localNovelNames.has(e))return!0;if(this.remainingNewNames>0)return this.localNovelNames.add(e),this.remainingNewNames-=1,!0;const t=this.droppedSinceLastReport.get(e)??0;var n;return this.droppedSinceLastReport.set(e,t+1),this.hasWarnedThisSession||(this.hasWarnedThisSession=!0,n=`[aegis] Event-name cap reached — "${e}" dropped locally. Upgrade your plan or remove dynamically-generated event names.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(n)),!1}drainDropReport(){if(0===this.droppedSinceLastReport.size)return null;const e={};let t=0;for(const[i,o]of this.droppedSinceLastReport)e[i]=o,t+=o;const n=this.reportWindowStart;return this.droppedSinceLastReport.clear(),this.reportWindowStart=Date.now(),{events:e,total:t,since:n}}_debugState(){return{hasBloom:null!==this.bloom,remaining:this.remainingNewNames,localNovel:this.localNovelNames.size,graceActive:this.graceActive}}}const A=["system.","user.","loyalty.","review.","cart.","checkout.","product.","pos.","bill.","feedback.","chat.","delivery.","event.","$","_"],L=/(.)([A-Z][a-z]+)/g,M=/([a-z0-9])([A-Z])/g,R=/[\s\-.]+/g,P=/_+/g,D=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/,N=new Set(["at","on","date","time","timestamp","dob","birthday","joined","expired","expires","created","updated","started","ended"]);function F(e){if(!e)return null;return e.replace(L,"$1_$2").replace(M,"$1_$2").replace(R,"_").toLowerCase().replace(P,"_").replace(/^_+|_+$/g,"")||null}function O(e){const t=e.toLowerCase();for(const n of A)if(t.startsWith(n))return n;return null}function B(e){for(const t of e.toLowerCase().split(/[_\-.\s]+/))if(N.has(t))return!0;return!1}function U(e){if("number"==typeof e&&Number.isFinite(e))return e<1e11?Math.floor(1e3*e):Math.floor(e);if("string"==typeof e&&e){const t=e.trim();if(D.test(t)){const e=Date.parse(t);if(!Number.isNaN(e))return e}const n=Number(t);if(Number.isFinite(n))return n<1e11?Math.floor(1e3*n):Math.floor(n)}return null}const W=class e{constructor(){this.warnCounts=new Map}process(e,t){const n={},i=[];if(!e||"object"!=typeof e)return{sanitized:n,drops:i};for(const o of Object.keys(e)){const t=O(o);if(null!==t){i.push({originalKey:o,verdict:"reserved_prefix",reason:`key uses reserved namespace ${JSON.stringify(t)}`});continue}const s=F(o);if(null===s){i.push({originalKey:o,verdict:"bad_key_format",reason:"key reduced to empty after normalization"});continue}if(null!==O(s)){i.push({originalKey:o,verdict:"reserved_prefix",reason:`normalized key ${JSON.stringify(s)} still uses a reserved namespace`});continue}let a=e[o];if("string"==typeof a){if(a.length>1e4){i.push({originalKey:o,verdict:"value_too_long",reason:`value length ${a.length} exceeds hard cap 10000`});continue}a.length>512&&(i.push({originalKey:o,verdict:"value_too_long",reason:`value truncated from ${a.length} to 512 chars`}),a=a.slice(0,512))}if(B(s)&&"string"==typeof a){const e=U(a);if(null===e){i.push({originalKey:o,verdict:"bad_date_format",reason:`value ${JSON.stringify(a)} on date-keyed field ${JSON.stringify(s)} didn't parse as ISO-8601 / epoch`});continue}a=e}n[s]=a}for(const o of i)this.maybeWarn(t??null,o);return{sanitized:n,drops:i}}maybeWarn(t,n){const i=t??"__no_workspace__";let o=this.warnCounts.get(i);o||(o=new Map,this.warnCounts.set(i,o));const s=o.get(n.verdict)??0;var a;s>=e.WARN_CAP||(o.set(n.verdict,s+1),a=`[Active Reach SDK] trait ${n.verdict}: ${n.reason} (original key: ${JSON.stringify(n.originalKey)}). Backend will reject; fix the SDK call to silence this warning.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(a))}};W.WARN_CAP=3;let j=W;const q=new Set(["email","sms","push","webpush","whatsapp","rcs","inapp"]),H=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,V=/^\+[1-9]\d{7,14}$/,X=/^[a-f0-9]{64}$/i,K=/^\d{4}-\d{2}-\d{2}$/;class Y{constructor(e){this.pendingTraits={},this.aegis=e}login(e,t){if("string"!=typeof e||0===e.length)return void o.warn("[user.login] userId must be a non-empty string");const n={...this.pendingTraits,...t||{}};this.pendingTraits={},this.aegis.identify(e,n)}logout(){this.pendingTraits={},this.aegis.reset()}setAttribute(e,t){"string"==typeof e&&0!==e.length?this.writeTraits({[e]:t}):o.warn("[user.setAttribute] key must be a non-empty string")}setAttributes(e){e&&"object"==typeof e?this.writeTraits(e):o.warn("[user.setAttributes] map must be an object")}setEmail(e){H.test(e)?this.writeTraits({email:e.toLowerCase()}):o.warn("[user.setEmail] invalid email format")}setPhone(e){V.test(e)?this.writeTraits({phone:e}):o.warn("[user.setPhone] phone must be E.164 (e.g. +15551234567)")}setHashedEmail(e){X.test(e)?this.writeTraits({email_sha256:e.toLowerCase()}):o.warn("[user.setHashedEmail] expected 64-char hex SHA-256")}setHashedPhone(e){X.test(e)?this.writeTraits({phone_sha256:e.toLowerCase()}):o.warn("[user.setHashedPhone] expected 64-char hex SHA-256")}setBirthDate(e){K.test(e)?this.writeTraits({birth_date:e}):o.warn("[user.setBirthDate] expected YYYY-MM-DD")}setOptIn(e,t){q.has(e)?"boolean"==typeof t?this.writeTraits({[`opt_in_${e}`]:t}):o.warn("[user.setOptIn] granted must be a boolean"):o.warn(`[user.setOptIn] unknown channel: ${e}`)}setSecureToken(e){"string"==typeof e&&0!==e.length?this.writeTraits({_secure_token:e}):o.warn("[user.setSecureToken] token must be a non-empty string")}_getPendingTraits(){return{...this.pendingTraits}}writeTraits(e){const t=this.aegis.getUserId();t?this.aegis.identify(t,e):Object.assign(this.pendingTraits,e)}}class Q{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._user=null,this.rateLimiter=null,this.nameGovernor=new z,this.traitGovernor=new j,this._lastPageUrl=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._lastEventIds=new Map,this._workspaceCodes=new Set,this._runtimeWorkspace=null,this._runtimeLocation=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)?o.warn("SDK already initialized"):this.shouldRespectDNT(t)?o.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&&o.enable(),o.info("Initializing Active Reach SDK...",this.config),this.storage=new l({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 u(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 a(this.storage,this.config.session_timeout),this.captureAdClickIDsOnInit(),this.transport=new c({writeKey:this.config.write_key,apiHost:this.config.api_host,cellEndpoints:this.config.cell_endpoints,preferredRegion:this.config.preferred_region,autoRegionDetection:this.config.auto_region_detection,requestTimeout:this.config.request_timeout,retryFailedRequests:this.config.retry_failed_requests,maxRetries:this.config.max_retries,retryBackoffMultiplier:this.config.retry_backoff_multiplier},this.storage),this.config.active_cell=this.transport.getActiveCell(),this.queue=new r({batchSize:this.config.batch_size,batchInterval:this.config.batch_interval,enableOfflineMode:this.config.enable_offline_mode,maxOfflineEvents:this.config.max_offline_events},this.transport,this.storage),this.rateLimiter=new E({burstCapacity:this.config.rate_limit_burst,refillPerSecond:this.config.rate_limit_per_second,onDropBatch:(e,t)=>this.emitRateLimitMeta(e,t)}),await this.initializePlugins(),this.config.auto_page_view&&(this.page(),this.startSPATracking()),o.info("Active Reach SDK initialized successfully")):o.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(e,n){return{...t,...n,write_key:e,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("[Active Reach URL Parser] parseAdClickIDs failed:",t),{}}}();(function(e){return Object.keys(e).length>0})(e)&&(this.session.setAdClickIDs(e,window.location.href),o.info("Ad click IDs captured on page load:",e))}async initializePlugins(){if(this.config){for(const e of this.config.plugins)o.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=>{o.error(`Failed to initialize plugin "${e.name}":`,t)})}removePlugin(e){this.plugins.unregister(e)}ingestWorkspaceCodes(e){this._workspaceCodes=new Set((e??[]).filter(e=>"string"==typeof e&&e.length>0)),o.debug("Workspace codes ingested",{count:this._workspaceCodes.size})}setWorkspace(e){if(this._runtimeWorkspace=e,"undefined"!=typeof window&&window.sessionStorage)try{e?window.sessionStorage.setItem("aegis_runtime_ws",e):window.sessionStorage.removeItem("aegis_runtime_ws")}catch{}o.debug("Runtime workspace set",{value:e})}clearWorkspace(){this.setWorkspace(null)}ingestLocationCodes(e){this._workspaceCodes=new Set((e??[]).filter(e=>"string"==typeof e&&e.length>0)),o.debug("Location codes ingested",{count:this._workspaceCodes.size})}setLocation(e){if(this._runtimeLocation=e,"undefined"!=typeof window&&window.sessionStorage)try{e?window.sessionStorage.setItem("aegis_runtime_location",e):window.sessionStorage.removeItem("aegis_runtime_location")}catch{}o.debug("Runtime location set",{value:e})}clearLocation(){this.setLocation(null)}getPathLocationCode(){return this.getPathWorkspaceCode()}getEffectiveLocationId(){var e;const t=null==(e=this.config)?void 0:e.location_id;if(t)return t;if("undefined"==typeof window)return;try{const e=new URLSearchParams(window.location.search),t=e.get("location")||e.get("ws");if(t&&t.length>0)return t}catch{}const n=this.getPathLocationCode();if(n)return n;if(this._runtimeLocation)return this._runtimeLocation;try{if(window.sessionStorage){const e=window.sessionStorage.getItem("aegis_runtime_location");if(e&&e.length>0)return e}}catch{}}getPathWorkspaceCode(){if("undefined"!=typeof window&&0!==this._workspaceCodes.size)try{const e=window.location.pathname.split("/").filter(Boolean);if(0===e.length)return;const t=e[0].toLowerCase();return this._workspaceCodes.has(t)?t:void 0}catch{return}}getEffectiveWorkspaceId(){var e;const t=null==(e=this.config)?void 0:e.workspace_id;if(t)return t;if("undefined"==typeof window)return;try{const e=new URLSearchParams(window.location.search).get("ws");if(e&&e.length>0)return e}catch{}const n=this.getPathWorkspaceCode();if(n)return n;if(this._runtimeWorkspace)return this._runtimeWorkspace;try{if(window.sessionStorage){const e=window.sessionStorage.getItem("aegis_runtime_ws");if(e&&e.length>0)return e}}catch{}}track(e,t){if(!this.assertInitialized())return;const n=i(),o={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(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this._lastEventIds.set(e,n),this.captureEvent(o)}identify(e,t){if(!this.assertInitialized())return;const n=this.getEffectiveWorkspaceId()||null,{sanitized:o}=this.traitGovernor.process(t,n);this.identity.setUserId(e,o);const s={type:"identify",traits:o,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(s)}page(e,t){if(!this.assertInitialized())return;const n={type:"page",name:e||document.title,properties:t||{},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(n)}group(e,t){if(!this.assertInitialized())return;const n=this.getEffectiveWorkspaceId()||null,{sanitized:o}=this.traitGovernor.process(t,n),s={type:"group",groupId:e,traits:o,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};this.captureEvent(s)}alias(e){if(!this.assertInitialized())return;const{previousId:t}=this.identity.alias(e),n={type:"alias",previousId:t,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};this.captureEvent(n)}screen(e,t){if(!this.assertInitialized())return;if("string"!=typeof e||0===e.length)return void o.warn("aegis.screen: name must be a non-empty string");const n={type:"screen",name:e,properties:t||{},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(n)}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 o.debug("Event blocked: analytics consent not granted");if("track"===e.type){const t=e;if(!("string"==typeof t.event&&t.event.startsWith("aegis.client."))&&!this.nameGovernor.shouldSend(t.event))return}if(this.rateLimiter){const t="track"===e.type&&e.event?e.event:e.type;if(!("track"===e.type&&"string"==typeof e.event&&e.event.startsWith("aegis.client."))&&!this.rateLimiter.tryConsume(t))return}const n=e.context,i=e.properties;if((null==n?void 0:n.campaign)&&i&&!i.campaign_id){const e=n.campaign;e.campaign&&(i.campaign_id=e.campaign),e.source&&(i.campaign_source=e.source),e.medium&&(i.campaign_medium=e.medium),e.content&&(i.campaign_content=e.content),e.term&&(i.campaign_term=e.term)}if((null==n?void 0:n.adClickIDs)&&i){const e=n.adClickIDs,t=e.gclid||e.fbclid||e.ctwa_clid||e.msclkid||e.ttclid;t&&!i.campaign_click_id&&(i.campaign_click_id=t)}if(i){const e={fbp:b(),fbc:v(),fbclid:w()};e.fbp&&!i.fbp&&(i.fbp=e.fbp),e.fbc&&!i.fbc&&(i.fbc=e.fbc),e.fbclid&&!i.fbclid&&(i.fbclid=e.fbclid)}o.debug("Capturing event:",e);const s=await this.plugins.executeHookChain("beforeEventCapture",e);s?(this.queue.push(s),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",s)):o.debug("Event cancelled by plugin")}emitRateLimitMeta(e,t){var n,o;if(!(null==(n=this.config)?void 0:n.initialized)||!this.session||!this.identity)return;const s={type:"track",event:"aegis.client.rate_limited",properties:{dropped_count:e,sample_event_name:t,burst_capacity:this.config.rate_limit_burst,refill_per_second:this.config.rate_limit_per_second},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};null==(o=this.queue)||o.push(s)}reset(){this.assertInitialized()&&(this.identity.reset(),this._user=null,o.info("User identity reset"))}ingestGovernanceHint(e){this.nameGovernor.ingestHint(e??null),o.debug("Governance hint ingested",e?{k:e.k,m:e.m,remaining:e.remaining_new_names}:"disabled")}emitGovernanceDropMeta(){var e,t;if(!(null==(e=this.config)?void 0:e.initialized)||!this.session||!this.identity)return;const n=this.nameGovernor.drainDropReport();if(!n)return;const o={type:"track",event:"aegis.client.name_governor_dropped",properties:{dropped_count:n.total,distinct_names:Object.keys(n.events).length,sample_names:Object.entries(n.events).sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({name:e,count:t})),window_start:n.since,window_end:Date.now()},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};null==(t=this.queue)||t.push(o)}async flush(){this.assertInitialized()&&(this.emitGovernanceDropMeta(),await this.queue.flush())}getAnonymousId(){return this.identity?this.identity.getAnonymousId():null}getUserId(){return this.identity?this.identity.getUserId():null}async getRewards(){const e=this.config;if(!e||!e.api_host||!this.identity)return null;const t=this.identity.getUserId();if(!t)return null;const n=e.api_host.replace(/\/$/,""),i={"X-Aegis-Write-Key":e.write_key,"X-Contact-ID":t,"X-User-ID":t},s=e.organization_id;s&&(i["X-Organization-ID"]=s);const a=this.getEffectiveLocationId();a&&(i["X-Location-Id"]=a);try{const e=await fetch(`${n}/api/v1/sdk/entitlements`,{method:"GET",headers:i,credentials:"include"});return 204!==e.status&&e.ok?await e.json():null}catch(r){return o.warn("getRewards() failed",r),null}}getSessionId(){return this.session?this.session.getSessionId():null}lastEventId(e){return this._lastEventIds.get(e)??null}debug(e=!0){e?o.enable():o.disable(),this.config&&(this.config.debug=e)}setCell(e){if(!this.config)return void o.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),o.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),o.info("Consent preferences updated")):o.warn("Consent manager not initialized")}grantConsent(e){this.consent?e?this.consent.setConsent({[e]:!0}):this.consent.grantAll():o.warn("Consent manager not initialized")}denyConsent(e){this.consent?e?this.consent.setConsent({[e]:!1}):this.consent.denyAll():o.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):(o.warn("Consent manager not initialized"),()=>{})}assertInitialized(){var e;return!!(null==(e=this.config)?void 0:e.initialized)||(o.warn("SDK not initialized. Call aegis.init() first."),!1)}get ecommerce(){return this._ecommerce||(this._ecommerce=new k(this)),this._ecommerce}get user(){return this._user||(this._user=new Y(this)),this._user}destroy(){this.stopSPATracking(),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.rateLimiter&&(this.rateLimiter.destroy(),this.rateLimiter=null),this.plugins.clear(),o.info("SDK destroyed")}}const G="aegis_sticky_dismissed:";function J(e,t){const{campaign:n,trackEvent:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=n.interactive_config||{},c=r.progress_goal_type||"cart_total",d=Number(r.progress_threshold);if(!(d>0))return s("progress_bar requires a positive progress_threshold — skipping","warn"),null;const l=r.progress_reward_text||n.body||"Unlocked!",p="sse"===r.progress_source?"sse":"client";a();const h=o(n.background_color||"#4169e1"),u="branded"===r.surface_style,g=u?h:"#ffffff",m=o(n.text_color||(u?"#ffffff":"#0f172a")),f=o(r.progress_fill_color||(u?"#ffffff":h)),x=u?"rgba(255,255,255,0.25)":`${f}22`,y=document.createElement("div");y.className="aegis-in-app-progress-bar",y.setAttribute("data-campaign-id",n.id),y.style.cssText=t?`\n background: ${g}; color: ${m};\n padding: 10px 14px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `:`\n position: fixed; left: 12px; right: 12px; bottom: 12px;\n max-width: 540px; margin: 0 auto;\n background: ${g}; color: ${m}; border-radius: 12px;\n padding: 10px 14px; z-index: 999997;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `;const b=document.createElement("div");b.style.cssText="display: flex; justify-content: space-between; font-size: 13px; font-weight: 600; margin-bottom: 6px;";const v=document.createElement("span");v.textContent=n.title,b.appendChild(v);const w=document.createElement("span");w.style.cssText="opacity: 0.7; font-weight: 500;",b.appendChild(w),y.appendChild(b);const _=document.createElement("div");_.style.cssText=`\n height: 8px; border-radius: 999px; background: ${x};\n overflow: hidden;\n `;const C=document.createElement("div");if(C.style.cssText=`\n position: relative; overflow: hidden;\n height: 100%; border-radius: 999px; background: ${f};\n width: 0%; transition: width 0.4s cubic-bezier(.4,0,.2,1);\n `,"undefined"!=typeof document&&!document.getElementById("aegis-progress-styles")){const e=document.createElement("style");e.id="aegis-progress-styles",e.textContent="@keyframes aegisProgShimmer{0%{transform:translateX(-100%)}60%,100%{transform:translateX(220%)}}",document.head.appendChild(e)}const k=document.createElement("div");k.style.cssText="position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.38), transparent); transform: translateX(-100%); animation: aegisProgShimmer 1.8s ease-in-out infinite;",C.appendChild(k),_.appendChild(C),y.appendChild(_);const E=document.createElement("div");E.style.cssText="font-size: 11.5px; opacity: 0.65; margin-top: 6px;",y.appendChild(E);let S=!1;const T=new Set,$=e=>{T.has(e)||(T.add(e),i(n.id,"impression",{stepId:e}))},I=()=>{const t=(()=>{var t,i,o;if("sse"===p){const e=window.__aegisProgressSSE;return e&&"number"==typeof e[n.id]?e[n.id]:0}if("cart_total"===c||"items_in_cart"===c){const n=null==(t=e.getCartState)?void 0:t.call(e);if(n)return"items_in_cart"===c?Number(n.itemCount)||0:Number(n.total)||0}try{if("cart_total"===c||"items_in_cart"===c){const e=window;if(null==(i=e.Shopify)?void 0:i.checkout){const t=parseFloat(String(e.Shopify.checkout.total_price||0));return"cart_total"===c?t:0}if(e.aegis_cart)return"items_in_cart"===c?Array.isArray(e.aegis_cart.cart_items)?e.aegis_cart.cart_items.length:0:Number(e.aegis_cart.cart_total||0);try{const e=null==(o=window.localStorage)?void 0:o.getItem("mage-cache-storage");if(e){const t=JSON.parse(e).cart;if(t)return"cart_total"===c?Number(t.subtotalAmount||0):Array.isArray(t.items)?t.items.length:0}}catch{}}return 0}catch{return 0}})(),o=Math.max(0,Math.min(100,t/d*100));if(C.style.width=`${o}%`,w.textContent=`${t.toFixed(0)} / ${d.toFixed(0)} · ${Math.round(o)}%`,k.style.display=o>=100?"none":"",o>=25&&$("q25"),o>=50&&$("q50"),o>=75&&$("q75"),o>=100)E.textContent=l,S||(S=!0,i(n.id,"clicked",{stepId:"unlocked"}));else{const e=Math.max(0,d-t);E.textContent=`Add ${e.toFixed(0)} more to unlock: ${l}`}};I();const z=setInterval(I,1e3),A=()=>clearInterval(z);return window.addEventListener("beforeunload",A,{once:!0}),y.addEventListener("remove",A),y}const Z="aegis_coachmark_progress:";function ee(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(Z+e,String(t))}catch{}}function te(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:o,addAnimationStyles:s}=e,a=t.interactive_config||{},r=a.resume_key;if(!r)return void o("coachmark_tour requires interactive_config.resume_key — skipping","warn");const c=Array.isArray(a.steps)?a.steps:[];if(0===c.length)return void o("coachmark_tour has no steps — skipping","warn");const d=!1!==a.allow_skip,l=!1!==a.show_progress_dots;s();const p=i(t.background_color||"#0f172a"),h=i(t.text_color||"#ffffff"),u="spotlight"===a.highlight_style,g="number"==typeof a.spotlight_padding?a.spotlight_padding:6,m="circle"===a.spotlight_shape?"50%":"10px",f="number"==typeof a.spotlight_dim?Math.max(0,Math.min(95,a.spotlight_dim))/100:u?.64:.4,x=a.spotlight_dim_color||"dark",y="black"===x?"#000000":"brand"===x?p:"custom"===x?i(a.spotlight_dim_custom||"#0f172a"):"#0f172a",b=Math.round(255*Math.max(0,Math.min(1,f))).toString(16).padStart(2,"0"),v=/^#[0-9a-fA-F]{6}$/.test(y)?`${y}${b}`:`rgba(15,23,42,${f})`;let w=function(e){try{if("undefined"==typeof localStorage)return 0;const t=localStorage.getItem(Z+e),n=t?parseInt(t,10):0;return Number.isFinite(n)&&n>=0?n:0}catch{return 0}}(r);if(w>=c.length)return void o(`coachmark_tour ${r} already complete — not re-showing`);n(t.id,"impression");let _=null,C=null,k=null;const E=()=>{null==_||_.remove(),null==C||C.remove(),null==k||k.remove(),_=null,C=null,k=null},S=i=>{var o;E();const s=`step_${i.lastStepIdx}`;i.skipped?n(t.id,"dismissed",{stepId:s}):(n(t.id,"clicked",{stepId:s}),null==(o=e.submitResponse)||o.call(e,"tour_complete",{steps:c.length})),ee(r,c.length)},T=e=>{E();const i=c[e];if(!i)return void S({skipped:!1,lastStepIdx:e-1});ee(r,e);const o=i.anchor_web;let s=null;if(o)try{s=document.querySelector(o)}catch{s=null}const a=!!o&&!s;a&&(console.warn(`[AegisInApp] Coachmark step ${e} anchor "${o}" not found on this surface — rendering centered fallback.`),n(t.id,"anchor_unresolved",{stepId:`step_${e}`,meta:{anchor_resolved:!1,anchor_selector:o,widget_type:"coachmark_tour"}})),n(t.id,"impression",{stepId:`step_${e}`,...a?{meta:{anchor_resolved:!1}}:{}});const x=s?s.getBoundingClientRect():null;if(k=document.createElement("div"),k.className="aegis-in-app-coachmark-highlight",x){const e=u?`0 0 0 3px rgba(255,255,255,0.92), 0 0 0 7px ${p}66, 0 0 0 9999px ${v}`:`0 0 0 2px ${h}, 0 0 0 9999px rgba(0,0,0,${f})`;k.style.cssText=`\n position: fixed;\n top: ${x.top-g}px; left: ${x.left-g}px;\n width: ${x.width+2*g}px; height: ${x.height+2*g}px;\n border-radius: ${u?m:"10px"}; z-index: 999998;\n box-shadow: ${e};\n pointer-events: none;\n transition: all 0.2s ease;\n `}else k.style.cssText=`\n position: fixed; inset: 0; z-index: 999998;\n background: ${v}; pointer-events: none;\n `;document.body.appendChild(k);const y=i.placement||"bottom";C=document.createElement("div"),C.className="aegis-in-app-coachmark-tip",C.setAttribute("data-campaign-id",t.id),C.style.cssText=`\n position: fixed; z-index: 999999;\n background: ${p}; color: ${h};\n padding: 12px 14px; border-radius: 12px;\n max-width: 260px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.25);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.2s ease;\n `;const b=document.createElement("div");b.textContent=i.title,b.style.cssText="font-weight: 700; font-size: 13px; margin-bottom: 4px;",C.appendChild(b);const w=document.createElement("div");w.textContent=i.body,w.style.cssText="font-size: 12.5px; line-height: 1.4; opacity: 0.9;",C.appendChild(w);const _=document.createElement("div");if(_.style.cssText="display: flex; align-items: center; justify-content: space-between; margin-top: 10px; gap: 8px;",l){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px;",c.forEach((n,i)=>{const o=document.createElement("span");o.style.cssText=`\n width: 5px; height: 5px; border-radius: 999px;\n background: ${h}; opacity: ${i===e?"0.95":"0.3"};\n `,t.appendChild(o)}),_.appendChild(t)}else _.appendChild(document.createElement("span"));const $=document.createElement("div");if($.style.cssText="display: flex; gap: 6px;",e>0){const t=document.createElement("button");t.textContent="Back",t.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",t.addEventListener("click",()=>T(e-1)),$.appendChild(t)}if(d&&e<c.length-1){const t=document.createElement("button");t.textContent="Skip",t.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",t.addEventListener("click",()=>S({skipped:!0,lastStepIdx:e})),$.appendChild(t)}const I=document.createElement("button"),z=e===c.length-1;I.textContent=i.cta_text||(z?"Done":"Next"),I.style.cssText=`\n background: ${h}; color: ${p};\n border: none; padding: 6px 12px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer;\n `,I.addEventListener("click",()=>{z?S({skipped:!1,lastStepIdx:e}):T(e+1)}),$.appendChild(I),_.appendChild($),C.appendChild(_),document.body.appendChild(C);const A=C.getBoundingClientRect();let L,M;x?(L=x.bottom+12,M=x.left,"top"===y?L=x.top-A.height-12:"left"===y?(L=x.top,M=x.left-A.width-12):"right"===y&&(L=x.top,M=x.right+12)):(L=(window.innerHeight-A.height)/2,M=(window.innerWidth-A.width)/2),L=Math.max(8,Math.min(window.innerHeight-A.height-8,L)),M=Math.max(8,Math.min(window.innerWidth-A.width-8,M)),C.style.top=`${L}px`,C.style.left=`${M}px`};T(w),window.aegisResetTour=e=>function(e){try{"undefined"!=typeof localStorage&&localStorage.removeItem(Z+e)}catch{}}(e)}const ne=["linear-gradient(160deg, #6366f1, #a855f7)","linear-gradient(160deg, #ec4899, #f43f5e)","linear-gradient(160deg, #0ea5e9, #22d3ee)","linear-gradient(160deg, #f59e0b, #ef4444)","linear-gradient(160deg, #10b981, #14b8a6)","linear-gradient(160deg, #8b5cf6, #6366f1)"],ie=e=>ne[e%ne.length],oe=e=>`conic-gradient(from 0deg, ${e}, color-mix(in srgb, ${e} 50%, #ffffff), ${e}, color-mix(in srgb, ${e} 72%, #000000), ${e})`,se=e=>`linear-gradient(110deg, ${e}, color-mix(in srgb, ${e} 50%, #ffffff), ${e}, color-mix(in srgb, ${e} 72%, #000000), ${e})`;function ae(e){const t=e.campaign.interactive_config||{},n=function(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];return t&&Array.isArray(t.frames)?e.slice(0,12).map(e=>({...e,frames:(e.frames||[]).slice(0,20)})).filter(e=>e.frames.length>0):[{frames:e.slice(0,20)}]}(t.stories);if(0===n.length)return e.log("stories rendered with zero groups — skipping","warn"),null;const i=e.sanitizeColor(e.campaign.background_color||"#4169e1"),o=t.stories_ring_style||"brand";let s,a;if("instagram"===o)s="conic-gradient(from 0deg, #feda75, #fa7e1e, #d62976, #962fbf, #4f5bd5, #feda75)",a="linear-gradient(110deg, #feda75, #fa7e1e, #d62976, #962fbf, #4f5bd5, #feda75)";else if("custom"===o){const n=e.sanitizeColor(t.stories_ring_color||i);s=oe(n),a=se(n)}else s=oe(i),a=se(i);return{groups:n,thumbnailShape:"rectangle"===t.stories_thumbnail_shape?"rectangle":"circle",ringBg:s,ringBgLinear:a,branded:"branded"===t.surface_style,brand:i,autoplay:!1!==t.stories_autoplay,loop:!0===t.stories_loop,showProgress:!1!==t.stories_show_progress,defaultDuration:Number(t.stories_default_duration_ms)||5e3,reduceMotion:"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function re(e,t){const n=ae(e);return!!n&&(e.addAnimationStyles(),de(),function(e,t,n){const{campaign:i}=e,o=!n,s=t.branded?"#ffffff":"#334155",a=document.createElement("div");a.className="aegis-in-app-stories-tray",a.setAttribute("data-campaign-id",i.id);const r=t.branded?t.brand:o?"rgba(255,255,255,0.96)":"transparent";if(a.style.cssText=o?`\n position: fixed; left: 0; right: 0; bottom: 0; z-index: 99998;\n display: flex; gap: 16px; align-items: flex-start; overflow-x: auto;\n padding: 14px 18px 16px 20px; scroll-padding-left: 20px;\n background: ${r}; backdrop-filter: blur(8px);\n box-shadow: 0 -4px 16px rgba(0,0,0,0.08); scrollbar-width: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `:`\n display: flex; gap: 16px; align-items: flex-start; overflow-x: auto;\n padding: 12px 18px 12px 18px; scroll-padding-left: 18px;\n background: ${r}; ${t.branded?"border-radius: 16px;":""}\n scrollbar-width: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,t.groups.forEach((n,i)=>a.appendChild(function(e,t,n,i,o){var s;const a="rectangle"===t.thumbnailShape,r=n.title||(null==(s=n.frames[0])?void 0:s.title)||`Story ${i+1}`,c=function(e){if(e.cover_image_url)return{img:e.cover_image_url,index:0};const t=e.frames.findIndex(e=>e.image_url);return t>=0?{img:e.frames[t].image_url||null,index:t}:{img:null,index:0}}(n),d=c.img?e.sanitizeUrl(c.img):null,l=ie(i),p=document.createElement("button");if(p.type="button",p.setAttribute("aria-label",`Open ${r} (${n.frames.length} frames)`),p.style.cssText="flex: 0 0 auto; display: flex; flex-direction: column; align-items: center; gap: 5px; border: none; background: transparent; cursor: pointer; padding: 0;",a){const n=document.createElement("div");n.style.cssText=`\n width: 92px; height: 124px; border-radius: 14px; padding: 2.5px;\n background: ${t.ringBgLinear}; background-size: 220% 100%; background-position: 0% 50%;\n ${t.reduceMotion?"":"animation: aegisStoryShimmer 3s ease-in-out infinite;"}\n `;const o=document.createElement("div");if(o.style.cssText=`\n position: relative; width: 100%; height: 100%; border-radius: 12px; overflow: hidden;\n background: ${l}; display: flex; align-items: flex-end;\n `,d){const e=document.createElement("img");e.src=d,e.alt="",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",o.appendChild(e)}const s=document.createElement("div");s.style.cssText="position: absolute; inset: 0; background: linear-gradient(to top, rgba(0,0,0,0.6), rgba(0,0,0,0) 55%);",o.appendChild(s);const a=document.createElement("div");return a.textContent=r,a.style.cssText="position: relative; z-index: 1; padding: 7px 8px; color: #fff; font-size: 11px; font-weight: 700; line-height: 1.2; text-shadow: 0 1px 4px rgba(0,0,0,0.5);",o.appendChild(a),n.appendChild(o),p.appendChild(n),p.addEventListener("click",()=>ce(e,t,i,0)),p}const h=document.createElement("div");h.style.cssText="position: relative; width: 66px; height: 66px;";const u=document.createElement("div");u.style.cssText=`\n position: absolute; inset: 0; border-radius: 50%; background: ${t.ringBg};\n ${t.reduceMotion?"":"animation: aegisStoryRing 4s linear infinite;"}\n `,h.appendChild(u);const g=document.createElement("div");g.style.cssText=`position: absolute; inset: 3px; border-radius: 50%; background: ${t.branded?t.brand:"#fff"};`,h.appendChild(g);const m=document.createElement("div");if(m.style.cssText=`position: absolute; inset: 5px; border-radius: 50%; overflow: hidden; background: ${l}; display: flex; align-items: center; justify-content: center;`,d){const e=document.createElement("img");e.src=d,e.alt="",e.style.cssText="width: 100%; height: 100%; object-fit: cover;",m.appendChild(e)}else{const e=document.createElement("span");e.textContent=r.trim().charAt(0).toUpperCase(),e.style.cssText="color: #fff; font-weight: 800; font-size: 22px; text-shadow: 0 1px 4px rgba(0,0,0,0.25);",m.appendChild(e)}h.appendChild(m),p.appendChild(h);const f=document.createElement("span");return f.textContent=r,f.style.cssText=`max-width: 70px; font-size: 11px; color: ${o}; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`,p.appendChild(f),p.addEventListener("click",()=>ce(e,t,i,0)),p}(e,t,n,i,s))),o){const n=document.createElement("button");n.type="button",n.textContent="✕",n.setAttribute("aria-label","Dismiss stories"),n.style.cssText=`\n flex: 0 0 auto; align-self: center; margin-left: auto;\n width: 28px; height: 28px; border: none; border-radius: 999px;\n background: ${t.branded?"rgba(255,255,255,0.18)":"rgba(0,0,0,0.06)"};\n color: ${t.branded?"#fff":"#475569"}; font-size: 14px; cursor: pointer;\n `,n.addEventListener("click",()=>{e.trackEvent(i.id,"dismissed"),a.remove()}),a.appendChild(n)}n?n.appendChild(a):document.body.appendChild(a)}(e,n,t),!0)}function ce(e,t,n,i=0){const{campaign:o,trackEvent:s,sanitizeUrl:a,log:r}=e,{loop:c,autoplay:d,showProgress:l,defaultDuration:p,reduceMotion:h}=t,u=t.groups;if(0===u.length)return;let g=Math.max(0,Math.min(n,u.length-1)),m=u[g].frames;r(`stories viewer open @ group ${g}`);const f=document.createElement("div");f.className="aegis-in-app-stories-overlay",f.setAttribute("data-campaign-id",o.id),f.setAttribute("role","dialog"),f.setAttribute("aria-label",o.title||"Stories"),f.style.cssText='\n position: fixed; inset: 0; z-index: 100000; background: #000;\n display: flex; align-items: center; justify-content: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.25s ease;\n ';const x=document.createElement("div");x.style.cssText="position: relative; width: 100%; height: 100%; max-width: 440px; max-height: 100vh; background: #111; overflow: hidden;",f.appendChild(x);const y=document.createElement("div");y.style.cssText="position: absolute; inset: 0;",x.appendChild(y);const b=document.createElement("div");b.style.cssText="position: absolute; top: 0; left: 0; right: 0; z-index: 4; display: flex; gap: 4px; padding: 10px 10px 0;",x.appendChild(b);let v=[];const w=()=>{b.replaceChildren(),v=[],l&&m.forEach(()=>{const e=document.createElement("div");e.style.cssText="flex: 1; height: 2.5px; border-radius: 999px; background: rgba(255,255,255,0.32); overflow: hidden;";const t=document.createElement("div");t.style.cssText="width: 0%; height: 100%; background: #fff; border-radius: 999px;",e.appendChild(t),b.appendChild(e),v.push(t)})},_=document.createElement("button");_.type="button",_.textContent="✕",_.setAttribute("aria-label","Close"),_.style.cssText="position: absolute; top: 12px; right: 10px; z-index: 5; width: 34px; height: 34px; border: none; border-radius: 999px; background: rgba(0,0,0,0.32); color: #fff; font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center; line-height: 1;",x.appendChild(_);let C=i,k=null,E=null,S=0,T=0,$=!1,I=null;const z=new Set,A=()=>{k&&(clearTimeout(k),k=null),null!==E&&(cancelAnimationFrame(E),E=null)};let L=!1;const M=n=>{var i;A(),document.removeEventListener("keydown",j),"dismissed"===n?s(o.id,"dismissed"):L||(L=!0,null==(i=e.submitResponse)||i.call(e,"story_complete",{groups:t.groups.length})),f.remove()},R=e=>{var t;const n=Number(null==(t=m[e])?void 0:t.duration_ms);return n>=1e3?n:p},P=()=>{if(!l||$)return;const e=R(C),t=T+(Date.now()-S),n=Math.max(0,Math.min(100,t/e*100));v[C]&&(v[C].style.width=`${n}%`),n<100&&(E=requestAnimationFrame(P))},D=()=>{if(!d)return;const e=R(C)-T;S=Date.now(),k=setTimeout(()=>O(1),Math.max(0,e)),l&&!h?E=requestAnimationFrame(P):l&&v[C]&&(v[C].style.width="0%")},N=n=>{var i;A(),T=0,$=!1,C=n,i=n,l&&v.forEach((e,t)=>{e.style.width=t<i?"100%":"0%"}),(n=>{var i;const r=m[n];y.replaceChildren(),I=null;const c=r.video_url?a(r.video_url):null,d=r.image_url?a(r.image_url):null;if(c){const e=document.createElement("video");e.src=c,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",y.appendChild(e),I=e,null==(i=e.play)||i.call(e).catch(()=>{})}else if(d){const e=document.createElement("img");e.src=d,e.alt=r.title||"",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",y.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`position: absolute; inset: 0; background: ${t.branded?t.brand:ie(n)};`,y.appendChild(e)}const l=document.createElement("div");l.style.cssText="position: absolute; inset: 0; pointer-events: none; background: linear-gradient(to top, rgba(0,0,0,0.72) 0%, rgba(0,0,0,0.18) 38%, rgba(0,0,0,0) 60%);",y.appendChild(l);const p=document.createElement("div");if(p.style.cssText="position: absolute; left: 0; right: 0; bottom: 0; z-index: 3; padding: 20px 18px 30px; color: #fff; text-align: left;",r.title){const e=document.createElement("div");e.textContent=r.title,e.style.cssText="font-family: 'Inter Tight', Inter, system-ui, sans-serif; font-size: 21px; font-weight: 800; letter-spacing: -0.01em; line-height: 1.2; margin-bottom: 6px; text-shadow: 0 1px 8px rgba(0,0,0,0.4);",p.appendChild(e)}if(r.body){const e=document.createElement("div");e.textContent=r.body,e.style.cssText="font-size: 14px; line-height: 1.45; opacity: 0.92; text-shadow: 0 1px 6px rgba(0,0,0,0.4);",p.appendChild(e)}const h=r.cta_url?a(r.cta_url):null,u=r.cta_text||(h?"Learn more":"");if(u){const t=document.createElement("button");t.type="button",t.className="aegis-cta",t.textContent=u,t.style.cssText="margin-top: 14px; padding: 11px 22px; border: none; border-radius: 999px; background: #fff; color: #0f172a; font-size: 14px; font-weight: 700; cursor: pointer;",t.addEventListener("pointerdown",e=>e.stopPropagation()),t.addEventListener("click",t=>{t.stopPropagation(),s(o.id,"clicked",{stepId:`g${g}_f${n}`}),h&&(A(),e.navigate?e.navigate(h,`g${g}_f${n}`):window.location.href=h)}),p.appendChild(t)}y.appendChild(p);const f=`${g}_${n}`;z.has(f)||(z.add(f),s(o.id,"impression",{stepId:`g${g}_f${n}`}))})(n),D()},F=(e,t)=>{g=e,m=u[e].frames,w(),N(Math.max(0,Math.min(t,m.length-1)))};function O(e){const t=C+e;t<0?g>0?F(g-1,u[g-1].frames.length-1):N(0):t>=m.length?g+1<u.length?F(g+1,0):c?(z.clear(),F(0,0)):M("completed"):N(t)}const B=()=>{var e;$&&($=!1,null==(e=null==I?void 0:I.play)||e.call(I).catch(()=>{}),D())};let U=0,W=0;function j(e){"Escape"===e.key?M("dismissed"):"ArrowRight"===e.key?O(1):"ArrowLeft"===e.key&&O(-1)}x.addEventListener("pointerdown",e=>{var t;U=Date.now(),W=e.clientX,$||($=!0,k&&(clearTimeout(k),k=null),null!==E&&(cancelAnimationFrame(E),E=null),T+=Date.now()-S,null==(t=null==I?void 0:I.pause)||t.call(I))}),x.addEventListener("pointerup",()=>{if(Date.now()-U<=220){const e=x.getBoundingClientRect();O(W-e.left<e.width/3?-1:1)}else B()}),x.addEventListener("pointercancel",B),x.addEventListener("pointerleave",B),_.addEventListener("pointerdown",e=>e.stopPropagation()),_.addEventListener("click",e=>{e.stopPropagation(),M("dismissed")}),document.addEventListener("keydown",j),w(),document.body.appendChild(f),N(i)}function de(){if("undefined"==typeof document)return;if(document.getElementById("aegis-stories-styles"))return;const e=document.createElement("style");e.id="aegis-stories-styles",e.textContent="\n @keyframes aegisStoryRing { to { transform: rotate(360deg); } }\n @keyframes aegisStoryShimmer { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }\n .aegis-in-app-stories-tray::-webkit-scrollbar { display: none; }\n ",document.head.appendChild(e)}const le=(e,t)=>{const n=Number(e);return Number.isFinite(n)?n:t},pe=(e,t="")=>"string"==typeof e?e:t,he=e=>Array.isArray(e)?e:[];function ue(e,t,n=360){const{campaign:i,trackEvent:o,addAnimationStyles:s}=e;s(),function(){if("undefined"==typeof document||document.getElementById("aegis-game-styles"))return;if("undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;const e=document.createElement("style");e.id="aegis-game-styles",e.textContent="@keyframes aegisBoxRattle{0%,100%{transform:scale(1) rotate(0)}20%{transform:scale(1.05) rotate(-4deg)}40%{transform:scale(1.05) rotate(4deg)}60%{transform:scale(1.06) rotate(-3deg)}80%{transform:scale(1.06) rotate(3deg)}}@keyframes aegisStampIn{0%{transform:scale(2.4) rotate(-20deg);opacity:0}55%{transform:scale(0.82) rotate(7deg);opacity:1}100%{transform:scale(1) rotate(-6deg);opacity:1}}@keyframes aegisBadgePop{0%{transform:scale(0) rotate(-12deg);opacity:0}70%{transform:scale(1.18) rotate(4deg);opacity:1}100%{transform:scale(1) rotate(0);opacity:1}}",document.head.appendChild(e)}();const a=function(e){return e.sanitizeColor(e.campaign.background_color||"#4169e1")}(e),r="branded"===(i.interactive_config||{}).surface_style,c=r?a:"#ffffff",d=r?"#ffffff":"#0f172a",l=document.createElement("div");l.className=t,l.setAttribute("data-campaign-id",i.id),l.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(15,23,42,0.55);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:16px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;animation:aegisFadeIn 0.25s ease;';const p=document.createElement("div");p.style.cssText=`position:relative;width:100%;max-width:${n}px;max-height:88vh;overflow-y:auto;background:${c};color:${d};border-radius:20px;padding:24px 20px 20px;box-shadow:0 16px 48px rgba(0,0,0,0.22);animation:aegisScaleIn 0.3s ease;text-align:center;`;let h=!1;const u=(e=!1)=>{h||(h=!0,e&&o(i.id,"dismissed"),l.style.animation="aegisFadeOut 0.2s ease",setTimeout(()=>l.remove(),180))},g=document.createElement("button");if(g.type="button",g.textContent="✕",g.setAttribute("aria-label","Close"),g.style.cssText=`position:absolute;top:10px;right:10px;width:30px;height:30px;border:none;border-radius:999px;background:${r?"rgba(255,255,255,0.18)":"rgba(0,0,0,0.05)"};color:${r?"#fff":"#475569"};font-size:15px;cursor:pointer;z-index:1;`,g.addEventListener("click",()=>u(!0)),p.appendChild(g),l.addEventListener("click",e=>{e.target===l&&u(!0)}),i.title){const e=document.createElement("div");e.textContent=i.title,e.style.cssText="font-family:'Inter Tight',Inter,system-ui,sans-serif;font-size:18px;font-weight:800;letter-spacing:-0.01em;margin:2px 24px 4px;line-height:1.25;",p.appendChild(e)}if(i.body){const e=document.createElement("div");e.textContent=i.body,e.style.cssText="font-size:13px;opacity:0.72;margin:0 6px 12px;line-height:1.4;",p.appendChild(e)}const m=document.createElement("div");p.appendChild(m),l.appendChild(p),document.body.appendChild(l);return{overlay:l,card:p,content:m,accent:a,branded:r,dismiss:u,ctaButton:(t,n)=>{if(!t)return null;const s=document.createElement("button");return s.type="button",s.className="aegis-cta",s.textContent=t,s.style.cssText=`margin-top:16px;width:100%;padding:12px 20px;border:none;border-radius:999px;background:${r?"#fff":a};color:${r?a:"#fff"};font-size:14px;font-weight:700;cursor:pointer;`,s.addEventListener("click",()=>{o(i.id,"clicked"),n&&n();const t=pe(i.action_url);t&&(e.navigate?e.navigate(t,"cta"):window.location.href=t)}),p.appendChild(s),s}}}function ge(e,t,n){const i=document.createElement(e);return t&&(i.style.cssText=t),null!=n&&(i.textContent=n),i}function me(e,t,n=8){const i=ge("div",`height:${n}px;border-radius:999px;background:rgba(148,163,184,0.25);overflow:hidden;margin:10px 0`);return i.appendChild(ge("div",`height:100%;width:${Math.max(0,Math.min(100,t))}%;background:${e};border-radius:999px;transition:width .5s ease`)),i}let fe=null;function xe(){try{if("undefined"==typeof window)return;const e=window.AudioContext||window.webkitAudioContext;if(!e)return;fe||(fe=new e);const t=fe;"suspended"===t.state&&t.resume();const n=t.currentTime,i=t.createOscillator(),o=t.createGain();i.type="triangle",i.frequency.setValueAtTime(190,n),i.frequency.exponentialRampToValueAtTime(68,n+.12),o.gain.setValueAtTime(1e-4,n),o.gain.exponentialRampToValueAtTime(.22,n+.006),o.gain.exponentialRampToValueAtTime(1e-4,n+.16),i.connect(o),o.connect(t.destination),i.start(n),i.stop(n+.18)}catch{}}const ye={streak:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-streak"),i=le(t.streak_count,5),o=le(t.streak_goal,i+1),s=pe(t.streak_reward_text,"Come back tomorrow to keep it going."),a=["M","T","W","T","F","S","S"];n.content.appendChild(ge("div","font-size:44px;line-height:1","🔥")),n.content.appendChild(ge("div","font-size:22px;font-weight:800;margin:4px 0 2px",`${i}-day streak!`));const r=ge("div","display:flex;justify-content:center;gap:8px;margin:12px 0");for(let d=0;d<7;d++){const e=ge("div","display:inline-flex;flex-direction:column;align-items:center;gap:3px;font-size:11px;opacity:0.8");e.appendChild(ge("span","",a[d])),e.appendChild(ge("span","font-size:16px",d<i%7||i>=7&&d<7?"✅":d===i%7?"🔥":"⚪")),r.appendChild(e)}n.content.appendChild(r);const c=ge("div","font-size:13px;opacity:0.8");c.appendChild(document.createTextNode(s+" ")),c.appendChild(ge("b","",`Day ${o}`)),c.appendChild(document.createTextNode(" unlocks a reward.")),n.content.appendChild(c),n.ctaButton(pe(t.streak_cta_text,"Keep my streak"),()=>{var t,o,s;null==(t=e.haptic)||t.call(e,20),null==(o=e.playReaction)||o.call(e,n.card,"affirm"),null==(s=e.submitResponse)||s.call(e,"streak",{streak_count:i})})},milestone:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-milestone"),i=pe(t.milestone_unit,""),o=le(t.milestone_current,1200),s=le(t.milestone_target,2e3),a=he(t.milestone_steps),r=s>0?o/s*100:0;if(n.content.appendChild(ge("div","font-size:13px;opacity:0.8;margin-bottom:2px",`${i}${o} of ${i}${s}`)),n.content.appendChild(me(n.accent,r)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${i}${Math.max(0,s-o)} to go`)),a.length){const e=ge("div","display:flex;justify-content:space-between;margin-top:6px;font-size:10px;opacity:0.7");a.forEach(t=>{const n=ge("span","display:flex;flex-direction:column;text-align:center;max-width:64px");n.appendChild(ge("span","",`${i}${le(t.value,0)}`)),n.appendChild(ge("span","",pe(t.reward))),e.appendChild(n)}),n.content.appendChild(e)}n.ctaButton(pe(t.milestone_cta_text,"Shop now"))},challenge:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-challenge"),i=he(t.challenge_tasks),o=i.filter(e=>e.done).length,s=i.length?o/i.length*100:0;pe(t.challenge_deadline_text)&&n.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:8px",pe(t.challenge_deadline_text))),i.forEach(e=>{const t=ge("div","display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid rgba(148,163,184,0.18);font-size:13px;text-align:left");t.appendChild(ge("span","",e.done?"☑":"☐")),t.appendChild(ge("span","flex:1;"+(e.done?"opacity:0.6":""),pe(e.label))),e.points&&t.appendChild(ge("span","opacity:0.7;font-size:12px",`+${le(e.points,0)}`)),n.content.appendChild(t)}),n.content.appendChild(me(n.accent,s)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${o} of ${i.length} · ${pe(t.challenge_bonus_text,"finish all to earn a bonus")}`)),n.ctaButton(pe(t.challenge_cta_text,"Continue"))},achievements:function(e){var t,n;const i=e.campaign.interactive_config||{},o=ue(e,"aegis-in-app-achievements",380),s=he(i.achievements_items),a=s.filter(e=>e.unlocked).length,r="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,c=ge("div","display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:6px 0 10px");let d=0;s.forEach(e=>{const t=ge("div",`display:flex;flex-direction:column;align-items:center;gap:4px;padding:10px 6px;border-radius:12px;background:${e.unlocked?o.accent+"1f":"rgba(148,163,184,0.12)"};${e.unlocked?"":"opacity:0.55"}`),n=ge("span","font-size:24px;display:inline-block",e.unlocked?pe(e.icon,"🏅"):"🔒");t.appendChild(n),t.appendChild(ge("span","font-size:10.5px;line-height:1.15",pe(e.label))),e.unlocked&&!r&&(n.style.animation=`aegisBadgePop 0.5s cubic-bezier(0.2,1.4,0.4,1) ${.08*d}s both`,d++),c.appendChild(t)}),o.content.appendChild(c),o.content.appendChild(ge("div","font-size:13px;font-weight:600",`${a} of ${s.length} unlocked`)),pe(i.achievements_next_text)&&o.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-top:2px",pe(i.achievements_next_text))),a>0&&!r&&(null==(t=e.haptic)||t.call(e,12),null==(n=e.playReaction)||n.call(e,o.card,"affirm")),o.ctaButton(pe(e.campaign.button_text,""))},leaderboard:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-leaderboard"),i=he(t.leaderboard_rows),o=["🥇","🥈","🥉"];pe(t.leaderboard_period_text)&&n.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:6px",pe(t.leaderboard_period_text))),i.forEach((e,t)=>{const i=ge("div",`display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:10px;${e.you?`background:${n.accent}14;font-weight:700`:""};font-size:13px;text-align:left`);i.appendChild(ge("span","width:22px",t<3?o[t]:String(t+1))),i.appendChild(ge("span","flex:1",pe(e.name)+(e.you?" (You)":""))),i.appendChild(ge("span","",le(e.score,0).toLocaleString())),n.content.appendChild(i)}),pe(t.leaderboard_gap_text)&&n.content.appendChild(ge("div","font-size:12.5px;opacity:0.8;margin-top:10px",pe(t.leaderboard_gap_text))),n.ctaButton(pe(e.campaign.button_text,""))},check_in:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-checkin",380),i=he(t.checkin_days),o=ge("div","display:flex;gap:8px;overflow-x:auto;padding:6px 2px 10px;scrollbar-width:none");i.forEach(e=>{const t="today"===e.state,i=ge("div",`flex:0 0 auto;width:60px;display:flex;flex-direction:column;align-items:center;gap:3px;padding:8px 4px;border-radius:12px;background:${t?n.accent+"1a":"rgba(148,163,184,0.12)"};border:1.5px solid ${t?n.accent:"transparent"}`);i.appendChild(ge("span","font-size:11px;opacity:0.7",pe(e.label))),i.appendChild(ge("span","font-size:18px","claimed"===e.state?"✅":t?"🎁":"🔒")),i.appendChild(ge("span","font-size:11px;font-weight:700",pe(e.reward))),o.appendChild(i)}),n.content.appendChild(o);const s=i.find(e=>"today"===e.state);n.ctaButton(pe(t.checkin_cta_text,s?`Claim ${pe(s.label)} · ${pe(s.reward)}`:"Claim"),()=>{var i,o,a;null==(i=e.haptic)||i.call(e,[0,20,15,30]),null==(o=e.playReaction)||o.call(e,n.card,"celebrate","gift.json"),null==(a=e.submitResponse)||a.call(e,"check_in",{day:pe(null==s?void 0:s.label),reset:pe(t.checkin_reset)||"daily"})})},stamp_card:function(e){var t,n,i;const o=e.campaign.interactive_config||{},s=ue(e,"aegis-in-app-stamp",380),a=le(o.stamp_total,9),r=Math.min(a,le(o.stamp_filled,1)),c="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,d=pe(o.stamp_logo_url)||pe(e.campaign.image_url),l=d?e.sanitizeUrl(d):null,p=he(o.stamp_rewards),h=new Map,u=new Map;p.length?p.forEach(e=>{"number"==typeof e.at&&e.at>=1&&e.at<=a&&(h.set(e.at,pe(e.label)||pe(e.prize_value)||"Reward"),u.set(e.at,pe(e.icon)||"🎁"))}):(h.set(a,pe(null==(t=o.stamp_reward)?void 0:t.label)||pe(o.stamp_reward_text)||"Reward"),u.set(a,"🎁"));const g="#10b981",m=Math.min(a,3),f=document.createElement("div");f.style.cssText=`display:grid;grid-template-columns:repeat(${m},1fr);gap:16px;margin:14px auto 16px;max-width:${110*m}px`;const x=[];let y=0;for(let C=0;C<a;C++){const t=C+1,n=h.has(t),i=C<r,o=document.createElement("div");if(o.title=n?`Reward: ${h.get(t)}`:"",o.style.cssText="position:relative;width:100%;aspect-ratio:1;border-radius:50%;display:flex;align-items:center;justify-content:center;overflow:visible;"+(i?`border:2.5px solid ${g};background:${g}14;${n?`box-shadow:0 0 0 3px ${g}55;`:""}`:`border:2.5px dashed ${n?g+"aa":"rgba(148,163,184,0.5)"};background:${n?g+"10":"transparent"};`),i){const t=ge("div","width:92%;height:92%;border-radius:50%;overflow:hidden;display:flex;align-items:center;justify-content:center;");if(t.appendChild(ge("span",`font-size:32px;font-weight:900;color:${g};transform:rotate(-6deg)`,"✓")),t.style.transform="rotate(-6deg) scale(1.02)",!c){const n=.1*Math.min(y,9);t.style.opacity="0",t.style.animation=`aegisStampIn 0.45s cubic-bezier(0.2,1.3,0.4,1) ${n}s both`;const i=y;window.setTimeout(()=>{var t;xe(),null==(t=e.haptic)||t.call(e,14)},1e3*n+(0===i?80:0))}l&&x.push(t),y++,o.appendChild(t)}else n&&o.appendChild(ge("span","font-size:30px",u.get(t)||"🎁"));n&&i&&o.appendChild(ge("span","position:absolute;top:-3px;right:-3px;font-size:17px;line-height:1;filter:drop-shadow(0 1px 1px rgba(0,0,0,0.25))",u.get(t)||"🎁")),f.appendChild(o)}if(s.content.appendChild(f),l&&x.length){const e=new Image;e.onload=()=>{const t=e.naturalWidth||96,n=e.naturalHeight||96,i=Math.min(1,160/Math.max(t,n)),o=Math.max(1,Math.round(t*i)),s=Math.max(1,Math.round(n*i)),a=document.createElement("canvas");a.width=o,a.height=s;const r=a.getContext("2d");if(!r)return;r.drawImage(e,0,0,o,s);let c=!1;try{c=[[0,0],[o-1,0],[0,s-1],[o-1,s-1]].some(([e,t])=>r.getImageData(e,t,1,1).data[3]<16)}catch{c=/transparent/i.test(l||"")}c&&(r.globalCompositeOperation="source-in",r.fillStyle=g,r.fillRect(0,0,o,s)),x.forEach(e=>{const t=document.createElement("canvas");t.width=o,t.height=s,t.style.cssText="width:100%;height:100%;object-fit:contain;";const n=t.getContext("2d");n&&n.drawImage(a,0,0),e.replaceChildren(t)})},e.onerror=()=>{},e.src=l}const b=[...h.keys()].filter(e=>e>r).sort((e,t)=>e-t)[0],v=b?`${b-r} more → ${h.get(b)}`:"Card complete!",w=ge("div","font-size:13px;font-weight:600;margin-top:2px");w.appendChild(me(g,r/a*100)),w.appendChild(ge("div","",`${r} of ${a}`)),w.appendChild(ge("div","font-weight:400;opacity:0.82;margin-top:1px",pe(o.stamp_reward_text)||v)),s.content.appendChild(w),s.ctaButton(pe(o.stamp_cta_text,"Order & earn"),()=>{var t;null==(t=e.haptic)||t.call(e,12)});const _=o.stamp_just_unlocked;if(_&&"object"==typeof _){const t=ge("div",`margin-top:12px;padding:11px 12px;border-radius:14px;background:${g}14;border:1.5px solid ${g}55;text-align:center`);t.appendChild(ge("div","font-size:24px",pe(_.icon)||"🎁")),t.appendChild(ge("div",`font-size:13.5px;font-weight:800;color:${g}`,`Unlocked: ${pe(_.label)||"Reward"}`)),t.appendChild(ge("div","font-size:11.5px;opacity:0.8;margin-top:1px",_.coupon_code?`Coupon ${String(_.coupon_code)} added to your account`:"Added to your account")),s.content.appendChild(t),c||(null==(n=e.haptic)||n.call(e,[0,30,20,40]),null==(i=e.playReaction)||i.call(e,s.card,"celebrate","gift.json"))}},mystery_box:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-mystery"),i=he(t.mystery_boxes),o=i.length?i:[{prize:"10% OFF"},{prize:"Free shipping"},{prize:"50 points"}];if(pe(t.mystery_subtitle)){const e=document.createElement("div");e.textContent=pe(t.mystery_subtitle),e.style.cssText="font-size:12.5px;opacity:0.75;margin-bottom:8px",n.content.appendChild(e)}const s=document.createElement("div");s.style.cssText="display:flex;gap:12px;justify-content:center;margin:8px 0 4px";let a=!1;o.forEach((t,i)=>{const o=document.createElement("button");o.type="button",o.style.cssText=`flex:1;max-width:96px;aspect-ratio:3/4;border:none;border-radius:14px;background:${n.accent}1a;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;cursor:pointer;font-size:13px;font-weight:700;color:#0f172a;transition:transform .15s`,o.appendChild(ge("span","font-size:30px","🎁")),o.appendChild(ge("span","opacity:0.7",`Box ${String.fromCharCode(65+i)}`)),o.addEventListener("click",()=>{var r,c;if(a)return;a=!0,null==(r=e.haptic)||r.call(e,12),Array.from(s.children).forEach(e=>{e!==o&&(e.style.opacity="0.4",e.style.transform="scale(0.94)")}),o.style.animation="aegisBoxRattle 0.45s ease-in-out";const d=null==(c=e.submitResponse)?void 0:c.call(e,"mystery_box",{box_index:i,prize:pe(t.prize)});window.setTimeout(()=>{(async()=>{var i,s,a,r;o.style.animation="";let c=!0,l=pe(t.prize,"You won!");try{const e=await d,t=e?e.prize:null;t&&(c=!1!==t.win,t.prize_label&&(l=String(t.prize_label)))}catch{}o.style.background=c?`${n.accent}`:"rgba(148,163,184,0.22)",o.style.color=c?"#fff":"#475569",o.style.transform="scale(1.08)",o.replaceChildren(),o.appendChild(ge("span","font-size:28px",c?"🎉":"🙈")),o.appendChild(ge("span","",c?l:"Not this time")),c?(null==(i=e.haptic)||i.call(e,[0,30,20,40]),null==(s=e.playReaction)||s.call(e,n.card,"celebrate","gift.json")):(null==(a=e.haptic)||a.call(e,15),null==(r=e.playReaction)||r.call(e,n.card,"empathize"))})()},520)}),s.appendChild(o)}),n.content.appendChild(s),n.ctaButton(pe(t.mystery_cta_text,""))},tier_ladder:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-tier"),i=he(t.tiers),o=i.length?i:[{name:"Bronze",icon:"🥉"},{name:"Silver",icon:"🥈"},{name:"Gold",icon:"🥇"}],s=Math.min(o.length-1,le(t.tier_current_index,1)),a=le(t.tier_current_points,640),r=le(t.tier_next_points,1e3),c=r>0?a/r*100:0,d=he(t.tier_perks),l=o[Math.min(o.length-1,s+1)],p=ge("div","display:flex;align-items:flex-start;justify-content:center;margin:6px 0 12px");if(o.forEach((e,t)=>{t>0&&p.appendChild(ge("span","flex:1;height:2px;background:rgba(148,163,184,0.4);margin:12px 4px 0;align-self:flex-start"));const i=ge("div","display:flex;flex-direction:column;align-items:center;gap:3px;"+(t===s?"font-weight:800":"opacity:0.6"));i.appendChild(ge("span","font-size:24px",pe(e.icon,"◆"))),i.appendChild(ge("span","font-size:11px",pe(e.name))),t===s&&i.appendChild(ge("span",`font-size:9px;color:${n.accent}`,"▲ you")),p.appendChild(i)}),n.content.appendChild(p),n.content.appendChild(me(n.accent,c)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${Math.max(0,r-a)} pts to ${pe(null==l?void 0:l.name,"next tier")}`)),d.length){const e=ge("div","text-align:left;margin-top:10px;font-size:12.5px;opacity:0.85");e.appendChild(ge("div","",`${pe(null==l?void 0:l.name,"Next")} unlocks:`)),d.forEach(t=>e.appendChild(ge("div","",`• ${pe(t)}`))),n.content.appendChild(e)}n.ctaButton(pe(t.tier_cta_text,""))},lucky_draw:function(e){var t;const n=e.campaign.interactive_config||{},i=ue(e,"aegis-in-app-draw"),o=le(n.draw_entries,6),s=he(n.draw_actions);pe(n.draw_deadline_text)&&i.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:6px",pe(n.draw_deadline_text))),i.content.appendChild(ge("div","font-size:30px","🎟️")),i.content.appendChild(ge("div","font-size:15px;font-weight:800;margin:2px 0 10px",`${o} entries`)),i.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-bottom:4px;text-align:left","Earn more entries:")),s.forEach(e=>{const t=ge("div","display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid rgba(148,163,184,0.18);font-size:13px;text-align:left");t.appendChild(ge("span","",e.done?"✅":"☐")),t.appendChild(ge("span","flex:1;"+(e.done?"opacity:0.6":""),pe(e.label))),t.appendChild(ge("span","opacity:0.7;font-size:12px",`+${le(e.entries,1)}`)),i.content.appendChild(t)}),pe(n.draw_pool_text)&&i.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-top:8px",pe(n.draw_pool_text))),null==(t=e.submitResponse)||t.call(e,"lucky_draw",{entries:o}),i.ctaButton(pe(n.draw_cta_text,"Get more entries"),()=>{var t;null==(t=e.haptic)||t.call(e,12)})},slot_machine:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-slot",400),i=he(t.slot_symbols).filter(e=>"string"==typeof e&&e),o=i.length>=3?i:["🍒","7️⃣","🍋","⭐","🔔"],s=e=>Math.floor(Math.random()*e),a=document.createElement("div");a.style.cssText="display:flex;align-items:center;justify-content:center;gap:12px;margin:12px 0 6px";const r=document.createElement("div");r.style.cssText="position:relative;display:flex;gap:8px;padding:12px;border-radius:18px;background:linear-gradient(180deg,#1f2937,#0f172a);box-shadow:inset 0 3px 10px rgba(0,0,0,0.55),0 6px 16px rgba(0,0,0,0.25)";const c=[0,1,2].map(()=>function(e,t){const n="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,i=document.createElement("div");i.style.cssText=`position:relative;width:${t}px;height:${t}px;overflow:hidden;border-radius:10px;background:linear-gradient(180deg,#ffffff,#f1f5f9);box-shadow:inset 0 6px 8px -4px rgba(0,0,0,0.35),inset 0 -6px 8px -4px rgba(0,0,0,0.35)`;const o=e.length*t,s=8*e.length,a=document.createElement("div");a.style.cssText="position:absolute;left:0;top:0;width:100%;will-change:transform";for(let l=0;l<s;l++){const n=document.createElement("div");n.style.cssText=`height:${t}px;display:flex;align-items:center;justify-content:center;font-size:${Math.round(.55*t)}px`,n.textContent=e[l%e.length],a.appendChild(n)}i.appendChild(a);let r=0,c=null;const d=()=>{a.style.transform=`translateY(${-r%o}px)`};return d(),{el:i,startSpin:()=>{if(n)return;a.style.transition="",a.style.filter="blur(1.5px)";const e=()=>{r+=34,d(),c=requestAnimationFrame(e)};c=requestAnimationFrame(e)},stop:(i,s)=>{null!==c&&(cancelAnimationFrame(c),c=null);const l=Math.max(0,e.indexOf(i))%e.length*t,p=r%o;if(n)return r=l,a.style.filter="",d(),void s();const h=p+2*o+((l-p)%o+o)%o;a.style.filter="",a.style.transition="transform 0.9s cubic-bezier(0.18,0.86,0.28,1.12)",a.style.transform=`translateY(${-h}px)`;const u=()=>{a.removeEventListener("transitionend",u),r=l,a.style.transition="",d(),s()};a.addEventListener("transitionend",u)}}}(o,68));c.forEach(e=>r.appendChild(e.el));const d=document.createElement("div");d.style.cssText="position:absolute;left:8px;right:8px;top:50%;height:68px;transform:translateY(-50%);border:2.5px solid transparent;border-radius:12px;pointer-events:none;transition:border-color 0.3s,box-shadow 0.3s",r.appendChild(d);const l=function(e,t){const n=document.createElement("div");n.style.cssText="position:relative;width:26px;height:96px;display:flex;justify-content:center;cursor:pointer;user-select:none",n.setAttribute("role","button"),n.setAttribute("aria-label","Pull the lever");const i=document.createElement("div");i.style.cssText="position:absolute;top:10px;bottom:10px;width:6px;border-radius:3px;background:linear-gradient(180deg,#64748b,#334155)";const o=document.createElement("div");return o.style.cssText=`position:absolute;top:0;width:26px;height:26px;border-radius:50%;background:radial-gradient(circle at 34% 30%,#ffffff,${e});box-shadow:0 3px 7px rgba(0,0,0,0.45);z-index:1`,n.appendChild(i),n.appendChild(o),n.addEventListener("click",t),{el:n,pull:()=>{o.style.transition="transform 0.12s ease-in",o.style.transform="translateY(60px)",window.setTimeout(()=>{o.style.transition="transform 0.5s cubic-bezier(0.2,1.5,0.4,1)",o.style.transform="translateY(0)"},130)}}}(n.accent,()=>{m()});a.appendChild(r),a.appendChild(l.el),n.content.appendChild(a);const p=document.createElement("div");p.style.cssText="font-size:13px;font-weight:700;min-height:18px;margin-top:8px",n.content.appendChild(p);let h=!1;const u=n.ctaButton(pe(t.slot_cta_text,"PULL 🎰"),()=>{}),g=u?u.cloneNode(!0):null;u&&g&&(u.replaceWith(g),g.addEventListener("click",()=>{m()}));const m=async()=>{var i,a;if(h)return;h=!0,g&&(g.disabled=!0),l.pull(),null==(i=e.haptic)||i.call(e,18),p.textContent="",d.style.borderColor="transparent",d.style.boxShadow="none",c.forEach(e=>e.startSpin());const r=[o[s(o.length)],o[s(o.length)],o[s(o.length)]],u=r[0]===r[1]&&r[1]===r[2],m=null==(a=e.submitResponse)?void 0:a.call(e,"slot_machine",{win:u,symbols:r});let f=null;try{const e=await Promise.race([m??Promise.resolve(null),new Promise(e=>window.setTimeout(()=>e(null),1400))]);f=e?e.prize:null}catch{}const x=f?!1!==f.win:u,y=f&&f.prize_label?String(f.prize_label):pe(t.slot_win_text,"You win!");let b;if(f)if(x){const e=o[s(o.length)];b=[e,e,e]}else b=[o[s(o.length)],o[s(o.length)],o[s(o.length)]],b[0]===b[1]&&b[1]===b[2]&&(b[2]=o[(o.indexOf(b[2])+1)%o.length]);else b=r;const v=t=>{c[t].stop(b[t],()=>{var i;null==(i=e.haptic)||i.call(e,10),t<c.length-1?window.setTimeout(()=>v(t+1),t===c.length-2?560:320):(()=>{var t,i,o,s;p.textContent=x?`🎉 ${y}`:"So close — try again next time!",p.style.color=x?n.accent:"#94a3b8",x?(d.style.borderColor=n.accent,d.style.boxShadow=`0 0 14px ${n.accent}aa, inset 0 0 14px ${n.accent}55`,null==(t=e.haptic)||t.call(e,[0,30,20,40]),null==(i=e.playReaction)||i.call(e,n.card,"celebrate")):(null==(o=e.haptic)||o.call(e,15),null==(s=e.playReaction)||s.call(e,n.card,"empathize")),e.trackEvent(e.campaign.id,"clicked",{stepId:x?"win":"lose"}),h=!1})()})};window.setTimeout(()=>v(0),620)}}},be=Object.keys(ye);const ve={"16:9":"16 / 9","9:16":"9 / 16","1:1":"1 / 1","4:5":"4 / 5"};function we(e,t,n,i){var o;const{campaign:s,sanitizeUrl:a}=e,r=a((s.interactive_config||{}).video_url||s.video_url||""),c=s.image_url?a(s.image_url):null,d=document.createElement("div");if(d.style.cssText=`position:relative;width:100%;aspect-ratio:${ve[t]||ve["16:9"]};background:#0b1220;border-radius:14px;overflow:hidden;`,r){const t=document.createElement("video");t.src=r,t.muted=!0,t.loop=i,t.autoplay=n,t.playsInline=!0,t.setAttribute("playsinline",""),c&&(t.poster=c),t.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;",d.appendChild(t),n&&(null==(o=t.play)||o.call(t).catch(()=>{}));let s=!1;const a=()=>{var n;!s&&t.duration&&isFinite(t.duration)&&t.currentTime/t.duration>=.9&&(s=!0,null==(n=e.submitResponse)||n.call(e,"video_complete",{duration_s:Math.round(t.duration)}))};t.addEventListener("timeupdate",a),t.addEventListener("ended",()=>{var n;s||(s=!0,null==(n=e.submitResponse)||n.call(e,"video_complete",{duration_s:Math.round(t.duration||0)}))});const l=document.createElement("button");l.type="button",l.textContent="🔇",l.setAttribute("aria-label","Unmute"),l.style.cssText="position:absolute;bottom:10px;right:10px;z-index:2;width:34px;height:34px;border:none;border-radius:999px;background:rgba(0,0,0,0.45);color:#fff;font-size:14px;cursor:pointer;",l.addEventListener("click",e=>{var n;e.stopPropagation(),t.muted=!t.muted,l.textContent=t.muted?"🔇":"🔊",t.muted||null==(n=t.play)||n.call(t).catch(()=>{})}),d.appendChild(l)}else if(c){const e=document.createElement("img");e.src=c,e.alt="",e.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;",d.appendChild(e)}else d.style.background="linear-gradient(160deg,#1f2937,#0f172a)";return d}function _e(e,t,n){const{campaign:i}=e;if(!(i.title||i.body||i.button_text||i.action_url))return null;const o=document.createElement("div");if(o.style.cssText=n?"position:absolute;left:0;right:0;bottom:0;z-index:2;padding:18px 16px 16px;color:#fff;text-align:left;background:linear-gradient(to top,rgba(0,0,0,0.72),rgba(0,0,0,0) 80%);":"padding:14px 4px 2px;text-align:left;color:#0f172a;",i.title){const e=document.createElement("div");e.textContent=i.title,e.style.cssText="font-family:'Inter Tight',Inter,system-ui,sans-serif;font-size:17px;font-weight:800;letter-spacing:-0.01em;line-height:1.2;"+(n?"text-shadow:0 1px 8px rgba(0,0,0,0.4);":""),o.appendChild(e)}if(i.body){const e=document.createElement("div");e.textContent=i.body,e.style.cssText="font-size:13px;line-height:1.45;margin-top:3px;"+(n?"opacity:0.92;text-shadow:0 1px 6px rgba(0,0,0,0.4);":"opacity:0.7;"),o.appendChild(e)}const s=i.button_text||(i.action_url?"Watch now":"");if(s){const a=document.createElement("button");a.type="button",a.className="aegis-cta",a.textContent=s,a.style.cssText=`margin-top:12px;padding:10px 22px;border:none;border-radius:999px;background:${n?"#fff":t};color:${n?"#0f172a":"#fff"};font-size:13px;font-weight:700;cursor:pointer;`,a.addEventListener("click",t=>{t.stopPropagation(),e.trackEvent(i.id,"clicked");const n=i.action_url||"";n&&(e.navigate?e.navigate(n,"cta"):window.location.href=n)}),o.appendChild(a)}return o}function Ce(e){const t=e.campaign.interactive_config||{};return{accent:e.sanitizeColor(e.campaign.background_color||"#4169e1"),aspect:t.video_aspect||"16:9",overlayCaption:"below"!==t.video_caption,autoplay:!1!==t.video_autoplay,loop:!1!==t.video_loop}}function ke(e){const{campaign:t,trackEvent:n,addAnimationStyles:i}=e;i();const o=Ce(e),s=document.createElement("div");s.className="aegis-in-app-video-overlay",s.setAttribute("data-campaign-id",t.id),s.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(15,23,42,0.6);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:16px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;animation:aegisFadeIn 0.25s ease;';const a=document.createElement("div");a.style.cssText=`position:relative;width:100%;max-width:${"9:16"===o.aspect?320:460}px;background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 16px 48px rgba(0,0,0,0.28);animation:aegisScaleIn 0.3s ease;`;const r=we(e,o.aspect,o.autoplay,o.loop);if(o.overlayCaption){const t=_e(e,o.accent,!0);t&&r.appendChild(t)}if(a.appendChild(r),!o.overlayCaption){const t=_e(e,o.accent,!1);t&&(t.style.padding="14px 16px 16px",a.appendChild(t))}const c=document.createElement("button");c.type="button",c.textContent="✕",c.setAttribute("aria-label","Close"),c.style.cssText="position:absolute;top:10px;left:10px;z-index:3;width:32px;height:32px;border:none;border-radius:999px;background:rgba(0,0,0,0.4);color:#fff;font-size:15px;cursor:pointer;",c.addEventListener("click",()=>{n(t.id,"dismissed"),s.remove()}),a.appendChild(c),s.addEventListener("click",e=>{e.target===s&&(n(t.id,"dismissed"),s.remove())}),s.appendChild(a),document.body.appendChild(s)}const Ee="aegis-chat-styles";class Se{constructor(e){this.open=!1,this.initialized=!1,this.unread=0,this.renderedIds=new Set,this.pendingEcho=[],this.hasInteracted=!1,this.writeKey=e.writeKey,this.apiHost=(e.apiHost??"").replace(/\/$/,""),this.contactId=e.contactId,this.channel=e.channel??"web",this.debugMode=e.debugMode??!1,this.title=e.title??"Shopping Assistant",this.greeting=e.greeting??"Hi! 👋 How can I help you today?",this.accent=e.accentColor??"#4169e1",this.icon=e.icon??"sparkle",this.logoUrl=e.logoUrl,this.position=e.position??"bottom-right",this.agentPersona=e.agentPersona,this.quickReplies=e.quickReplies,this.onSessionStart=e.onSessionStart,this.onSessionEnd=e.onSessionEnd,this.onMessageSent=e.onMessageSent,this.anonymousId=this.readAnonId()}initialize(){this.initialized||"undefined"==typeof document||(this.initialized=!0,this.injectStyles(),this.mount(),this.scheduleAttention())}updateContactId(e){e&&e!==this.contactId&&(this.contactId=e)}openPanel(e){var t,n,i,o;if(this.panel||this.initialize(),!this.open){this.open=!0,this.hasInteracted=!0;try{null==(t=this.onSessionStart)||t.call(this)}catch{}this.dismissAttention(),null==(n=this.panel)||n.classList.add("aegis-chat-panel--open"),null==(i=this.bubble)||i.classList.add("aegis-chat-bubble--hidden"),this.clearUnread(),e&&this.input&&(this.input.value=e),this.refreshHistory(),this.startPolling(),null==(o=this.input)||o.focus()}}closePanel(){var e,t,n;const i=this.open;if(this.open=!1,null==(e=this.panel)||e.classList.remove("aegis-chat-panel--open"),null==(t=this.bubble)||t.classList.remove("aegis-chat-bubble--hidden"),this.disconnectSSE(),this.stopPolling(),i)try{null==(n=this.onSessionEnd)||n.call(this)}catch{}}destroy(){var e;this.disconnectSSE(),this.stopPolling(),null==(e=this.root)||e.remove(),this.initialized=!1}async send(e){var t;const n=e.trim();if(n){this.appendBubble({id:`local_${Date.now()}`,sender:"customer",role:"user",content:n}),this.pendingEcho.push(n),this.input&&(this.input.value="",this.input.style.height="auto"),this.showTyping();try{const e=await fetch(`${this.apiHost}/v1/chat/message`,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify({message_text:n,channel:this.channel,anonymous_id:this.anonymousId,contact_id:this.contactId,agent_persona:this.agentPersona}),keepalive:!0});if(!e.ok)return this.log("send failed",e.status),void this.appendSystem("Sorry — your message could not be delivered. Please try again.");const i=await e.json();try{null==(t=this.onMessageSent)||t.call(this)}catch{}this.contactId=i.contact_id,this.sseTicket=i.sse_ticket,this.connectSSE(i.sse_ticket),this.refreshHistory()}catch(i){this.log("send error",i),this.appendSystem("Sorry — your message could not be delivered. Please try again.")}}}connectSSE(e){if(!this.open)return;if("undefined"==typeof EventSource||!this.contactId)return;if(!e)return;this.disconnectSSE();const t=new URL("/v1/stream/realtime",this.apiHost||window.location.origin);t.searchParams.set("ticket",e),t.searchParams.set("mode","ephemeral");try{this.eventSource=new EventSource(t.toString()),this.eventSource.onopen=()=>{this.stopPolling(),this.log("SSE connected")},this.eventSource.addEventListener("chat.message",()=>{this.refreshHistory()}),this.eventSource.onerror=()=>{this.startPolling()}}catch(n){this.log("SSE connect failed",n),this.startPolling()}}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}startPolling(){this.open&&(this.pollTimer||(this.pollTimer=setInterval(()=>{this.refreshHistory()},5e3)))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0)}async refreshHistory(){if(this.contactId&&this.sseTicket)try{const e=new URL("/v1/chat/history",this.apiHost||window.location.origin);e.searchParams.set("contact_id",this.contactId),e.searchParams.set("ticket",this.sseTicket),e.searchParams.set("channel",this.channel),e.searchParams.set("limit","50");const t=await fetch(e.toString(),{method:"GET",headers:{"X-Aegis-Write-Key":this.writeKey}});if(!t.ok)return;const n=await t.json();let i=!1;for(const o of n.messages||[])if(!this.renderedIds.has(o.id)){if("customer"===o.sender){const e=this.pendingEcho.indexOf(o.content||"");if(-1!==e){this.pendingEcho.splice(e,1),o.id&&this.renderedIds.add(o.id);continue}}"assistant"===o.sender&&this.hideTyping(),this.appendBubble(o),i=!0,"assistant"!==o.sender||this.open||this.bumpUnread()}i&&this.scrollToBottom()}catch(e){this.log("history fetch error",e)}}bubbleIconHtml(){if("chat"===this.icon)return'<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';if("logo"===this.icon&&this.logoUrl&&/^https?:\/\//i.test(this.logoUrl)){return`<img class="aegis-chat-bubble-logo" src="${this.logoUrl.replace(/"/g,""")}" alt="" />`}return'<svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2.3l1.85 5.0 5.0 1.85-5.0 1.85L12 16l-1.85-5.0L5.15 9.15l5.0-1.85L12 2.3z"/><path d="M18.7 14.3l.78 2.1 2.1.78-2.1.78-.78 2.1-.78-2.1-2.1-.78 2.1-.78.78-2.1z" opacity="0.85"/></svg>'}mount(){const e=document.createElement("div");e.className=`aegis-chat-root aegis-chat-root--${this.position}`,e.style.setProperty("--aegis-chat-accent",this.accent);const t=document.createElement("button");t.className="aegis-chat-bubble",t.setAttribute("aria-label",`Open ${this.title}`),t.innerHTML=this.bubbleIconHtml();const n=document.createElement("span");n.className="aegis-chat-badge",n.style.display="none",t.appendChild(n),t.addEventListener("click",()=>this.openPanel());const i=document.createElement("div");i.className="aegis-chat-panel",i.setAttribute("role","dialog"),i.setAttribute("aria-label",this.title);const o=document.createElement("div");o.className="aegis-chat-header";const s=document.createElement("span");s.className="aegis-chat-title",s.textContent=this.title;const a=document.createElement("button");a.className="aegis-chat-close",a.setAttribute("aria-label","Close chat"),a.textContent="✕",a.addEventListener("click",()=>this.closePanel()),o.appendChild(s),o.appendChild(a);const r=document.createElement("div");r.className="aegis-chat-thread";const c=document.createElement("form");c.className="aegis-chat-composer";const d=document.createElement("textarea");d.className="aegis-chat-input",d.rows=1,d.placeholder="Type a message…",d.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.send(d.value))});const l=document.createElement("button");l.type="submit",l.className="aegis-chat-send",l.setAttribute("aria-label","Send message"),l.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',c.addEventListener("submit",e=>{e.preventDefault(),this.send(d.value)}),c.appendChild(d),c.appendChild(l),i.appendChild(o),i.appendChild(r),i.appendChild(c);const p=document.createElement("div");p.className="aegis-chat-tip";const h=document.createElement("span");h.textContent=this.greeting||"Need help finding something? Ask me 👋";const u=document.createElement("button");u.className="aegis-chat-tip-close",u.setAttribute("aria-label","Dismiss"),u.textContent="✕",u.addEventListener("click",e=>{e.stopPropagation(),this.dismissAttention()}),p.appendChild(h),p.appendChild(u),p.addEventListener("click",()=>this.openPanel()),e.appendChild(i),e.appendChild(p),e.appendChild(t),document.body.appendChild(e),this.greetingTip=p,this.root=e,this.bubble=t,this.badge=n,this.panel=i,this.thread=r,this.input=d,this.appendSystemGreeting(this.greeting),this.renderQuickReplies()}renderQuickReplies(){var e;if(!this.thread||!(null==(e=this.quickReplies)?void 0:e.length))return;const t=document.createElement("div");t.className="aegis-chat-quickreplies";for(const n of this.quickReplies){if("string"!=typeof n||!n.trim())continue;const e=document.createElement("button");e.type="button",e.className="aegis-chat-chip",e.textContent=n,e.addEventListener("click",()=>{t.remove(),this.send(n)}),t.appendChild(e)}t.childElementCount>0&&this.thread.appendChild(t)}appendBubble(e){if(!this.thread)return;e.id&&this.renderedIds.add(e.id);const t=document.createElement("div");if(t.className=`aegis-chat-msg aegis-chat-msg--${e.sender}`,e.content){const n=document.createElement("div");n.className="aegis-chat-bubbletext",n.textContent=e.content,t.appendChild(n)}if(e.interactive&&Array.isArray(e.interactive))for(const n of e.interactive){const e=this.renderInteractive(n);e&&t.appendChild(e)}this.thread.appendChild(t),this.scrollToBottom()}renderInteractive(e){if("product_carousel"!==(null==e?void 0:e.type))return null;const t=e.products||[];if(!t.length)return null;const n=document.createElement("div");n.className="aegis-chat-carousel";for(const i of t){const e=document.createElement("a");e.className="aegis-chat-card";const t=i.cta_url||"#";if(e.href=t,e.target="_blank",e.rel="noopener noreferrer",i.image_url){const t=document.createElement("img");t.className="aegis-chat-card-img",t.src=i.image_url,t.alt=i.name||"",t.loading="lazy",e.appendChild(t)}const o=document.createElement("div");if(o.className="aegis-chat-card-name",o.textContent=i.name||"",e.appendChild(o),null!=i.price){const t=document.createElement("div");t.className="aegis-chat-card-price",t.textContent=(i.price,String(i.price)),e.appendChild(t)}n.appendChild(e)}if("string"==typeof e.browse_all_url&&e.browse_all_url){const t=document.createElement("a");t.className="aegis-chat-card aegis-chat-card--more",t.href=e.browse_all_url,t.target="_blank",t.rel="noopener noreferrer",t.textContent="View all →",n.appendChild(t)}return n}appendSystem(e){this.appendBubble({id:`sys_${Date.now()}`,sender:"system",role:"system",content:e})}appendSystemGreeting(e){this.appendBubble({id:`greeting_${Date.now()}`,sender:"assistant",role:"bot",content:e})}bumpUnread(){this.unread+=1,this.badge&&(this.badge.textContent=String(this.unread),this.badge.style.display="flex")}clearUnread(){this.unread=0,this.badge&&(this.badge.style.display="none")}scrollToBottom(){this.thread&&(this.thread.scrollTop=this.thread.scrollHeight)}readAnonId(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}showTyping(){if(!this.thread||this.typingEl)return;const e=document.createElement("div");e.className="aegis-chat-msg aegis-chat-msg--assistant aegis-chat-typing",e.innerHTML='<div class="aegis-chat-bubbletext aegis-chat-typingdots"><span></span><span></span><span></span></div>',this.thread.appendChild(e),this.typingEl=e,this.scrollToBottom()}hideTyping(){this.typingEl&&(this.typingEl.remove(),this.typingEl=void 0)}scheduleAttention(){"undefined"!=typeof window&&(this.attentionTimer=setTimeout(()=>{var e,t;this.hasInteracted||this.open||(null==(e=this.bubble)||e.classList.add("aegis-chat-bubble--pulse"),null==(t=this.greetingTip)||t.classList.add("aegis-chat-tip--show"))},4500))}dismissAttention(){var e,t;this.attentionTimer&&(clearTimeout(this.attentionTimer),this.attentionTimer=void 0),null==(e=this.bubble)||e.classList.remove("aegis-chat-bubble--pulse"),null==(t=this.greetingTip)||t.classList.remove("aegis-chat-tip--show")}log(...e){this.debugMode&&console.log("[AegisChat]",...e)}injectStyles(){if("undefined"==typeof document||document.getElementById(Ee))return;const e=document.createElement("style");e.id=Ee,e.textContent=Te,document.head.appendChild(e)}}const Te='\n.aegis-chat-root{position:fixed;bottom:20px;right:20px;z-index:2147483000;font-family:Inter,system-ui,-apple-system,sans-serif}\n.aegis-chat-root--bottom-left{left:20px;right:auto}\n.aegis-chat-root--bottom-left .aegis-chat-panel{left:0;right:auto}\n.aegis-chat-bubble-logo{width:34px;height:34px;border-radius:9999px;object-fit:cover}\n.aegis-chat-bubble{width:60px;height:60px;border-radius:9999px;border:none;background:var(--aegis-chat-accent,#4169e1);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 8px 24px rgba(0,0,0,.18);transition:transform .18s ease,box-shadow .18s ease;position:relative;animation:aegis-chat-in .4s cubic-bezier(.16,1,.3,1)}\n.aegis-chat-bubble:hover{transform:translateY(-2px) scale(1.04);box-shadow:0 12px 28px rgba(0,0,0,.22)}\n.aegis-chat-bubble--hidden{display:none}\n/* Attention pulse — an expanding accent ring that draws the eye to a live, ready assistant. */\n.aegis-chat-bubble--pulse::before{content:"";position:absolute;inset:0;border-radius:9999px;background:var(--aegis-chat-accent,#4169e1);z-index:-1;animation:aegis-chat-pulse 1.8s ease-out infinite}\n.aegis-chat-bubble--pulse{animation:aegis-chat-in .4s cubic-bezier(.16,1,.3,1),aegis-chat-nudge 1.8s ease-in-out 2}\n@keyframes aegis-chat-in{from{opacity:0;transform:scale(.6)}to{opacity:1;transform:scale(1)}}\n@keyframes aegis-chat-pulse{0%{transform:scale(1);opacity:.55}100%{transform:scale(1.9);opacity:0}}\n@keyframes aegis-chat-nudge{0%,100%{transform:translateY(0)}25%{transform:translateY(-5px)}50%{transform:translateY(0)}}\n/* One-time greeting tooltip */\n.aegis-chat-tip{position:absolute;bottom:14px;right:74px;max-width:230px;background:#fff;color:#0f172a;border:1px solid #e2e8f0;border-radius:14px;border-bottom-right-radius:4px;box-shadow:0 10px 30px rgba(0,0,0,.16);padding:10px 30px 10px 13px;font-size:13.5px;line-height:1.4;cursor:pointer;opacity:0;transform:translateX(8px) scale(.92);transform-origin:bottom right;pointer-events:none;transition:opacity .25s ease,transform .25s ease}\n.aegis-chat-tip--show{opacity:1;transform:translateX(0) scale(1);pointer-events:auto}\n.aegis-chat-tip-close{position:absolute;top:5px;right:6px;width:18px;height:18px;border:none;background:transparent;color:#94a3b8;font-size:12px;line-height:1;cursor:pointer;border-radius:9999px}\n.aegis-chat-tip-close:hover{background:#f1f5f9;color:#475569}\n@media (prefers-reduced-motion:reduce){.aegis-chat-bubble,.aegis-chat-bubble--pulse{animation:none}.aegis-chat-bubble--pulse::before{animation:none;display:none}}\n.aegis-chat-badge{position:absolute;top:-2px;right:-2px;min-width:20px;height:20px;padding:0 5px;border-radius:9999px;background:#ef4444;color:#fff;font-size:12px;font-weight:600;display:flex;align-items:center;justify-content:center}\n.aegis-chat-panel{position:absolute;bottom:0;right:0;width:380px;max-width:calc(100vw - 32px);height:560px;max-height:calc(100vh - 48px);background:#fff;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.24);display:none;flex-direction:column;overflow:hidden}\n.aegis-chat-panel--open{display:flex}\n.aegis-chat-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;background:var(--aegis-chat-accent,#4169e1);color:#fff}\n.aegis-chat-title{font-weight:600;font-size:15px}\n.aegis-chat-close{background:transparent;border:none;color:#fff;font-size:16px;cursor:pointer;opacity:.85}\n.aegis-chat-close:hover{opacity:1}\n.aegis-chat-thread{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#f8fafc}\n.aegis-chat-msg{display:flex;flex-direction:column;max-width:85%}\n.aegis-chat-msg--customer{align-self:flex-end;align-items:flex-end}\n.aegis-chat-msg--assistant,.aegis-chat-msg--system{align-self:flex-start;align-items:flex-start}\n.aegis-chat-bubbletext{padding:9px 13px;border-radius:14px;font-size:14px;line-height:1.45;white-space:pre-wrap;word-break:break-word}\n.aegis-chat-msg--customer .aegis-chat-bubbletext{background:var(--aegis-chat-accent,#4169e1);color:#fff;border-bottom-right-radius:4px}\n.aegis-chat-msg--assistant .aegis-chat-bubbletext{background:#fff;color:#0f172a;border:1px solid #e2e8f0;border-bottom-left-radius:4px}\n.aegis-chat-quickreplies{display:flex;flex-wrap:wrap;gap:6px;padding:2px 4px 6px;justify-content:flex-start}\n.aegis-chat-chip{appearance:none;cursor:pointer;border:1px solid var(--aegis-chat-accent,#4169e1);background:#fff;color:var(--aegis-chat-accent,#4169e1);border-radius:9999px;padding:6px 12px;font-size:13px;line-height:1;font-family:inherit;transition:background .15s,color .15s}\n.aegis-chat-chip:hover{background:var(--aegis-chat-accent,#4169e1);color:#fff}\n.aegis-chat-msg--system .aegis-chat-bubbletext{background:#fef3c7;color:#92400e;font-size:13px}\n.aegis-chat-typingdots{display:flex;gap:4px;align-items:center;padding:12px 14px}\n.aegis-chat-typingdots span{width:7px;height:7px;border-radius:9999px;background:#94a3b8;display:inline-block;animation:aegis-chat-typing 1.2s infinite ease-in-out}\n.aegis-chat-typingdots span:nth-child(2){animation-delay:.18s}\n.aegis-chat-typingdots span:nth-child(3){animation-delay:.36s}\n@keyframes aegis-chat-typing{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}}\n.aegis-chat-carousel{display:flex;gap:10px;overflow-x:auto;padding:8px 0;max-width:320px;scroll-snap-type:x mandatory}\n.aegis-chat-card{flex:0 0 140px;scroll-snap-align:start;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:8px;text-decoration:none;color:#0f172a;display:flex;flex-direction:column;gap:4px;transition:box-shadow .15s ease}\n.aegis-chat-card:hover{box-shadow:0 6px 16px rgba(0,0,0,.1)}\n.aegis-chat-card-img{width:100%;height:96px;object-fit:cover;border-radius:8px}\n.aegis-chat-card-name{font-size:13px;font-weight:500;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}\n.aegis-chat-card-price{font-size:13px;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-card--more{align-items:center;justify-content:center;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-composer{display:flex;align-items:flex-end;gap:8px;padding:12px;border-top:1px solid #e2e8f0;background:#fff}\n.aegis-chat-input{flex:1;resize:none;border:1px solid #e2e8f0;border-radius:12px;padding:9px 12px;font-size:14px;font-family:inherit;max-height:96px;outline:none}\n.aegis-chat-input:focus{border-color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-send{width:40px;height:40px;border-radius:9999px;border:none;background:var(--aegis-chat-accent,#4169e1);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto}\n/* Mobile: raise the bubble above the storefront\'s full-width cart bar so they\n never overlap; widen the panel and reduce the tooltip width. */\n@media (max-width:480px){\n .aegis-chat-root{bottom:84px;right:16px}\n .aegis-chat-panel{width:calc(100vw - 24px);height:calc(100vh - 140px)}\n .aegis-chat-tip{max-width:200px}\n}\n';class $e{constructor(){this.listeners=new Map,this.isStarted=!1,this.scrollDepthTargets=new Set,this.scrollDepthReached=new Set,this.timeOnPageTargets=new Map,this.exitIntentEnabled=!1,this.exitIntentFired=!1,this.inactivityTargets=new Map,this.lastActivityTime=Date.now(),this.scrollVelocityEnabled=!1,this.scrollVelocityFired=!1,this.scrollVelocityConfig={threshold:.5,minScrollPosition:100,cooldown:5e3},this.lastScrollY=0,this.lastScrollTime=Date.now(),this.visibilityChangeEnabled=!1,this.backButtonEnabled=!1,this.backButtonFired=!1,this.rageClickEnabled=!1,this.rageClickConfig={threshold:3,windowMs:1e3},this.rageClickBuffer=new Map,this.rageClickFiredInBurst=new Set,this.hoverEnabled=!1,this.hoverStartAt=new Map,this.hoverLastMs=new Map,this.hoverThresholds=new Map([["price",[1500]],["cta",[1500]]]),this.hoverThresholdsFired=new Map,this.hoverThresholdTimers=new Map,this.mouseVelEnabled=!1,this.mouseVelConfig={threshold:1.5,windowMs:400,cooldownMs:5e3},this.mouseSamples=[],this.mouseVelLast=0,this.mouseVelLastFiredAt=0,this.handleScroll=()=>{const e=window.pageYOffset||document.documentElement.scrollTop,t=document.documentElement.scrollHeight-window.innerHeight,n=t>0?e/t*100:0;for(const i of this.scrollDepthTargets)n>=i&&!this.scrollDepthReached.has(i)&&(this.scrollDepthReached.add(i),this.emit(`scroll_depth_${i}`,{depth_percent:i,actual_percent:n,scroll_top:e,scroll_height:t}))},this.handleExitIntent=e=>{this.exitIntentFired||e.clientY<10&&(this.exitIntentFired=!0,this.emit("exit_intent",{client_y:e.clientY,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleScrollVelocity=()=>{if(this.scrollVelocityFired)return;const e=window.scrollY||document.documentElement.scrollTop,t=Date.now(),n=t-this.lastScrollTime;if(n>100){const i=this.lastScrollY-e,o=Math.abs(i/n);i>0&&o>this.scrollVelocityConfig.threshold&&e>this.scrollVelocityConfig.minScrollPosition&&(this.scrollVelocityFired=!0,this.emit("mobile_exit_intent",{scroll_velocity:o,scroll_distance:i,current_position:e,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}),this.scrollVelocityCooldownTimer=window.setTimeout(()=>{this.scrollVelocityFired=!1},this.scrollVelocityConfig.cooldown)),this.lastScrollY=e,this.lastScrollTime=t}},this.handleVisibilityChange=()=>{document.hidden?this.emit("visibility_hidden",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}):this.emit("visibility_visible",{page_url:window.location.href})},this.handleBackButton=()=>{this.backButtonFired||(this.backButtonFired=!0,window.history.pushState(null,"",window.location.href),this.emit("back_button",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleActivity=()=>{this.lastActivityTime=Date.now()}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}registerScrollDepth(e){this.scrollDepthTargets.add(e)}registerTimeOnPage(e){if(!this.timeOnPageTargets.has(e)){const t=window.setTimeout(()=>{this.emit(`time_on_page_${e}`,{seconds:e,page_url:window.location.href}),this.timeOnPageTargets.delete(e)},1e3*e);this.timeOnPageTargets.set(e,t)}}registerExitIntent(){this.exitIntentEnabled=!0}registerInactivity(e){if(!this.inactivityTargets.has(e)){const t=window.setTimeout(()=>{const t=(Date.now()-this.lastActivityTime)/1e3;t>=e&&this.emit(`inactivity_${e}`,{idle_seconds:e,actual_idle_time:t}),this.inactivityTargets.delete(e)},1e3*e);this.inactivityTargets.set(e,t)}}registerScrollVelocity(e){this.scrollVelocityEnabled=!0,e&&(this.scrollVelocityConfig={threshold:e.threshold??this.scrollVelocityConfig.threshold,minScrollPosition:e.minScrollPosition??this.scrollVelocityConfig.minScrollPosition,cooldown:e.cooldown??this.scrollVelocityConfig.cooldown})}registerVisibilityChange(){this.visibilityChangeEnabled=!0}registerBackButton(){this.backButtonEnabled=!0}registerRageClick(e){this.rageClickEnabled=!0,e&&(this.rageClickConfig={threshold:e.threshold??this.rageClickConfig.threshold,windowMs:e.windowMs??this.rageClickConfig.windowMs})}noteClick(e,t=Date.now()){if(!this.rageClickEnabled)return 0;const n=this.rageClickBuffer.get(e)??[],i=t-this.rageClickConfig.windowMs;let o=0;for(;o<n.length&&n[o]<i;)o++;const s=0===o?n:n.slice(o);return s.push(t),this.rageClickBuffer.set(e,s),s.length<this.rageClickConfig.threshold&&this.rageClickFiredInBurst.delete(e),s.length>=this.rageClickConfig.threshold&&!this.rageClickFiredInBurst.has(e)&&(this.rageClickFiredInBurst.add(e),this.emit("rage_click",{intent:e,count:s.length,window_ms:this.rageClickConfig.windowMs})),s.length}getRageClickCount(e){if(!this.rageClickEnabled)return 0;const t=this.rageClickBuffer.get(e);if(!t)return 0;const n=Date.now()-this.rageClickConfig.windowMs;let i=0;for(const o of t)o>=n&&i++;return i}registerHoverDwell(e){if(this.hoverEnabled=!0,null==e?void 0:e.thresholdsByIntent)for(const[t,n]of Object.entries(e.thresholdsByIntent))n&&this.hoverThresholds.set(t,n)}noteHoverStart(e,t=Date.now()){if(!this.hoverEnabled)return;this.hoverStartAt.has(e)&&this.noteHoverEnd(e,t),this.hoverStartAt.set(e,t),this.hoverThresholdsFired.set(e,new Set);const n=this.hoverThresholds.get(e);if(n){const i=[];for(const o of n){const n=setTimeout(()=>{if(!this.hoverStartAt.has(e))return;const n=this.hoverThresholdsFired.get(e);(null==n?void 0:n.has(o))||(null==n||n.add(o),this.emit(`${e}_hover_dwell_${o}`,{intent:e,threshold_ms:o,actual_ms:Date.now()-t}))},o);i.push(n)}this.hoverThresholdTimers.set(e,i)}}noteHoverEnd(e,t=Date.now()){if(!this.hoverEnabled)return;const n=this.hoverStartAt.get(e);if(void 0===n)return;const i=Math.max(0,t-n);this.hoverLastMs.set(e,i),this.hoverStartAt.delete(e);const o=this.hoverThresholdTimers.get(e);if(o){for(const e of o)clearTimeout(e);this.hoverThresholdTimers.delete(e)}this.hoverThresholdsFired.delete(e)}registerMouseVelocityToTop(e){this.mouseVelEnabled=!0,e&&(this.mouseVelConfig={threshold:e.threshold??this.mouseVelConfig.threshold,windowMs:e.windowMs??this.mouseVelConfig.windowMs,cooldownMs:e.cooldownMs??this.mouseVelConfig.cooldownMs})}noteMousePosition(e,t,n=Date.now()){if(!this.mouseVelEnabled)return 0;const i=n-this.mouseVelConfig.windowMs;let o=0;for(;o<this.mouseSamples.length&&this.mouseSamples[o].ts<i;)o++;if(o>0&&(this.mouseSamples=this.mouseSamples.slice(o)),this.mouseSamples.push({x:e,y:t,ts:n}),this.mouseSamples.length<2)return this.mouseVelLast=0,0;const s=this.mouseSamples[0],a=this.mouseSamples[this.mouseSamples.length-1],r=a.ts-s.ts;if(r<=0)return this.mouseVelLast=0,0;const c=-(a.y-s.y)/r;this.mouseVelLast=c;const d=0===this.mouseVelLastFiredAt||n-this.mouseVelLastFiredAt>=this.mouseVelConfig.cooldownMs;return c>=this.mouseVelConfig.threshold&&d&&(this.mouseVelLastFiredAt=n,this.emit("mouse_velocity_to_top",{velocity:c,threshold:this.mouseVelConfig.threshold,window_ms:this.mouseVelConfig.windowMs,samples:this.mouseSamples.length})),c}getMouseVelocityToTop(){return this.mouseVelEnabled?this.mouseVelLast:0}getHoverMs(e){if(!this.hoverEnabled)return 0;const t=this.hoverStartAt.get(e);return void 0!==t?Math.max(0,Date.now()-t):this.hoverLastMs.get(e)??0}start(){this.isStarted||(this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollDepthTargets.size>0&&this.attachScrollListener(),this.exitIntentEnabled&&this.attachExitIntentListener(),this.scrollVelocityEnabled&&this.attachScrollVelocityListener(),this.visibilityChangeEnabled&&this.attachVisibilityChangeListener(),this.backButtonEnabled&&this.attachBackButtonListener(),this.attachActivityListeners(),this.startInactivityCheck(),this.isStarted=!0)}stop(){this.isStarted&&(this.removeScrollListener(),this.removeExitIntentListener(),this.removeScrollVelocityListener(),this.removeVisibilityChangeListener(),this.removeBackButtonListener(),this.removeActivityListeners(),this.timeOnPageTargets.forEach(e=>clearTimeout(e)),this.timeOnPageTargets.clear(),this.inactivityTargets.forEach(e=>clearTimeout(e)),this.inactivityTargets.clear(),this.inactivityCheckInterval&&(clearInterval(this.inactivityCheckInterval),this.inactivityCheckInterval=void 0),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0),this.isStarted=!1)}reset(){this.scrollDepthReached.clear(),this.exitIntentFired=!1,this.scrollVelocityFired=!1,this.backButtonFired=!1,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0)}attachScrollListener(){window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.handleScroll()}removeScrollListener(){window.removeEventListener("scroll",this.handleScroll)}attachExitIntentListener(){document.addEventListener("mouseleave",this.handleExitIntent)}removeExitIntentListener(){document.removeEventListener("mouseleave",this.handleExitIntent)}attachScrollVelocityListener(){window.addEventListener("scroll",this.handleScrollVelocity,{passive:!0})}removeScrollVelocityListener(){window.removeEventListener("scroll",this.handleScrollVelocity)}attachVisibilityChangeListener(){document.addEventListener("visibilitychange",this.handleVisibilityChange)}removeVisibilityChangeListener(){document.removeEventListener("visibilitychange",this.handleVisibilityChange)}attachBackButtonListener(){"undefined"!=typeof window&&window.history&&(window.history.pushState(null,"",window.location.href),window.addEventListener("popstate",this.handleBackButton))}removeBackButtonListener(){window.removeEventListener("popstate",this.handleBackButton)}attachActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.addEventListener(e,this.handleActivity,{passive:!0})})}removeActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.removeEventListener(e,this.handleActivity)})}startInactivityCheck(){this.inactivityCheckInterval=window.setInterval(()=>{const e=(Date.now()-this.lastActivityTime)/1e3;for(const[t]of this.inactivityTargets)if(e>=t){this.emit(`inactivity_${t}`,{idle_seconds:t,actual_idle_time:e});const n=this.inactivityTargets.get(t);n&&(clearTimeout(n),this.inactivityTargets.delete(t))}},1e3)}emit(e,t){const n={type:e,data:t,timestamp:Date.now()},i=this.listeners.get(e);i&&i.forEach(t=>{try{t(n)}catch(i){console.error(`Error in trigger callback for ${e}:`,i)}});const o=this.listeners.get("*");o&&o.forEach(e=>{try{e(n)}catch(t){console.error("Error in wildcard trigger callback:",t)}})}}let Ie=null,ze=null;function Ae(e){return"string"==typeof e&&e.length>0?e:void 0}function Le(e){try{const t=(new DOMParser).parseFromString(e,"image/svg+xml").documentElement;return!t||t.getElementsByTagName("parsererror").length>0?null:document.importNode(t,!0)}catch{return null}}const Me=class e{constructor(e){this.campaigns=[],this.displayedCampaigns=new Set,this.suppressedUntil=new Map,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.hooks=new Map,this.ready=new Promise(e=>{this.readyResolve=e}),this.currentSurface=null,this.currentScreen=null,this.currentLocationId=null,this.filledSlots=new WeakSet,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.propertyId=e.propertyId,this.debugMode=e.debugMode||!1,this.enableSSE=!0===e.enableSSE,this.onInteractiveCampaign=e.onInteractiveCampaign,this.getWorkspaceId=e.getWorkspaceId,this.getCartState=e.getCartState}emit(e,t){const n=this.hooks.get(e);if(!n||0===n.size)return!0;let i=!0;for(const s of n)try{!1===s(t)&&(i=!1)}catch(o){this.emitError(o,{event:e})}return i}emitError(e,t){const n=this.hooks.get("error");if(n&&0!==n.size)for(const i of n)try{i({message:e instanceof Error?e.message:String(e),error:e,context:t??{}})}catch{}else this.log(`Active Reach SDK error: ${e instanceof Error?e.message:String(e)}`,"error")}register(e,t){return this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add(t),()=>{var n;null==(n=this.hooks.get(e))||n.delete(t)}}on(e,t){return this.register(e,t)}onCampaignsLoaded(e){return this.register("campaigns-loaded",e)}onCampaignWillShow(e){return this.register("campaign-will-show",e)}onCampaignShown(e){return this.register("campaign-shown",e)}onCampaignClick(e){return this.register("campaign-click",e)}onCampaignDismiss(e){return this.register("campaign-dismiss",e)}onError(e){return this.register("error",e)}async initialize(){this.isInitialized?this.log("AegisInApp already initialized"):("undefined"!=typeof localStorage&&localStorage.setItem("aegis_returning_user","1"),await this.refreshCampaigns(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisInApp initialized successfully"))}updateUserId(e){this.userId=e,this.refreshCampaigns()}updateContactId(e){var t;this.contactId=e,null==(t=this.activeWebChat)||t.updateContactId(e),this.disconnectSSE(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.refreshCampaigns()}refreshOnEvent(t,n=!1){this.isInitialized?(t&&e.KNOWN_SURFACES.has(t)&&(this.currentSurface=t),n&&t&&"page_view"!==t&&(this.currentScreen=t),this.refreshDebounceTimer&&clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=setTimeout(()=>{this.refreshDebounceTimer=void 0,this.log(`refreshOnEvent(${t}) — firing refreshCampaigns()`),this.refreshCampaigns()},e.REFRESH_DEBOUNCE_MS)):this.log(`refreshOnEvent(${t}) before initialize — ignored`)}setLocation(t){const n=t||null;n!==this.currentLocationId&&(this.currentLocationId=n,this.isInitialized&&(this.refreshDebounceTimer&&clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=setTimeout(()=>{this.refreshDebounceTimer=void 0,this.log(`setLocation(${n}) — firing refreshCampaigns()`),this.refreshCampaigns()},e.REFRESH_DEBOUNCE_MS)))}notifyConversion(t){if(!t)return void this.log("notifyConversion called with empty goalName; ignored","warn");const n=Date.now();if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(`${e.CONVERSION_STORAGE_PREFIX}${t}`,JSON.stringify({ts:n}))}catch{}this.applySuppressionFromCampaigns(n),this.log(`notifyConversion: ${t} — suppressing ${this.suppressedUntil.size} armed campaigns`)}applySuppressionFromCampaigns(e){var t,n;for(const i of this.campaigns){const o=null==(t=i.frequency)?void 0:t.suppress_after_conversion_seconds;if("number"!=typeof o||o<=0)continue;const s=(null==(n=i.frequency)?void 0:n.scope)??"session";"session"!==s&&this.log(`applySuppressionFromCampaigns: scope=${s} not implemented; degrading to session for campaign ${i.id}`,"warn");const a=e+1e3*o,r=this.suppressedUntil.get(i.id);(void 0===r||r<a)&&this.suppressedUntil.set(i.id,a)}}rehydrateSuppressionFromStorage(){if("undefined"==typeof sessionStorage)return;let t=null;try{for(let n=0;n<sessionStorage.length;n++){const i=sessionStorage.key(n);if(!i||!i.startsWith(e.CONVERSION_STORAGE_PREFIX))continue;const o=sessionStorage.getItem(i);if(!o)continue;const s=JSON.parse(o);"number"==typeof s.ts&&(t=null===t?s.ts:Math.min(t,s.ts))}}catch{return}null!==t&&this.applySuppressionFromCampaigns(t)}isSuppressed(e){const t=this.suppressedUntil.get(e);return void 0!==t&&(!(Date.now()>=t)||(this.suppressedUntil.delete(e),!1))}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID","warn");const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("in_app_campaign_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received in-app campaign update: ${t.campaign_id}`),this.refreshCampaigns()}catch(t){this.log(`Error parsing SSE event: ${t}`,"error")}}),this.eventSource.addEventListener("heartbeat",()=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",()=>{var e;this.log("SSE connection error","error"),(null==(e=this.eventSource)?void 0:e.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up","warn");this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}async refreshCampaigns(){try{const e=new URLSearchParams({device_type:this.detectDeviceType(),page_url:"undefined"!=typeof window?window.location.pathname:"/"});e.set("is_new_user",this.isNewUser()?"true":"false"),this.currentSurface&&e.set("current_surface",this.currentSurface),this.currentScreen&&e.set("current_screen",this.currentScreen),this.currentLocationId&&e.set("location_id",this.currentLocationId);const t=`${this.apiHost}/v1/in-app/active?${e.toString()}`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId),this.propertyId&&(n["X-Property-Id"]=this.propertyId);const i=this.getABAssignments();Object.keys(i).length>0&&(n["X-AB-Assignments"]=btoa(JSON.stringify(i)));const o=await fetch(t,{method:"GET",headers:n,credentials:"include"});if(!o.ok)throw new Error(`Failed to fetch campaigns: ${o.status}`);const s=await o.json();this.campaigns=Array.isArray(s)?s:[],this.processABAssignments(this.campaigns),this.rehydrateSuppressionFromStorage(),this.log(`Fetched ${this.campaigns.length} campaigns`),this.emitServedEvents(this.campaigns),this.emit("campaigns-loaded",this.campaigns),this.readyResolve(),this.tryDisplayNextCampaign(),this.renderIntoSlots(),this.renderIntoAnchors(),this.renderTokenAnchors()}catch(e){this.emitError(e,{stage:"refresh-campaigns"}),this.log(`Error refreshing campaigns: ${e}`,"error")}}emitServedEvents(t){if("undefined"!=typeof sessionStorage)for(const n of t){const t=e.SERVED_DEDUP_PREFIX+n.id;if(!sessionStorage.getItem(t)){try{sessionStorage.setItem(t,"1")}catch{}this.trackEvent(n.id,"served")}}else for(const e of t)this.trackEvent(e.id,"served")}detectDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/Mobi|Android/i.test(e)?"mobile":/iPad|Tablet/i.test(e)?"tablet":"desktop"}isNewUser(){return"undefined"==typeof localStorage||!localStorage.getItem("aegis_returning_user")}getABAssignments(){if("undefined"==typeof localStorage)return{};try{return JSON.parse(localStorage.getItem("aegis_ab_assignments")||"{}")}catch{return{}}}processABAssignments(e){if("undefined"==typeof localStorage)return;const t=this.getABAssignments();for(const n of e)n.assigned_variant_id&&(t[n.id]=n.assigned_variant_id);localStorage.setItem("aegis_ab_assignments",JSON.stringify(t))}getVariantId(e){return this.getABAssignments()[e]??void 0}tryDisplayNextCampaign(){const e=this.campaigns.find(e=>!this.displayedCampaigns.has(e.id)&&!e.client_trigger&&!this.isSuppressed(e.id));e&&this.displayCampaign(e)}matchesCurrentSurface(e){return!e.surface||0===e.surface.length||(null===this.currentSurface||e.surface.includes(this.currentSurface))}matchesCurrentScreenOrSurface(e){const t=e.target_screens;if(!t||0===t.length)return this.matchesCurrentSurface(e);const n=null!==this.currentScreen&&t.includes(this.currentScreen);return e.surface&&0!==e.surface.length?n||this.matchesCurrentSurface(e):n}renderIntoSlots(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-slot]");if(0===e.length)return;const t=new Map;for(const n of this.campaigns){if(!this.matchesCurrentScreenOrSurface(n))continue;const e=n.delivery_modes,i=n.widget_category;if(!e||!e.includes("embedded_card"))continue;if(!i)continue;const o=t.get(i);o?o.push(n):t.set(i,[n])}0!==t.size&&e.forEach(e=>{if(this.filledSlots.has(e))return;const n=e.getAttribute("data-aegis-slot");if(!n)return;const i=t.get(n);if(!i||0===i.length)return;e.querySelectorAll(":scope > [data-aegis-slot-default]").forEach(e=>e.remove());const o=parseInt(e.getAttribute("data-aegis-slot-rotate")||"0",10);o>0&&i.length>1?this.renderRotatingSlot(e,i,o):this.renderCampaignIntoSlot(i[0],e),this.filledSlots.add(e)})}renderRotatingSlot(e,t,n){const i=[];for(const c of t){const t=document.createElement("div");t.setAttribute("data-aegis-rotate-pane",c.id),t.style.display="none",e.appendChild(t),this.renderCampaignIntoSlot(c,t,{deferImpression:!0}),t.childElementCount>0?i.push({el:t,campaign:c}):t.remove()}if(0===i.length)return;const o=new Set,s=e=>{o.has(e.id)||(o.add(e.id),this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))};let a=0;if(i[0].el.style.display="",s(i[0].campaign),1===i.length)return;const r=setInterval(()=>{i[a].el.style.display="none",a=(a+1)%i.length,i[a].el.style.display="",s(i[a].campaign)},n);"undefined"!=typeof window&&window.addEventListener("beforeunload",()=>clearInterval(r),{once:!0})}renderIntoAnchors(){var e;if("undefined"!=typeof document)for(const t of this.campaigns){if(!this.matchesCurrentScreenOrSurface(t))continue;const n=t.delivery_modes;if(!n||!n.includes("embedded_card"))continue;const i=t.interactive_config,o=null==i?void 0:i.anchor,s=null==o?void 0:o.element_selector;if(!s)continue;let a=null;try{a=document.querySelector(s)}catch{a=null}if(!a){this.trackEvent(t.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:s,widget_type:t.sub_type}});continue}const r=(null==o?void 0:o.position)||"inside";let c;"before"===r||"after"===r?(c=document.createElement("div"),c.setAttribute("data-aegis-anchor-wrapper",t.id),null==(e=a.parentNode)||e.insertBefore(c,"before"===r?a:a.nextSibling)):(c=a,"replace"===r&&c.querySelectorAll(":scope > [data-aegis-slot-default]").forEach(e=>e.remove())),this.filledSlots.has(c)||(this.renderCampaignIntoSlot(t,c),this.filledSlots.add(c))}}renderTokenAnchors(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-token-data]");0!==e.length&&e.forEach(e=>{if(this.filledSlots.has(e))return;const t=e.getAttribute("data-aegis-token-data");if(!t)return;let n=null;try{n=JSON.parse(t)}catch(i){return this.log(`data-aegis-token-data: invalid JSON, skipping anchor (${i})`,"warn"),void this.filledSlots.add(e)}if(!n||!n.campaign||!n.campaign.id)return this.log("data-aegis-token-data: missing `campaign` in payload, skipping","warn"),void this.filledSlots.add(e);this.renderCampaignIntoSlot(n.campaign,e,{submitUrl:n.submit_url}),this.filledSlots.add(e)})}renderCampaignIntoSlot(e,t,n){if(!this.emit("campaign-will-show",e))return void this.log(`slot campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id),this.addAnimationStyles();const i=e.interactive_config||{},{bg:o,text:s}=this._surfacePalette(e),a=null==n?void 0:n.submitUrl,r=Array.isArray(i.form_fields)?i.form_fields:null;let c=!1;if(r&&r.length>0)return c=this.renderFormSlot(e,r,o,s,t),c?void((null==n?void 0:n.deferImpression)||(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))):void this.displayedCampaigns.delete(e.id);switch(e.sub_type){case"star_rating":c=this.renderStarRatingSlot(e,i,o,s,t,a);break;case"nps_survey":c=this.renderNPSSurveySlot(e,i,o,s,t,a);break;case"spin_wheel":c=this.renderSpinWheelSlot(e,i,o,s,t);break;case"quick_poll":c=this.renderQuickPollSlot(e,i,o,s,t);break;case"carousel_cards":c=this.renderCarouselCardsSlot(e,i,o,s,t);break;case"countdown_offer":c=this.renderCountdownSlot(e,i,o,s,t);break;case"scratch_card":c=this.renderScratchCardSlot(e,i,o,s,t);break;case"custom_html":c=this.renderCustomHtmlSlot(e,i,o,s,t);break;case"stories":c=re(this.buildRenderContext(e),t);break;case"video":c=function(e,t){if(!t)return ke(e),!0;e.addAnimationStyles();const n=Ce(e),i=document.createElement("div");i.className="aegis-in-app-video-banner",i.setAttribute("data-campaign-id",e.campaign.id),i.style.cssText='width:100%;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';const o=we(e,n.aspect,n.autoplay,n.loop);if(n.overlayCaption){const t=_e(e,n.accent,!0);t&&o.appendChild(t)}if(i.appendChild(o),!n.overlayCaption){const t=_e(e,n.accent,!1);t&&i.appendChild(t)}return t.appendChild(i),!0}(this.buildRenderContext(e),t);break;case"progress_bar":c=function(e,t){const n=J(e,!0);return!!n&&(t.appendChild(n),!0)}(this.buildRenderContext(e),t);break;case"quiz":c=this.renderQuizSlot(e,i,o,s,t),c||(c=this.renderGenericCardSlot(e,i,o,s,t));break;default:c=this.renderGenericCardSlot(e,i,o,s,t)}c&&((null==n?void 0:n.deferImpression)||(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)))}renderStarRatingSlot(e,t,n,i,o,s){const a=this._slotStyle(e),r=this._wrapInSlotCard("aegis-in-app-rating-card",e.id,n,i,a.radius);return r.appendChild(this._buildStarRatingBody(e,t,i,"slot",s,a)),o.appendChild(r),!0}renderNPSSurveySlot(e,t,n,i,o,s){const a=this._slotStyle(e),r=this._wrapInSlotCard("aegis-in-app-nps-card",e.id,n,i,a.radius);return r.appendChild(this._buildNPSSurveyBody(e,t,i,"slot",s,a)),o.appendChild(r),!0}renderGenericCardSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-generic-card",e.id,n,i,s.radius),r=e,c="string"==typeof r.image_url?r.image_url:"",d="string"==typeof t.coupon_code?t.coupon_code:"",l="string"==typeof r.button_text?r.button_text:"",p="string"==typeof r.action_url?r.action_url:"";if(c){const e=document.createElement("img");e.src=c,e.alt="",e.style.cssText="width: 100%; height: 96px; object-fit: cover; display: block;",a.appendChild(e)}const h=document.createElement("div");if(h.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 6px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,h.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 11px; opacity: 0.85; line-height: 1.35;",t.textContent=e.body,h.appendChild(t)}if(d){const e=document.createElement("span");e.style.cssText=`align-self: flex-start; border: 1px dashed ${i}66; border-radius: 6px; padding: 2px 8px; font-family: monospace; font-size: 11px; letter-spacing: 0.04em;`,e.textContent=d,h.appendChild(e)}if(l){const t=document.createElement("button");t.textContent=l,t.style.cssText=`margin-top: 2px; align-self: flex-start; padding: 8px 14px; border-radius: ${s.btnRadius??9}px; border: none; background: ${i}; color: ${n}; font-size: 13px; font-weight: 600; cursor: pointer;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),p&&window.open(p,"_blank","noopener")}),h.appendChild(t)}return a.appendChild(h),o.appendChild(a),!0}renderFormSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-form-card",e.id,n,i,s.radius);return a.appendChild(this._buildFormBody(e,t,n,i,s)),o.appendChild(a),!0}_buildFormBody(e,t,n,i,o){const s=document.createElement("div");if(s.style.cssText=`padding: ${(null==o?void 0:o.padY)??16}px ${(null==o?void 0:o.padX)??16}px; display: flex; flex-direction: column; gap: 10px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 14px; font-weight: ${(null==o?void 0:o.weight)??"700"};`,t.textContent=e.title,s.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 12px; opacity: 0.8; margin-top: -4px;",t.textContent=e.body,s.appendChild(t)}const a=new Map,r=new Set,c=`padding: 9px 11px; border-radius: 9px; border: 1px solid ${i}33; background: ${i}0d; color: ${i}; font-size: 13px; width: 100%; box-sizing: border-box; font-family: inherit;`;for(const p of t){const e="string"==typeof p.key?p.key:null;if(!e)continue;const t="string"==typeof p.type?p.type:"text",n="string"==typeof p.label&&p.label||e,o=!0===p.required;o&&r.add(e);const d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 4px;";const l=document.createElement("label");let h;if(l.textContent=n+(o?" *":""),l.style.cssText=`font-size: 11px; font-weight: 600; opacity: 0.8; color: ${i};`,d.appendChild(l),"select"===t){const e=document.createElement("select");e.style.cssText=c;const t=document.createElement("option");t.value="",t.textContent="string"==typeof p.placeholder&&p.placeholder||"Select…",e.appendChild(t),(Array.isArray(p.options)?p.options:[]).forEach(t=>{const n=document.createElement("option");n.value=t,n.textContent=t,e.appendChild(n)}),h=e}else if("textarea"===t){const e=document.createElement("textarea");e.className="aegis-field",e.rows=3,e.placeholder="string"==typeof p.placeholder&&p.placeholder||n,e.style.cssText=`${c} resize: vertical;`,h=e}else{const e=document.createElement("input");e.className="aegis-field",e.type="email"===t?"email":"date"===t?"date":"tel"===t?"tel":"number"===t?"number":"text",e.placeholder="string"==typeof p.placeholder&&p.placeholder||n,e.style.cssText=c,h=e}o&&(h.required=!0),a.set(e,h),d.appendChild(h),s.appendChild(d)}const d=document.createElement("button"),l=e;return d.textContent="string"==typeof l.button_text&&l.button_text||"Save",d.style.cssText=`margin-top: 4px; padding: 10px 16px; border-radius: ${(null==o?void 0:o.btnRadius)??10}px; border: none; background: ${i}; color: ${n}; font-size: 14px; font-weight: 600; cursor: pointer;`,d.addEventListener("click",()=>{var t;const n={};let o=!0;for(const[e,s]of a){const t=(s.value||"").trim();r.has(e)&&!t?(o=!1,s.style.borderColor="#e11d48"):s.style.borderColor=`${i}33`,t&&(n[e]=t)}if(!o||0===Object.keys(n).length)return;for(this.submitFormResponse(e,n),this.trackEvent(e.id,"clicked",{meta:{fields:Object.keys(n)}});s.firstChild;)s.removeChild(s.firstChild);const c=s.parentElement;c&&(c.style.overflow="visible"),s.style.position="relative",s.style.minHeight="176px",s.style.alignItems="center",s.style.justifyContent="center";const d=document.createElement("div");d.style.cssText="padding: 8px 0; font-size: 13px; font-weight: 600; text-align: center;",d.textContent="string"==typeof(null==(t=e.interactive_config)?void 0:t.thank_you_message)?e.interactive_config.thank_you_message:"✓ Thanks — your details are saved.",s.appendChild(d),this._playReaction(s,"affirm","check.json",e.interactive_config)}),s.appendChild(d),s}async submitFormResponse(e,t){if(this.organizationId)try{const n={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(n["X-Contact-ID"]=this.contactId);const i=e.assigned_variant_id,o=await fetch(`${this.apiHost}/v1/in-app/responses`,{method:"POST",headers:n,keepalive:!0,body:JSON.stringify({campaign_id:e.id,response_type:"form",contact_id:this.contactId,user_id:this.userId,variant_id:i,platform:"web",payload:{fields:t}})});o.ok||this.log(`submitFormResponse failed (${o.status})`,"warn")}catch(n){this.log(`submitFormResponse error: ${n}`,"warn")}else this.log("submitFormResponse: no organizationId — cannot submit","warn")}async submitWidgetResponse(e,t,n){if(!this.organizationId)return null;try{const i={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(i["X-Contact-ID"]=this.contactId);const o=e.assigned_variant_id,s=await fetch(`${this.apiHost}/v1/in-app/responses`,{method:"POST",headers:i,keepalive:!0,body:JSON.stringify({campaign_id:e.id,response_type:t,contact_id:this.contactId,user_id:this.userId,variant_id:o,platform:"web",payload:n})});return s.ok?await s.json().catch(()=>null):(this.log(`submitWidgetResponse ${t} failed (${s.status})`,"warn"),null)}catch(i){return this.log(`submitWidgetResponse ${t} error: ${i}`,"warn"),null}}renderSpinWheelSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-spin-card",e.id,n,i,s.radius),r=(Array.isArray(t.segments)?t.segments:[]).filter(e=>"string"==typeof e.label&&e.label),c=r.map(e=>e.label),d=c.length>=2?c.length:8,l=e=>!!r[e]&&"no_prize"===String(r[e].prize_type||"").toLowerCase(),p=t.already_won&&"object"==typeof t.already_won?t.already_won:null,h=Array.from({length:d},(e,t)=>{const n=r[t]&&"number"==typeof r[t].probability?r[t].probability:NaN;return Number.isFinite(n)&&n>0?n:0}),u=h.reduce((e,t)=>e+t,0),g=u>0?h:Array.from({length:d},()=>1),m=u>0?u:d,f="equal"===("string"==typeof t.spin_slice_sizing?t.spin_slice_sizing:"proportional")?Array.from({length:d},()=>360/d):g.map(e=>e/m*360),x=[];f.reduce((e,t,n)=>(x[n]=e,e+t),0);const y=e=>x[e]+f[e]/2,b=Array.from({length:d},(e,t)=>`${(e=>(r[e]&&"string"==typeof r[e].color?r[e].color:"")||(e%2==0?i:`${i}40`))(t)} ${x[t]}deg ${x[t]+f[t]}deg`).join(", "),v=e=>"string"==typeof t[e]?t[e]:"",w=v("spin_mode")||"both",_=v("spin_idle_animation")||"shimmer",C=v("spin_win_reveal")||"inline",k=!1!==t.spin_haptics_enabled;let E=!1!==t.spin_sound_enabled;const S=v("spin_pointer_color")||"#ffffff",T=v("spin_hub_image_url"),$=v("wheel_background_url"),I=v("pointer_image_url"),z=e=>/^https?:\/\//i.test(e),A=()=>"undefined"!=typeof performance&&performance.now?performance.now():Date.now();let L=0;if("undefined"!=typeof document&&!document.getElementById("aegis-spin-kf")){const e=document.createElement("style");e.id="aegis-spin-kf",e.textContent="@keyframes aegisSpinWobble{0%,100%{transform:rotate(-5deg)}50%{transform:rotate(5deg)}}@keyframes aegisSpinSheen{0%{transform:translateX(-130%)}100%{transform:translateX(360%)}}@keyframes aegisSpinRevealIn{0%{opacity:0;transform:scale(0.86)}100%{opacity:1;transform:scale(1)}}",document.head.appendChild(e)}let M=null;const R=()=>{if(!E)return null;try{if(!M){const e=window.AudioContext||window.webkitAudioContext;if(!e)return null;M=new e}return"suspended"===M.state&&M.resume(),M}catch{return null}},P=(e,t,n="triangle",i=.06)=>{const o=R();if(!o)return;const s=o.createOscillator(),a=o.createGain();s.type=n,s.frequency.value=e,a.gain.setValueAtTime(i,o.currentTime),a.gain.exponentialRampToValueAtTime(1e-4,o.currentTime+t/1e3),s.connect(a),a.connect(o.destination),s.start(),s.stop(o.currentTime+t/1e3)},D=e=>{var t;if(k)try{null==(t=navigator.vibrate)||t.call(navigator,e)}catch{}},N=document.createElement("div");if(N.style.cssText=`padding: ${s.padY??22}px ${s.padX??20}px 20px; display: flex; flex-direction: column; align-items: center; gap: 16px;`,e.title){const t=document.createElement("div");t.style.cssText="font-size: 18px; font-weight: 800; letter-spacing: -0.01em; text-align: center; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;",t.textContent=e.title,N.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 12.5px; opacity: 0.82; text-align: center; margin-top: -8px; line-height: 1.35;",t.textContent=e.body,N.appendChild(t)}const F=document.createElement("div");F.style.cssText="position: relative; width: 172px; height: 172px; filter: drop-shadow(0 10px 22px rgba(0,0,0,0.30));";const O=document.createElement("div");O.style.cssText=I?`position: absolute; left: 50%; top: -10px; transform: translateX(-50%); transform-origin: 50% 0; width: 26px; height: 30px; background: center / contain no-repeat url("${I}"); z-index: 5; filter: drop-shadow(0 2px 2px rgba(0,0,0,0.35));`:`position: absolute; left: 50%; top: -7px; transform: translateX(-50%); transform-origin: 50% 0; width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent; border-top: 16px solid ${S}; z-index: 5; filter: drop-shadow(0 2px 2px rgba(0,0,0,0.35));`;const B=document.createElement("div"),U=$?`center / cover no-repeat url("${$}")`:`conic-gradient(${b})`;B.style.cssText=`position: relative; width: 172px; height: 172px; border-radius: 50%; border: 5px solid #ffffff; box-shadow: 0 0 0 2px ${i}2e, inset 0 0 22px rgba(0,0,0,0.20); background: ${U}; overflow: hidden; will-change: transform; touch-action: none; cursor: ${"button"===w?"default":"grab"};`,"wobble"===_&&(B.style.animation="aegisSpinWobble 3s ease-in-out infinite"),$||x.forEach(e=>{const t=document.createElement("div");t.style.cssText=`position: absolute; left: 50%; top: 0; width: 1.5px; height: 50%; background: rgba(255,255,255,0.55); transform-origin: bottom center; transform: translateX(-50%) rotate(${e}deg); pointer-events: none;`,B.appendChild(t)});$||c.forEach((e,t)=>{const n=y(t),i=r[t]&&"string"==typeof r[t].image_url?r[t].image_url:"";if(i&&z(i)){const t=n>180&&n<360,o=Math.max(18,Math.min(40,34.72)),s=document.createElement("img");return s.src=i,s.alt=e||"",s.style.cssText=`position: absolute; left: 50%; top: 50%; width: ${o}px; height: ${o}px; object-fit: contain; transform: translate(-50%, -50%) rotate(${n}deg) translateY(-50px) rotate(${t?90:-90}deg); filter: drop-shadow(0 1px 3px rgba(0,0,0,0.55)); pointer-events: none;`,void B.appendChild(s)}const o=r[t]&&"string"==typeof r[t].icon?r[t].icon:"",s=.6*(100*Math.sin(f[t]*Math.PI/180/2)),a=56/Math.max(4,.62*e.length+(o?1.6:0)),c=Math.max(7,Math.min(13,Math.floor(Math.min(s,a)))),d=n>180&&n<360,l=d?90:-90,p=document.createElement("div");if(p.style.cssText=`position: absolute; left: 50%; top: 50%; width: 56px; transform: translate(-50%, -50%) rotate(${n}deg) translateY(-50px) rotate(${l}deg); display: flex; flex-direction: ${d?"row-reverse":"row"}; align-items: center; justify-content: center; gap: 4px; white-space: nowrap; pointer-events: none;`,o)if(z(o)){const e=document.createElement("img");e.src=o,e.alt="",e.style.cssText=`width: ${c+6}px; height: ${c+6}px; object-fit: contain; flex: 0 0 auto; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.5));`,p.appendChild(e)}else{const e=document.createElement("span");e.textContent=o,e.style.cssText=`font-size: ${c+4}px; line-height: 1; flex: 0 0 auto;`,p.appendChild(e)}const h=document.createElement("span");h.textContent=e,h.style.cssText=`white-space: nowrap; line-height: 1.05; font-size: ${c}px; font-weight: 900; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif; letter-spacing: 0.2px; text-transform: uppercase; color: #fff; text-shadow: 0 1px 3px rgba(0,0,0,0.65), 0 0 1px rgba(0,0,0,0.9); -webkit-font-smoothing: antialiased;`,p.appendChild(h),B.appendChild(p)});const W=document.createElement("div");W.style.cssText="position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 2; background: radial-gradient(circle at 50% 22%, rgba(255,255,255,0.30), rgba(255,255,255,0.04) 42%, transparent 62%);";let j=null;if("shimmer"===_){const e=document.createElement("div");e.style.cssText="position: absolute; inset: 0; border-radius: 50%; overflow: hidden; pointer-events: none; z-index: 3;";const t=document.createElement("div");t.style.cssText="position: absolute; top: -25%; left: 0; width: 36%; height: 150%; transform: skewX(-12deg); background: linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent); animation: aegisSpinSheen 2.8s ease-in-out infinite; animation-delay: 0.5s;",e.appendChild(t),j=e}const q=document.createElement("div");if(q.style.cssText="position: absolute; left: 50%; top: 50%; width: 40px; height: 40px; transform: translate(-50%, -50%); border-radius: 50%; background: radial-gradient(circle at 35% 30%, #ffffff, #e9edf5); border: 3px solid #fff; box-shadow: 0 3px 8px rgba(0,0,0,0.30); z-index: 4; overflow: hidden; display: flex; align-items: center; justify-content: center;",T){const e=document.createElement("canvas");e.width=40,e.height=40,e.style.cssText="width: 100%; height: 100%;";const t=e.getContext("2d"),n=new Image;n.crossOrigin="anonymous",n.onload=()=>{if(!t)return;const e=n.width/n.height||1;let i=32,o=32;e>1?o=32/e:i=32*e,t.drawImage(n,(40-i)/2,(40-o)/2,i,o),t.globalCompositeOperation="source-in",t.fillStyle="#5b626e",t.fillRect(0,0,40,40)},n.onerror=()=>{},n.src=T,q.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`width: 11px; height: 11px; border-radius: 50%; background: ${n};`,q.appendChild(e)}F.appendChild(O),F.appendChild(B),F.appendChild(W),j&&F.appendChild(j),F.appendChild(q),N.appendChild(F),a.style.position||(a.style.position="relative");const H=document.createElement("div");if(H.style.cssText="font-size: 14px; font-weight: 800; min-height: 20px; text-align: center; letter-spacing: 0.2px;",!1!==t.spin_sound_enabled){const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Toggle sound"),e.textContent=E?"🔊":"🔇",e.style.cssText="position: absolute; top: 10px; left: 12px; background: transparent; border: none; font-size: 15px; cursor: pointer; opacity: 0.65; z-index: 6; line-height: 1;",e.addEventListener("click",()=>{E=!E,e.textContent=E?"🔊":"🔇"}),a.appendChild(e)}const V=document.createElement("button");V.textContent=e.button_text||"Spin the wheel",V.style.cssText=`padding: 12px 32px; border-radius: 999px; border: none; background: #ffffff; color: ${n}; font-size: 15px; font-weight: 800; letter-spacing: 0.2px; cursor: pointer; box-shadow: 0 6px 16px rgba(0,0,0,0.22); transition: transform 0.15s, box-shadow 0.15s; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;`,V.addEventListener("mouseenter",()=>{V.disabled||(V.style.transform="translateY(-1px)",V.style.boxShadow="0 9px 22px rgba(0,0,0,0.28)")}),V.addEventListener("mouseleave",()=>{V.disabled||(V.style.transform="translateY(0)",V.style.boxShadow="0 6px 16px rgba(0,0,0,0.22)")});let X=!1,K=!1,Y=-1;const Q=()=>{try{null==j||j.remove()}catch{}B.style.animation=""};let G=0,J=0,Z=0,ee=0;const te=()=>{Z+=.18*-J,Z*=.7,J+=Z,Math.abs(J)>.06||Math.abs(Z)>.06?(O.style.transform=`translateX(-50%) rotate(${J.toFixed(2)}deg)`,ee=requestAnimationFrame(te)):(J=0,Z=0,O.style.transform="translateX(-50%) rotate(0deg)",ee=0)},ne=e=>{const t=(e=>{const t=(e%360+360)%360;for(let n=0;n<d;n++)if(t>=x[n]&&t<x[n]+f[n])return n;return d-1})(((360-e%360)%360+360)%360);t!==Y&&(Y=t,P(1180,26,"square",.035),D(5),Z+=Math.min(9,1.4+.5*G),ee||(ee=requestAnimationFrame(te)))},ie=(e,t,n)=>{const i=L,o=e-i,s=A();let a=i;const r=()=>{const c=Math.min(1,(A()-s)/t);L=i+o*(e=>1-Math.pow(1-e,3))(c),G=Math.abs(L-a),a=L,B.style.transform=`rotate(${L}deg)`,ne(L),c<1?requestAnimationFrame(r):(B.style.transition="transform 0.18s ease-out",B.style.transform=`rotate(${e-2}deg)`,window.setTimeout(()=>{B.style.transform=`rotate(${e}deg)`,L=e,window.setTimeout(()=>{B.style.transition="",n()},180)},70))};requestAnimationFrame(r)},oe=t=>{const o=document.createElement("div");o.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; padding: 22px; text-align: center; background: ${n}; color: ${i}; border-radius: inherit; animation: aegisSpinRevealIn 0.4s cubic-bezier(0.16,0.86,0.28,1); z-index: 7;`;const s=document.createElement("div");s.textContent="🎉 You won",s.style.cssText="font-size: 13px; font-weight: 700; letter-spacing: 0.3px; opacity: 0.8;";const r=document.createElement("div");if(r.textContent=t.label,r.style.cssText="font-size: 24px; font-weight: 900; letter-spacing: -0.02em; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;",o.appendChild(s),o.appendChild(r),t.code){const e=document.createElement("button");e.type="button",e.textContent=`${t.code} ⧉`,e.style.cssText=`margin-top: 4px; padding: 9px 16px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 14px; letter-spacing: 1px; cursor: pointer;`,e.addEventListener("click",()=>{var n;try{null==(n=navigator.clipboard)||n.writeText(t.code),e.textContent="Copied ✓"}catch{}}),o.appendChild(e)}else if("freebie"===t.kind){const e=document.createElement("div");e.textContent="🎟️ Show this screen to claim",e.style.cssText="margin-top: 2px; font-size: 12.5px; font-weight: 600; opacity: 0.85;",o.appendChild(e)}const c=document.createElement("button");c.type="button",c.textContent="Awesome!",c.style.cssText=`margin-top: 6px; padding: 11px 28px; border-radius: 999px; border: none; background: ${i}; color: ${n}; font-weight: 800; font-size: 14px; cursor: pointer;`,c.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),o.style.transition="opacity 0.25s ease",o.style.opacity="0",window.setTimeout(()=>o.remove(),250)}),o.appendChild(c),a.appendChild(o)},se=e=>{if(K=!0,e.won?([523,659,784,1047].forEach((e,t)=>window.setTimeout(()=>P(e,170,"sine",.07),105*t)),D([0,35,25,35,25,90]),this._playReaction(a,"celebrate",void 0,t)):(P(320,220,"sine",.05),D(18),this._playReaction(a,"empathize",void 0,t)),"takeover"===C&&e.won)oe(e);else if(e.label&&e.code){H.textContent="";const t=document.createElement("span");t.textContent=`${e.label} — `;const n=document.createElement("button");n.type="button",n.textContent=`${e.code} ⧉`,n.style.cssText=`padding: 2px 8px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 12px; letter-spacing: 0.5px; cursor: pointer;`,n.addEventListener("click",()=>{var t;try{null==(t=navigator.clipboard)||t.writeText(e.code),n.textContent="Copied ✓"}catch{}}),H.appendChild(t),H.appendChild(n)}else H.textContent=e.label||"Thanks for playing!";V.style.transition="opacity 0.3s ease",V.style.opacity="0",V.style.pointerEvents="none",window.setTimeout(()=>{V.style.display="none"},320)},ae=t=>{if(X||K)return;X=!0,Q(),V.disabled=!0,V.style.opacity="0.6",V.style.transform="scale(0.97)",H.textContent="",this.trackEvent(e.id,"clicked"),R();const n=Math.min(2.4,Math.max(.25,t||.6)),i=Math.round(3+2*n),o=Math.floor(Math.random()*d),s=.5+.35*n;let a=!0,p=!1,h=A();const u=()=>{if(!a)return;const e=A(),t=s*(e-h);h=e,L+=t,G=t,B.style.transform=`rotate(${L}deg)`,ne(L),requestAnimationFrame(u)};requestAnimationFrame(u);const g=(e,t)=>{if(p)return;p=!0,a=!1;const n=y(e);let o=L-(L%360+360)%360+((360-n)%360+360)%360+360*i;o<=L+360&&(o+=360);const r=3*(o-L)/Math.max(.05,s),c=Math.min(4200,Math.max(2300,r));ie(o,c,()=>{X=!1,se(t)})};this.submitWidgetResponse(e,"spin",{segment_index:o}).then(e=>{const t=e&&e.prize?e.prize:null;let n=o;t&&"number"==typeof t.segment_index&&(n=t.segment_index%d);const i=t&&"string"==typeof t.prize_label?t.prize_label:c[n]||"",s=t&&"string"==typeof t.coupon_code?t.coupon_code:"",a=t&&"string"==typeof t.prize_type?t.prize_type.toLowerCase():r[n]&&"string"==typeof r[n].prize_type?String(r[n].prize_type).toLowerCase():"",p=t?"no_prize"===String(t.prize_type||"").toLowerCase():l(n);g(n,{label:i,code:s,won:!!i&&!p,kind:a})}).catch(()=>{}),window.setTimeout(()=>{if(p)return;const e=(()=>{for(let e=0;e<d;e++)if(l(e))return e;return o})();g(e,{label:c[e]||"",code:"",won:!1,kind:r[e]&&"string"==typeof r[e].prize_type?String(r[e].prize_type).toLowerCase():"no_prize"})},8e3)};if("button"===w||"both"===w?V.addEventListener("click",()=>ae(.7)):V.style.display="none","drag"===w||"both"===w){let e=!1,t=0,n=0,i=0,o=0,s=0;const a=e=>{const t=B.getBoundingClientRect(),n=t.left+t.width/2,i=t.top+t.height/2;return 180*Math.atan2(e.clientY-i,e.clientX-n)/Math.PI};B.addEventListener("pointerdown",r=>{if(!X&&!K){e=!0,t=a(r),n=L,i=t,o=A(),s=0,B.style.cursor="grabbing",Q();try{B.setPointerCapture(r.pointerId)}catch{}}}),B.addEventListener("pointermove",r=>{if(!e)return;const c=a(r),d=L;L=n+(c-t),G=Math.abs(L-d),B.style.transform=`rotate(${L}deg)`,ne(L);const l=A(),p=l-o;if(p>0){let e=c-i;e>180&&(e-=360),e<-180&&(e+=360),s=e/p,i=c,o=l}});const r=t=>{if(!e)return;e=!1,B.style.cursor="grab";try{B.releasePointerCapture(t.pointerId)}catch{}const n=Math.abs(s);n>.15&&ae(n)};B.addEventListener("pointerup",r),B.addEventListener("pointercancel",r)}if(N.appendChild(H),N.appendChild(V),a.appendChild(N),o.appendChild(a),p){Q();const e=String(p.prize_type||"").toLowerCase();se({label:String(p.label||""),code:String(p.coupon_code||""),won:"no_prize"!==e,kind:e})}return!0}renderQuickPollSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-poll-card",e.id,n,i,s.radius),r=Array.isArray(t.poll_options)?t.poll_options.filter(e=>"string"==typeof e):[],c=document.createElement("div");if(c.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 6px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,c.appendChild(t)}const d=[];return r.forEach((n,o)=>{const l=document.createElement("button");l.style.cssText=`position: relative; overflow: hidden; text-align: left; padding: 8px 10px; border-radius: ${s.btnRadius??8}px; border: 1px solid ${i}40; background: transparent; color: ${i}; font-size: 12px; cursor: pointer; transition: border-color 0.2s ease;`;const p=document.createElement("span");p.style.cssText="position: relative; z-index: 1; display: flex; justify-content: space-between; gap: 8px;";const h=document.createElement("span");h.textContent=n;const u=document.createElement("span");u.style.cssText="font-weight: 700; opacity: 0; transition: opacity 0.3s ease;",p.appendChild(h),p.appendChild(u),l.appendChild(p),l.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),d.forEach(e=>e.disabled=!0),this._paintPollResult(d,r,o,null,i),this.addAnimationStyles(),this.submitWidgetResponse(e,"poll",{option_index:o,option_label:n}).then(e=>{const t=this._readPollDistribution(e,r.length);t&&this._paintPollResult(d,r,o,t,i)}),this._playReaction(a,"affirm","check.json",t)}),d.push(l),c.appendChild(l)}),a.appendChild(c),o.appendChild(a),!0}_readPollDistribution(e,t){if(!e)return null;const n=e.results??e.distribution??e.tallies;if(!Array.isArray(n)||n.length!==t)return null;const i=n.map(e=>"number"==typeof e&&isFinite(e)&&e>=0?e:0);return i.some(e=>e>0)?i:null}_paintPollResult(e,t,n,i,o){const s=i&&i.reduce((e,t)=>e+t,0)||1;e.forEach((e,t)=>{const a=i?Math.round(i[t]/s*100):t===n?100:0;let r=e.querySelector(".aegis-poll-fill");r||(r=document.createElement("span"),r.className="aegis-poll-fill",r.style.cssText=`position: absolute; inset: 0 auto 0 0; z-index: 0; background: ${t===n?o:o+"22"}; opacity: ${t===n?"0.16":"0.1"};`,e.insertBefore(r,e.firstChild)),r.style.setProperty("--pct",`${a}%`),r.style.animation="aegisPollFill 0.5s ease forwards",t===n&&(e.style.borderColor=o);const c=e.querySelector("span > span:last-child");c&&i?(c.textContent=`${a}%`,c.style.opacity="0.8"):c&&t===n&&(c.textContent="✓",c.style.opacity="0.8")})}renderCarouselCardsSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-carousel-card",e.id,n,i,s.radius),r=Array.isArray(t.cards)?t.cards:[];if(e.title){const t=document.createElement("div");t.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px 0; font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,a.appendChild(t)}const c=document.createElement("div");return c.style.cssText=`display: flex; gap: 8px; overflow-x: auto; scroll-snap-type: x mandatory; padding: ${s.padY??12}px ${s.padX??12}px;`,r.forEach((t,o)=>{const a=document.createElement("div"),r="string"==typeof t.cta_url?t.cta_url:"";a.style.cssText=`flex: 0 0 auto; width: 150px; scroll-snap-align: start; background: ${i}0a; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; gap: 6px; cursor: ${r?"pointer":"default"};`;const d="string"==typeof t.video_url?t.video_url:"",l="string"==typeof t.image_url?t.image_url:"";if(d){const e=document.createElement("video");e.src=d,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="width: 100%; height: 90px; object-fit: cover; display: block;",a.appendChild(e)}else if(l){const e=document.createElement("img");e.src=l,e.alt="",e.loading="lazy",e.style.cssText="width: 100%; height: 90px; object-fit: cover; display: block;",a.appendChild(e)}const p=document.createElement("div");if(p.style.cssText="padding: 0 8px 8px; display: flex; flex-direction: column; gap: 4px;","string"==typeof t.title&&t.title){const e=document.createElement("div");e.style.cssText="font-size: 12px; font-weight: 600; line-height: 1.3;",e.textContent=t.title,p.appendChild(e)}if("string"==typeof t.body&&t.body){const e=document.createElement("div");e.style.cssText="font-size: 10.5px; opacity: 0.72; line-height: 1.3;",e.textContent=t.body,p.appendChild(e)}const h="string"==typeof t.cta_text?t.cta_text:"";if(h&&r){const t=document.createElement("button");t.textContent=h,t.style.cssText=`margin-top: auto; align-self: flex-start; background: ${i}; color: ${n}; border: none; padding: 5px 10px; border-radius: ${s.btnRadius??999}px; font-size: 11px; font-weight: 600; cursor: pointer;`;const c=t=>{t.stopPropagation(),this.trackEvent(e.id,"clicked",{stepId:`card_${o}`}),window.open(r,"_blank","noopener")};t.addEventListener("click",c),a.addEventListener("click",c),p.appendChild(t)}a.appendChild(p),c.appendChild(a)}),a.appendChild(c),o.appendChild(a),!0}renderCountdownSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-countdown-card",e.id,n,i,s.radius),r=document.createElement("div");if(r.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 8px; align-items: center; text-align: center;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,r.appendChild(t)}const c=document.createElement("div");c.style.cssText="font-size: 11px; opacity: 0.75;",c.textContent=t.countdown_label||"Ends in",r.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 6px; justify-content: center;";const l=()=>{const e=document.createElement("span");return e.style.cssText=`padding: 6px 9px; border-radius: 8px; font-size: 18px; font-weight: 700; font-family: ui-monospace, monospace; background: ${i}1a; transition: background 0.3s ease, color 0.3s ease;`,e.textContent="00",e},p=l(),h=l(),u=l();[p,":",h,":",u].forEach(e=>{if(":"===e){const e=document.createElement("span");e.style.cssText="font-size: 18px; font-weight: 700; align-self: center;",e.textContent=":",d.appendChild(e)}else d.appendChild(e)}),r.appendChild(d);const g=t.countdown_target,m=g?new Date(g).getTime():Date.now()+6e5;let f=!1;const x=()=>{if(!document.body.contains(a))return;const n=Math.max(0,m-Date.now()),i=Math.floor(n/36e5),o=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);p.textContent=String(i).padStart(2,"0"),h.textContent=String(o).padStart(2,"0"),u.textContent=String(s).padStart(2,"0"),n>0&&n<=6e4&&!f&&(f=!0,[p,h,u].forEach(e=>{e.style.boxShadow="0 0 0 2px #ef4444",e.style.animation="aegisUrgencyPulse 1s ease-in-out infinite"})),n>0?requestAnimationFrame(x):y||(y=!0,this.submitWidgetResponse(e,"countdown",{state:"expired"}),this._playReaction(a,"celebrate","alarm-clock.json",t))};let y=!1;if(this.addAnimationStyles(),x(),e.body){const t=document.createElement("div");t.style.cssText="font-size: 11px; opacity: 0.8;",t.textContent=e.body,r.appendChild(t)}if(e.button_text){const t=document.createElement("button");t.textContent=e.button_text,t.style.cssText=`margin-top: 2px; background: ${i}; color: ${n}; border: none; padding: 7px 14px; border-radius: ${s.btnRadius??999}px; font-size: 12px; font-weight: 600; cursor: pointer;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),this.submitWidgetResponse(e,"countdown",{state:"engaged"});const t=e.action_url;t&&window.open(t,"_blank","noopener")}),r.appendChild(t)}return a.appendChild(r),o.appendChild(a),!0}renderScratchCardSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-scratch-card",e.id,n,i,s.radius);a.style.position||(a.style.position="relative");const r=(e,n)=>"number"==typeof t[e]?t[e]:n,c=e=>"string"==typeof t[e]?t[e]:"",d=Math.min(1,Math.max(.1,r("scratch_threshold_pct",.5))),l=Math.min(60,Math.max(8,r("scratch_brush_radius",22))),p=!1!==t.scratch_idle_shimmer,h=c("scratch_win_reveal")||"inline",u=!1!==t.scratch_haptics_enabled;let g=!1!==t.scratch_sound_enabled;const m=c("reveal_image_url"),f=c("scratch_foil_image_url"),x=Array.isArray(t.prize_pool)?t.prize_pool:[],y=e=>/^https?:\/\//i.test(e),b=x.find(e=>"string"==typeof e.prize_type&&"no_prize"!==e.prize_type.toLowerCase())||null;if("undefined"!=typeof document&&!document.getElementById("aegis-scratch-kf")){const e=document.createElement("style");e.id="aegis-scratch-kf",e.textContent="@keyframes aegisScratchSheen{0%{transform:translateX(-140%) skewX(-12deg)}100%{transform:translateX(260%) skewX(-12deg)}}@keyframes aegisScratchPop{0%{opacity:0;transform:scale(0.8)}100%{opacity:1;transform:scale(1)}}@keyframes aegisScratchDust{0%{opacity:0.9;transform:translate(0,0) scale(1)}100%{opacity:0;transform:translate(var(--dx),var(--dy)) scale(0.4)}}",document.head.appendChild(e)}let v=null;const w=()=>{if(!g)return null;try{if(!v){const e=window.AudioContext||window.webkitAudioContext;if(!e)return null;v=new e}return"suspended"===v.state&&v.resume(),v}catch{return null}};let _=0;const C=(e,t)=>{const n=w();n&&e.forEach((e,i)=>window.setTimeout(()=>{const i=n.createOscillator(),o=n.createGain();i.type="sine",i.frequency.value=e,o.gain.setValueAtTime(t,n.currentTime),o.gain.exponentialRampToValueAtTime(1e-4,n.currentTime+.22),i.connect(o),o.connect(n.destination),i.start(),i.stop(n.currentTime+.22)},100*i))},k=document.createElement("div");if(k.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 8px; align-items: center; text-align: center;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,k.appendChild(t)}const E=document.createElement("div");if(E.style.cssText="font-size: 11px; opacity: 0.7;",E.textContent=c("scratch_hint")||"Scratch to reveal your prize",k.appendChild(E),!1!==t.scratch_sound_enabled){const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Toggle sound"),e.textContent=g?"🔊":"🔇",e.style.cssText="position: absolute; top: 10px; left: 12px; background: transparent; border: none; font-size: 15px; cursor: pointer; opacity: 0.65; z-index: 6; line-height: 1;",e.addEventListener("click",()=>{g=!g,e.textContent=g?"🔊":"🔇"}),a.appendChild(e)}let S=!1,T=!1,$=0;const I=document.createElement("div");I.style.cssText="position: relative; width: 280px; max-width: 100%; aspect-ratio: 3 / 2; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 14px rgba(0,0,0,0.12);";const z=document.createElement("div");z.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 12px; text-align: center; font-size: 20px; font-weight: 800; color: ${i}; `+(m?`background: ${i}0f center/cover no-repeat;`:`background: ${i}0f;`),m&&(z.style.backgroundImage=`url("${m.replace(/"/g,"%22")}")`);const A=document.createElement("div"),L=b&&"string"==typeof b.icon?b.icon:"",M=b&&"string"==typeof b.label?b.label:"";A.textContent=M?L&&!y(L)?`${L} ${M}`:M:"🎁",z.appendChild(A),I.appendChild(z);const R=document.createElement("canvas");R.width=300,R.height=200,R.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; cursor: grab; touch-action: none;",I.appendChild(R);const P=R.getContext("2d"),D=R.width,N=R.height,F=e=>{if(!P)return;P.globalCompositeOperation="source-over";const t=P.createLinearGradient(0,0,D,N);if(t.addColorStop(0,"#d7dbe2"),t.addColorStop(.5,"#b4bac4"),t.addColorStop(1,"#c9cdd6"),P.fillStyle=t,P.fillRect(0,0,D,N),P.textAlign="center",P.textBaseline="middle",e)P.globalAlpha=.6,P.drawImage(e,(D-e.width)/2,.42*N-e.height/2,e.width,e.height),P.globalAlpha=1,P.fillStyle="#6b7280",P.font="700 12px system-ui, sans-serif",P.fillText("SCRATCH HERE",D/2,.84*N);else{P.fillStyle="rgba(108,116,128,0.18)",P.font="12px system-ui, sans-serif";for(let e=18;e<N;e+=30){for(let t=16+((e/30|0)%2?16:0);t<D;t+=32)P.fillText("✦",t,e)}P.fillStyle="#7c828e",P.font="700 13px system-ui, sans-serif",P.fillText("SCRATCH HERE",D/2,N/2)}P.globalCompositeOperation="destination-out"};if(P&&(F(null),f)){const e=new Image;e.crossOrigin="anonymous",e.onload=()=>{if(S||!P)return;const t=.52*D,n=.42*N,i=e.width/e.height||1;let o=t,s=t/i;s>n&&(s=n,o=n*i);const a=document.createElement("canvas");a.width=Math.max(1,Math.round(o)),a.height=Math.max(1,Math.round(s));const r=a.getContext("2d");r&&(r.drawImage(e,0,0,a.width,a.height),r.globalCompositeOperation="source-in",r.fillStyle="#5b626e",r.fillRect(0,0,a.width,a.height),F(a))},e.onerror=()=>{},e.src=f}const O=new Uint8Array(600);let B=0;let U=null;if(p){const e=document.createElement("div");e.style.cssText="position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 2;";const t=document.createElement("div");t.style.cssText="position: absolute; top: -20%; left: 0; width: 34%; height: 140%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.55), transparent); animation: aegisScratchSheen 2.6s ease-in-out infinite; animation-delay: 0.4s;",e.appendChild(t),U=e,I.appendChild(e)}const W=document.createElement("div");W.style.cssText="position: absolute; inset: 0; pointer-events: none; z-index: 3;",I.appendChild(W);const j=e=>{const t=e&&e.prize||null,n=t&&"number"==typeof t.segment_index?t.segment_index:-1;if(n>=0&&x[n])return x[n];const i=this._extractPrizeLabel(e);return x.find(e=>e.label===i)||b||null},q=(e,o,s)=>{if("takeover"===h){const t=document.createElement("div");if(t.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 22px; text-align: center; background: ${n}; color: ${i}; border-radius: inherit; animation: aegisScratchPop 0.4s cubic-bezier(0.16,0.86,0.28,1); z-index: 7;`,s){const e=document.createElement(y(s)?"img":"div");y(s)?(e.src=s,e.style.cssText="width: 42px; height: 42px; object-fit: contain;"):(e.textContent=s,e.style.cssText="font-size: 36px; line-height: 1;"),t.appendChild(e)}const r=document.createElement("div");r.textContent="You won",r.style.cssText="font-size: 12px; font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; opacity: 0.7;";const c=document.createElement("div");if(c.textContent=e,c.style.cssText="font-size: 22px; font-weight: 900; letter-spacing: -0.02em; font-family: 'Inter Tight', Inter, system-ui, sans-serif;",t.appendChild(r),t.appendChild(c),o){const e=document.createElement("button");e.type="button",e.textContent=`${o} ⧉`,e.style.cssText=`margin-top: 4px; padding: 8px 14px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 13px; letter-spacing: 1px; cursor: pointer;`,e.addEventListener("click",()=>{var t;try{null==(t=navigator.clipboard)||t.writeText(o),e.textContent="Copied ✓"}catch{}}),t.appendChild(e)}a.appendChild(t);try{this._fireConfetti(t)}catch{}}else{if(A.textContent=s&&!y(s)?`${s} ${e}`:e,o){const e=document.createElement("div");e.style.cssText=`margin-top: 6px; font-family: ui-monospace, monospace; font-size: 12px; font-weight: 700; padding: 4px 8px; border-radius: 6px; background: ${i}14; color: ${i};`,e.textContent=o,k.appendChild(e)}this._playReaction(k,"celebrate","gift.json",t)}},H=()=>{if(!S){S=!0;try{null==U||U.remove()}catch{}R.style.transition="opacity 0.4s ease",R.style.opacity="0",this.addAnimationStyles(),this.trackEvent(e.id,"clicked"),this.submitWidgetResponse(e,"scratch",{state:"revealed"}).then(e=>{var n;const i=e&&(!0===e.won||!0===(null==(n=e.reward)?void 0:n.granted)),o=b&&"string"==typeof b.label?b.label:"",s=this._extractPrizeLabel(e)||o||t.scratch_prize_label||"You won!",a=this._extractCouponCode(e)||"",r=j(e),c=r&&"string"==typeof r.icon?r.icon:"",d=r&&"string"==typeof r.prize_type?r.prize_type.toLowerCase():"";if(!1===i)(()=>{var e;if(C([392,330],.05),u)try{null==(e=navigator.vibrate)||e.call(navigator,18)}catch{}})(),A.textContent="Better luck next time",this._playReaction(k,"empathize",void 0,t);else if((()=>{var e;if(C([523,659,784,1047],.07),u)try{null==(e=navigator.vibrate)||e.call(navigator,[0,35,25,60])}catch{}})(),q(s,a,c),!a&&"freebie"===d&&"takeover"!==h){const e=document.createElement("div");e.textContent="🎟️ Show this screen to claim",e.style.cssText="margin-top: 4px; font-size: 12px; font-weight: 600; opacity: 0.85;",k.appendChild(e)}})}},V=(e,t)=>{if(!S){if(!P)return H();$+=1,P.beginPath(),P.arc(e,t,l,0,2*Math.PI),P.fill(),((e,t)=>{const n=D/30,i=N/20,o=l,s=Math.max(0,Math.floor((e-o)/n)),a=Math.min(29,Math.floor((e+o)/n)),r=Math.max(0,Math.floor((t-o)/i)),c=Math.min(19,Math.floor((t+o)/i));for(let d=r;d<=c;d++)for(let r=s;r<=a;r++){const s=30*d+r;if(O[s])continue;const a=(r+.5)*n-e,c=(d+.5)*i-t;a*a+c*c<=o*o&&(O[s]=1,B++)}})(e,t),$%2==0&&((()=>{var e;const t=w(),n="undefined"!=typeof performance?performance.now():Date.now();if(t&&n-_>45){_=n;const e=.05,i=t.createBuffer(1,Math.floor(t.sampleRate*e),t.sampleRate),o=i.getChannelData(0);for(let t=0;t<o.length;t++)o[t]=43758.5453*Math.sin(12.9898*t)%1*2-1;const s=t.createBufferSource();s.buffer=i;const a=t.createBiquadFilter();a.type="highpass",a.frequency.value=2200;const r=t.createGain();r.gain.setValueAtTime(.05,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-4,t.currentTime+e),s.connect(a),a.connect(r),r.connect(t.destination),s.start()}if(u)try{null==(e=navigator.vibrate)||e.call(navigator,4)}catch{}})(),((e,t)=>{const n=e/R.width*100,i=t/R.height*100;for(let o=0;o<2;o++){const e=document.createElement("div"),t=(53*o+17*$)%30-15,s=8+13*$%14;e.style.cssText=`position: absolute; left: ${n}%; top: ${i}%; width: 3px; height: 3px; border-radius: 50%; background: #b4bac4; --dx:${t}px; --dy:${s}px; animation: aegisScratchDust 0.5s ease-out forwards;`,W.appendChild(e),window.setTimeout(()=>e.remove(),520)}})(e,t)),B/600>d&&H()}},X=e=>{const t=R.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*R.width,y:(e.clientY-t.top)/t.height*R.height}};R.addEventListener("pointerdown",e=>{if(S)return;T=!0;try{R.setPointerCapture(e.pointerId)}catch{}const t=X(e);V(t.x,t.y)}),R.addEventListener("pointermove",e=>{if(!T)return;const t=X(e);V(t.x,t.y)});const K=()=>{T=!1};return R.addEventListener("pointerup",K),R.addEventListener("pointercancel",K),R.addEventListener("pointerleave",K),k.appendChild(I),a.appendChild(k),o.appendChild(a),!0}_extractPrizeLabel(e){var t;if(!e)return null;const n=e.reward,i=[e.prize_label,e.label,null==n?void 0:n.label,null==(t=e.prize)?void 0:t.prize_label];for(const o of i)if("string"==typeof o&&o)return o;return null}_extractCouponCode(e){if(!e)return null;const t=e.reward,n=[e.coupon_code,null==t?void 0:t.coupon_code];for(const i of n)if("string"==typeof i&&i)return i;return null}_submitTokenResponse(e,t){e&&fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({response:t}),keepalive:!0}).catch(e=>{this.log(`token submit failed: ${e}`,"warn")})}_slotStyle(e){const t=e.interactive_config||{},n=(e,t,n)=>{if(null==e||""===e)return;const i=Number(e);return Number.isFinite(i)?Math.max(t,Math.min(n,i)):void 0},i=null!=t.heading_font_weight?String(t.heading_font_weight):"",o=this._surfacePalette(e);return{bg:o.bg,text:o.text,radius:n(t.border_radius,0,24)??12,padX:n(t.padding_x,0,32),padY:n(t.padding_y,0,24),btnRadius:n(t.button_radius,0,999),weight:["400","500","600","700"].includes(i)?i:void 0}}_wrapInSlotCard(e,t,n,i,o=12){const s=document.createElement("div");return s.className=e,s.setAttribute("data-campaign-id",t),s.style.cssText=`\n width: 100%; border-radius: ${o}px; overflow: hidden;\n background: ${n}; color: ${i};\n box-shadow: 0 4px 12px rgba(0,0,0,0.06);\n `,s}_appendHeaderImage(e,t){const n=t.header_image_url;if(!n)return;const i=this.sanitizeUrl(n);if(!i)return;const o=document.createElement("img");o.src=i,o.alt="",o.style.cssText="display: block; max-height: 72px; max-width: 60%; margin: 0 auto 14px; object-fit: contain;",e.appendChild(o)}_buildStarRatingBody(e,t,n,i,o,s){const a="overlay"===i,r=a?"24px":`${(null==s?void 0:s.padY)??20}px ${(null==s?void 0:s.padX)??20}px`,c=a?"18px":"16px",d=a?"700":(null==s?void 0:s.weight)??"600",l=a?"16px":"12px",p=a?"32px":"28px",h=a?"16px":"0",u=a?"1.2":"1.15",g=document.createElement("div");g.style.cssText=`padding: ${r}; text-align: center;`,this._appendHeaderImage(g,t);const m=document.createElement("div");m.style.cssText=`font-size: ${c}; font-weight: ${d}; margin-bottom: ${l};`,m.textContent=e.title||"Rate your experience",g.appendChild(m);const f=document.createElement("div");f.style.cssText="display: flex; gap: 8px; justify-content: center;"+("0"!==h?` margin-bottom: ${h};`:"");const x=t.rating_scale||5,y=t.rating_icon||"star",b=["😞","🙁","😐","🙂","😀","🤩"],v=(e,t)=>"emoji"===y?(e=>{const t=x<=1?b.length-1:Math.round(e/(x-1)*(b.length-1));return b[Math.max(0,Math.min(b.length-1,t))]})(t):"heart"===y?e?"♥":"♡":e?"★":"☆",w=Array.isArray(t.rating_labels)?t.rating_labels:null;let _=null;w&&w.length>0&&(_=document.createElement("div"),_.style.cssText=`font-size: 12px; opacity: 0.7; margin-top: 8px; min-height: 16px; color: ${n||"inherit"};`);const C=[];let k=0;const E=e=>{if(C.forEach((t,i)=>{const o=i<e;t.textContent=v(o,i),"emoji"===y?(t.style.opacity=o||0===e?"1":"0.3",t.style.color="inherit"):t.style.color=o?"#fbbf24":n||"inherit",t.style.transform=o&&i===e-1?`scale(${u})`:"scale(1)"}),_&&w){const t=e>0?w[Math.min(e-1,w.length-1)]:"";_.textContent=t||""}};for(let S=1;S<=x;S++){const i=document.createElement("span");i.style.cssText=`font-size: ${p}; cursor: pointer; transition: transform 0.12s, color 0.12s, opacity 0.12s; user-select: none;`+("emoji"!==y&&n?` color: ${n};`:"")+("emoji"===y?" opacity: 0.3;":""),i.setAttribute("role","button"),i.setAttribute("aria-label",`${S} ${"heart"===y?"heart":"star"}${S>1?"s":""}`),i.textContent=v(!1,S-1);const s=S;i.addEventListener("mouseenter",()=>E(s)),i.addEventListener("mouseleave",()=>E(k)),i.addEventListener("click",()=>{k=s,E(k),i.style.transform="scale(1.28)",setTimeout(()=>E(k),160),this.trackEvent(e.id,"clicked"),this._onStarRatingPicked(e,t,g,s,x,n,a,o)}),C.push(i),f.appendChild(i)}return g.appendChild(f),_&&g.appendChild(_),g}_onStarRatingPicked(e,t,n,i,o,s,a,r){r&&this._submitTokenResponse(r,{sub_type:"star_rating",value:i});const c=a&&!1!==t.rating_followup_enabled,d=i>=(t.rating_followup_threshold||Math.ceil(.8*o));if(a)return c?void(d?(this.submitWidgetResponse(e,"rating",{stars:i}),this._renderRatingThankYou(e,t,n,!0)):this._renderRatingLowFollowup(e,t,n,i,s)):(this.submitWidgetResponse(e,"rating",{stars:i}),void this._renderRatingThankYou(e,t,n,d));d?this._playReaction(n,"affirm",void 0,t):i<=Math.max(1,Math.floor(.4*o))?this._playReaction(n,"empathize",void 0,t):this._playReaction(n,"acknowledge",void 0,t)}_renderRatingThankYou(e,t,n,i){for(;n.firstChild;)n.removeChild(n.firstChild);const o=n.parentElement;o&&(o.style.overflow="visible"),n.style.position="relative",n.style.minHeight="176px",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center";const s=document.createElement("div");s.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 8px;",s.textContent=i?t.rating_high_prompt||"Thanks — glad you loved it!":t.thank_you_message||"Thanks for your feedback!",n.appendChild(s);const a=t.rating_review_url;if(i&&a){const t=document.createElement("div");t.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 14px;",t.textContent="Would you share that with others?",n.appendChild(t);const i=this.inAppStyle(e),o=document.createElement("button");o.type="button",o.textContent=e.button_text||"Leave a review",o.style.cssText=`padding: 10px 24px; border-radius: 999px; border: none; background: ${i.btnBg}; color: ${i.btnText}; font-weight: 800; font-size: 13.5px; cursor: pointer;`,o.addEventListener("click",()=>{this.trackEvent(e.id,"clicked",{meta:{action:"review_redirect"}});const t=this.sanitizeUrl(a);t&&this.navigateToCampaignAction(e,t)}),n.appendChild(o)}else this._playReaction(n,i?"affirm":"acknowledge",void 0,t)}_renderRatingLowFollowup(e,t,n,i,o){for(this.addAnimationStyles();n.firstChild;)n.removeChild(n.firstChild);const s=document.createElement("div");s.style.cssText="font-size: 15px; font-weight: 700; margin-bottom: 10px;",s.textContent=t.rating_low_prompt||"Sorry to hear that. What went wrong?",n.appendChild(s);const a=document.createElement("textarea");a.className="aegis-rating-comment",a.rows=3,a.placeholder="Tell us how we can do better…",a.style.cssText=`width: 100%; box-sizing: border-box; padding: 10px; border-radius: 10px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 13px; resize: vertical; margin-bottom: 12px; font-family: inherit;`,n.appendChild(a);const r=this.inAppStyle(e),c=document.createElement("div");c.style.cssText="display: flex; gap: 8px; justify-content: center;";let d=!1;const l=o=>{if(d)return;d=!0;const s=o?a.value.trim():"";this.submitWidgetResponse(e,"rating",s?{stars:i,comment:s}:{stars:i}),this._renderRatingThankYou(e,t,n,!1)},p=document.createElement("button");p.type="button",p.textContent="Send feedback",p.style.cssText=`padding: 9px 20px; border-radius: 999px; border: none; background: ${r.btnBg}; color: ${r.btnText}; font-weight: 800; font-size: 13px; cursor: pointer;`,p.addEventListener("click",()=>l(!0));const h=document.createElement("button");h.type="button",h.textContent="Skip",h.style.cssText=`padding: 9px 16px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-weight: 600; font-size: 13px; cursor: pointer;`,h.addEventListener("click",()=>l(!1)),c.appendChild(p),c.appendChild(h),n.appendChild(c),a.focus()}_buildNPSSurveyBody(e,t,n,i,o,s){const a="overlay"===i,r=a?"24px":`${(null==s?void 0:s.padY)??20}px ${(null==s?void 0:s.padX)??20}px`,c=document.createElement("div");c.style.cssText=`padding: ${r};`+(a?" text-align: center;":""),this._appendHeaderImage(c,t);const d=document.createElement("div");d.style.cssText=`font-size: 16px; font-weight: ${a?"700":(null==s?void 0:s.weight)??"600"}; margin-bottom: ${a?"16px":"12px"}; text-align: center;`,d.textContent=t.nps_question||e.title||"How likely are you to recommend us?",c.appendChild(d);const l=e=>e<=6?"#ef4444":e<=8?"#f59e0b":"#10b981",p=document.createElement("div");p.style.cssText=a?"display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;":"display: grid; grid-template-columns: repeat(11, 1fr); gap: 4px;";const h=i=>{this.trackEvent(e.id,"clicked"),o&&this._submitTokenResponse(o,{sub_type:"nps_survey",value:i});if(a&&!1!==t.nps_followup_enabled)return void this._renderNpsReasonFollowup(e,t,c,i,n);this.submitWidgetResponse(e,"nps",{score:i}),this.addAnimationStyles();const s=document.createElement("div");s.style.cssText=`font-size: 14px; font-weight: 600; padding: 8px 0; text-align: center; color: ${n};`,s.textContent=i>=9?"Thanks! We are glad you love it.":i<=6?"Thanks for the honest feedback — we will do better.":"Thank you for your feedback!",p.replaceWith(s),null==u||u.remove(),i>=9?this._playReaction(c,"affirm",void 0,t):i<=6?this._playReaction(c,"empathize",void 0,t):this._playReaction(c,"acknowledge",void 0,t)};for(let g=0;g<=10;g++){const e=l(g),t=g;if(a){const n=document.createElement("span");n.style.cssText=`\n width: 28px; height: 28px; border-radius: 6px; display: flex;\n align-items: center; justify-content: center; font-size: 12px;\n font-weight: 700; cursor: pointer; background: ${e}; color: #fff;\n opacity: 0.85; transition: transform 0.1s, opacity 0.15s;\n `,n.textContent=String(g),n.addEventListener("mouseenter",()=>{n.style.opacity="1",n.style.transform="translateY(-1px)"}),n.addEventListener("mouseleave",()=>{n.style.opacity="0.85",n.style.transform="translateY(0)"}),n.addEventListener("click",()=>h(t)),p.appendChild(n)}else{const n=document.createElement("button");n.style.cssText=`\n padding: 8px 0; border-radius: 6px; border: 1px solid ${e}88;\n background: ${e}14; color: ${e}; font-size: 13px; font-weight: 700;\n cursor: pointer; transition: transform 0.12s, background 0.15s;\n `,n.textContent=String(g),n.addEventListener("mouseenter",()=>{n.style.background=e,n.style.color="#fff",n.style.transform="translateY(-1px)"}),n.addEventListener("mouseleave",()=>{n.style.background=`${e}14`,n.style.color=e,n.style.transform="translateY(0)"}),n.addEventListener("click",()=>h(t)),p.appendChild(n)}}c.appendChild(p);let u=null;if(a){u=document.createElement("div"),u.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const e=document.createElement("span");e.textContent="Not likely";const t=document.createElement("span");t.textContent="Very likely",u.appendChild(e),u.appendChild(t),c.appendChild(u)}return c}_renderNpsReasonFollowup(e,t,n,i,o){this.addAnimationStyles();const s=t.nps_promoter_threshold||9,a=i>=s?t.nps_follow_up_promoter||"What do you love most about us?":i<=6?t.nps_follow_up_detractor||"How can we improve?":t.nps_follow_up_passive||"What would make us a 10?";for(;n.firstChild;)n.removeChild(n.firstChild);const r=document.createElement("div");r.style.cssText="font-size: 15px; font-weight: 700; margin-bottom: 10px; text-align: center;",r.textContent=a,n.appendChild(r);const c=document.createElement("textarea"),d=Array.isArray(t.nps_reason_chips)?t.nps_reason_chips:[];if(d.length){const e=document.createElement("div");e.style.cssText="display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-bottom: 10px;",d.slice(0,8).forEach(t=>{const n=document.createElement("button");n.type="button",n.textContent=t,n.style.cssText=`padding: 5px 11px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 12px; cursor: pointer;`,n.addEventListener("click",()=>{c.value=c.value?`${c.value}, ${t}`:t,c.focus()}),e.appendChild(n)}),n.appendChild(e)}c.className="aegis-rating-comment",c.rows=3,c.placeholder="Share a little more…",c.style.cssText=`width: 100%; box-sizing: border-box; padding: 10px; border-radius: 10px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 13px; resize: vertical; margin-bottom: 12px; font-family: inherit;`,n.appendChild(c);const l=this.inAppStyle(e),p=document.createElement("div");p.style.cssText="display: flex; gap: 8px; justify-content: center;";let h=!1;const u=o=>{if(h)return;h=!0;const a=o?c.value.trim():"";this.submitWidgetResponse(e,"nps",a?{score:i,comment:a}:{score:i}),this._renderNpsThankYou(e,t,n,i>=s)},g=document.createElement("button");g.type="button",g.textContent="Send",g.style.cssText=`padding: 9px 20px; border-radius: 999px; border: none; background: ${l.btnBg}; color: ${l.btnText}; font-weight: 800; font-size: 13px; cursor: pointer;`,g.addEventListener("click",()=>u(!0));const m=document.createElement("button");m.type="button",m.textContent="Skip",m.style.cssText=`padding: 9px 16px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-weight: 600; font-size: 13px; cursor: pointer;`,m.addEventListener("click",()=>u(!1)),p.appendChild(g),p.appendChild(m),n.appendChild(p),c.focus()}_renderNpsThankYou(e,t,n,i){for(;n.firstChild;)n.removeChild(n.firstChild);const o=n.parentElement;o&&(o.style.overflow="visible"),n.style.position="relative",n.style.minHeight="176px",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center";const s=document.createElement("div");s.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 8px; text-align: center;",s.textContent=t.thank_you_message||(i?"Thanks — glad you love it!":"Thanks for your feedback!"),n.appendChild(s);const a=t.nps_promoter_url;if(i&&a){const t=document.createElement("div");t.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 14px; text-align: center;",t.textContent="Would you share that with others?",n.appendChild(t);const i=this.inAppStyle(e),o=document.createElement("button");o.type="button",o.textContent=e.button_text||"Leave a review",o.style.cssText=`padding: 10px 24px; border-radius: 999px; border: none; background: ${i.btnBg}; color: ${i.btnText}; font-weight: 800; font-size: 13.5px; cursor: pointer;`,o.addEventListener("click",()=>{this.trackEvent(e.id,"clicked",{meta:{action:"nps_review_redirect"}});const t=this.sanitizeUrl(a);t&&this.navigateToCampaignAction(e,t)}),n.appendChild(o)}else this._playReaction(n,i?"affirm":"acknowledge",void 0,t)}onClientEvent(e,t={}){for(const n of this.campaigns)this.displayedCampaigns.has(n.id)||n.client_trigger&&(this.isSuppressed(n.id)||this.matchesClientTrigger(n.client_trigger,e,t)&&this.displayCampaign(n))}matchesClientTrigger(e,t,n){var i;const o=e.config||{};switch(e.type){case"custom_event":return"string"==typeof o.event&&o.event===t;case"product_match":{if("product_viewed"!==t&&"product_view"!==t)return!1;const e=o.product_id,s=Array.isArray(e)?e:"string"==typeof e?[e]:[];if(0===s.length)return!1;const a=String(n.product_id??n.productId??(null==(i=n.product)?void 0:i.id)??"");return s.includes(a)}default:return!1}}displayCampaign(e){if(!this.emit("campaign-will-show",e))return void this.log(`campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id);const t=new Set(["spin_wheel","scratch_card","nps_survey","quiz","countdown_offer","star_rating","quick_poll","multi_step_form","push_primer",...be]);if(e.sub_type&&t.has(e.sub_type))return this.renderInteractive(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);switch(e.type){case"custom_html":return this.renderCustomHtml(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"modal":this.renderModal(e);break;case"banner":this.renderBanner(e);break;case"full_screen":this.renderFullScreen(e);break;case"half_interstitial":this.renderHalfInterstitial(e);break;case"alert":this.renderAlert(e);break;case"pip":this.renderPIP(e);break;case"tooltip":this.renderTooltip(e);break;case"carousel_cards":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c=(Array.isArray(r.cards)?r.cards:[]).slice(0,10);if(0===c.length)return void s("carousel_cards rendered with zero cards — skipping","warn");const d=Number(r.autoplay_ms)||0,l=!1!==r.loop;a();const p="#0f172a",h=o(t.background_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-carousel-overlay",u.setAttribute("data-campaign-id",t.id),u.style.cssText='\n position: fixed; left: 0; right: 0; bottom: 0;\n z-index: 99999; padding: 12px 12px 20px;\n background: rgba(0,0,0,0.12); backdrop-filter: blur(8px);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n ';const g=document.createElement("div");g.style.cssText=`\n background: #ffffff; color: ${p}; border-radius: 16px;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08); padding: 16px;\n max-width: 520px; margin: 0 auto; position: relative;\n `;const m=document.createElement("div");m.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 12px;";const f=document.createElement("div"),x=document.createElement("div");x.textContent=t.title,x.style.cssText="font-weight: 700; font-size: 15px; margin-bottom: 2px;";const y=document.createElement("div");y.textContent=t.body,y.style.cssText="font-size: 13px; opacity: 0.75;",f.appendChild(x),f.appendChild(y),m.appendChild(f);const b=document.createElement("button");b.textContent="✕",b.setAttribute("aria-label","Close"),b.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; opacity: 0.6; padding: 2px 6px;\n ",b.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),m.appendChild(b),g.appendChild(m);const v=document.createElement("div");v.style.cssText="\n display: flex; gap: 10px; overflow-x: auto; scroll-snap-type: x proximity;\n scroll-padding-left: 0; scrollbar-width: none; -ms-overflow-style: none;\n padding-bottom: 4px; -webkit-overflow-scrolling: touch;\n ",v.style.msOverflowStyle="none",c.forEach((e,o)=>{const s=document.createElement("div");s.setAttribute("data-card-index",String(o)),s.style.cssText=`\n flex: 0 0 auto; width: 140px; scroll-snap-align: start;\n background: ${p}0a; border-radius: 12px; padding: 10px;\n display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n `;const a=e.video_url?i(e.video_url):"";if(a){const e=document.createElement("video");e.src=a,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",s.appendChild(e)}else if(e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",s.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",s.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",s.appendChild(t)}if(e.cta_text&&e.cta_url){const a=document.createElement("button");a.className="aegis-cta",a.textContent=e.cta_text,a.style.cssText=`\n margin-top: auto; background: ${h}; color: #fff;\n border: none; padding: 6px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const r=s=>{s.stopPropagation(),n(t.id,"clicked",{stepId:`card_${o}`});const a=i(e.cta_url);a&&(window.location.href=a)};a.addEventListener("click",r),s.appendChild(a),s.addEventListener("click",r)}v.appendChild(s)}),g.appendChild(v);const w=document.createElement("div");w.style.cssText="display: flex; justify-content: center; gap: 6px; margin-top: 10px;";const _=[];c.forEach(()=>{const e=document.createElement("span");e.style.cssText=`\n width: 6px; height: 6px; border-radius: 999px; background: ${p};\n opacity: 0.25; transition: opacity 0.2s;\n `,_.push(e),w.appendChild(e)}),g.appendChild(w);const C=new Set,k=e=>{_.forEach((t,n)=>{t.style.opacity=n===e?"1":"0.25",t.style.background=n===e?h:p}),C.has(e)||(C.add(e),n(t.id,"impression",{stepId:`card_${e}`}))};k(0);let E=0;const S=v.querySelectorAll("[data-card-index]"),T=e=>{E=(e%c.length+c.length)%c.length;const t=S[E];if(t){const e=t.getBoundingClientRect().left-v.getBoundingClientRect().left;v.scrollTo({left:v.scrollLeft+e,behavior:"smooth"}),k(E)}};if(c.length>1){const e=(e,t,n)=>{const i=document.createElement("button");return i.type="button",i.textContent=e,i.setAttribute("aria-label",t),i.style.cssText=`background: transparent; border: none; color: ${p}; opacity: 0.55; font-size: 18px; line-height: 1; cursor: pointer; padding: 0 4px;`,i.addEventListener("click",()=>{I(),T(E+n)}),i};w.style.alignItems="center",w.insertBefore(e("‹","Previous",-1),w.firstChild),w.appendChild(e("›","Next",1))}let $=null;const I=()=>{$&&(clearInterval($),$=null)};d>0&&c.length>1&&($=setInterval(()=>{if(!document.body.contains(u))return void I();const e=E+1;e>=c.length&&!l?I():T(e)},d)),["pointerdown","wheel","touchstart"].forEach(e=>v.addEventListener(e,I,{passive:!0})),v.addEventListener("scroll",()=>{const e=Math.round(v.scrollLeft/150);e!==E&&e>=0&&e<c.length&&(E=e,k(E))}),u.appendChild(g),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"sticky_bar":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c="top"===r.sticky_position?"top":"bottom",d=!1!==r.sticky_dismissible,l=Number(r.sticky_auto_hide_ms)||0;try{if("undefined"!=typeof localStorage&&localStorage.getItem(G+t.id))return void s(`sticky_bar ${t.id} suppressed — user dismissed earlier`)}catch{}a();const p=o(r.sticky_bg_color||t.background_color||"#4169e1"),h=o(t.text_color||"#ffffff"),u=document.createElement("div");u.className="aegis-in-app-sticky-bar",u.setAttribute("data-campaign-id",t.id);const g="top"===c?"top: 0; left: 0; right: 0; animation: aegisSlideDown 0.3s ease-out;":"bottom: 0; left: 0; right: 0; animation: aegisSlideInFromBottom 0.3s ease-out;";u.style.cssText=`\n position: fixed; ${g}\n background: ${p}; color: ${h};\n padding: 10px 14px; z-index: 999998;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex; align-items: center; gap: 12px; justify-content: center;\n box-shadow: 0 ${"top"===c?"2px":"-2px"} 8px rgba(0,0,0,0.08);\n `;const m=document.createElement("div");m.style.cssText="flex: 0 1 auto; font-size: 13px; font-weight: 500; text-align: center;";const f=document.createElement("strong");f.textContent=t.title,f.style.cssText="margin-right: 6px; font-weight: 700;",m.appendChild(f),m.appendChild(document.createTextNode(t.body)),u.appendChild(m);const x=t.button_text||(t.action_url?"Shop now":"");if(x){const e=document.createElement("button");e.className="aegis-cta",e.textContent=x,e.style.cssText=`\n background: ${h}; color: ${p};\n border: none; padding: 6px 14px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer; white-space: nowrap;\n `,e.addEventListener("click",()=>{if(n(t.id,"clicked"),t.action_url){const e=i(t.action_url);e&&(window.location.href=e)}}),u.appendChild(e)}let y=null;const b=e=>{if(y&&clearTimeout(y),e)try{"undefined"!=typeof localStorage&&localStorage.setItem(G+t.id,"1")}catch{}u.remove()};if(d){const e=document.createElement("button");e.textContent="✕",e.setAttribute("aria-label","Dismiss"),e.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; padding: 0 4px; opacity: 0.75;\n ",e.addEventListener("click",()=>{n(t.id,"dismissed"),b(!0)}),u.appendChild(e)}l>0&&(y=setTimeout(()=>b(!1),l)),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"progress_bar":return function(e){const t=J(e,!1);t&&document.body.appendChild(t)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"coachmark_tour":return te(this.buildRenderContext(e)),void this.emit("campaign-shown",e);case"product_recommendation":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c=(Array.isArray(r.cards)?r.cards:[]).slice(0,24);if(0===c.length)return void s("product_recommendation rendered with zero products — skipping","warn");const d=r.rec_layout||"grid",l=r.rec_cta_text||"Shop now";a();const p="#0f172a",h=o(t.background_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-product-rec",u.setAttribute("data-campaign-id",t.id),u.style.cssText="\n position: fixed; inset: 0;\n background: rgba(15,23,42,0.55); backdrop-filter: blur(4px);\n display: flex; align-items: flex-end; justify-content: center;\n z-index: 99999; animation: aegisFadeIn 0.25s ease;\n ";const g=document.createElement("div");g.style.cssText=`\n background: #ffffff; color: ${p};\n max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;\n border-radius: 20px 20px 0 0;\n padding: 18px 16px 22px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n box-shadow: 0 -12px 30px rgba(0,0,0,0.12);\n `;const m=document.createElement("div");m.style.cssText=`\n width: 36px; height: 4px; border-radius: 999px; background: ${p}1f;\n margin: 0 auto 12px;\n `,g.appendChild(m);const f=document.createElement("div");f.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;";const x=document.createElement("div"),y=document.createElement("div");y.textContent=t.title,y.style.cssText="font-weight: 700; font-size: 16px; margin-bottom: 2px;";const b=document.createElement("div");b.textContent=t.body,b.style.cssText="font-size: 13px; opacity: 0.7; line-height: 1.4;",x.appendChild(y),x.appendChild(b),f.appendChild(x);const v=document.createElement("button");v.textContent="✕",v.setAttribute("aria-label","Close"),v.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 18px; cursor: pointer; padding: 4px 8px; opacity: 0.7;\n ",v.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),f.appendChild(v),g.appendChild(f);const w=document.createElement("div");w.style.cssText="row"===d?"\n display: flex; gap: 10px; overflow-x: auto;\n scroll-snap-type: x mandatory; padding: 14px 0 4px;\n ":"\n display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;\n padding-top: 14px;\n ",c.forEach(e=>{const o=document.createElement("div"),s="row"===d;if(o.style.cssText=`\n background: ${p}08; border-radius: 12px;\n padding: 10px; display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n ${s?"flex: 0 0 150px; scroll-snap-align: start;":""}\n transition: transform 0.15s ease;\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; aspect-ratio: 1 / 1; border-radius: 8px; object-fit: cover;",o.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",o.appendChild(t)}const a=e.metadata&&"object"==typeof e.metadata?e.metadata:{},r=a.price,c=a.compare_at_price??a.compare_at??a.original_price;if(void 0!==r){const e=document.createElement("div");e.style.cssText="display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap;";const t=document.createElement("span");t.textContent=String(r),t.style.cssText=`color: ${h}; font-weight: 700; font-size: 13px;`,e.appendChild(t);const n=parseFloat(String(r).replace(/[^0-9.]/g,"")),i=void 0!==c?parseFloat(String(c).replace(/[^0-9.]/g,"")):NaN;if(isFinite(i)&&isFinite(n)&&i>n){const t=document.createElement("span");t.textContent=String(c),t.style.cssText="text-decoration: line-through; opacity: 0.5; font-size: 11px;",e.appendChild(t);const o=document.createElement("span");o.textContent=`-${Math.round(100*(1-n/i))}%`,o.style.cssText="background: #ef444422; color: #ef4444; font-weight: 700; font-size: 10px; padding: 1px 5px; border-radius: 999px;",e.appendChild(o)}o.appendChild(e)}else if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",o.appendChild(t)}const u=document.createElement("button");u.className="aegis-cta",u.textContent=e.cta_text||l,u.style.cssText=`\n margin-top: auto;\n background: ${h}; color: #fff;\n border: none; padding: 7px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const g=o=>{if(o.stopPropagation(),n(t.id,"clicked"),e.cta_url){const t=i(e.cta_url);t&&(window.location.href=t)}};u.addEventListener("click",g),o.appendChild(u),e.cta_url&&o.addEventListener("click",g),w.appendChild(o)}),g.appendChild(w),u.appendChild(g),u.addEventListener("click",e=>{e.target===u&&(n(t.id,"dismissed"),u.remove())}),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"stories":return function(e){const t=ae(e);t&&(e.addAnimationStyles(),de(),ce(e,t,0,0))}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"video":return ke(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"active_web_chat":return this.renderActiveWebChatLauncher(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e)}this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)}renderActiveWebChatLauncher(e){if(this.activeWebChat)return;const t=function(e,t){if("undefined"==typeof document)return null;if(Ie)return Ie;const n=e.campaign.interactive_config||{},i=Ae(n.chat_accent_color),o=Ae(n.chat_logo_url),s=Ae(n.chat_icon),a={writeKey:t.writeKey,apiHost:t.apiHost,contactId:t.contactId,channel:t.channel??"web",title:Ae(n.chat_title),greeting:Ae(n.chat_greeting),accentColor:i?e.sanitizeColor(i):void 0,icon:"sparkle"===s||"chat"===s||"logo"===s?s:void 0,logoUrl:o?e.sanitizeUrl(o)??void 0:void 0,position:"bottom-left"===n.chat_position?"bottom-left":void 0,agentPersona:Ae(n.chat_agent_persona),quickReplies:Array.isArray(n.chat_quick_replies)?n.chat_quick_replies.filter(e=>"string"==typeof e):void 0,onSessionStart:()=>e.trackEvent(e.campaign.id,"clicked",{meta:{action:"session_start"}}),onSessionEnd:()=>e.trackEvent(e.campaign.id,"dismissed",{meta:{action:"session_end"}}),onMessageSent:()=>e.trackEvent(e.campaign.id,"clicked",{meta:{action:"message_sent"}})},r=new Se(a);r.initialize(),Ie=r;const c=n.chat_proactive||{},d=!0===c.exit_intent,l=!0===c.cart_idle;if(d||l){const e=new $e;d&&(e.registerExitIntent(),e.on("exit_intent",()=>r.openPanel())),l&&(e.registerInactivity(60),e.on("inactivity_60",()=>r.openPanel())),e.start(),ze=e}return r}(this.buildRenderContext(e),{writeKey:this.writeKey,apiHost:this.apiHost,contactId:this.contactId,channel:"web"});t&&(this.activeWebChat=t)}buildRenderContext(e){return{campaign:e,getCartState:this.getCartState,trackEvent:(e,t,n)=>{this.trackEvent(e,t,n)},sanitizeUrl:e=>this.sanitizeUrl(e),navigate:(t,n)=>this.navigateToCampaignAction(e,t,n),submitResponse:(t,n)=>this.submitWidgetResponse(e,t,n),playReaction:(t,n,i)=>this._playReaction(t,n,i,e.interactive_config),haptic:e=>{try{"undefined"!=typeof navigator&&"function"==typeof navigator.vibrate&&navigator.vibrate(e)}catch{}},sanitizeColor:e=>this.sanitizeColor(e),log:(e,t)=>this.log(e,t),addAnimationStyles:()=>this.addAnimationStyles()}}renderInteractive(e){const t=e.interactive_config||{},{bg:n,text:i}=this._surfacePalette(e);if(!e.sub_type||!function(e,t){const n=ye[t];return!!n&&(n(e),!0)}(this.buildRenderContext(e),e.sub_type))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"multi_step_form":this.renderMultiStepForm(e,t,n,i);break;case"push_primer":this.renderPushPrimer(e,t,n,i);break;case"spin_wheel":case"scratch_card":this.onInteractiveCampaign?this.onInteractiveCampaign(e):this.renderGamificationOverlay(e,t,n,i);break;default:this.log(`Unknown interactive sub_type: ${e.sub_type}`,"warn"),this.renderModal(e)}}renderGamificationOverlay(e,t,n,i){const o=this.createOverlay(`aegis-in-app-${e.sub_type}-overlay`),s=document.createElement("div");s.style.cssText=`\n position: relative; max-width: 340px; width: 90%; border-radius: 20px;\n overflow: hidden; background: ${n}; color: ${i};\n animation: aegisScaleIn 0.3s ease; box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n `,"scratch_card"===e.sub_type?this.renderScratchCardSlot(e,t,n,i,s):this.renderSpinWheelSlot(e,t,n,i,s),this._addCornerClose(s,o,e.id,i),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}_addCornerClose(e,t,n,i){const o=document.createElement("button");o.setAttribute("aria-label","Close");const s=Le('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>');s?o.appendChild(s):o.textContent="✕",o.style.cssText=`\n position: absolute; top: 12px; right: 12px; z-index: 4; width: 28px; height: 28px;\n display: flex; align-items: center; justify-content: center; border: none;\n border-radius: 50%; cursor: pointer; color: ${i};\n background: ${i}1f; backdrop-filter: blur(4px); transition: background 0.15s, transform 0.15s;\n `,o.addEventListener("mouseenter",()=>{o.style.background=`${i}33`,o.style.transform="scale(1.08)"}),o.addEventListener("mouseleave",()=>{o.style.background=`${i}1f`,o.style.transform="scale(1)"}),o.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(o)}renderCustomHtml(e){const t=e.interactive_config||{},n=this.createOverlay("aegis-in-app-custom-html-overlay"),i=document.createElement("div");i.style.cssText="position: relative; max-width: 420px; width: 92%; border-radius: 16px; overflow: hidden; background: #ffffff; box-shadow: 0 16px 48px rgba(0,0,0,0.22); animation: aegisScaleIn 0.3s ease;",i.appendChild(this._buildCustomHtmlFrame(e,t,n)),this._addCornerClose(i,n,e.id,"#111827"),n.appendChild(i),this.addAnimationStyles(),document.body.appendChild(n)}_buildCustomHtmlFrame(e,t,n){const i="string"==typeof t.html?t.html:"",o="number"==typeof t.html_height?t.html_height:360,s=this.inAppStyle(e),a=`:root{--aegis-bg:${s.bg};--aegis-text:${s.text};--aegis-primary:${s.btnBg};--aegis-on-primary:${s.btnText};}`,r=document.createElement("iframe");r.setAttribute("sandbox","allow-scripts"),r.setAttribute("referrerpolicy","no-referrer"),r.style.cssText=`width: 100%; height: ${o}px; border: none; display: block; background: #fff; transform: translateZ(0); backface-visibility: hidden;`,r.title=e.title||"In-app content";r.srcdoc='<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>'+a+"html,body{margin:0;padding:0;font-family:system-ui,-apple-system,sans-serif;}</style><script>window.aegis={close:function(){parent.postMessage({__aegis:'close'},'*')},track:function(e,p){parent.postMessage({__aegis:'track',event:e,payload:p},'*')},cta:function(u){parent.postMessage({__aegis:'cta',url:u},'*')},resize:function(h){parent.postMessage({__aegis:'resize',height:h},'*')}};<\/script></head><body>"+i+"</body></html>";const c=t=>{if(t.source!==r.contentWindow)return;const i=t.data;if(i&&"string"==typeof i.__aegis)switch(i.__aegis){case"close":window.removeEventListener("message",c),this.trackEvent(e.id,"dismissed"),this.removeModal(n);break;case"track":this.trackEvent(e.id,"clicked");break;case"cta":{this.trackEvent(e.id,"clicked");const t="string"==typeof i.url?this.sanitizeUrl(i.url):null;if(t){const n=new CustomEvent("aegis:campaign-click",{detail:{campaign:e,url:t},cancelable:!0});window.dispatchEvent(n)&&window.open(t,"_blank","noopener")}break}case"resize":"number"==typeof i.height&&i.height>=40&&i.height<=2e3&&(r.style.height=`${i.height}px`)}};return window.addEventListener("message",c),r}renderCustomHtmlSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-custom-html-card",e.id,n,i,s.radius);return a.appendChild(this._buildCustomHtmlFrame(e,t,a)),o.appendChild(a),!0}renderNPSSurvey(e,t,n,i){const o=this.createOverlay("aegis-in-app-nps-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=this._buildNPSSurveyBody(e,t,i,"overlay");this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderCountdownOffer(e,t,n,i){const o=this.createOverlay("aegis-in-app-countdown-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\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=t.countdown_target,l=d?new Date(d).getTime():Date.now()+6e5,p=l-Date.now()>=864e5,h=p?[["d","Days"],["h","Hrs"],["m","Min"],["s","Sec"]]:[["h","Hrs"],["m","Min"],["s","Sec"]],u={},g=document.createElement("div");g.style.cssText="display: flex; gap: 10px; justify-content: center; margin-bottom: 16px;";for(const[b,v]of h){const e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; align-items: center; gap: 4px;";const t=document.createElement("div");t.style.cssText=`min-width: 46px; padding: 8px 6px; border-radius: 8px; font-size: 24px; font-weight: 700; font-family: monospace; background: ${i}22; color: ${i}; transition: background 0.2s, color 0.2s;`,t.textContent="00";const n=document.createElement("div");n.style.cssText="font-size: 10px; opacity: 0.6; text-transform: uppercase; letter-spacing: 0.5px;",n.textContent=v,e.appendChild(t),e.appendChild(n),u[b]=t,g.appendChild(e)}a.appendChild(g);const m=e=>String(e).padStart(2,"0");let f=!1,x=!1;const y=()=>{const n=Math.max(0,l-Date.now()),i=Math.floor(n/864e5),o=Math.floor(n%864e5/36e5),s=Math.floor(n%36e5/6e4),r=Math.floor(n%6e4/1e3);u.d&&(u.d.textContent=m(i)),u.h&&(u.h.textContent=m(p?o:Math.floor(n/36e5))),u.m&&(u.m.textContent=m(s)),u.s&&(u.s.textContent=m(r)),!x&&n>0&&n<=6e4&&(x=!0,Object.values(u).forEach(e=>{e&&(e.style.boxShadow="0 0 0 2px #ef4444")}),g.style.animation="aegisCountdownPulse 1.1s ease-in-out infinite"),n>0?requestAnimationFrame(y):f||(f=!0,this.submitWidgetResponse(e,"countdown",{state:"expired"}),this._playReaction(a,"celebrate","alarm-clock.json",t))};if(y(),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,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderStarRating(e,t,n,i){const o=this.createOverlay("aegis-in-app-rating-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=this._buildStarRatingBody(e,t,i,"overlay");this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderQuickPoll(e,t,n,i){const o=this.createOverlay("aegis-in-app-poll-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");if(r.style.cssText=`font-size: 16px; font-weight: 700; margin-bottom: ${e.body?"6px":"16px"};`,r.textContent=e.title||"Quick question",a.appendChild(r),e.body){const t=document.createElement("div");t.style.cssText=`font-size: 13px; opacity: 0.8; margin-bottom: 16px; color: ${i};`,t.textContent=e.body,a.appendChild(t)}const c=t.poll_options||[],d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;";const l=[];c.forEach((n,o)=>{const s=document.createElement("button");s.style.cssText=`\n position: relative; overflow: hidden;\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: border-color 0.2s ease;\n `;const r=document.createElement("span");r.style.cssText="position: relative; z-index: 1; display: flex; justify-content: space-between; gap: 8px;";const p=document.createElement("span");p.textContent=n;const h=document.createElement("span");h.style.cssText="font-weight: 700; opacity: 0; transition: opacity 0.3s ease;",r.appendChild(p),r.appendChild(h),s.appendChild(r),s.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),l.forEach(e=>e.disabled=!0),this._paintPollResult(l,c,o,null,i),this.submitWidgetResponse(e,"poll",{option_index:o,option_label:n}).then(e=>{const t=this._readPollDistribution(e,c.length);t&&this._paintPollResult(l,c,o,t,i)});const s=a.parentElement;s&&(s.style.overflow="visible"),this._playReaction(a,"affirm","check.json",t)}),l.push(s),d.appendChild(s)}),a.appendChild(d),this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderMultiStepForm(e,t,n,i){const o=this.createOverlay("aegis-in-app-multistep-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=Array.isArray(t.form_fields)?t.form_fields:null;if(a&&a.length>0){const t=this._buildFormBody(e,a,n,i);return this.addCloseButton(t,o,e.id),s.appendChild(t),o.appendChild(s),this.addAnimationStyles(),void document.body.appendChild(o)}const r=document.createElement("div");r.style.cssText="padding: 24px;";const c=Array.isArray(t.steps)?t.steps:[],d=c.length>0?c:[{question:e.title||"Tell us more",options:[]}],l=d.length;let p=0;const h=new Array(l).fill(null),u=document.createElement("div");u.style.cssText=`height: 4px; border-radius: 2px; background: ${i}22; margin-bottom: 16px; overflow: hidden;`;const g=document.createElement("div");g.style.cssText=`height: 100%; background: ${i}; transition: width 0.2s ease; width: 0%;`,u.appendChild(g),r.appendChild(u);const m=document.createElement("div");m.style.cssText="font-size: 11px; opacity: 0.7; margin-bottom: 6px;",r.appendChild(m);const f=document.createElement("div");f.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 14px;",r.appendChild(f);const x=document.createElement("div");x.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;",r.appendChild(x);const y=document.createElement("div");y.style.cssText="display: flex; gap: 8px; justify-content: space-between;";const b=document.createElement("button");b.textContent="Back",b.style.cssText=`padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33; background: transparent; color: ${i}; font-size: 14px; cursor: pointer;`;const v=document.createElement("button");v.style.cssText=`padding: 10px 16px; border-radius: 10px; border: none; background: ${i}; color: ${n}; font-size: 14px; font-weight: 600; cursor: pointer; flex: 1;`,y.appendChild(b),y.appendChild(v),r.appendChild(y);const w=()=>{const e=d[p]||{},t=e.question||e.label||`Step ${p+1}`,n=Array.isArray(e.options)?e.options:[];for(g.style.width=`${Math.round(p/l*100)}%`,m.textContent=`Step ${p+1} of ${l}`,f.textContent=t;x.firstChild;)x.removeChild(x.firstChild);n.forEach(e=>{const t=document.createElement("button");t.textContent=e;const n=h[p]===e;t.style.cssText=`padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33; background: ${n?i+"22":"transparent"}; color: ${i}; font-size: 14px; cursor: pointer; text-align: left;`,t.addEventListener("click",()=>{h[p]=e,w()}),x.appendChild(t)}),b.style.visibility=0===p?"hidden":"visible",v.textContent=p===l-1?"Submit":"Next";const o=n.length>0&&null==h[p];v.disabled=o,v.style.opacity=o?"0.5":"1",v.style.cursor=o?"not-allowed":"pointer"};b.addEventListener("click",()=>{p>0&&(p-=1,w())}),v.addEventListener("click",()=>{p<l-1?(p+=1,w()):(g.style.width="100%",this.trackEvent(e.id,"clicked",{meta:{answers:h}}),this.submitWidgetResponse(e,"form",{answers:h}),this._playReaction(r,"affirm","check.json",t),window.setTimeout(()=>{o.parentNode&&document.body.removeChild(o)},2300))}),w(),this.addCloseButton(r,o,e.id),s.appendChild(r),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderPushPrimer(e,t,n,i){const o=this.createOverlay("aegis-in-app-push-primer-overlay"),s=document.createElement("div");s.style.cssText=`\n max-width: 340px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 36px; margin-bottom: 8px;",r.textContent=t.icon||"🔔",a.appendChild(r);const c=document.createElement("div");c.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",c.textContent=e.title||"Stay in the loop",a.appendChild(c);const d=document.createElement("div");d.style.cssText="font-size: 14px; opacity: 0.85; margin-bottom: 18px;",d.textContent=e.body||"Enable notifications so you never miss an offer.",a.appendChild(d);const l="undefined"!=typeof Notification&&"function"==typeof Notification.requestPermission,p=document.createElement("button");p.textContent=t.allow_text||"Enable notifications",p.style.cssText=`width: 100%; padding: 12px 16px; border-radius: 10px; border: none; background: ${i}; color: ${n}; font-size: 15px; font-weight: 600; cursor: pointer; margin-bottom: 8px;`,p.addEventListener("click",()=>{if(!l)return this.trackEvent(e.id,"dismissed",{meta:{reason:"unsupported"}}),void(o.parentNode&&document.body.removeChild(o));Promise.resolve(Notification.requestPermission()).then(t=>{this.trackEvent(e.id,"clicked",{meta:{permission:t}}),o.parentNode&&document.body.removeChild(o)})}),a.appendChild(p);const h=document.createElement("button");h.textContent=t.dismiss_text||"Not now",h.style.cssText=`width: 100%; padding: 10px 16px; border-radius: 10px; border: none; background: transparent; color: ${i}; opacity: 0.7; font-size: 14px; cursor: pointer;`,h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),o.parentNode&&document.body.removeChild(o)}),a.appendChild(h),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderQuiz(e,t,n,i){const o=this.createOverlay("aegis-in-app-quiz-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 22px; text-align: center;",s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o),this._runQuizFlow(e,t,n,i,a,o)}renderQuizSlot(e,t,n,i,o){if(0===(Array.isArray(t.questions)?t.questions:[]).length)return!1;const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-quiz-card",e.id,n,i,s.radius),r=document.createElement("div");return r.style.cssText=`padding: ${s.padY??18}px ${s.padX??18}px; text-align: center;`,a.appendChild(r),o.appendChild(a),this._runQuizFlow(e,t,n,i,r,null),!0}_runQuizFlow(e,t,n,i,o,s){const a=Array.isArray(t.questions)?t.questions:[],r=Array.isArray(t.result_mapping)?t.result_mapping:[],c="knowledge"===t.quiz_type,d=a.length,l=[],p={},h=c?a.reduce((e,t)=>e+("number"==typeof t.points?t.points:1),0):0;let u=0,g=0;const m=()=>{for(;o.firstChild;)o.removeChild(o.firstChild)},f=(e,t=!1)=>{const n=document.createElement("div");return n.style.cssText=`font-size: ${t?19:14}px; font-weight: ${t?800:600}; letter-spacing: -0.01em; line-height: 1.3; margin-bottom: ${t?6:14}px; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;`,n.textContent=e,n},x=()=>{m();let a=null,d=u;if(c)a=r.find(e=>{const t="number"==typeof e.min_score?e.min_score:-1/0,n="number"==typeof e.max_score?e.max_score:1/0;return u>=t&&u<=n})||r[r.length-1]||null;else{let e=-1;for(const t of r){const n="string"==typeof t.id?t.id:"",i=n&&p[n]||0;i>e&&(e=i,a=t)}d=e<0?0:e,a=a||r[0]||null}const g=a&&"string"==typeof a.title?a.title:c&&h?`You scored ${u} of ${h}`:"Your result",x=a&&"string"==typeof a.body?a.body:t.thank_you_message||"Thanks for completing the quiz!";o.appendChild(f(g,!0));const y=document.createElement("div");y.style.cssText="font-size: 13.5px; opacity: 0.85; line-height: 1.45; margin: 2px 0 14px;",y.textContent=x,o.appendChild(y);const b=a&&"string"==typeof a.action_url?a.action_url:"";if(b){const t=document.createElement("button");t.type="button",t.textContent=e.button_text||"Continue",t.style.cssText=`padding: 11px 28px; border-radius: 999px; border: none; background: ${i}; color: ${n}; font-weight: 800; font-size: 14px; cursor: pointer; margin-top: 2px;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const t=this.sanitizeUrl(b);t&&this.navigateToCampaignAction(e,t)}),o.appendChild(t)}this._playReaction(o,"affirm","check.json",t),s&&this.addCloseButton(o,s,e.id),this.submitWidgetResponse(e,"quiz",{answers:l,score:d,result_title:g,result_id:a&&"string"==typeof a.id?a.id:void 0,quiz_type:c?"knowledge":"personality"})},y=()=>{if(g>=d)return void x();m();const t=a[g];if(e.title){const t=document.createElement("div");t.style.cssText="font-size: 11px; font-weight: 700; letter-spacing: 0.3px; text-transform: uppercase; opacity: 0.55; margin-bottom: 10px;",t.textContent=e.title,o.appendChild(t)}const n=document.createElement("div");n.style.cssText=`height: 4px; border-radius: 999px; background: ${i}1f; overflow: hidden; margin-bottom: 8px;`;const r=document.createElement("div");r.style.cssText=`height: 100%; width: ${d?Math.round(g/d*100):0}%; background: ${i}; border-radius: 999px; transition: width 0.3s ease;`,n.appendChild(r),o.appendChild(n);const h=document.createElement("div");h.style.cssText="font-size: 11.5px; opacity: 0.6; margin-bottom: 12px; font-weight: 600;",h.textContent=`Question ${g+1} of ${d}`,o.appendChild(h);const b=t.image_url;if("string"==typeof b&&/^https?:\/\//i.test(b)){const e=document.createElement("img");e.src=b,e.alt="",e.style.cssText="width: 100%; max-height: 140px; object-fit: cover; border-radius: 10px; margin-bottom: 12px;",o.appendChild(e)}o.appendChild(f("string"==typeof t.question?t.question:""));const v=Array.isArray(t.options)?t.options.filter(e=>"string"==typeof e):[],w="number"==typeof t.correct_index?t.correct_index:-1,_="number"==typeof t.points?t.points:1,C=document.createElement("div");C.style.cssText="display: flex; flex-direction: column; gap: 8px;";const k=[];v.forEach((e,n)=>{const o=document.createElement("button");o.type="button",o.style.cssText=`padding: 11px 14px; border-radius: 10px; border: 1.5px solid ${i}2e; background: transparent; color: ${i}; font-size: 14px; cursor: pointer; text-align: left; transition: all 0.15s; font-weight: 600;`,o.textContent=e,o.addEventListener("click",()=>{if(o.disabled)return;k.forEach(e=>{e.disabled=!0}),l.push(n);let e=280;if(c){if(n===w&&(u+=_),w>=0){const t=n===w;o.style.borderColor=t?"#10b981":"#ef4444",o.style.background=(t?"#10b981":"#ef4444")+"22",!t&&k[w]&&(k[w].style.borderColor="#10b981",k[w].style.background="#10b98114"),e=680}}else{const e=(Array.isArray(t.option_results)?t.option_results:[])[n];"string"==typeof e&&e&&(p[e]=(p[e]||0)+1),o.style.borderColor=i,o.style.background=`${i}14`}window.setTimeout(()=>{g+=1,y()},e)}),C.appendChild(o),k.push(o)}),o.appendChild(C),s&&this.addCloseButton(o,s,e.id)};y()}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.className="aegis-cta",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&&this.navigateToCampaignAction(e,t)}}),i}addCloseButton(e,t,n){const i=document.createElement("div");i.style.cssText="margin-top: 12px; font-size: 12px; opacity: 0.6; cursor: pointer;",i.textContent="Close",i.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(i)}navigateToCampaignAction(e,t,n="cta"){if("undefined"==typeof window)return;if(t.startsWith("aegis://"))return void this.runCampaignActionVerb(e,t);let i=!1;const o={campaign:e,action_url:t,button_id:n,preventDefault:()=>{i=!0,o.defaultPrevented=!0},defaultPrevented:!1},s=this.emit("campaign-click",o),a=new CustomEvent("aegis:campaign-click",{detail:{campaign_id:e.id,campaign_type:e.type,action_url:t,button_id:n},cancelable:!0}),r=window.dispatchEvent(a);!s||i||!r||a.defaultPrevented||(window.location.href=t)}runCampaignActionVerb(e,t){const n=t.slice(8),[i,o]=n.split("?"),s=new URLSearchParams(o||"");switch(i){case"dismiss":this.trackEvent(e.id,"dismissed",{meta:{reason:"cta"}}),this.removeCampaignEl(e.id);break;case"request-push":this.trackEvent(e.id,"clicked",{meta:{verb:"request-push"}}),"undefined"!=typeof Notification&&"function"==typeof Notification.requestPermission&&Promise.resolve(Notification.requestPermission()).then(t=>{this.trackEvent(e.id,"clicked",{meta:{permission:t}})}),this.removeCampaignEl(e.id);break;case"cart-add":{const t=s.get("sku")||"";this.trackEvent(e.id,"clicked",{meta:{verb:"cart-add",sku:t}});const n=new CustomEvent("aegis:cart-add",{detail:{sku:t,qty:1,campaign_id:e.id},cancelable:!0});window.dispatchEvent(n)&&!n.defaultPrevented&&t&&(window.location.href=`/p/${encodeURIComponent(t)}`);break}default:this.log(`Unknown campaign action verb: ${i}`,"warn")}}removeCampaignEl(e){"undefined"!=typeof document&&document.querySelectorAll(`[data-campaign-id="${e}"]`).forEach(e=>{var t;return null==(t=e.parentNode)?void 0:t.removeChild(e)})}_contrastText(e){const t=/^#?([0-9a-fA-F]{6})$/.exec(this.sanitizeColor(e));if(!t)return"#ffffff";const n=parseInt(t[1],16);return(.299*(n>>16&255)+.587*(n>>8&255)+.114*(255&n))/255>.62?"#0f172a":"#ffffff"}_surfacePalette(e){const t=e.interactive_config||{},n=this.sanitizeColor(e.background_color||"#4169e1");if("branded"===t.surface_style){const t=n,i=e.text_color?this.sanitizeColor(e.text_color):"#ffffff";return{bg:t,text:i,btnBg:i,btnText:t,accent:i,branded:!0}}return{bg:"#ffffff",text:"#0f172a",btnBg:n,btnText:this._contrastText(n),accent:n,branded:!1}}inAppStyle(e){const t=e.interactive_config||{},n=(e,t)=>{const n=Number(e);return Number.isFinite(n)?n:t},i=this._surfacePalette(e);return{bg:i.bg,text:i.text,btnBg:i.btnBg,btnText:i.btnText,accent:i.accent,radius:n(t.border_radius,16),btnRadius:n(t.button_radius,999),padX:n(t.padding_x,24),padY:n(t.padding_y,24),weight:String(t.heading_font_weight||"700"),mediaHeight:n(t.media_height,160),overlay:n(t.overlay_opacity,50)/100}}renderBanner(e){const t=document.createElement("div");t.className="aegis-in-app-banner",t.setAttribute("data-campaign-id",e.id);const n=this.inAppStyle(e),i=n.padY,o=n.padX,s=e.interactive_config||{},a="bottom"===s.banner_position;t.style.cssText=`\n position: fixed;\n ${a?"bottom: 0;":"top: 0;"}\n left: 0;\n right: 0;\n background: ${n.bg};\n color: ${n.text};\n padding: ${i}px ${o}px;\n z-index: 999999;\n box-shadow: 0 ${a?"-2px":"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: ${a?"aegisSlideInFromBottom":"aegisSlideDown"} 0.3s ease-out;\n `,t.setAttribute("data-banner-position",a?"bottom":"top");const r=document.createElement("div");if(r.style.cssText="flex: 1; display: flex; align-items: center; gap: 12px;",e.image_url){const t=document.createElement("img"),n=this.sanitizeUrl(e.image_url);n&&(t.src=n,t.alt="",t.style.cssText="width: 40px; height: 40px; border-radius: 4px; object-fit: cover;",r.appendChild(t))}const c=document.createElement("div");c.style.cssText="flex: 1;";const d=document.createElement("div");d.textContent=e.title,d.style.cssText=`font-weight: ${n.weight}; font-size: 14px; margin-bottom: 4px;`,c.appendChild(d);const l=document.createElement("div");l.textContent=e.body,l.style.cssText="font-size: 13px; opacity: 0.9;",c.appendChild(l),r.appendChild(c);const p=document.createElement("div");p.style.cssText="display: flex; align-items: center; gap: 12px; margin-left: 16px;";const h=e.button_text||(e.action_url?"Learn more":"");if(h){const i=document.createElement("button");i.className="aegis-cta",i.textContent=h,i.style.cssText=`\n background: ${n.btnBg};\n color: ${n.btnText};\n border: none;\n padding: 8px 16px;\n border-radius: ${n.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 13px;\n white-space: nowrap;\n `,i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeBanner(t)}),p.appendChild(i)}const u=document.createElement("button");u.textContent="✕",u.setAttribute("aria-label","Close"),u.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 ",u.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),p.appendChild(u),t.appendChild(r),t.appendChild(p),this.addAnimationStyles(),document.body.appendChild(t);const g=Number(s.banner_auto_dismiss_ms)||0;g>0&&window.setTimeout(()=>{t.parentNode&&this.removeBanner(t)},g)}renderModal(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=document.createElement("div");o.className="aegis-in-app-modal-overlay",o.setAttribute("data-campaign-id",e.id),o.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n `;const s=document.createElement("div");if(s.className="aegis-in-app-modal",s.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow: auto;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n animation: aegisScaleIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,i){const n=document.createElement("div");n.style.cssText=`position: relative; width: 100%; height: ${t.mediaHeight}px; overflow: hidden; border-radius: ${t.radius}px ${t.radius}px 0 0; background: #000;`,this._heroVideo(i,e.image_url,n,"bottom-left"),s.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%; height: ${t.mediaHeight}px; object-fit: cover; border-radius: ${t.radius}px ${t.radius}px 0 0;`,s.appendChild(n))}const a=document.createElement("div");a.style.cssText=`padding: ${t.padY}px ${t.padX}px;`;const r=document.createElement("h2");r.textContent=e.title,r.style.cssText=`margin: 0 0 12px 0; font-size: 20px; font-weight: ${t.weight}; color: ${t.text};`,a.appendChild(r);const c=document.createElement("p");c.textContent=e.body,c.style.cssText=`margin: 0 0 20px 0; font-size: 15px; line-height: 1.5; color: ${t.text}; opacity: 0.9;`,a.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 12px; justify-content: flex-end; align-items: center;";const l=n.modal_secondary_text;if(l){const i=n.modal_secondary_url,s=document.createElement("button");s.type="button",s.textContent=l,s.style.cssText=`background: transparent; border: 1px solid ${t.text}55; color: ${t.text}; opacity: 0.8; padding: 10px 24px; border-radius: ${t.btnRadius}px; font-weight: 600; cursor: pointer; font-size: 14px;`,s.addEventListener("click",()=>{if(i){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const t=this.sanitizeUrl(i);if(t)return this.navigateToCampaignAction(e,t),void this.removeModal(o)}this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),d.appendChild(s)}const p=e.button_text||(e.action_url?"Continue":"");if(p){const n=document.createElement("button");n.className="aegis-cta",n.textContent=p,n.style.cssText=`\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n padding: 10px 24px;\n border-radius: ${t.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(o)}),d.appendChild(n)}const h=document.createElement("button");h.textContent="Close",h.style.cssText=`\n background: transparent;\n border: 1px solid ${t.text}55;\n color: ${t.text};\n opacity: 0.8;\n padding: 10px 24px;\n border-radius: ${t.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),d.appendChild(h),a.appendChild(d),s.appendChild(a),o.appendChild(s),!1!==n.modal_dismiss_on_overlay&&o.addEventListener("click",t=>{t.target===o&&(this.trackEvent(e.id,"dismissed"),this.removeModal(o))}),this.addAnimationStyles(),document.body.appendChild(o)}_heroVideo(e,t,n,i){const o=this.sanitizeUrl(e);if(!o)return null;const s=document.createElement("video");if(s.src=o,s.muted=!0,s.loop=!0,s.autoplay=!0,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline",""),s.controls=!1,t){const e=this.sanitizeUrl(t);e&&(s.poster=e)}s.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; background: #000;",n.appendChild(s);const a=document.createElement("button");a.type="button";const r=()=>{a.replaceChildren();const e=document.createElement("span");if(e.style.fontSize="13px",e.textContent=s.muted?"🔇":"🔊",a.appendChild(e),s.muted){const e=document.createElement("span");e.textContent="Tap for sound",a.appendChild(e)}};return a.style.cssText=`position: absolute; ${"top-left"===i?"top: 16px; left: 16px;":"bottom: 16px; left: 16px;"} display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,0.6); color: #fff; border: none; border-radius: 999px; padding: 6px 11px; font-size: 11.5px; font-weight: 700; cursor: pointer; z-index: 3; backdrop-filter: blur(3px);`,a.setAttribute("aria-label","Toggle sound"),a.addEventListener("click",e=>{e.stopPropagation(),s.muted=!s.muted,!s.muted&&s.paused&&s.play().catch(()=>{}),r()}),s.addEventListener("volumechange",r),r(),n.appendChild(a),s.play().catch(()=>{}),s}renderFullScreen(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=!(!i&&!e.image_url),s="background"===(n.fullscreen_layout||(o?"background":"centered"))&&o,a=s?"#ffffff":t.text,r=document.createElement("div");if(r.className="aegis-in-app-fullscreen-overlay",r.setAttribute("data-campaign-id",e.id),r.style.cssText=`\n position: fixed; inset: 0; background: ${t.bg}; color: ${t.text};\n z-index: 1000001; display: flex; flex-direction: column; align-items: center;\n justify-content: ${s?"flex-end":"center"}; padding: ${s?"0":"40px 20px"};\n animation: aegisFadeIn 0.3s ease-out; overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,s){const t=document.createElement("div");if(t.style.cssText="position: absolute; inset: 0; z-index: 0; background: #000;",i)this._heroVideo(i,e.image_url,t,"top-left");else if(e.image_url){const n=this.sanitizeUrl(e.image_url);if(n){const e=document.createElement("img");e.src=n,e.alt="",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",t.appendChild(e)}}const n=document.createElement("div");n.style.cssText="position: absolute; inset: 0; z-index: 1; background: linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.35) 42%, rgba(0,0,0,0.05) 100%);",t.appendChild(n),r.appendChild(t)}else if(i){const t=document.createElement("div");t.style.cssText="position: relative; width: min(100%, 560px); aspect-ratio: 16/9; margin-bottom: 32px; border-radius: 14px; overflow: hidden; background: #000;",this._heroVideo(i,e.image_url,t,"bottom-left"),r.appendChild(t)}else if(e.image_url){const t=this.sanitizeUrl(e.image_url);if(t){const e=document.createElement("img");e.src=t,e.alt="",e.style.cssText="max-width: 100%; max-height: 40vh; object-fit: contain; margin-bottom: 32px;",r.appendChild(e)}}const c=document.createElement("div");c.style.cssText=s?`position: relative; z-index: 2; max-width: 640px; width: 100%; box-sizing: border-box; text-align: center; padding: 0 24px 52px; color: ${a}; animation: aegisFadeIn 0.45s ease-out 0.1s both;`:"max-width: 600px; text-align: center;";const d=document.createElement("h1");d.textContent=e.title,d.style.cssText=`margin: 0 0 16px 0; font-size: ${s?"30px":"32px"}; font-weight: ${t.weight}; color: ${a};`+(s?" text-shadow: 0 2px 12px rgba(0,0,0,0.4);":""),c.appendChild(d);const l=document.createElement("p");l.textContent=e.body,l.style.cssText=`margin: 0 0 28px 0; font-size: ${s?"16px":"18px"}; line-height: 1.6; opacity: 0.92; color: ${a};`,c.appendChild(l);const p=e.button_text||(e.action_url?"Continue":"");if(p){const n=document.createElement("button");n.className="aegis-cta",n.textContent=p,n.style.cssText=`\n background: ${t.btnBg}; color: ${t.btnText}; border: none;\n padding: 16px 48px; border-radius: ${t.btnRadius}px; font-weight: 700;\n font-size: 18px; cursor: pointer; display: block; margin: 0 auto 12px;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(r)}),c.appendChild(n)}const h=n.fullscreen_secondary_text;if(h){const t=n.fullscreen_secondary_url,i=document.createElement("button");i.type="button",i.textContent=h,i.style.cssText=`background: transparent; border: none; color: ${a}; opacity: 0.75; font-size: 14px; font-weight: 600; cursor: pointer; padding: 8px; display: block; margin: 0 auto; text-decoration: underline;`,i.addEventListener("click",()=>{if(t){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const n=this.sanitizeUrl(t);if(n)return this.navigateToCampaignAction(e,n),void this.removeModal(r)}this.trackEvent(e.id,"dismissed"),this.removeModal(r)}),c.appendChild(i)}r.appendChild(c);const u=document.createElement("button");u.textContent="✕",u.setAttribute("aria-label","Close"),u.style.cssText=`\n position: absolute; top: 20px; right: 20px; z-index: 3; background: ${s?"rgba(0,0,0,0.45)":"transparent"};\n border: none; color: ${s?"#fff":"inherit"}; font-size: ${s?"20px":"32px"}; cursor: pointer;\n padding: 0; width: ${s?"36px":"48px"}; height: ${s?"36px":"48px"}; border-radius: 50%;\n display: flex; align-items: center; justify-content: center; opacity: ${s?"0.9":"0.6"};\n `,u.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(r)}),r.appendChild(u),this.addAnimationStyles(),document.body.appendChild(r)}renderHalfInterstitial(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=document.createElement("div");o.className="aegis-in-app-half-interstitial-overlay",o.setAttribute("data-campaign-id",e.id),o.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\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 s=document.createElement("div");s.className="aegis-in-app-half-interstitial",s.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px ${t.radius}px 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 `;const a=document.createElement("div");if(a.style.cssText=`width: 40px; height: 4px; border-radius: 2px; background: ${t.text}33; margin: 10px auto 0;`,s.appendChild(a),i){const n=document.createElement("div");n.style.cssText=`position: relative; width: 100%; height: ${t.mediaHeight}px; overflow: hidden; margin-top: 10px; background: #000;`,this._heroVideo(i,e.image_url,n,"bottom-left"),s.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%; height: ${t.mediaHeight}px; object-fit: cover; margin-top: 10px;`,s.appendChild(n))}const r=document.createElement("div");r.style.cssText=`padding: ${t.padY}px ${t.padX}px;`;const c=document.createElement("h2");c.textContent=e.title,c.style.cssText=`margin: 0 0 12px 0; font-size: 24px; font-weight: ${t.weight}; color: ${t.text};`,r.appendChild(c);const d=document.createElement("p");d.textContent=e.body,d.style.cssText=`margin: 0 0 24px 0; font-size: 16px; line-height: 1.5; color: ${t.text}; opacity: 0.9;`,r.appendChild(d);const l=e.button_text||(e.action_url?"Continue":"");if(l){const n=document.createElement("button");n.className="aegis-cta",n.textContent=l,n.style.cssText=`\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n padding: 14px 32px;\n border-radius: ${t.btnRadius}px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(o)}),r.appendChild(n)}const p=n.half_secondary_text;if(p){const i=n.half_secondary_url,s=document.createElement("button");s.type="button",s.textContent=p,s.style.cssText=`margin-top: 10px; background: transparent; border: none; color: ${t.text}; opacity: 0.75; font-weight: 600; font-size: 14px; cursor: pointer; width: 100%; text-decoration: underline;`,s.addEventListener("click",()=>{if(i){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const t=this.sanitizeUrl(i);if(t)return this.navigateToCampaignAction(e,t),void this.removeModal(o)}this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),r.appendChild(s)}s.appendChild(r);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: 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 ",h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),s.style.position="relative",s.appendChild(h),o.appendChild(s),!1!==n.half_dismiss_on_overlay&&o.addEventListener("click",t=>{t.target===o&&(this.trackEvent(e.id,"dismissed"),this.removeModal(o))}),this.addAnimationStyles(),document.body.appendChild(o)}renderAlert(e){const t=this.inAppStyle(e),n=document.createElement("div");n.className="aegis-in-app-alert-overlay",n.setAttribute("data-campaign-id",e.id),n.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.2s ease-out;\n `;const i=document.createElement("div");i.className="aegis-in-app-alert",i.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px;\n max-width: 320px;\n width: 85%;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n animation: aegisScaleIn 0.2s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow: hidden;\n `;const o=document.createElement("div");o.style.cssText=`padding: ${t.padY}px ${t.padX}px; text-align: center;`;const s={info:{glyph:"ℹ",color:"#3b82f6"},success:{glyph:"✓",color:"#10b981"},warning:{glyph:"!",color:"#f59e0b"},error:{glyph:"✕",color:"#ef4444"}}[(e.interactive_config||{}).alert_variant||""];if(s){const e=document.createElement("div");e.style.cssText=`width: 48px; height: 48px; border-radius: 50%; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 800; background: ${s.color}22; color: ${s.color};`,e.textContent=s.glyph,o.appendChild(e)}const a=document.createElement("h3");a.textContent=e.title,a.style.cssText=`margin: 0 0 8px 0; font-size: 18px; font-weight: ${t.weight}; color: ${t.text};`,o.appendChild(a);const r=document.createElement("p");r.textContent=e.body,r.style.cssText=`margin: 0; font-size: 14px; line-height: 1.4; color: ${t.text}; opacity: 0.85;`,o.appendChild(r),i.appendChild(o);const c=document.createElement("div");c.style.cssText=`display: flex; gap: 8px; justify-content: center; padding: 0 ${t.padX}px ${t.padY}px;`;const d=e.button_text||(e.action_url?"OK":"");if(d){const i=document.createElement("button");i.className="aegis-cta",i.textContent=d,i.style.cssText=`\n flex: 1;\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n border-radius: ${t.btnRadius}px;\n padding: 12px;\n font-weight: 600;\n font-size: 15px;\n cursor: pointer;\n `,i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(n)}),c.appendChild(i)}const l=document.createElement("button");l.textContent="Cancel",l.style.cssText=`\n flex: 1;\n background: transparent;\n border: 1px solid ${t.text}55;\n color: ${t.text};\n opacity: 0.85;\n border-radius: ${t.btnRadius}px;\n padding: 12px;\n font-weight: 600;\n font-size: 15px;\n cursor: pointer;\n `,l.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(n)}),c.appendChild(l),i.appendChild(c),n.appendChild(i),this.addAnimationStyles(),document.body.appendChild(n)}_pipCornerCss(e,t){switch(e){case"bottom-left":return`bottom: ${t}px; left: ${t}px;`;case"top-right":return`top: ${t}px; right: ${t}px;`;case"top-left":return`top: ${t}px; left: ${t}px;`;default:return`bottom: ${t}px; right: ${t}px;`}}renderPIP(e){const t=e.interactive_config||{},n=t.pip_position||"bottom-right",i=t.pip_size||"standard",o=!1!==t.pip_autoplay,s=!1!==t.pip_loop,a=!1!==t.pip_muted,r=!1!==t.pip_expandable,c=!0===t.pip_draggable,d=20,l="undefined"!=typeof window&&window.innerWidth||360,p=Math.min({compact:250,standard:320,large:400}[i]??320,l-40),h=document.createElement("div");h.className="aegis-in-app-pip",h.setAttribute("data-campaign-id",e.id);const u=this._pipCornerCss(n,d),g=n.startsWith("top")?"aegisSlideDown":"aegisSlideUp";h.style.cssText=`\n position: fixed; ${u} width: ${p}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 14px; overflow: hidden;\n box-shadow: 0 10px 30px rgba(0,0,0,0.38); z-index: 999999;\n animation: ${g} 0.3s ease-out; transition: width 0.25s ease, border-radius 0.25s ease;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `;const m=document.createElement("div");m.style.cssText="position: relative; width: 100%; background: #000; line-height: 0; aspect-ratio: 16 / 9;";const f=e.video_url||t.video_url;let x=null,y=!1;if(f){const t=this.sanitizeUrl(f);if(t){if(x=document.createElement("video"),x.src=t,x.muted=a,x.loop=s,x.autoplay=o,x.playsInline=!0,x.setAttribute("playsinline",""),x.setAttribute("webkit-playsinline",""),x.controls=!1,e.image_url){const t=this.sanitizeUrl(e.image_url);t&&(x.poster=t)}x.style.cssText="width: 100%; height: 100%; display: block; object-fit: cover; background: #000;",m.appendChild(x),y=!0}}else if(e.image_url){const t=this.sanitizeUrl(e.image_url);if(t){const e=document.createElement("img");e.src=t,e.alt="",e.style.cssText="width: 100%; height: 100%; display: block; object-fit: cover;",m.appendChild(e),y=!0}}if(!y){const e=document.createElement("div");e.style.cssText="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #1f2937, #0f172a); color: rgba(255,255,255,0.35); font-size: 34px;",e.textContent="▶",m.appendChild(e)}if(h.appendChild(m),x){const e=x,t=document.createElement("button");t.type="button",t.setAttribute("aria-label","Play or pause"),t.style.cssText="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 52px; height: 52px; border-radius: 50%; border: none; background: rgba(0,0,0,0.45); color: #fff; font-size: 22px; cursor: pointer; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.25s ease; backdrop-filter: blur(2px);";const n=()=>{t.textContent=e.paused?"▶":"❚❚",t.style.opacity=e.paused?"1":"0"},i=()=>{e.paused?e.play().catch(()=>{}):e.pause()};t.addEventListener("click",e=>{e.stopPropagation(),i()}),m.addEventListener("click",i),e.addEventListener("play",()=>{n(),setTimeout(()=>{e.paused||(t.style.opacity="0")},600)}),e.addEventListener("pause",n),m.appendChild(t);const s=document.createElement("button");s.type="button";const a=()=>{s.replaceChildren();const t=document.createElement("span");if(t.style.fontSize="13px",t.textContent=e.muted?"🔇":"🔊",s.appendChild(t),e.muted){const e=document.createElement("span");e.textContent="Tap for sound",s.appendChild(e)}s.style.padding=e.muted?"6px 11px":"6px 9px"};s.style.cssText="position: absolute; left: 10px; bottom: 10px; display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,0.6); color: #fff; border: none; border-radius: 999px; font-size: 11.5px; font-weight: 700; cursor: pointer; z-index: 3; backdrop-filter: blur(3px);",s.setAttribute("aria-label","Toggle sound"),s.addEventListener("click",t=>{t.stopPropagation(),e.muted=!e.muted,!e.muted&&e.paused&&e.play().catch(()=>{}),a()}),e.addEventListener("volumechange",a),a(),m.appendChild(s),o&&e.play().catch(()=>{})}const b=this.inAppStyle(e),v=b.btnBg,w=b.btnText,_=document.createElement("div");if(_.style.cssText="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(to top, rgba(0,0,0,0.92), rgba(0,0,0,0.2) 70%, transparent); padding: 36px 14px 13px; color: #fff; pointer-events: none;",e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-size: 14px; font-weight: 700; margin-bottom: 3px; line-height: 1.25;",_.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 12px; opacity: 0.9; line-height: 1.35;",_.appendChild(t)}if(e.action_url&&e.button_text){const t=document.createElement("button");t.type="button",t.textContent=e.button_text,t.style.cssText=`pointer-events: auto; margin-top: 10px; padding: 8px 18px; border-radius: 999px; border: none; background: ${v}; color: ${w}; font-weight: 800; font-size: 12.5px; cursor: pointer;`,t.addEventListener("click",t=>{t.stopPropagation(),this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n)}),_.appendChild(t)}h.appendChild(_);const C=document.createElement("div");C.style.cssText="position: absolute; top: 8px; right: 8px; display: flex; gap: 6px; z-index: 4;";const k="background: rgba(0,0,0,0.6); border: none; color: #fff; font-size: 14px; cursor: pointer; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(3px);";let E=!1,S=null,T=null;const $=()=>{E=!1,S&&(S.remove(),S=null),h.style.position="fixed",h.style.cssText=`\n position: fixed; ${u} width: ${p}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 14px; overflow: hidden;\n box-shadow: 0 10px 30px rgba(0,0,0,0.38); z-index: 999999; transition: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,T&&(T.textContent="⤢",T.setAttribute("aria-label","Expand"))},I=()=>{E=!0,this.trackEvent(e.id,"impression",{meta:{action:"pip_expand"}}),S=document.createElement("div"),S.style.cssText="position: fixed; inset: 0; background: rgba(0,0,0,0.72); z-index: 999998; animation: aegisFadeIn 0.2s ease-out;",S.addEventListener("click",$),document.body.appendChild(S);const t=Math.min(760,l-40);h.style.cssText=`\n position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);\n width: ${t}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 16px; overflow: hidden;\n box-shadow: 0 24px 60px rgba(0,0,0,0.55); z-index: 999999; transition: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,T&&(T.textContent="✕",T.setAttribute("aria-label","Minimize")),x&&x.muted&&(x.muted=!1,x.dispatchEvent(new Event("volumechange")))};r&&y&&(T=document.createElement("button"),T.type="button",T.textContent="⤢",T.setAttribute("aria-label","Expand"),T.style.cssText=k,T.addEventListener("click",e=>{e.stopPropagation(),E?$():I()}),C.appendChild(T));const z=document.createElement("button");if(z.type="button",z.textContent="✕",z.setAttribute("aria-label","Close"),z.style.cssText=k,z.addEventListener("click",t=>{t.stopPropagation(),this.trackEvent(e.id,"dismissed"),S&&S.remove(),h.style.animation=("aegisSlideDown"===g?"aegisSlideUp":"aegisSlideDown")+" 0.3s ease-out",setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},300)}),C.appendChild(z),h.appendChild(C),c){let e=!1,t=0,n=0,i=0,o=0;const s=s=>{if(E)return;if(s.target.closest("button"))return;e=!0;const a=h.getBoundingClientRect();i=a.left,o=a.top,t=s.clientX,n=s.clientY,h.style.bottom="auto",h.style.right="auto",h.style.left=`${i}px`,h.style.top=`${o}px`,h.setPointerCapture(s.pointerId)},a=s=>{if(!e)return;const a=Math.max(4,Math.min(l-h.offsetWidth-4,i+(s.clientX-t))),r=Math.max(4,Math.min((window.innerHeight||800)-h.offsetHeight-4,o+(s.clientY-n)));h.style.left=`${a}px`,h.style.top=`${r}px`},r=()=>{e=!1};h.addEventListener("pointerdown",s),h.addEventListener("pointermove",a),h.addEventListener("pointerup",r),h.style.touchAction="none"}this.addAnimationStyles(),document.body.appendChild(h),this.trackEvent(e.id,"impression")}removeBanner(e){const t="bottom"===e.getAttribute("data-banner-position");e.style.animation=(t?"aegisSlideOutToBottom":"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)}_spotlightDimColor(e,t,n){const i=e.spotlight_dim_color||"dark",o="black"===i?"#000000":"brand"===i?t:"custom"===i?this.sanitizeColor(e.spotlight_dim_custom||"#0f172a"):"#0f172a",s=Math.round(255*Math.max(0,Math.min(1,n))).toString(16).padStart(2,"0");return/^#[0-9a-fA-F]{6}$/.test(o)?`${o}${s}`:`rgba(15,23,42,${n})`}renderTooltip(e){const t=e.interactive_config||{},n=t.tooltip_anchor_selector||"[data-aegis-tooltip]",i=t.tooltip_position||"auto",o=!1!==t.tooltip_highlight;let s=document.querySelector(n);if(!s)return console.warn(`[AegisInApp] Tooltip anchor "${n}" not found on this surface — tooltip not shown. On native apps this must be a key registered via registerInAppAnchor(); adding a new anchor needs an app release.`),void this.trackEvent(e.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:n,widget_type:"tooltip"}});const a=this.sanitizeColor(e.background_color||"#1a1a1a"),r=this.sanitizeColor(e.text_color||"#ffffff"),c=document.createElement("div");c.className="aegis-in-app-tooltip",c.setAttribute("data-campaign-id",e.id),c.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${a}; color: ${r}; border-radius: 10px; padding: 14px 16px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.18); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.2s ease-out; pointer-events: auto;\n `;const d=document.createElement("div");d.className="aegis-tooltip-arrow",d.style.cssText=`\n position: absolute; width: 10px; height: 10px; background: ${a};\n transform: rotate(45deg);\n `;let l=null,p=null,h=null;const u=()=>{c.style.animation="aegisFadeOut 0.2s ease-out",l&&(l.remove(),l=null),p&&(document.removeEventListener("click",p),p=null),h&&(h(),h=null),setTimeout(()=>{var e;null==(e=c.parentNode)||e.removeChild(c)},200),this.trackEvent(e.id,"dismissed")},g=document.createElement("button");if(g.type="button",g.textContent="×",g.setAttribute("aria-label","Close"),g.style.cssText=`\n position: absolute; top: 4px; right: 4px; z-index: 1; background: none; border: none;\n color: ${r}; opacity: 0.7; font-size: 16px; line-height: 1; cursor: pointer;\n width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; padding: 0;\n `,g.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),u()}),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: 18px;",c.appendChild(t)}const m=document.createElement("div");if(m.textContent=e.body||"Here’s a quick tip.",m.style.cssText="font-size: 12px; line-height: 1.4; opacity: 0.9; padding-right: 18px;",c.appendChild(m),e.button_text&&e.action_url){const t=document.createElement("a");t.textContent=e.button_text,t.href=e.action_url,t.style.cssText=`\n display: inline-block; margin-top: 8px; font-size: 12px; font-weight: 600;\n color: ${r}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),c.appendChild(t)}c.appendChild(g),c.appendChild(d),document.body.appendChild(c);const f="spotlight"===t.highlight_style,x="number"==typeof t.spotlight_padding?t.spotlight_padding:f?6:4,y="circle"===t.spotlight_shape?"50%":"12px",b="number"==typeof t.spotlight_dim?Math.max(0,Math.min(95,t.spotlight_dim))/100:.64,v=this._spotlightDimColor(t,a,b);if(o){l=document.createElement("div"),l.className="aegis-tooltip-highlight";const e=f?`box-shadow: 0 0 0 3px rgba(255,255,255,0.92), 0 0 0 6px ${a}66, 0 0 0 9999px ${v};`:`box-shadow: 0 0 0 3px ${a}55, 0 0 0 9999px rgba(0,0,0,0.04);`,t=f?"":"animation: aegisTooltipPulse 1.6s ease-in-out infinite;";l.style.cssText=`position: absolute; z-index: 1000000; pointer-events: none; border-radius: ${f?y:"8px"}; ${e} ${t}`,document.body.appendChild(l)}const w=10+("number"==typeof t.tooltip_offset?t.tooltip_offset:0),_={top:"bottom",bottom:"top",left:"right",right:"left"},C=()=>{if(!s)return;const e=s.getBoundingClientRect(),t=c.getBoundingClientRect(),n=window.scrollX,o=window.scrollY,a=window.innerWidth,r=window.innerHeight;l&&(l.style.top=e.top+o-x+"px",l.style.left=e.left+n-x+"px",l.style.width=`${e.width+2*x}px`,l.style.height=`${e.height+2*x}px`);const p=r-e.bottom,h=e.top,u=a-e.right,g=e.left,m=t.height+w,f=t.width+w,y=e=>"top"===e?h>=m:"bottom"===e?p>=m:"left"===e?g>=f:u>=f;let b=i;"auto"===b?b=p>=m?"bottom":h>=m?"top":u>=f?"right":g>=f?"left":p>=h?"bottom":"top":!y(b)&&y(_[b])&&(b=_[b]);let v=0,C=0,k="",E="",S="",T="";switch(b){case"top":v=e.top+o-t.height-w,C=e.left+n+(e.width-t.width)/2,S="-5px",E=t.width/2-5+"px";break;case"left":v=e.top+o+(e.height-t.height)/2,C=e.left+n-t.width-w,T="-5px",k=t.height/2-5+"px";break;case"right":v=e.top+o+(e.height-t.height)/2,C=e.right+n+w,E="-5px",k=t.height/2-5+"px";break;default:v=e.bottom+o+w,C=e.left+n+(e.width-t.width)/2,k="-5px",E=t.width/2-5+"px"}C=Math.max(8,Math.min(C,a+n-t.width-8)),v=Math.max(8+o,Math.min(v,r+o-t.height-8)),c.style.top=`${v}px`,c.style.left=`${C}px`,d.style.top=k||"",d.style.left=E||"",d.style.bottom=S||"",d.style.right=T||""},k=()=>{if(s&&s.isConnected)return!0;const t=document.querySelector(n);return t?(s=t,!0):(this.trackEvent(e.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:n,widget_type:"tooltip",phase:"runtime"}}),u(),!1)};let E=0;const S=()=>{E||(E=window.requestAnimationFrame(()=>{E=0,k()&&C()}))};C(),window.addEventListener("scroll",S,{passive:!0,capture:!0}),window.addEventListener("resize",S,{passive:!0});let T=null,$=null;"undefined"!=typeof ResizeObserver&&(T=new ResizeObserver(S),s&&T.observe(s),T.observe(document.documentElement)),"undefined"!=typeof MutationObserver&&($=new MutationObserver(S),$.observe(document.body,{childList:!0,subtree:!0,attributes:!0})),h=()=>{E&&(window.cancelAnimationFrame(E),E=0),window.removeEventListener("scroll",S,{capture:!0}),window.removeEventListener("resize",S),T&&(T.disconnect(),T=null),$&&($.disconnect(),$=null)},p=e=>{c.contains(e.target)||s&&s.contains(e.target)||u()},setTimeout(()=>{p&&document.addEventListener("click",p)},100)}_fireConfetti(e){var t;try{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;this.addAnimationStyles();const n=document.createElement("div");n.className="aegis-in-app-confetti",n.style.cssText="position: fixed; left: 0; right: 0; top: 0; height: 0; z-index: 2147483647; pointer-events: none;";const i=["#fbbf24","#10b981","#4169e1","#ef4444","#a855f7"],o=80;for(let e=0;e<o;e++){const t=document.createElement("span"),s=Math.round(e/o*100),a=Math.round(240*(Math.random()-.5))+"px",r=Math.round(1080*Math.random())+"deg",c=(.2*Math.random()).toFixed(2),d=(1.6+1.2*Math.random()).toFixed(2),l=i[e%i.length],p=6+Math.round(6*Math.random());t.style.cssText=`position: absolute; top: 0; left: ${s}%; width: ${p}px; height: ${p}px; background: ${l}; border-radius: 2px; --dx: ${a}; --r: ${r}; animation: aegisConfetti ${d}s cubic-bezier(.2,.6,.3,1) ${c}s forwards;`,n.appendChild(t)}((null==(t=null==e?void 0:e.ownerDocument)?void 0:t.body)||document.body).appendChild(n),window.setTimeout(()=>n.remove(),3200)}catch{}}_playReaction(e,t,n,i){try{if("undefined"==typeof document)return;this.addAnimationStyles();const o="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=e||document.body,a=s.style.position;a&&"static"!==a||(s.style.position="relative");const r=document.createElement("div");r.className="aegis-in-app-reaction",r.style.cssText="position: absolute; inset: 0; z-index: 2147483646; pointer-events: none; overflow: visible;";const c={celebrate:{file:"trophy.json",svg:"gift",ring:"#fbbf24",festive:!0},affirm:{file:"affirm.json",svg:"star",ring:"#fbbf24",festive:!0},acknowledge:{file:"check.json",svg:"check",ring:"#34d399",festive:!1},empathize:{file:"empathize.json",svg:"heart",ring:"",festive:!1}}[t],d=c.festive;if(d&&!o)for(let e=0;e<3;e++){const t=document.createElement("div");t.style.cssText=`position: absolute; left: 50%; top: 50%; width: 60px; height: 60px; border-radius: 50%; border: 3px solid ${c.ring}; animation: aegisRing 1.1s ease-out ${.18*e}s forwards;`,r.appendChild(t)}const l=document.createElement("div"),p=Le(this._reactionSvg(c.svg));p&&l.appendChild(p);const h=o?"":"empathize"!==t?"animation: aegisReactionPop 0.7s cubic-bezier(.2,.9,.3,1.2) forwards, aegisReactionFloatOut 0.7s ease-in 1.9s forwards;":"animation: aegisReactionSoft 0.9s ease-out forwards;",u=d?150:"acknowledge"===t?92:124;l.style.cssText=`position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: ${u}px; height: ${u}px; display: flex; align-items: center; justify-content: center; line-height: 0; filter: drop-shadow(0 8px 16px rgba(0,0,0,0.30)); ${h}`,r.appendChild(l),s.appendChild(r),d&&!o&&this._fireConfetti(e);const g=i&&"object"==typeof i?i.reaction_animations:void 0,m=(g&&"string"==typeof g[t]?g[t]:void 0)||n||c.file;if(!o&&m){const e=this._assetBase(),n="empathize"===t,i=/^https?:\/\//.test(m)?m:`${e}lottie/${m}`;this._loadLottie().then(e=>{e&&l.isConnected&&(l.replaceChildren(),e.loadAnimation({container:l,renderer:"svg",loop:n,autoplay:!0,path:i}))}).catch(()=>{})}window.setTimeout(()=>{r.remove(),s.style.position!==a&&(s.style.position=a)},"acknowledge"===t?1800:d?2700:2200)}catch{}}_reactionSvg(e){switch(e){case"star":return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#fbbf24"/><circle cx="37" cy="37" r="31" fill="none" stroke="#fff" stroke-width="2" opacity="0.6"/><path d="M37 19 l5.6 11.8 13 1.7 -9.5 9 2.4 12.8 -11.5 -6.2 -11.5 6.2 2.4 -12.8 -9.5 -9 13 -1.7 Z" fill="#fff"/></svg>';case"gift":return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#eef2ff"/><rect x="20" y="35" width="34" height="22" rx="3" fill="#6366f1"/><rect x="17" y="28" width="40" height="10" rx="3" fill="#4f46e5"/><rect x="34" y="28" width="6" height="29" fill="#fbbf24"/><path d="M34 28 C28 20 20 24 24 28 Z" fill="#fbbf24"/><path d="M40 28 C46 20 54 24 50 28 Z" fill="#fbbf24"/></svg>';case"heart":return'<svg width="66" height="66" viewBox="0 0 66 66" fill="none" style="animation: aegisBreathe 1.6s ease-in-out infinite; transform-origin: center;"><circle cx="33" cy="33" r="30" fill="#f1f5f9"/><path d="M33 49 C16 38 19 23 28 23 C32 23 33 27 33 27 C33 27 34 23 38 23 C47 23 50 38 33 49 Z" fill="rgba(244,114,182,0.18)" stroke="#f472b6" stroke-width="2.5" stroke-linejoin="round"/></svg>';default:return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#10b981"/><circle cx="37" cy="37" r="31" fill="none" stroke="#fff" stroke-width="2" opacity="0.6"/><path d="M24 38 l9 9 l18 -21" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100" style="animation: aegisDraw 0.45s 0.25s ease forwards"/></svg>'}}_assetBase(){try{const e=Array.from(document.getElementsByTagName("script")).find(e=>/\/(?:aegis|lottie)\.min\.js/.test(e.src));if(e&&e.src)return e.src.replace(/[^/]*(?:\?.*)?$/,"")}catch{}return"/sdk/"}_loadLottie(){const e=window;return e.lottie?Promise.resolve(e.lottie):(e.__aegisLottieP||(e.__aegisLottieP=new Promise((e,t)=>{try{const n=document.createElement("script");n.src=`${this._assetBase()}lottie.min.js`,n.async=!0,n.onload=()=>e(window.lottie),n.onerror=()=>t(new Error("lottie player failed to load")),document.head.appendChild(n)}catch(n){t(n instanceof Error?n:new Error("lottie load error"))}})),e.__aegisLottieP)}addAnimationStyles(){if(document.getElementById("aegis-in-app-styles"))return;const e=document.createElement("style");e.id="aegis-in-app-styles",e.textContent="\n @keyframes aegisSlideDown {\n from { transform: translateY(-100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisSlideUp {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(-100%); opacity: 0; }\n }\n \n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.9); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n\n /* Bottom-anchored slide IN (opposite of aegisSlideUp which slides OUT).\n Used by the preload-first renderers: sticky_bar (bottom),\n progress_bar, carousel_cards, product_recommendation. */\n @keyframes aegisSlideInFromBottom {\n from { transform: translateY(100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n\n /* Bottom-anchored slide OUT (mirror of aegisSlideInFromBottom). A\n bottom banner must exit DOWNWARD, not up through the viewport. */\n @keyframes aegisSlideOutToBottom {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(100%); opacity: 0; }\n }\n\n /* Celebration confetti (ported from the cashier-portal aegis-confetti\n keyframe) — fired on positive moments: high star rating, won spin/\n scratch prize, completed form. Empathetic (no confetti) on negatives. */\n @keyframes aegisConfetti {\n 0% { transform: translate3d(0,0,0) rotate(0); opacity: 1; }\n 100% { transform: translate3d(var(--dx), 112vh, 0) rotate(var(--r)); opacity: 0; }\n }\n\n /* Poll result bar — fills to its share once a vote lands. */\n @keyframes aegisPollFill {\n from { width: 0%; }\n to { width: var(--pct, 0%); }\n }\n\n /* Countdown urgency — pulse the digits red in the final stretch (<60s). */\n @keyframes aegisUrgencyPulse {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n\n /* Emotional reaction (success) — the hero glyph springs in with an\n overshoot, gives a happy wiggle, then gently settles + floats out. */\n @keyframes aegisReactionPop {\n 0% { transform: translate(-50%, -40%) scale(0.2) rotate(-12deg); opacity: 0; }\n 45% { transform: translate(-50%, -52%) scale(1.18) rotate(6deg); opacity: 1; }\n 62% { transform: translate(-50%, -50%) scale(0.94) rotate(-3deg); }\n 78% { transform: translate(-50%, -50%) scale(1.05) rotate(1deg); }\n 100% { transform: translate(-50%, -50%) scale(1) rotate(0); opacity: 1; }\n }\n @keyframes aegisReactionFloatOut {\n 0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }\n 100% { transform: translate(-50%, -150%) scale(0.9); opacity: 0; }\n }\n /* Empathetic reaction — soft fade-in + gentle sway, NO celebration. */\n @keyframes aegisReactionSoft {\n 0% { transform: translate(-50%, -45%) scale(0.7); opacity: 0; }\n 25% { transform: translate(-50%, -50%) scale(1); opacity: 1; }\n 50% { transform: translate(-52%, -50%) scale(1) rotate(-4deg); }\n 75% { transform: translate(-48%, -50%) scale(1) rotate(4deg); }\n 100% { transform: translate(-50%, -50%) scale(1) rotate(0); opacity: 1; }\n }\n /* Radiating celebration rings behind the success glyph. */\n @keyframes aegisRing {\n 0% { transform: translate(-50%, -50%) scale(0.3); opacity: 0.55; }\n 100% { transform: translate(-50%, -50%) scale(2.4); opacity: 0; }\n }\n /* Self-drawing stroke (the check / outline draws itself in). */\n @keyframes aegisDraw {\n from { stroke-dashoffset: 100; }\n to { stroke-dashoffset: 0; }\n }\n /* Gentle breathing for the empathetic heart. */\n @keyframes aegisBreathe {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n /* Comment-box placeholder — inherit the modal's text color (not the\n browser default near-black, which is invisible on a dark/accent modal). */\n .aegis-rating-comment::placeholder, .aegis-field::placeholder { color: currentColor; opacity: 0.55; }\n /* Tooltip target highlight — a soft pulsing ring drawing the eye. */\n @keyframes aegisTooltipPulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n /* Countdown final-minute urgency — a gentle breathing pulse (NOT a harsh\n solid-red fill). */\n @keyframes aegisCountdownPulse {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.04); }\n }\n /* Shared CTA micro-interaction — one consistent hover-lift + press across\n every widget's primary button, so they feel like one system. */\n .aegis-cta { transition: transform 0.12s ease, box-shadow 0.12s ease, filter 0.12s ease; }\n .aegis-cta:hover { transform: translateY(-1px); box-shadow: 0 6px 16px rgba(0,0,0,0.18); filter: brightness(1.04); }\n .aegis-cta:active { transform: translateY(0); box-shadow: 0 2px 6px rgba(0,0,0,0.15); filter: brightness(0.98); }\n @media (prefers-reduced-motion: reduce) { .aegis-cta { transition: none; } .aegis-cta:hover { transform: none; } }\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,n){var i;const o=this.campaigns.find(t=>t.id===e);"dismissed"===t&&o&&this.emit("campaign-dismiss",{campaign:o,source:"close_button"});try{const s=`${this.apiHost}/v1/in_app/events`,a=`inapp_${e}_${t}_${Date.now()}`,r={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey};this.organizationId&&(r["X-Organization-ID"]=this.organizationId),this.userId&&(r["X-User-ID"]=this.userId),this.contactId&&(r["X-Contact-ID"]=this.contactId);const c=null==(i=this.getWorkspaceId)?void 0:i.call(this),d={campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,anonymous_id:this.userId,platform:"web",workspace_id:c,current_surface:this.currentSurface??void 0,step_id:null==n?void 0:n.stepId,journey_execution_id:null==o?void 0:o.journey_execution_id,lifecycle_fork_id:null==o?void 0:o.lifecycle_fork_id,location_id:null==o?void 0:o.location_id,metadata:{property_id:this.propertyId,variant_id:this.getVariantId(e)??void 0,lifecycle_fork_id:null==o?void 0:o.lifecycle_fork_id,location_id:null==o?void 0:o.location_id,...(null==n?void 0:n.meta)??{}},idempotency_key:a};fetch(s,{method:"POST",headers:r,body:JSON.stringify(d),credentials:"include"}).catch(e=>{this.log(`Error tracking event: ${e}`,"error")}),this.log(`Tracked ${t} event for campaign ${e}`)}catch(s){this.log(`Error tracking event: ${s}`,"error")}}log(e,t="log"){this.debugMode&&console[t](`[AegisInApp] ${e}`)}destroy(e){if(this.disconnectSSE(),null==ze||ze.stop(),ze=null,null==Ie||Ie.destroy(),Ie=null,this.activeWebChat=void 0,this.refreshDebounceTimer&&(clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=void 0),"undefined"!=typeof document){document.querySelectorAll(".aegis-in-app-banner, .aegis-in-app-modal-overlay, .aegis-in-app-fullscreen-overlay, .aegis-in-app-half-interstitial-overlay, .aegis-in-app-alert-overlay, .aegis-in-app-pip, .aegis-in-app-nps-overlay, .aegis-in-app-countdown-overlay, .aegis-in-app-rating-overlay, .aegis-in-app-poll-overlay, .aegis-in-app-quiz-overlay, .aegis-in-app-rating-card, .aegis-in-app-nps-card").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const e=document.getElementById("aegis-in-app-styles");e&&e.parentNode&&e.parentNode.removeChild(e)}(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}};Me.CONVERSION_STORAGE_PREFIX="aegis_conv_",Me.REFRESH_DEBOUNCE_MS=300,Me.KNOWN_SURFACES=new Set(["bill","storefront_catalog","storefront_rewards","storefront_feedback","storefront_reviews","storefront_members","external_website","external_mobile_screen"]),Me.SERVED_DEDUP_PREFIX="aegis_served_fired:";let Re=Me;function Pe(e){if(e.id)return`#${CSS.escape(e.id)}`;for(const i of["data-testid","data-test","data-aegis-anchor","data-qa","name"]){const t=e.getAttribute(i);if(t){const n=`${e.tagName.toLowerCase()}[${i}="${CSS.escape(t)}"]`;if(1===document.querySelectorAll(n).length)return n}}const t=[];let n=e;for(;n&&n!==document.body&&t.length<6;){if(n.id){t.unshift(`#${CSS.escape(n.id)}`);break}const e=n.tagName.toLowerCase(),i=n.parentElement;if(!i){t.unshift(e);break}const o=Array.from(i.children).filter(e=>e.tagName===n.tagName),s=o.indexOf(n)+1;t.unshift(o.length>1?`${e}:nth-of-type(${s})`:e),n=i}return t.join(" > ")}async function De(e,t,n={}){const i=`${e.replace(/\/$/,"")}/v1/device-pairing`,o=()=>{};try{const e=await fetch(`${i}/${encodeURIComponent(t)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:"web",device_label:n.deviceLabel||"Web browser"})});if(!e.ok)return{ok:!1,stop:o,error:`claim failed (${e.status})`};const s=async()=>{try{const e=function(e){const t=[],n=document.querySelectorAll("a,button,input,select,textarea,[role],[data-aegis-anchor],[data-testid],h1,h2,h3,img,[data-aegis-slot]");for(const i of Array.from(n)){if(t.length>=400)break;const e=i.getBoundingClientRect();if(e.width<=0||e.height<=0)continue;const n=i.getAttribute("data-aegis-slot"),o=n?`slot:${n}`:i.getAttribute("role")||i.tagName.toLowerCase(),s=(i.textContent||i.getAttribute("aria-label")||"").trim().slice(0,80);t.push({selector:Pe(i),role:o,...s?{text:s}:{},bounds:{x:Math.round(e.left+window.scrollX),y:Math.round(e.top+window.scrollY),w:Math.round(e.width),h:Math.round(e.height)}})}return{screen_name:e||window.location.pathname||"/",view_tree:t,viewport:{w:window.innerWidth,h:window.innerHeight,scale:window.devicePixelRatio||1},platform:"web"}}(n.screenName);await fetch(`${i}/${encodeURIComponent(t)}/screens`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}};if(await s(),!1===n.live)return{ok:!0,stop:o};let a=null;const r=()=>{s()};window.addEventListener("popstate",r),window.addEventListener("hashchange",r),a=setInterval(()=>{s()},4e3);return{ok:!0,stop:()=>{window.removeEventListener("popstate",r),window.removeEventListener("hashchange",r),a&&(clearInterval(a),a=null)}}}catch(s){return{ok:!1,stop:o,error:s instanceof Error?s.message:"pairing error"}}}let Ne=!1;function Fe(e){if(!Ne&&"undefined"!=typeof window)try{const t=new URLSearchParams(window.location.search).get("aegis_pair");if(!t)return;Ne=!0,De(e||"https://api.active-reach.ai",t,{live:!0})}catch{}}class Oe{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.isDestroyed=!1,this.prefetchWidgetConfigs={},this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.triggerEngine=e.triggerEngine,this.ownsTriggerEngine=!0===e.ownsTriggerEngine,this.enablePrefetch=!1!==e.enablePrefetch,this.cssCustomization=e.cssCustomization||{},this.onEvent=e.onEvent,this.sourcePlatform=e.sourcePlatform,this.getWorkspaceId=e.getWorkspaceId}updateCSSCustomization(e){this.cssCustomization={...this.cssCustomization,...e},this.log("CSS customization updated")}async updateContactId(e){this.contactId!==e&&(this.contactId=e,this.log(`Contact ID updated → ${e??"(cleared)"}`),this.isInitialized&&!this.isDestroyed&&this.enablePrefetch&&e&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()))}renderInteractiveCampaign(e){if(this.isDestroyed)return;if("undefined"==typeof document)return;const t=e.sub_type;if("spin_wheel"!==t&&"scratch_card"!==t)return void this.log(`renderInteractiveCampaign: unsupported sub_type "${t}"`,!0);const n={widget_id:e.id,widget_type:t,name:e.title,config:e.interactive_config??{},priority:e.priority??0};this.renderedWidgets.has(n.widget_id)||(this.renderedWidgets.add(n.widget_id),"spin_wheel"===t?this.renderSpinWheel(n):this.renderScratchCard(n))}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.triggerEngine&&this.ownsTriggerEngine&&this.triggerEngine.stop(),"undefined"!=typeof document){const e=document.getElementById("aegis-widget-animations");null==e||e.remove(),document.querySelectorAll("[data-aegis-widget-root]").forEach(e=>{e.remove()})}this.renderedWidgets.clear(),this.widgets=[],this.isInitialized=!1,this.log("AegisWidgets destroyed"),this.emitEvent("destroyed",{})}}emitEvent(e,t){if(this.onEvent)try{this.onEvent(e,t)}catch(n){this.log(`Error in event callback: ${n}`,!0)}}async initialize(){this.isInitialized?this.log("AegisWidgets already initialized"):(this.enablePrefetch&&this.contactId&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()),await this.fetchWidgets(),this.renderImmediateWidgets(),this.setupTriggerListeners(),this.setupExitIntentWithPrefetch(),this.isInitialized=!0,this.log("AegisWidgets initialized successfully"))}setCartData(e){this.cartData=e,this.log(`Cart data updated: ${e.cart_items.length} items, total: ${e.cart_currency} ${e.cart_total}`)}detectPlatformCart(){const e=this.normalizeShopifyCart();if(e)return this.log("Detected Shopify cart via browser globals"),e;const t=this.normalizeWooCart();if(t)return this.log("Detected WooCommerce cart via injected data"),t;const n=this.normalizeMagentoCart();return n?(this.log("Detected Magento cart via localStorage"),n):this.cartData?(this.log("Using manually set cart data"),this.cartData):null}normalizeShopifyCart(){var e;try{if("undefined"==typeof window)return null;const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=t.Shopify.checkout;return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:parseFloat(e.total_price)||0,cart_currency:e.currency||"USD",cart_items:(e.line_items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.title||e.product_title,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}const n=document.getElementById("cart-json");if(null==n?void 0:n.textContent){const e=JSON.parse(n.textContent);return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:(e.total_price||0)/100,cart_currency:e.currency||"USD",cart_items:(e.items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.product_title||e.title,quantity:e.quantity||1,price:(e.price||0)/100}))}}return null}catch(t){return this.log(`Error detecting Shopify cart: ${t}`,!0),null}}normalizeWooCart(){try{if("undefined"==typeof window)return null;const e=window;if(e.aegis_cart){const t=e.aegis_cart;return{cart_id:t.cart_id||`woo_${Date.now()}`,cart_total:parseFloat(t.cart_total)||0,cart_currency:t.cart_currency||"USD",cart_items:(t.cart_items||[]).map(e=>({product_id:String(e.product_id),product_name:e.product_name,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}return null}catch(e){return this.log(`Error detecting WooCommerce cart: ${e}`,!0),null}}normalizeMagentoCart(){try{if("undefined"==typeof window||!window.localStorage)return null;const e=localStorage.getItem("mage-cache-storage");if(!e)return null;const t=JSON.parse(e);if(!(null==t?void 0:t.cart))return null;const n=t.cart;return{cart_id:n.quote_id||n.id||`magento_${Date.now()}`,cart_total:parseFloat(n.subtotalAmount||n.subtotal||0),cart_currency:n.currencyCode||"USD",cart_items:(n.items||[]).map(e=>({product_id:String(e.item_id||e.product_id),product_name:e.product_name||e.name,quantity:e.qty||1,price:parseFloat(e.product_price_value||e.price||0)}))}}catch(e){return this.log(`Error detecting Magento cart: ${e}`,!0),null}}preloadWidgetAssets(){try{const e=this.prefetchWidgetConfigs.exit_intent;if(null==e?void 0:e.enabled){const t=e.image_url;if(t){(new Image).src=t,this.log(`Preloading exit intent image: ${t}`)}}const t=this.prefetchWidgetConfigs.spin_wheel;if(null==t?void 0:t.enabled){const e=t.image_url;if(e){(new Image).src=e,this.log(`Preloading spin wheel image: ${e}`)}}}catch(e){this.log(`Error preloading widget assets: ${e}`,!0)}}async fetchPrefetchConfigs(){try{const e=performance.now(),t=`${this.apiHost}/v1/widgets/config/prefetch`,n={"X-Aegis-Write-Key":this.writeKey};this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n,credentials:"include"});if(!i.ok)throw new Error(`Failed to fetch prefetch configs: ${i.status}`);this.prefetchWidgetConfigs=await i.json();const o=performance.now()-e;this.log(`Fetched prefetch widget configs in ${o.toFixed(2)}ms`)}catch(e){this.log(`Error fetching prefetch configs: ${e}`,!0)}}async fetchWidgets(){try{const e=`${this.apiHost}/v1/widgets/config`,t={"X-Aegis-Write-Key":this.writeKey,"X-Device-Platform":"web","X-Device-Type":this.getDeviceType()};this.userId&&(t["X-User-ID"]=this.userId),this.contactId&&(t["X-Contact-ID"]=this.contactId),this.organizationId&&(t["X-Organization-ID"]=this.organizationId),this.sourcePlatform&&(t["X-Source-Platform"]=this.sourcePlatform);const n=await fetch(e,{headers:t,credentials:"include"});if(!n.ok)throw new Error(`Failed to fetch widgets: ${n.status}`);this.widgets=await n.json(),this.log(`Fetched ${this.widgets.length} widgets`)}catch(e){this.log(`Error fetching widgets: ${e}`,!0)}}renderImmediateWidgets(){this.widgets.filter(e=>!e.trigger_rules||"immediate"===e.trigger_rules.type).forEach(e=>this.renderWidget(e))}setupTriggerListeners(){this.triggerEngine?this.widgets.forEach(e=>{if(!e.trigger_rules)return;const{type:t,config:n}=e.trigger_rules;switch(t){case"exit_intent":this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"scroll_depth":const t=(null==n?void 0:n.depth_percent)||50;this.triggerEngine.registerScrollDepth(t),this.triggerEngine.on(`scroll_depth_${t}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"time_on_page":const i=(null==n?void 0:n.seconds)||30;this.triggerEngine.registerTimeOnPage(i),this.triggerEngine.on(`time_on_page_${i}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)})}}):this.log("TriggerEngine not provided, skipping trigger-based widgets")}setupExitIntentWithPrefetch(){if(!this.enablePrefetch||!this.triggerEngine)return;const e=this.prefetchWidgetConfigs.spin_wheel,t=this.prefetchWidgetConfigs.exit_intent;if(e&&e.enabled){const n=this.isMobileDevice(),i=(null==t?void 0:t.mobile_triggers)||{},o=()=>{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",o),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}`,o),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",o),this.log("Registered mobile visibility change trigger for spin wheel (cart detected)"))}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",o),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",o),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||{},o=()=>{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",o),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}`,o),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",o),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",o),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",o),this.log(`Setup desktop exit intent: type=${t.type}, priority=${t.priority}`)}sendCartAbandonmentBeacon(){if(!this.cartData)return void this.log("No cart data available for beacon",!0);const e={organization_id:this.organizationId||"default",contact_id:this.contactId,cart_id:this.cartData.cart_id,cart_total:this.cartData.cart_total,cart_currency:this.cartData.cart_currency,cart_items:this.cartData.cart_items,user_email:this.userId,abandoned_at:(new Date).toISOString(),page_url:window.location.href,referrer:document.referrer},t=`${this.apiHost}/v1/widgets/beacon/cart-abandoned`;if(navigator.sendBeacon){const n=new Blob([JSON.stringify(e)],{type:"application/json"});navigator.sendBeacon(t,n)?this.log("Cart abandonment beacon sent successfully"):this.log("Failed to send cart abandonment beacon",!0)}else fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(e),keepalive:!0,credentials:"include"}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!this.isDestroyed&&!this.renderedWidgets.has(e.widget_id)){switch(this.renderedWidgets.add(e.widget_id),e.widget_type){case"chat_bubble":this.renderChatBubble(e);break;case"spin_wheel":this.renderSpinWheel(e);break;case"scratch_card":this.renderScratchCard(e);break;case"toast":this.renderToast(e);break;case"feedback_form":this.renderFeedbackForm(e);break;case"exit_intent_popup":this.renderExitIntentPopup(e);break;default:this.log(`Unknown widget type: ${e.widget_type}`,!0)}this.trackEvent(e.widget_id,"show")}}renderChatBubble(e){const{text:t,icon_url:n,link_url:i,background_color:o,text_color:s}=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(o||"#25D366")};\n color: ${this.sanitizeColor(s||"#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(),r.setAttribute("data-aegis-widget-root",""),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 o=document.createElement("p");o.textContent=e.config.description||"Try your luck and win exclusive prizes!",o.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(o);const s=Array.isArray(e.config.segments)?e.config.segments:[{label:"Prize 1",color:"#ff6b6b"},{label:"Prize 2",color:"#feca57"},{label:"Prize 3",color:"#48dbfb"},{label:"Prize 4",color:"#ff6348"}],a="http://www.w3.org/2000/svg",r=document.createElementNS(a,"svg");r.setAttribute("viewBox","-160 -160 320 320"),r.setAttribute("width","300"),r.setAttribute("height","300"),r.style.cssText="margin: 0 auto 24px; display: block;";const c=s.length,d=2*Math.PI/c,l=140;for(let u=0;u<c;u++){const e=u*d-Math.PI/2,t=e+d,n=Math.cos(e)*l,i=Math.sin(e)*l,o=Math.cos(t)*l,c=Math.sin(t)*l,p=d>Math.PI?1:0,h=document.createElementNS(a,"path");h.setAttribute("d",`M 0 0 L ${n.toFixed(2)} ${i.toFixed(2)} A 140 140 0 ${p} 1 ${o.toFixed(2)} ${c.toFixed(2)} Z`),h.setAttribute("fill",this.sanitizeColor(s[u].color||"#cccccc")),h.setAttribute("stroke","#ffffff"),h.setAttribute("stroke-width","2"),r.appendChild(h);const g=e+d/2,m=Math.cos(g)*l*.65,f=Math.sin(g)*l*.65,x=document.createElementNS(a,"text");x.setAttribute("x",m.toFixed(2)),x.setAttribute("y",f.toFixed(2)),x.setAttribute("fill","#ffffff"),x.setAttribute("font-size","13"),x.setAttribute("font-weight","600"),x.setAttribute("text-anchor","middle"),x.setAttribute("dominant-baseline","middle"),x.textContent=s[u].label||`#${u+1}`,r.appendChild(x)}n.appendChild(r);const p=document.createElement("button");p.textContent="SPIN NOW!",p.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 ",p.addEventListener("click",async()=>{p.disabled=!0,p.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);r.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),p.disabled=!1,p.textContent="TRY AGAIN"}}),n.appendChild(p);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: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",h.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(h),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderSpinWheelWidget(e,t){if(this.isDestroyed)return;const n=this.detectPlatformCart();if("cart_recovery"===t.type&&!n)return void this.log("Spin wheel requires cart, but none detected");n&&(this.cartData=n);const i=this.cssCustomization.spinWheel||{},o=i.accentColor||t.accent_color||"#FF6B6B",s=i.backgroundColor||t.background_color||"#FFFFFF",a=i.textColor||t.text_color||"#333333",r=i.buttonColor||t.button_color||o,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(s)};\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 p=document.createElement("button");p.innerHTML="✕",p.className="aegis-spin-wheel-close",p.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 ",p.onclick=()=>{this.trackEvent(e,"dismiss",{type:"spin_wheel"}),document.body.removeChild(d),this.renderedWidgets.delete(e)},l.appendChild(p);const h=document.createElement("h2");if(h.textContent=this.interpolateCartVariables(t.title||"Spin to Win!"),h.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(h),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 x=document.createElement("input");x.type="text",x.placeholder="Enter your name (optional)",x.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(x);const y=document.createElement("button");y.type="submit",y.textContent="Spin the Wheel!",y.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(y);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(),o=f.value.trim(),s=x.value.trim();return this.validatePhone(i)?o&&!this.validateEmail(o)?(b.textContent="Please enter a valid email address",void(b.style.display="block")):(b.style.display="none",y.disabled=!0,y.textContent="Spinning...",u.style.animation="aegisSpin 2s ease-out",void setTimeout(async()=>{try{const t=await this.submitSpinWheel({phone:i,email:o,name:s,cart:n,widgetId:e});this.showSpinWheelPrize(l,t),this.trackEvent(e,"submit",{type:"spin_wheel",prize_label:t.prize_label,has_email:!!o})}catch(t){this.log(`Error submitting spin wheel: ${t}`,!0),b.textContent="Failed to submit. Please try again.",b.style.display="block",y.disabled=!1,y.textContent="Spin the Wheel!",u.style.animation=""}},2e3)):(b.textContent="Please enter a valid phone number (e.g., +1234567890)",void(b.style.display="block"))}),l.appendChild(u),l.appendChild(g),d.appendChild(l),this.addAnimationStyles(),d.setAttribute("data-aegis-widget-root",""),document.body.appendChild(d),this.trackEvent(e,"show",{type:"spin_wheel"})}validatePhone(e){return/^\+?[1-9]\d{1,14}$/.test(e.replace(/[\s()-]/g,""))}validateEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}async submitSpinWheel(e){var t,n,i,o,s;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(),p={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==(o=e.cart)?void 0:o.cart_currency)||"USD",cart_items:(null==(s=e.cart)?void 0:s.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},h=await fetch(a,{method:"POST",headers:r,body:JSON.stringify(p),credentials:"include"});if(!h.ok){const e=await h.text();throw new Error(`Failed to submit spin wheel: ${h.status} - ${e}`)}return await h.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 o=document.createElement("h2");o.textContent="Congratulations!",o.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(o);const s=document.createElement("p");if(s.textContent=t.prize_label,s.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(s),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 o=document.createElement("div");o.textContent=t.coupon_code,o.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(o),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 o=document.createElement("p");o.textContent=e.config.description||"Scratch to reveal your prize!",o.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(o);const s=document.createElement("canvas");s.width=300,s.height=200,s.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(s);const a=s.getContext("2d");if(a){a.fillStyle="#c0c0c0",a.fillRect(0,0,s.width,s.height),a.fillStyle="#888",a.font="20px Arial",a.textAlign="center",a.fillText("Scratch here!",s.width/2,s.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()};s.addEventListener("mousedown",()=>{e=!0}),s.addEventListener("mouseup",()=>{e=!1}),s.addEventListener("mousemove",n=>{if(e){const e=s.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(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderToast(e){const{message:t,icon:n,duration:i}=e.config,o=e.position||"bottom_left",s=document.createElement("div");s.className="aegis-toast",s.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(s.style.cssText=`\n position: fixed;\n ${a[o]||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;",s.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;",s.appendChild(r),this.addAnimationStyles(),s.setAttribute("data-aegis-widget-root",""),document.body.appendChild(s),setTimeout(()=>{s.style.animation="aegisToastOut 0.3s ease-out",setTimeout(()=>{document.body.contains(s)&&document.body.removeChild(s),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 o=document.createElement("form"),s=document.createElement("label");s.textContent="How likely are you to recommend us? (0-10)",s.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",o.appendChild(s);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 ",o.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;",o.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 ",o.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 ",o.appendChild(d),o.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(o);const l=document.createElement("button");l.textContent="×",l.setAttribute("aria-label","Close"),l.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",l.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),t.appendChild(l),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:o,image_url:s}=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 ',s){const e=document.createElement("img"),t=this.sanitizeUrl(s);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&&o){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(o);t&&(window.location.href=t)}),c.appendChild(t)}r.appendChild(c);const p=document.createElement("button");p.textContent="×",p.setAttribute("aria-label","Close"),p.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: 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 ",p.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(a),this.renderedWidgets.delete(e.widget_id)}),r.style.position="relative",r.appendChild(p),a.appendChild(r),this.addAnimationStyles(),a.setAttribute("data-aegis-widget-root",""),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}),credentials:"include"});if(!i.ok)throw new Error(`Failed to generate prize: ${i.status}`);return await i.json()}showPrizeResult(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const o=document.createElement("h2");o.textContent="Congratulations!",o.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(o);const s=document.createElement("p");if(s.textContent=t.prize_label,s.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(s),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 o=document.createElement("div");o.textContent=t.coupon_code,o.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(o),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){var n;const i=`${this.apiHost}/v1/widgets/track-event`,o={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};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 s=null==(n=this.getWorkspaceId)?void 0:n.call(this),a=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({widget_id:e,event_type:"submit",event_data:t,workspace_id:s}),credentials:"include"});if(!a.ok)throw new Error(`Failed to submit feedback: ${a.status}`)}async trackEvent(e,t,n){var i;try{const o=`${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);const a=null==(i=this.getWorkspaceId)?void 0:i.call(this);await fetch(o,{method:"POST",headers:s,body:JSON.stringify({widget_id:e,event_type:t,event_data:n||{},workspace_id:a}),credentials:"include"})}catch(o){this.log(`Error tracking widget event: ${o}`,!0)}}sanitizeUrl(e){if(!e)return null;try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked dangerous URL: ${e}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-F]{3,8}$/i.test(e)||/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/i.test(e)||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/i.test(e)?e:"#1a73e8"}getDeviceType(){const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"}isMobileDevice(){const e=this.getDeviceType();return"mobile"===e||"tablet"===e}addAnimationStyles(){if(document.getElementById("aegis-widget-animations"))return;const e=document.createElement("style");e.id="aegis-widget-animations",e.textContent="\n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.8); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n \n @keyframes aegisBubbleIn {\n from { transform: translateY(20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisToastIn {\n from { transform: translateX(-100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n \n @keyframes aegisToastOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(-100%); opacity: 0; }\n }\n \n @keyframes aegisSlideInRight {\n from { transform: translateX(100%); }\n to { transform: translateX(0); }\n }\n \n @keyframes aegisSpin {\n from { transform: rotate(0deg); }\n to { transform: rotate(1440deg); }\n }\n ",document.head.appendChild(e)}renderCartRecoveryPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-cart-recovery-modal",i.style.cssText=`\n background: ${this.sanitizeColor(t.background_color||"#FFFFFF")};\n color: ${this.sanitizeColor(t.text_color||"#333333")};\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n `;const o=document.createElement("h2"),s=this.interpolateCartVariables(t.title||"Complete Your Order");o.textContent=s,o.style.cssText=`margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: ${this.sanitizeColor(t.accent_color||"#FF6B00")};`,i.appendChild(o);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(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-leadgen-modal",i.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 500px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n ';const o=document.createElement("h2");o.textContent=t.title||"Get 10% Off Your First Order!",o.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",i.appendChild(o);const s=document.createElement("p");s.textContent=t.message||"Subscribe to our newsletter and get an exclusive discount code.",s.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666;",i.appendChild(s);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(o){this.log(`Error submitting lead gen form: ${o}`,!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(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"lead_gen"})}interpolateCartVariables(e){return this.cartData?e.replace(/\{\{cart_total\}\}/g,`${this.cartData.cart_currency} ${this.cartData.cart_total.toFixed(2)}`).replace(/\{\{cart_currency\}\}/g,this.cartData.cart_currency).replace(/\{\{cart_items_count\}\}/g,this.cartData.cart_items.length.toString()):e}log(e,t=!1){if(this.debugMode||t){console[t?"error":"log"](`[AegisWidgets] ${e}`)}}}function Be(e,t){if(!e||!t)return;let n=e;for(const i of t.split(".")){if(null===n||"object"!=typeof n||Array.isArray(n))return;n=n[i]}return n}function Ue(e,t,n){if(function(e){return!("operands"in e)}(e))return function(e,t,n){const i=void 0!==e.path?Be(n,e.path):void 0!==e.signal?t[e.signal]:void 0;if(null==i)return null;const o=e.value;switch(e.op){case"gte":case"lte":case"gt":case"lt":return"number"==typeof i&&"number"==typeof o&&("gte"===e.op?i>=o:"lte"===e.op?i<=o:"gt"===e.op?i>o:i<o);case"eq":return i===o;case"neq":return i!==o;case"in":case"nin":{if(!Array.isArray(o))return!1;const t=o.some(e=>e===i);return"in"===e.op?t:!t}default:return e.op,!1}}(e,t,n);switch(e.op){case"AND":for(const i of e.operands){const e=Ue(i,t,n);if(null===e)return!1;if(!e)return!1}return!0;case"OR":{let i=!0;for(const o of e.operands){const e=Ue(o,t,n);if(!0===e)return!0;null!==e&&(i=!1)}return!!i&&null}case"NOT":{const i=Ue(e.operands[0],t,n);return null===i?null:!i}default:return!1}}function We(e,t,n){return!0===Ue(e.when,t,n)}class je{constructor(){this.armed=[],this.snapshot={},this.namespaces={},this.firedThisSession=new Set,this.silencedThisSession=new Set}updateSignal(e,t){this.snapshot[e]=t}updateSnapshot(e){Object.assign(this.snapshot,e)}getSnapshot(){return this.snapshot}updateContext(e,t){e&&t&&(this.namespaces[e]={...this.namespaces[e],...t})}getNamespaces(){return this.namespaces}getValueByPath(e){return Be(this.namespaces,e)}setArmed(e){this.armed=[...e]}getArmed(){return this.armed}markFired(e){this.firedThisSession.add(e)}reset(){this.firedThisSession.clear(),this.silencedThisSession.clear()}onSignalChanged(e){const t=this.armed.filter(t=>t.rule.fire_on.includes(e)).filter(e=>!this.firedThisSession.has(e.id)).filter(e=>!this.silencedThisSession.has(e.id)).sort((e,t)=>t.rule.priority!==e.rule.priority?t.rule.priority-e.rule.priority:e.id<t.id?-1:e.id>t.id?1:0);for(let n=0;n<t.length;n++){const e=t[n];if(We(e.rule,this.snapshot,this.namespaces)){if(e.rule.suppress_competing){const t=this.armed.filter(t=>t.id!==e.id).map(e=>e.id);return t.forEach(e=>this.silencedThisSession.add(e)),{kind:"suppress",campaignId:e.id,suppressIds:t}}return{kind:"fire",campaignId:e.id}}}return{kind:"none"}}}class qe{constructor(e){this.lastFetchedAt=0,this.latestSnapshot=null,this.apiHost=e.apiHost.replace(/\/$/,""),this.writeKey=e.writeKey,this.organizationId=e.organizationId,this.evaluator=e.evaluator,this.dedupWindowMs=e.dedupWindowMs??6e4,this.fetchImpl=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):()=>Promise.reject(new Error("fetch unavailable"))),this.onError=e.onError}updateOrganizationId(e){this.organizationId=e}getSnapshot(){return this.latestSnapshot}async fetchForContact(e,t={}){var n;if(!e)return null;const i=Date.now();if(!t.force&&this.lastFetchedContactId===e&&i-this.lastFetchedAt<this.dedupWindowMs)return this.latestSnapshot;this.lastFetchedContactId=e,this.lastFetchedAt=i;const o={"X-Aegis-Write-Key":this.writeKey,"X-Contact-ID":e,"X-User-ID":e};this.organizationId&&(o["X-Organization-ID"]=this.organizationId);try{const e=await this.fetchImpl(`${this.apiHost}/v1/sdk/contact-scores`,{method:"GET",headers:o,credentials:"include"});if(204===e.status)return this.latestSnapshot=null,null;if(!e.ok)return this.latestSnapshot=null,null;const t=await e.json();if(this.latestSnapshot=t,this.evaluator&&(this.evaluator.updateSnapshot(function(e){const t={};e.rfm_segment&&(t.rfm_segment=e.rfm_segment);e.lifecycle_stage&&(t.lifecycle_stage=e.lifecycle_stage);e.churn_risk_tier&&(t.churn_risk_tier=e.churn_risk_tier);e.predicted_ltv_tier&&(t.predicted_ltv_tier=e.predicted_ltv_tier);"number"==typeof e.predicted_ltv&&(t.predicted_ltv=e.predicted_ltv);"number"==typeof e.price_sensitivity_score&&(t.price_sensitivity_score=e.price_sensitivity_score);e.scoring_tier&&(t.scoring_tier=e.scoring_tier);return t}(t)),t.context&&"object"==typeof t.context))for(const[n,i]of Object.entries(t.context))i&&"object"==typeof i&&this.evaluator.updateContext(n,i);return t}catch(s){return null==(n=this.onError)||n.call(this,s,e),null}}}class He{constructor(e){this.config=e}url(e){return`${(this.config.apiHost??"").replace(/\/$/,"")}/api/v1/commerce/store/${encodeURIComponent(this.config.slug)}${e}`}async get(e){const t=await fetch(this.url(e),{method:"GET",credentials:this.config.credentials??"include",headers:{"content-type":"application/json"}});if(!t.ok){const n=await t.text();throw new Error(`GET ${e} failed (${t.status}): ${n}`)}return t.json()}async post(e,t){const n=await fetch(this.url(e),{method:"POST",credentials:this.config.credentials??"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const t=await n.text();let i=t;try{i=JSON.parse(t).detail??t}catch{}throw new Error(`POST ${e} failed (${n.status}): ${i}`)}return n.json()}}class Ve{constructor(e){this.http=e}async listActive(e){return((await this.http.get(`/store-credit/list-active?phone=${encodeURIComponent(e)}`)).balances??[]).map(e=>({workspaceId:e.workspace_id,balancePaise:e.balance_paise,expiresAt:e.expires_at,lastActivityAt:e.last_activity_at}))}async startReload(e){if(!e.workspaceId)throw new Error("workspaceId is required for store credit reload (closed-loop C1)");const t=await this.http.post("/store-credit/reload",{phone:e.phone,workspace_id:e.workspaceId,amount_paise:e.amountPaise,first_name:e.firstName,email:e.email,callback_url:e.callbackUrl});return{contactId:t.contact_id,checkoutUrl:t.checkout_url,provider:t.provider,paymentLinkId:t.payment_link_id,amountPaise:t.amount_paise}}}class Xe{constructor(e){this.http=e}async startPurchase(e){if(!e.workspaceId)throw new Error("workspaceId is required for gift card purchase (closed-loop C1)");if(!e.recipientPhone)throw new Error("recipientPhone is required (no bearer cards — C3)");const t=await this.http.post("/gift-cards/purchase",{sender_phone:e.senderPhone,workspace_id:e.workspaceId,recipient_phone:e.recipientPhone,recipient_name:e.recipientName,amount_paise:e.amountPaise,personal_message:e.personalMessage,callback_url:e.callbackUrl});return{senderContactId:t.sender_contact_id,giftCardId:t.gift_card_id,checkoutUrl:t.checkout_url,provider:t.provider,paymentLinkId:t.payment_link_id,amountPaise:t.amount_paise}}async claim(e){const t=await this.http.post("/gift-cards/claim",{gift_card_id:e.giftCardId,phone:e.phone});return{recipientContactId:t.recipient_contact_id,giftCardId:t.gift_card_id,amountCreditedPaise:t.amount_credited_paise,newBalancePaise:t.new_balance_paise}}async listReceived(e){return((await this.http.get(`/gift-cards/received?phone=${encodeURIComponent(e)}`)).gift_cards??[]).map(e=>({id:e.id,workspaceId:e.workspace_id,senderContactId:e.sender_contact_id,amountPaise:e.amount_paise,status:e.status,personalMessage:e.personal_message,deliveredAt:e.delivered_at,claimedAt:e.claimed_at,expiresAt:e.expires_at,createdAt:e.created_at}))}}class Ke{constructor(e){if(!e.slug)throw new Error("AegisLoyaltyManager requires a slug");const t=new He(e);this.storeCredit=new Ve(t),this.giftCards=new Xe(t)}}const Ye="aegis_fpc";class Qe extends Error{constructor(e,t){super(t),this.status=e,this.name="BootstrapError"}}const Ge="aegis",Je=window[Ge]||[],Ze=new Q;if(Array.isArray(Je)){const e=Je._loadOptions;Je.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("string"!=typeof t||0===t.length)return;const i=t.split(".");let o=null,s=Ze;for(let r=0;r<i.length&&null!=s;r+=1)o=s,s=s[i[r]];if("function"==typeof s)try{s.apply(o,n)}catch(a){console.error(`[Active Reach SDK] Error executing queued method "${t}":`,a)}else console.warn(`[Active Reach SDK] Unknown method "${t}"`)}),(null==e?void 0:e.key)&&Ze.init(e.key,e.options).catch(e=>{console.error("[Active Reach SDK] Initialization failed:",e)})}window[Ge]=Ze,window.Aegis=Q,window.AegisMessageRuntime=class{constructor(e){var t;this.initialized=!1;const n=e.triggerEngine??new $e,i=!e.triggerEngine;if(this.contactId=e.contactId,this.pairingApiHost=e.apiHost??"",this.widgets=new Oe({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,debugMode:e.debugMode,triggerEngine:n,ownsTriggerEngine:i,enablePrefetch:!1!==e.enableWidgetPrefetch,sourcePlatform:e.sourcePlatform,getWorkspaceId:e.getWorkspaceId}),this.inApp=new Re({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,propertyId:e.propertyId,debugMode:e.debugMode,enableSSE:e.enableSSE,onInteractiveCampaign:e=>{this.widgets.renderInteractiveCampaign(e)},getWorkspaceId:e.getWorkspaceId,getCartState:()=>this.deriveCartState()}),this.intentRuleEvaluator=new je,this.contactScores=new qe({apiHost:e.apiHost??"",writeKey:e.writeKey,organizationId:e.organizationId,evaluator:this.intentRuleEvaluator}),this.loyalty=new Ke({slug:e.storefrontSlug??"__unconfigured__",apiHost:e.apiHost,debugMode:e.debugMode}),e.enableChat){this.chat=new Se({writeKey:e.writeKey,apiHost:e.apiHost,organizationId:e.organizationId,contactId:e.contactId,debugMode:e.debugMode,...e.chat});const i=(null==(t=e.chat)?void 0:t.proactiveTriggers)??[];for(const e of i)n.on(e,()=>{var e;return null==(e=this.chat)?void 0:e.openPanel()})}}async initialize(){var e;this.initialized||(this.initialized=!0,Fe(this.pairingApiHost),await Promise.all([this.inApp.initialize(),this.widgets.initialize()]),null==(e=this.chat)||e.initialize(),this.contactId&&this.contactScores.fetchForContact(this.contactId))}async updateContactId(e){var t,n,i;this.contactId=e,null==(n=(t=this.inApp).updateContactId)||n.call(t,e),null==(i=this.chat)||i.updateContactId(e),await this.widgets.updateContactId(e),this.contactScores.fetchForContact(e)}onClientEvent(e,t={}){var n,i;null==(i=(n=this.inApp).onClientEvent)||i.call(n,e,t)}updateContext(e,t){e&&"string"==typeof e&&t&&(this.intentRuleEvaluator.updateContext(e,t),this.bridgeContextToSignals(e),this.inApp.refreshOnEvent("context_updated"))}getContext(){return this.intentRuleEvaluator.getNamespaces()}bridgeContextToSignals(e){if("cart"===e){const e=Number(this.intentRuleEvaluator.getValueByPath("cart.total")??this.intentRuleEvaluator.getValueByPath("cart.cart_value"));Number.isFinite(e)&&this.intentRuleEvaluator.updateSignal("cart_value",e)}}deriveCartState(){const e=Number(this.intentRuleEvaluator.getValueByPath("cart.total"));if(!Number.isFinite(e))return;const t=Number(this.intentRuleEvaluator.getValueByPath("cart.items")??this.intentRuleEvaluator.getValueByPath("cart.itemCount")),n=this.intentRuleEvaluator.getValueByPath("cart.currency");return{total:e,itemCount:Number.isFinite(t)?t:0,currency:"string"==typeof n?n:"INR"}}setCartState(e){this.updateContext("cart",{total:e.total,items:e.itemCount,currency:e.currency})}track(e){e&&this.inApp.refreshOnEvent(e)}page(e){this.inApp.refreshOnEvent(e??"page_view",!0)}screen(e){e&&this.inApp.refreshOnEvent(e,!0)}notifyConversion(e){var t,n;null==(n=(t=this.inApp).notifyConversion)||n.call(t,e)}destroy(){var e,t,n;null==(t=(e=this.inApp).destroy)||t.call(e),this.widgets.destroy(),null==(n=this.chat)||n.destroy(),this.initialized=!1}getCampaigns(){return this.inApp.campaigns??[]}},window.TriggerEngine=$e,window.AegisChat=Se,window.aegisBootstrap=async function(e,t){const n={writeKey:t.writeKey};t.currentOrigin&&(n.currentOrigin=t.currentOrigin),t.firstPartyCookieId&&(n.firstPartyCookieId=t.firstPartyCookieId),t.attestationToken&&(n.attestationToken=t.attestationToken),t.userAgent&&(n.userAgent=t.userAgent);const i=`${e.replace(/\/$/,"")}/v1/sdk/bootstrap`,o=async()=>fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"omit"});let s=await o();if(s.status>=500&&(await new Promise(e=>setTimeout(e,750)),s=await o()),401===s.status)throw new Qe(401,"writeKey not recognized or revoked");if(403===s.status)throw new Qe(403,"Origin validation failed — this writeKey is bound to a different property");if(!s.ok)throw new Qe(s.status,`Bootstrap failed: HTTP ${s.status}`);const a=await s.json();return function(e){if("undefined"==typeof document)return;const t=new Date;t.setDate(t.getDate()+730),document.cookie=`${Ye}=${encodeURIComponent(e)};expires=${t.toUTCString()};path=/;SameSite=Lax`;try{window.localStorage.setItem(Ye,e)}catch{}}(a.firstPartyCookieId),a},window.AegisRenderPreview=function(e){document.querySelectorAll('[class^="aegis-in-app-"]').forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});try{if("undefined"!=typeof localStorage)for(let e=localStorage.length-1;e>=0;e--){const t=localStorage.key(e);t&&(t.startsWith("aegis_coachmark_progress:")||t.startsWith("aegis_sticky_dismissed:"))&&localStorage.removeItem(t)}}catch{}if(!e)return;const t=new Re({writeKey:"preview-mode",apiHost:"",debugMode:!1,enableSSE:!1});if(t.trackEvent=async()=>{},t.addAnimationStyles(),"stories"===e.type||"stories"===e.sub_type){const n=document.createElement("div");return n.className="aegis-in-app-stories-host",n.style.cssText="position: fixed; left: 0; right: 0; top: 0; z-index: 99998; padding-top: 4px;background: rgba(255,255,255,0.94); backdrop-filter: blur(8px);box-shadow: 0 2px 12px rgba(0,0,0,0.06);",document.body.appendChild(n),void re(t.buildRenderContext(e),n)}t.displayCampaign(e)};try{const t=null==Je?void 0:Je._loadOptions;Fe(null==(e=null==t?void 0:t.options)?void 0:e.apiHost)}catch{}return Ze}();
|
|
1
|
+
var Aegis=function(){"use strict";var e;const t={workspace_id:null,batch_size:10,batch_interval:1e3,capture_utm:!0,capture_referrer:!0,auto_page_view:!1,session_timeout:30,debug:!1,respect_dnt:!0,cross_domain_tracking:!1,secure_cookie:!0,enable_offline_mode:!0,max_offline_events:100,retry_failed_requests:!0,max_retries:3,retry_backoff_multiplier:2,request_timeout:5e3,rate_limit_burst:100,rate_limit_per_second:20,auto_region_detection:!0,wait_for_consent:!1,enable_consent_mode:!1,integrate_onetrust:!1,integrate_cookiebot:!1,integrate_google_consent_mode:!1,default_consent:{analytics:!1,marketing:!1,functional:!0},initialized:!1,api_host:null,cell_endpoints:[],preferred_region:null,cookie_domain:null,plugins:[],active_cell:null};function n(){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 i(){return`msg_${Date.now()}_${n().slice(0,8)}`}const o=new class{constructor(){this.enabled=!1,this.prefix="[Active Reach 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?o.debug("Loaded existing anonymous ID:",e):(e=n(),this.storage.set("anon_id",e,365),o.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,o.debug("Loaded user ID:",e)),t)try{this.traits=JSON.parse(t),o.debug("Loaded user traits:",this.traits)}catch(n){o.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),o.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),o.debug("User traits updated:",this.traits)}getTraits(){return{...this.traits}}reset(){this.userId=null,this.traits={},this.anonymousId=n(),this.storage.remove("user_id"),this.storage.remove("user_traits"),this.storage.set("anon_id",this.anonymousId,365),o.info("Identity reset, new anonymous ID:",this.anonymousId)}alias(e){const t=this.userId||this.anonymousId;return this.setUserId(e),o.info("User aliased:",{previousId:t,newUserId:e}),{previousId:t,newUserId:e}}getState(){return{anonymousId:this.anonymousId,userId:this.userId,traits:this.getTraits()}}}class a{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,o.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:(o.debug("Session expired, creating new session"),this.storage.remove("session"),null)}catch(t){return o.warn("Failed to parse session data:",t),this.storage.remove("session"),null}}createNewSession(){const e=`sess_${Date.now()}_${n().slice(0,8)}`;return this.sessionStartTime=Date.now(),this.lastActivityTime=Date.now(),this.eventCount=0,this.sessionId=e,this.persistSession(),o.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?(o.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&&(o.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(),o.info("Ad click IDs stored in session:",this.adClickIDs))}getAdClickIDs(){return this.adClickIDs}getLandingPage(){return this.landingPage}destroy(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=null)}}class r{constructor(e,t,n){this.buffer=[],this.flushInterval=null,this.isFlushing=!1,this.offlineQueue=[],this.isOnline=navigator.onLine,this.config=e,this.transport=t,this.storage=n,e.enableOfflineMode&&(this.loadOfflineQueue(),this.setupOnlineListener()),this.startFlushTimer(),this.setupUnloadHandlers()}loadOfflineQueue(){const e=this.storage.get("offline_queue");if(e)try{const t=JSON.parse(e);Array.isArray(t)&&t.length>0&&(this.offlineQueue=t.slice(0,this.config.maxOfflineEvents),o.info(`Loaded ${this.offlineQueue.length} offline events`),this.isOnline&&this.flushOfflineQueue())}catch(t){o.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),o.debug(`Saved ${this.offlineQueue.length} events to offline queue`)}catch(e){o.warn("Failed to save offline queue:",e)}else this.storage.remove("offline_queue")}setupOnlineListener(){window.addEventListener("online",()=>{o.info("Connection restored"),this.isOnline=!0,this.flushOfflineQueue(),this.flush()}),window.addEventListener("offline",()=>{o.warn("Connection lost, entering offline mode"),this.isOnline=!1})}async flushOfflineQueue(){if(0===this.offlineQueue.length)return;o.info(`Flushing ${this.offlineQueue.length} offline events`);const e=[...this.offlineQueue];this.offlineQueue=[],this.storage.remove("offline_queue");(await this.transport.send(e)).success?o.info("Offline events sent successfully"):(o.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),o.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&&(o.warn("Offline queue full, dropping oldest event"),this.offlineQueue.shift()),this.offlineQueue.push(e),this.saveOfflineQueue(),o.debug("Event added to offline queue")}async flush(){if(this.isFlushing)return void o.debug("Flush already in progress, skipping");if(0===this.buffer.length)return;this.isFlushing=!0;const e=[...this.buffer];this.buffer=[],o.info(`Flushing ${e.length} events`);try{const t=await this.transport.send(e);t.success?o.info("Events sent successfully"):(o.error("Failed to send events:",t.error),this.config.enableOfflineMode?(this.offlineQueue=[...this.offlineQueue,...e].slice(0,this.config.maxOfflineEvents),this.saveOfflineQueue(),o.info("Events saved to offline queue")):(this.buffer.unshift(...e),o.warn("Events re-queued for retry")))}catch(t){o.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),o.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(),o.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"),o.info("Queue cleared")}destroy(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}}class c{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,o.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 o.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(o.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 o.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 o.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 i=n[0].cell;this.activeCell=i,this.saveCachedCell(i),o.info("Optimal cell selected:",{region:i.region,latency:n[0].latency})}async measureLatency(e){const t=performance.now();try{const n=new AbortController,i=setTimeout(()=>n.abort(),2e3),o=await fetch(`${e.url}/health`,{method:"GET",signal:n.signal});return clearTimeout(i),o.ok?performance.now()-t:1/0}catch(n){return o.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]),o.info("Cell selected by priority:",e[0])):o.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&&(o.warn("Active cell unhealthy, selecting new cell"),await this.selectOptimalCell()),o.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(o.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)?(o.debug("Batch sent via Beacon"),{success:!0,endpoint:e}):(o.warn("Beacon send failed, falling back to fetch"),this.sendViaFetch(e,t))}catch(n){return o.error("Beacon send error:",n),{success:!1,error:n,endpoint:e}}}async sendViaFetch(e,t,n=1){try{const i=new AbortController,s=setTimeout(()=>i.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:i.signal});if(clearTimeout(s),a.ok){const t=await a.json();return o.debug("Batch sent successfully:",t),{success:!0,response:t,endpoint:e}}{const i=await a.text(),s=new Error(`HTTP ${a.status}: ${i||a.statusText}`);return o.error("Batch send failed:",s),this.shouldRetry(a.status,n)?this.retryRequest(e,t,n):{success:!1,error:s,endpoint:e}}}catch(i){return o.error("Fetch error:",i),this.shouldRetry(0,n)?this.retryRequest(e,t,n):{success:!1,error:i,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 i=1e3*Math.pow(this.config.retryBackoffMultiplier,n);return o.info(`Retrying request in ${i}ms (attempt ${n+1})`),await new Promise(e=>setTimeout(e,i)),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 d="aegis_";class l{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=d+e;if(this.useLocalStorage)try{const e={value:t,expiry:Date.now()+24*n*60*60*1e3};localStorage.setItem(i,JSON.stringify(e))}catch(o){console.warn("[Active Reach Storage] localStorage.setItem failed:",o)}this.setCookie(i,t,n)}get(e){const t=d+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("[Active Reach Storage] localStorage.getItem failed:",n)}return this.getCookie(t)}remove(e){const t=d+e;if(this.useLocalStorage)try{localStorage.removeItem(t)}catch(n){console.warn("[Active Reach Storage] localStorage.removeItem failed:",n)}this.deleteCookie(t)}clear(){if(this.useLocalStorage)try{Object.keys(localStorage).forEach(e=>{e.startsWith(d)&&localStorage.removeItem(e)})}catch(e){console.warn("[Active Reach Storage] localStorage.clear failed:",e)}document.cookie.split(";").forEach(e=>{const t=e.split("=")[0].trim();t.startsWith(d)&&this.deleteCookie(t)})}setCookie(e,t,n){try{const i=new Date;i.setTime(i.getTime()+24*n*60*60*1e3);let o=`${e}=${t};${`expires=${i.toUTCString()}`};path=/`;if(this.options.secureCookie&&"https:"===window.location.protocol&&(o+=";Secure"),o+=";SameSite=Lax",this.options.cookieDomain)o+=`;domain=${this.options.cookieDomain}`;else if(this.options.crossDomain){const e=this.getRootDomain();e&&(o+=`;domain=${e}`)}document.cookie=o}catch(i){console.warn("[Active Reach 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("[Active Reach 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("[Active Reach 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("[Active Reach Storage] getRootDomain failed:",e),null}}}function p(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("[Active Reach 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"}}(),o=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"}}(),s=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("[Active Reach 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},...o&&{os:o},...s&&{browser:s},...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)?o.warn(`Plugin "${e.name}" already registered, skipping`):(this.plugins.set(e.name,e),o.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){o.error(`Error destroying plugin "${e}":`,n)}this.plugins.delete(e),o.info(`Plugin unregistered: ${e}`)}else o.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 s of this.plugins.values()){const a=s[e];if("function"==typeof a)try{const e=await a.apply(s,t);if(void 0!==e)return e}catch(n){if(o.error(`Error executing ${String(e)} in plugin "${s.name}":`,n),s.onError)try{s.onError(n,{hookName:e,args:t})}catch(i){o.error(`Error in onError handler for plugin "${s.name}":`,i)}}}}async executeHookChain(e,t,...n){let i=t;for(const r of this.plugins.values()){const t=r[e];if("function"==typeof t)try{const e=await t.apply(r,[i,...n]);null!=e&&(i=e)}catch(s){if(o.error(`Error executing ${String(e)} in plugin "${r.name}":`,s),r.onError)try{r.onError(s,{hookName:e,value:i,additionalArgs:n})}catch(a){o.error(`Error in onError handler for plugin "${r.name}":`,a)}}}return i}async executeHookParallel(e,...t){const n=[];for(const i of this.plugins.values()){const s=i[e];if("function"==typeof s){const a=(async()=>{try{return await s.apply(i,t)}catch(n){if(o.error(`Error executing ${String(e)} in plugin "${i.name}":`,n),i.onError)try{i.onError(n,{hookName:e,args:t})}catch(a){o.error(`Error in onError handler for plugin "${i.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){o.error(`Error destroying plugin "${t.name}":`,e)}this.plugins.clear(),o.info("All plugins cleared")}}class u{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 o.info("Loaded consent preferences:",t),this.mergeWithDefaults(t)}catch(t){o.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),o.info("Saved consent preferences:",this.preferences)}catch(e){o.error("Failed to save consent preferences:",e)}}setConsent(e){const t={...this.preferences,...e};t.necessary=!0,this.preferences=t,this.savePreferences(),this.notifyListeners(),o.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){o.error("Consent listener error:",t)}})}reset(){this.storage.remove(this.config.consentStorageKey),this.preferences=this.getDefaultPreferences(),this.notifyListeners(),o.info("Consent preferences reset")}integrateOneTrust(){if("undefined"==typeof window)return;if(!window.OneTrust)return void o.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")}),o.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 o.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}),o.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 o.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"}),o.info("Updated Google Consent Mode")};this.onChange(t),t()}}const g="_fbp",m="_fbc";function f(e){if("undefined"==typeof document)return null;try{const t=`${e}=`,n=document.cookie.split(";");for(let e=0;e<n.length;e++){let i=n[e];for(;" "===i.charAt(0);)i=i.substring(1);if(0===i.indexOf(t))return decodeURIComponent(i.substring(t.length))}}catch{}return null}function x(e,t,n){if("undefined"!=typeof document&&"undefined"!=typeof window)try{const i=new Date(Date.now()+24*n*60*60*1e3).toUTCString(),o=function(){if("undefined"==typeof window)return null;const e=window.location.hostname;if(!e||"localhost"===e)return null;if(/^\d+\.\d+\.\d+\.\d+$/.test(e))return null;const t=e.split(".");return t.length<2?null:"."+t.slice(-2).join(".")}(),s="https:"===window.location.protocol;let a=`${e}=${encodeURIComponent(t)};expires=${i};path=/;SameSite=Lax`;s&&(a+=";Secure"),o&&(a+=`;domain=${o}`),document.cookie=a}catch{}}function y(){if("undefined"==typeof window)return 1;const e=window.location.hostname;if(!e||"localhost"===e||/^\d+\.\d+\.\d+\.\d+$/.test(e))return 1;const t=e.split(".");return Math.max(1,t.length-1)}function b(){const e=f(g);if(e)return e;const t=`fb.${y()}.${Date.now()}.${Math.floor(1e10*Math.random()).toString().padStart(10,"0")}`;return x(g,t,90),t}function v(){const e=f(m);if(e)return e;const t=w();if(!t)return null;const n=`fb.${y()}.${Date.now()}.${t}`;return x(m,n,90),n}function w(){if("undefined"==typeof window)return null;try{return new URLSearchParams(window.location.search).get("fbclid")}catch{return null}}function _(e){return e.reduce((e,t)=>e+(t.quantity??1),0)}function C(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 k{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:C(e.products)})}productClicked(e,t){this.aegis.track("product_clicked",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}productImpressed(e,t){this.aegis.track("product_impression",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,currency:e.currency??"INR",category:e.category,list_id:null==t?void 0:t.list_id,position:(null==t?void 0:t.position)??e.position,section:null==t?void 0:t.section})}categoryFiltered(e,t){this.aegis.track("category_filtered",{category:e,previous_category:null==t?void 0:t.previous_category,result_count:null==t?void 0:t.result_count})}searchPerformed(e){this.aegis.track("search_performed",{query:e.query,results_count:e.results_count,filters:e.filters})}addToCart(e){this.aegis.track("cart_item_added",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",category:e.category,brand:e.brand,variant_id:e.variant_id,variant_label:e.variant_label})}removeFromCart(e){this.aegis.track("cart_item_removed",{product_id:e.product_id,sku:e.sku??e.product_id,name:e.name,price:e.price,quantity:e.quantity??1,currency:e.currency??"INR",variant_id:e.variant_id})}cartViewed(e){this.aegis.track("cart_viewed",{cart_id:e.cart_id,value:e.value,currency:e.currency??"INR",num_items:_(e.products),products:C(e.products)})}checkoutStarted(e){this.aegis.track("checkout_started",{checkout_id:e.checkout_id,value:e.value,currency:e.currency??"INR",num_items:_(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,products:C(e.products)})}checkoutStep(e,t){this.aegis.track("checkout_step",{step:e,...t})}checkoutOption(e){this.aegis.track("checkout_option",{...e})}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:_(e.products),coupon:e.coupon,shipping:e.shipping,tax:e.tax,discount:e.discount,payment_method:e.payment_method,products:C(e.products)})}orderRefunded(e,t,n){this.aegis.track("order_refunded",{order_id:e,value:t,products:n?C(n):void 0})}orderShipped(e,t){this.aegis.track("order_shipped",{order_id:e,carrier:null==t?void 0:t.carrier,tracking_code:null==t?void 0:t.tracking_code,tracking_url:null==t?void 0:t.tracking_url})}couponApplied(e){this.aegis.track("coupon_applied",{...e})}couponRemoved(e){this.aegis.track("coupon_removed",{...e})}couponDenied(e,t){this.aegis.track("coupon_denied",{...e,reason:t})}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})}productRemovedFromWishlist(e){this.aegis.track("wishlist_item_removed",{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})}productWaitlisted(e){this.aegis.track("product_waitlisted",{product_id:e.product.product_id,sku:e.product.sku??e.product.product_id,variant_id:e.product.variant_id,name:e.product.name,price:e.product.price,channels:e.channels})}promotionViewed(e){this.aegis.track("promotion_viewed",{...e})}promotionClicked(e){this.aegis.track("promotion_clicked",{...e})}}class E{constructor(e={}){this.droppedThisWindow=0,this.firstDroppedName=null,this.windowFlushTimer=null,this.capacity=Math.max(1,e.burstCapacity??100),this.refillPerSecond=Math.max(1,e.refillPerSecond??20),this.windowMs=e.dropCoalesceWindowMs??1e3,this.onDropBatch=e.onDropBatch,this.tokens=this.capacity,this.lastRefillMs=Date.now()}tryConsume(e){return this.refill(),this.tokens>=1?(this.tokens-=1,!0):(this.droppedThisWindow+=1,null===this.firstDroppedName&&(this.firstDroppedName=e,o.warn(`[Aegis] Rate limit reached — dropping event "${e}" and any further events for ${this.windowMs}ms. Burst=${this.capacity}, refill=${this.refillPerSecond}/s.`)),this.windowFlushTimer||(this.windowFlushTimer=setTimeout(()=>this.flushWindow(),this.windowMs)),!1)}getAvailableTokens(){return this.refill(),Math.floor(this.tokens)}destroy(){this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.flushWindow()}refill(){const e=Date.now(),t=(e-this.lastRefillMs)/1e3;if(t<=0)return;const n=t*this.refillPerSecond;this.tokens=Math.min(this.capacity,this.tokens+n),this.lastRefillMs=e}flushWindow(){if(this.windowFlushTimer&&(clearTimeout(this.windowFlushTimer),this.windowFlushTimer=null),this.droppedThisWindow>0&&this.onDropBatch)try{this.onDropBatch(this.droppedThisWindow,this.firstDroppedName)}catch(e){o.warn("[Active Reach] RateLimiter.onDropBatch threw:",e)}this.droppedThisWindow=0,this.firstDroppedName=null}}const S=3432918353,T=461845907;function $(e,t=0){return function(e,t=0){const n=e.length,i=Math.floor(n/4);let o=t>>>0;for(let c=0;c<i;c++){const t=4*c;let n=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24;n=Math.imul(n,S),n=n<<15|n>>>17,n=Math.imul(n,T),o^=n,o=o<<13|o>>>19,o=Math.imul(o,5)+3864292196>>>0}const s=4*i;let a=0;const r=n-s;3===r&&(a^=e[s+2]<<16);r>=2&&(a^=e[s+1]<<8);r>=1&&(a^=e[s],a=Math.imul(a,S),a=a<<15|a>>>17,a=Math.imul(a,T),o^=a);return o^=n,o^=o>>>16,o=Math.imul(o,2246822507),o^=o>>>13,o=Math.imul(o,3266489909),o^=o>>>16,o>>>0}((new TextEncoder).encode(e),t)}class I{constructor(e,t){if(this.params=t,t.m&t.m-1)throw new Error(`Bloom filter m must be a power of 2, got ${t.m}`);if(e.length!==t.m>>3)throw new Error(`Bloom filter buffer size mismatch: expected ${t.m>>3} bytes, got ${e.length}`);this.buf=e,this.mask=t.m-1}static fromBase64(e,t){const n=function(e){if("undefined"!=typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const t=globalThis.Buffer;if(t&&"function"==typeof t.from){const n=t.from(e,"base64");return new Uint8Array(n)}throw new Error("No base64 decoder available (neither atob nor Buffer)")}(e);return new I(n,t)}has(e){const t=$(e,this.params.seedA),n=$(e,this.params.seedB);for(let i=0;i<this.params.k;i++){const e=t+Math.imul(i,n)>>>0&this.mask;if(0===(this.buf[e>>3]&1<<(7&e)))return!1}return!0}}class z{constructor(){this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,this.localNovelNames=new Set,this.droppedSinceLastReport=new Map,this.reportWindowStart=Date.now(),this.hasWarnedThisSession=!1}ingestHint(e){if(!e||"mmh3_x86_32_km"!==e.bloom_algo)return this.bloom=null,this.remainingNewNames=1/0,this.graceActive=!1,void this.localNovelNames.clear();try{this.bloom=I.fromBase64(e.bloom_b64,{m:e.m,k:e.k,seedA:e.seed_a,seedB:e.seed_b})}catch{this.bloom=null}this.remainingNewNames=e.remaining_new_names??1/0,this.graceActive=!0===e.grace_active,this.localNovelNames.clear()}shouldSend(e){if(!this.bloom)return!0;if(this.graceActive)return!0;if(this.bloom.has(e))return!0;if(this.localNovelNames.has(e))return!0;if(this.remainingNewNames>0)return this.localNovelNames.add(e),this.remainingNewNames-=1,!0;const t=this.droppedSinceLastReport.get(e)??0;var n;return this.droppedSinceLastReport.set(e,t+1),this.hasWarnedThisSession||(this.hasWarnedThisSession=!0,n=`[aegis] Event-name cap reached — "${e}" dropped locally. Upgrade your plan or remove dynamically-generated event names.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(n)),!1}drainDropReport(){if(0===this.droppedSinceLastReport.size)return null;const e={};let t=0;for(const[i,o]of this.droppedSinceLastReport)e[i]=o,t+=o;const n=this.reportWindowStart;return this.droppedSinceLastReport.clear(),this.reportWindowStart=Date.now(),{events:e,total:t,since:n}}_debugState(){return{hasBloom:null!==this.bloom,remaining:this.remainingNewNames,localNovel:this.localNovelNames.size,graceActive:this.graceActive}}}const A=["system.","user.","loyalty.","review.","cart.","checkout.","product.","pos.","bill.","feedback.","chat.","delivery.","event.","$","_"],M=/(.)([A-Z][a-z]+)/g,L=/([a-z0-9])([A-Z])/g,R=/[\s\-.]+/g,P=/_+/g,D=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/,N=new Set(["at","on","date","time","timestamp","dob","birthday","joined","expired","expires","created","updated","started","ended"]);function F(e){if(!e)return null;return e.replace(M,"$1_$2").replace(L,"$1_$2").replace(R,"_").toLowerCase().replace(P,"_").replace(/^_+|_+$/g,"")||null}function O(e){const t=e.toLowerCase();for(const n of A)if(t.startsWith(n))return n;return null}function B(e){for(const t of e.toLowerCase().split(/[_\-.\s]+/))if(N.has(t))return!0;return!1}function U(e){if("number"==typeof e&&Number.isFinite(e))return e<1e11?Math.floor(1e3*e):Math.floor(e);if("string"==typeof e&&e){const t=e.trim();if(D.test(t)){const e=Date.parse(t);if(!Number.isNaN(e))return e}const n=Number(t);if(Number.isFinite(n))return n<1e11?Math.floor(1e3*n):Math.floor(n)}return null}const j=class e{constructor(){this.warnCounts=new Map}process(e,t){const n={},i=[];if(!e||"object"!=typeof e)return{sanitized:n,drops:i};for(const o of Object.keys(e)){const t=O(o);if(null!==t){i.push({originalKey:o,verdict:"reserved_prefix",reason:`key uses reserved namespace ${JSON.stringify(t)}`});continue}const s=F(o);if(null===s){i.push({originalKey:o,verdict:"bad_key_format",reason:"key reduced to empty after normalization"});continue}if(null!==O(s)){i.push({originalKey:o,verdict:"reserved_prefix",reason:`normalized key ${JSON.stringify(s)} still uses a reserved namespace`});continue}let a=e[o];if("string"==typeof a){if(a.length>1e4){i.push({originalKey:o,verdict:"value_too_long",reason:`value length ${a.length} exceeds hard cap 10000`});continue}a.length>512&&(i.push({originalKey:o,verdict:"value_too_long",reason:`value truncated from ${a.length} to 512 chars`}),a=a.slice(0,512))}if(B(s)&&"string"==typeof a){const e=U(a);if(null===e){i.push({originalKey:o,verdict:"bad_date_format",reason:`value ${JSON.stringify(a)} on date-keyed field ${JSON.stringify(s)} didn't parse as ISO-8601 / epoch`});continue}a=e}n[s]=a}for(const o of i)this.maybeWarn(t??null,o);return{sanitized:n,drops:i}}maybeWarn(t,n){const i=t??"__no_workspace__";let o=this.warnCounts.get(i);o||(o=new Map,this.warnCounts.set(i,o));const s=o.get(n.verdict)??0;var a;s>=e.WARN_CAP||(o.set(n.verdict,s+1),a=`[Active Reach SDK] trait ${n.verdict}: ${n.reason} (original key: ${JSON.stringify(n.originalKey)}). Backend will reject; fix the SDK call to silence this warning.`,"undefined"!=typeof console&&"function"==typeof console.warn&&console.warn(a))}};j.WARN_CAP=3;let W=j;const q=new Set(["email","sms","push","webpush","whatsapp","rcs","inapp"]),H=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,V=/^\+[1-9]\d{7,14}$/,X=/^[a-f0-9]{64}$/i,K=/^\d{4}-\d{2}-\d{2}$/;class Y{constructor(e){this.pendingTraits={},this.aegis=e}login(e,t){if("string"!=typeof e||0===e.length)return void o.warn("[user.login] userId must be a non-empty string");const n={...this.pendingTraits,...t||{}};this.pendingTraits={},this.aegis.identify(e,n)}logout(){this.pendingTraits={},this.aegis.reset()}setAttribute(e,t){"string"==typeof e&&0!==e.length?this.writeTraits({[e]:t}):o.warn("[user.setAttribute] key must be a non-empty string")}setAttributes(e){e&&"object"==typeof e?this.writeTraits(e):o.warn("[user.setAttributes] map must be an object")}setEmail(e){H.test(e)?this.writeTraits({email:e.toLowerCase()}):o.warn("[user.setEmail] invalid email format")}setPhone(e){V.test(e)?this.writeTraits({phone:e}):o.warn("[user.setPhone] phone must be E.164 (e.g. +15551234567)")}setHashedEmail(e){X.test(e)?this.writeTraits({email_sha256:e.toLowerCase()}):o.warn("[user.setHashedEmail] expected 64-char hex SHA-256")}setHashedPhone(e){X.test(e)?this.writeTraits({phone_sha256:e.toLowerCase()}):o.warn("[user.setHashedPhone] expected 64-char hex SHA-256")}setBirthDate(e){K.test(e)?this.writeTraits({birth_date:e}):o.warn("[user.setBirthDate] expected YYYY-MM-DD")}setOptIn(e,t){q.has(e)?"boolean"==typeof t?this.writeTraits({[`opt_in_${e}`]:t}):o.warn("[user.setOptIn] granted must be a boolean"):o.warn(`[user.setOptIn] unknown channel: ${e}`)}setSecureToken(e){"string"==typeof e&&0!==e.length?this.writeTraits({_secure_token:e}):o.warn("[user.setSecureToken] token must be a non-empty string")}_getPendingTraits(){return{...this.pendingTraits}}writeTraits(e){const t=this.aegis.getUserId();t?this.aegis.identify(t,e):Object.assign(this.pendingTraits,e)}}class Q{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._user=null,this.rateLimiter=null,this.nameGovernor=new z,this.traitGovernor=new W,this._lastPageUrl=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._lastEventIds=new Map,this._workspaceCodes=new Set,this._runtimeWorkspace=null,this._runtimeLocation=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)?o.warn("SDK already initialized"):this.shouldRespectDNT(t)?o.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&&o.enable(),o.info("Initializing Active Reach SDK...",this.config),this.storage=new l({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 u(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 a(this.storage,this.config.session_timeout),this.captureAdClickIDsOnInit(),this.transport=new c({writeKey:this.config.write_key,apiHost:this.config.api_host,cellEndpoints:this.config.cell_endpoints,preferredRegion:this.config.preferred_region,autoRegionDetection:this.config.auto_region_detection,requestTimeout:this.config.request_timeout,retryFailedRequests:this.config.retry_failed_requests,maxRetries:this.config.max_retries,retryBackoffMultiplier:this.config.retry_backoff_multiplier},this.storage),this.config.active_cell=this.transport.getActiveCell(),this.queue=new r({batchSize:this.config.batch_size,batchInterval:this.config.batch_interval,enableOfflineMode:this.config.enable_offline_mode,maxOfflineEvents:this.config.max_offline_events},this.transport,this.storage),this.rateLimiter=new E({burstCapacity:this.config.rate_limit_burst,refillPerSecond:this.config.rate_limit_per_second,onDropBatch:(e,t)=>this.emitRateLimitMeta(e,t)}),await this.initializePlugins(),this.config.auto_page_view&&(this.page(),this.startSPATracking()),o.info("Active Reach SDK initialized successfully")):o.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(e,n){return{...t,...n,write_key:e,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("[Active Reach URL Parser] parseAdClickIDs failed:",t),{}}}();(function(e){return Object.keys(e).length>0})(e)&&(this.session.setAdClickIDs(e,window.location.href),o.info("Ad click IDs captured on page load:",e))}async initializePlugins(){if(this.config){for(const e of this.config.plugins)o.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=>{o.error(`Failed to initialize plugin "${e.name}":`,t)})}removePlugin(e){this.plugins.unregister(e)}ingestWorkspaceCodes(e){this._workspaceCodes=new Set((e??[]).filter(e=>"string"==typeof e&&e.length>0)),o.debug("Workspace codes ingested",{count:this._workspaceCodes.size})}setWorkspace(e){if(this._runtimeWorkspace=e,"undefined"!=typeof window&&window.sessionStorage)try{e?window.sessionStorage.setItem("aegis_runtime_ws",e):window.sessionStorage.removeItem("aegis_runtime_ws")}catch{}o.debug("Runtime workspace set",{value:e})}clearWorkspace(){this.setWorkspace(null)}ingestLocationCodes(e){this._workspaceCodes=new Set((e??[]).filter(e=>"string"==typeof e&&e.length>0)),o.debug("Location codes ingested",{count:this._workspaceCodes.size})}setLocation(e){if(this._runtimeLocation=e,"undefined"!=typeof window&&window.sessionStorage)try{e?window.sessionStorage.setItem("aegis_runtime_location",e):window.sessionStorage.removeItem("aegis_runtime_location")}catch{}o.debug("Runtime location set",{value:e})}clearLocation(){this.setLocation(null)}getPathLocationCode(){return this.getPathWorkspaceCode()}getEffectiveLocationId(){var e;const t=null==(e=this.config)?void 0:e.location_id;if(t)return t;if("undefined"==typeof window)return;try{const e=new URLSearchParams(window.location.search),t=e.get("location")||e.get("ws");if(t&&t.length>0)return t}catch{}const n=this.getPathLocationCode();if(n)return n;if(this._runtimeLocation)return this._runtimeLocation;try{if(window.sessionStorage){const e=window.sessionStorage.getItem("aegis_runtime_location");if(e&&e.length>0)return e}}catch{}}getPathWorkspaceCode(){if("undefined"!=typeof window&&0!==this._workspaceCodes.size)try{const e=window.location.pathname.split("/").filter(Boolean);if(0===e.length)return;const t=e[0].toLowerCase();return this._workspaceCodes.has(t)?t:void 0}catch{return}}getEffectiveWorkspaceId(){var e;const t=null==(e=this.config)?void 0:e.workspace_id;if(t)return t;if("undefined"==typeof window)return;try{const e=new URLSearchParams(window.location.search).get("ws");if(e&&e.length>0)return e}catch{}const n=this.getPathWorkspaceCode();if(n)return n;if(this._runtimeWorkspace)return this._runtimeWorkspace;try{if(window.sessionStorage){const e=window.sessionStorage.getItem("aegis_runtime_ws");if(e&&e.length>0)return e}}catch{}}track(e,t){if(!this.assertInitialized())return;const n=i(),o={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(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this._lastEventIds.set(e,n),this.captureEvent(o)}identify(e,t){if(!this.assertInitialized())return;const n=this.getEffectiveWorkspaceId()||null,{sanitized:o}=this.traitGovernor.process(t,n);this.identity.setUserId(e,o);const s={type:"identify",traits:o,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(s)}page(e,t){if(!this.assertInitialized())return;const n={type:"page",name:e||document.title,properties:t||{},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(n)}group(e,t){if(!this.assertInitialized())return;const n=this.getEffectiveWorkspaceId()||null,{sanitized:o}=this.traitGovernor.process(t,n),s={type:"group",groupId:e,traits:o,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};this.captureEvent(s)}alias(e){if(!this.assertInitialized())return;const{previousId:t}=this.identity.alias(e),n={type:"alias",previousId:t,messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:e,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};this.captureEvent(n)}screen(e,t){if(!this.assertInitialized())return;if("string"!=typeof e||0===e.length)return void o.warn("aegis.screen: name must be a non-empty string");const n={type:"screen",name:e,properties:t||{},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),workspace_id:this.getEffectiveWorkspaceId(),location_id:this.getEffectiveLocationId(),context:p(this.config,this.session)};this.captureEvent(n)}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 o.debug("Event blocked: analytics consent not granted");if("track"===e.type){const t=e;if(!("string"==typeof t.event&&t.event.startsWith("aegis.client."))&&!this.nameGovernor.shouldSend(t.event))return}if(this.rateLimiter){const t="track"===e.type&&e.event?e.event:e.type;if(!("track"===e.type&&"string"==typeof e.event&&e.event.startsWith("aegis.client."))&&!this.rateLimiter.tryConsume(t))return}const n=e.context,i=e.properties;if((null==n?void 0:n.campaign)&&i&&!i.campaign_id){const e=n.campaign;e.campaign&&(i.campaign_id=e.campaign),e.source&&(i.campaign_source=e.source),e.medium&&(i.campaign_medium=e.medium),e.content&&(i.campaign_content=e.content),e.term&&(i.campaign_term=e.term)}if((null==n?void 0:n.adClickIDs)&&i){const e=n.adClickIDs,t=e.gclid||e.fbclid||e.ctwa_clid||e.msclkid||e.ttclid;t&&!i.campaign_click_id&&(i.campaign_click_id=t)}if(i){const e={fbp:b(),fbc:v(),fbclid:w()};e.fbp&&!i.fbp&&(i.fbp=e.fbp),e.fbc&&!i.fbc&&(i.fbc=e.fbc),e.fbclid&&!i.fbclid&&(i.fbclid=e.fbclid)}o.debug("Capturing event:",e);const s=await this.plugins.executeHookChain("beforeEventCapture",e);s?(this.queue.push(s),this.session.incrementEventCount(),await this.plugins.executeHook("afterEventCapture",s)):o.debug("Event cancelled by plugin")}emitRateLimitMeta(e,t){var n,o;if(!(null==(n=this.config)?void 0:n.initialized)||!this.session||!this.identity)return;const s={type:"track",event:"aegis.client.rate_limited",properties:{dropped_count:e,sample_event_name:t,burst_capacity:this.config.rate_limit_burst,refill_per_second:this.config.rate_limit_per_second},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};null==(o=this.queue)||o.push(s)}reset(){this.assertInitialized()&&(this.identity.reset(),this._user=null,o.info("User identity reset"))}ingestGovernanceHint(e){this.nameGovernor.ingestHint(e??null),o.debug("Governance hint ingested",e?{k:e.k,m:e.m,remaining:e.remaining_new_names}:"disabled")}emitGovernanceDropMeta(){var e,t;if(!(null==(e=this.config)?void 0:e.initialized)||!this.session||!this.identity)return;const n=this.nameGovernor.drainDropReport();if(!n)return;const o={type:"track",event:"aegis.client.name_governor_dropped",properties:{dropped_count:n.total,distinct_names:Object.keys(n.events).length,sample_names:Object.entries(n.events).sort((e,t)=>t[1]-e[1]).slice(0,10).map(([e,t])=>({name:e,count:t})),window_start:n.since,window_end:Date.now()},messageId:i(),timestamp:(new Date).toISOString(),anonymousId:this.identity.getAnonymousId(),userId:this.identity.getUserId()||void 0,sessionId:this.session.getSessionId(),context:p(this.config,this.session)};null==(t=this.queue)||t.push(o)}async flush(){this.assertInitialized()&&(this.emitGovernanceDropMeta(),await this.queue.flush())}getAnonymousId(){return this.identity?this.identity.getAnonymousId():null}getUserId(){return this.identity?this.identity.getUserId():null}async getRewards(){const e=this.config;if(!e||!e.api_host||!this.identity)return null;const t=this.identity.getUserId();if(!t)return null;const n=e.api_host.replace(/\/$/,""),i={"X-Aegis-Write-Key":e.write_key,"X-Contact-ID":t,"X-User-ID":t},s=e.organization_id;s&&(i["X-Organization-ID"]=s);const a=this.getEffectiveLocationId();a&&(i["X-Location-Id"]=a);try{const e=await fetch(`${n}/api/v1/sdk/entitlements`,{method:"GET",headers:i,credentials:"include"});return 204!==e.status&&e.ok?await e.json():null}catch(r){return o.warn("getRewards() failed",r),null}}getSessionId(){return this.session?this.session.getSessionId():null}lastEventId(e){return this._lastEventIds.get(e)??null}debug(e=!0){e?o.enable():o.disable(),this.config&&(this.config.debug=e)}setCell(e){if(!this.config)return void o.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),o.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),o.info("Consent preferences updated")):o.warn("Consent manager not initialized")}grantConsent(e){this.consent?e?this.consent.setConsent({[e]:!0}):this.consent.grantAll():o.warn("Consent manager not initialized")}denyConsent(e){this.consent?e?this.consent.setConsent({[e]:!1}):this.consent.denyAll():o.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):(o.warn("Consent manager not initialized"),()=>{})}assertInitialized(){var e;return!!(null==(e=this.config)?void 0:e.initialized)||(o.warn("SDK not initialized. Call aegis.init() first."),!1)}get ecommerce(){return this._ecommerce||(this._ecommerce=new k(this)),this._ecommerce}get user(){return this._user||(this._user=new Y(this)),this._user}destroy(){this.stopSPATracking(),this.queue&&this.queue.destroy(),this.session&&this.session.destroy(),this.transport&&this.transport.destroy(),this.rateLimiter&&(this.rateLimiter.destroy(),this.rateLimiter=null),this.plugins.clear(),o.info("SDK destroyed")}}const G="aegis_sticky_dismissed:";function J(e,t){const{campaign:n,trackEvent:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=n.interactive_config||{},c=r.progress_goal_type||"cart_total",d=Number(r.progress_threshold);if(!(d>0))return s("progress_bar requires a positive progress_threshold — skipping","warn"),null;const l=r.progress_reward_text||n.body||"Unlocked!",p="sse"===r.progress_source?"sse":"client";a();const h=o(n.background_color||"#4169e1"),u="branded"===r.surface_style,g=u?h:"#ffffff",m=o(n.text_color||(u?"#ffffff":"#0f172a")),f=o(r.progress_fill_color||(u?"#ffffff":h)),x=u?"rgba(255,255,255,0.25)":`${f}22`,y=document.createElement("div");y.className="aegis-in-app-progress-bar",y.setAttribute("data-campaign-id",n.id),y.style.cssText=t?`\n background: ${g}; color: ${m};\n padding: 10px 14px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `:`\n position: fixed; left: 12px; right: 12px; bottom: 12px;\n max-width: 540px; margin: 0 auto;\n background: ${g}; color: ${m}; border-radius: 12px;\n padding: 10px 14px; z-index: 999997;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `;const b=document.createElement("div");b.style.cssText="display: flex; justify-content: space-between; font-size: 13px; font-weight: 600; margin-bottom: 6px;";const v=document.createElement("span");v.textContent=n.title,b.appendChild(v);const w=document.createElement("span");w.style.cssText="opacity: 0.7; font-weight: 500;",b.appendChild(w),y.appendChild(b);const _=document.createElement("div");_.style.cssText=`\n height: 8px; border-radius: 999px; background: ${x};\n overflow: hidden;\n `;const C=document.createElement("div");if(C.style.cssText=`\n position: relative; overflow: hidden;\n height: 100%; border-radius: 999px; background: ${f};\n width: 0%; transition: width 0.4s cubic-bezier(.4,0,.2,1);\n `,"undefined"!=typeof document&&!document.getElementById("aegis-progress-styles")){const e=document.createElement("style");e.id="aegis-progress-styles",e.textContent="@keyframes aegisProgShimmer{0%{transform:translateX(-100%)}60%,100%{transform:translateX(220%)}}",document.head.appendChild(e)}const k=document.createElement("div");k.style.cssText="position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.38), transparent); transform: translateX(-100%); animation: aegisProgShimmer 1.8s ease-in-out infinite;",C.appendChild(k),_.appendChild(C),y.appendChild(_);const E=document.createElement("div");E.style.cssText="font-size: 11.5px; opacity: 0.65; margin-top: 6px;",y.appendChild(E);let S=!1;const T=new Set,$=e=>{T.has(e)||(T.add(e),i(n.id,"impression",{stepId:e}))},I=()=>{const t=(()=>{var t,i,o;if("sse"===p){const e=window.__aegisProgressSSE;return e&&"number"==typeof e[n.id]?e[n.id]:0}if("cart_total"===c||"items_in_cart"===c){const n=null==(t=e.getCartState)?void 0:t.call(e);if(n)return"items_in_cart"===c?Number(n.itemCount)||0:Number(n.total)||0}try{if("cart_total"===c||"items_in_cart"===c){const e=window;if(null==(i=e.Shopify)?void 0:i.checkout){const t=parseFloat(String(e.Shopify.checkout.total_price||0));return"cart_total"===c?t:0}if(e.aegis_cart)return"items_in_cart"===c?Array.isArray(e.aegis_cart.cart_items)?e.aegis_cart.cart_items.length:0:Number(e.aegis_cart.cart_total||0);try{const e=null==(o=window.localStorage)?void 0:o.getItem("mage-cache-storage");if(e){const t=JSON.parse(e).cart;if(t)return"cart_total"===c?Number(t.subtotalAmount||0):Array.isArray(t.items)?t.items.length:0}}catch{}}return 0}catch{return 0}})(),o=Math.max(0,Math.min(100,t/d*100));if(C.style.width=`${o}%`,w.textContent=`${t.toFixed(0)} / ${d.toFixed(0)} · ${Math.round(o)}%`,k.style.display=o>=100?"none":"",o>=25&&$("q25"),o>=50&&$("q50"),o>=75&&$("q75"),o>=100)E.textContent=l,S||(S=!0,i(n.id,"clicked",{stepId:"unlocked"}));else{const e=Math.max(0,d-t);E.textContent=`Add ${e.toFixed(0)} more to unlock: ${l}`}};I();const z=setInterval(I,1e3),A=()=>clearInterval(z);return window.addEventListener("beforeunload",A,{once:!0}),y.addEventListener("remove",A),y}const Z="aegis_coachmark_progress:";function ee(e,t){try{"undefined"!=typeof localStorage&&localStorage.setItem(Z+e,String(t))}catch{}}function te(e){const{campaign:t,trackEvent:n,sanitizeColor:i,log:o,addAnimationStyles:s}=e,a=t.interactive_config||{},r=a.resume_key;if(!r)return void o("coachmark_tour requires interactive_config.resume_key — skipping","warn");const c=Array.isArray(a.steps)?a.steps:[];if(0===c.length)return void o("coachmark_tour has no steps — skipping","warn");const d=!1!==a.allow_skip,l=!1!==a.show_progress_dots;s();const p=i(t.background_color||"#0f172a"),h=i(t.text_color||"#ffffff"),u="spotlight"===a.highlight_style,g="number"==typeof a.spotlight_padding?a.spotlight_padding:6,m="circle"===a.spotlight_shape?"50%":"10px",f="number"==typeof a.spotlight_dim?Math.max(0,Math.min(95,a.spotlight_dim))/100:u?.64:.4,x=a.spotlight_dim_color||"dark",y="black"===x?"#000000":"brand"===x?p:"custom"===x?i(a.spotlight_dim_custom||"#0f172a"):"#0f172a",b=Math.round(255*Math.max(0,Math.min(1,f))).toString(16).padStart(2,"0"),v=/^#[0-9a-fA-F]{6}$/.test(y)?`${y}${b}`:`rgba(15,23,42,${f})`;let w=function(e){try{if("undefined"==typeof localStorage)return 0;const t=localStorage.getItem(Z+e),n=t?parseInt(t,10):0;return Number.isFinite(n)&&n>=0?n:0}catch{return 0}}(r);if(w>=c.length)return void o(`coachmark_tour ${r} already complete — not re-showing`);n(t.id,"impression");let _=null,C=null,k=null;const E=()=>{null==_||_.remove(),null==C||C.remove(),null==k||k.remove(),_=null,C=null,k=null},S=i=>{var o;E();const s=`step_${i.lastStepIdx}`;i.skipped?n(t.id,"dismissed",{stepId:s}):(n(t.id,"clicked",{stepId:s}),null==(o=e.submitResponse)||o.call(e,"tour_complete",{steps:c.length})),ee(r,c.length)},T=e=>{E();const i=c[e];if(!i)return void S({skipped:!1,lastStepIdx:e-1});ee(r,e);const o=i.anchor_web;let s=null;if(o)try{s=document.querySelector(o)}catch{s=null}const a=!!o&&!s;a&&(console.warn(`[AegisInApp] Coachmark step ${e} anchor "${o}" not found on this surface — rendering centered fallback.`),n(t.id,"anchor_unresolved",{stepId:`step_${e}`,meta:{anchor_resolved:!1,anchor_selector:o,widget_type:"coachmark_tour"}})),n(t.id,"impression",{stepId:`step_${e}`,...a?{meta:{anchor_resolved:!1}}:{}});const x=s?s.getBoundingClientRect():null;if(k=document.createElement("div"),k.className="aegis-in-app-coachmark-highlight",x){const e=u?`0 0 0 3px rgba(255,255,255,0.92), 0 0 0 7px ${p}66, 0 0 0 9999px ${v}`:`0 0 0 2px ${h}, 0 0 0 9999px rgba(0,0,0,${f})`;k.style.cssText=`\n position: fixed;\n top: ${x.top-g}px; left: ${x.left-g}px;\n width: ${x.width+2*g}px; height: ${x.height+2*g}px;\n border-radius: ${u?m:"10px"}; z-index: 999998;\n box-shadow: ${e};\n pointer-events: none;\n transition: all 0.2s ease;\n `}else k.style.cssText=`\n position: fixed; inset: 0; z-index: 999998;\n background: ${v}; pointer-events: none;\n `;document.body.appendChild(k);const y=i.placement||"bottom";C=document.createElement("div"),C.className="aegis-in-app-coachmark-tip",C.setAttribute("data-campaign-id",t.id),C.style.cssText=`\n position: fixed; z-index: 999999;\n background: ${p}; color: ${h};\n padding: 12px 14px; border-radius: 12px;\n max-width: 260px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.25);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.2s ease;\n `;const b=document.createElement("div");b.textContent=i.title,b.style.cssText="font-weight: 700; font-size: 13px; margin-bottom: 4px;",C.appendChild(b);const w=document.createElement("div");w.textContent=i.body,w.style.cssText="font-size: 12.5px; line-height: 1.4; opacity: 0.9;",C.appendChild(w);const _=document.createElement("div");if(_.style.cssText="display: flex; align-items: center; justify-content: space-between; margin-top: 10px; gap: 8px;",l){const t=document.createElement("div");t.style.cssText="display: flex; gap: 4px;",c.forEach((n,i)=>{const o=document.createElement("span");o.style.cssText=`\n width: 5px; height: 5px; border-radius: 999px;\n background: ${h}; opacity: ${i===e?"0.95":"0.3"};\n `,t.appendChild(o)}),_.appendChild(t)}else _.appendChild(document.createElement("span"));const $=document.createElement("div");if($.style.cssText="display: flex; gap: 6px;",e>0){const t=document.createElement("button");t.textContent="Back",t.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",t.addEventListener("click",()=>T(e-1)),$.appendChild(t)}if(d&&e<c.length-1){const t=document.createElement("button");t.textContent="Skip",t.style.cssText="\n background: transparent; color: inherit; opacity: 0.7;\n border: none; font-size: 12px; cursor: pointer; padding: 6px 8px;\n ",t.addEventListener("click",()=>S({skipped:!0,lastStepIdx:e})),$.appendChild(t)}const I=document.createElement("button"),z=e===c.length-1;I.textContent=i.cta_text||(z?"Done":"Next"),I.style.cssText=`\n background: ${h}; color: ${p};\n border: none; padding: 6px 12px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer;\n `,I.addEventListener("click",()=>{z?S({skipped:!1,lastStepIdx:e}):T(e+1)}),$.appendChild(I),_.appendChild($),C.appendChild(_),document.body.appendChild(C);const A=C.getBoundingClientRect();let M,L;x?(M=x.bottom+12,L=x.left,"top"===y?M=x.top-A.height-12:"left"===y?(M=x.top,L=x.left-A.width-12):"right"===y&&(M=x.top,L=x.right+12)):(M=(window.innerHeight-A.height)/2,L=(window.innerWidth-A.width)/2),M=Math.max(8,Math.min(window.innerHeight-A.height-8,M)),L=Math.max(8,Math.min(window.innerWidth-A.width-8,L)),C.style.top=`${M}px`,C.style.left=`${L}px`};T(w),window.aegisResetTour=e=>function(e){try{"undefined"!=typeof localStorage&&localStorage.removeItem(Z+e)}catch{}}(e)}const ne=["linear-gradient(160deg, #6366f1, #a855f7)","linear-gradient(160deg, #ec4899, #f43f5e)","linear-gradient(160deg, #0ea5e9, #22d3ee)","linear-gradient(160deg, #f59e0b, #ef4444)","linear-gradient(160deg, #10b981, #14b8a6)","linear-gradient(160deg, #8b5cf6, #6366f1)"],ie=e=>ne[e%ne.length],oe=e=>`conic-gradient(from 0deg, ${e}, color-mix(in srgb, ${e} 50%, #ffffff), ${e}, color-mix(in srgb, ${e} 72%, #000000), ${e})`,se=e=>`linear-gradient(110deg, ${e}, color-mix(in srgb, ${e} 50%, #ffffff), ${e}, color-mix(in srgb, ${e} 72%, #000000), ${e})`;function ae(e){const t=e.campaign.interactive_config||{},n=function(e){if(!Array.isArray(e)||0===e.length)return[];const t=e[0];return t&&Array.isArray(t.frames)?e.slice(0,12).map(e=>({...e,frames:(e.frames||[]).slice(0,20)})).filter(e=>e.frames.length>0):[{frames:e.slice(0,20)}]}(t.stories);if(0===n.length)return e.log("stories rendered with zero groups — skipping","warn"),null;const i=e.sanitizeColor(e.campaign.background_color||"#4169e1"),o=t.stories_ring_style||"brand";let s,a;if("instagram"===o)s="conic-gradient(from 0deg, #feda75, #fa7e1e, #d62976, #962fbf, #4f5bd5, #feda75)",a="linear-gradient(110deg, #feda75, #fa7e1e, #d62976, #962fbf, #4f5bd5, #feda75)";else if("custom"===o){const n=e.sanitizeColor(t.stories_ring_color||i);s=oe(n),a=se(n)}else s=oe(i),a=se(i);return{groups:n,thumbnailShape:"rectangle"===t.stories_thumbnail_shape?"rectangle":"circle",ringBg:s,ringBgLinear:a,branded:"branded"===t.surface_style,brand:i,autoplay:!1!==t.stories_autoplay,loop:!0===t.stories_loop,showProgress:!1!==t.stories_show_progress,defaultDuration:Number(t.stories_default_duration_ms)||5e3,reduceMotion:"undefined"!=typeof window&&"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function re(e,t){const n=ae(e);return!!n&&(e.addAnimationStyles(),de(),function(e,t,n){const{campaign:i}=e,o=!n,s=t.branded?"#ffffff":"#334155",a=document.createElement("div");a.className="aegis-in-app-stories-tray",a.setAttribute("data-campaign-id",i.id);const r=t.branded?t.brand:o?"rgba(255,255,255,0.96)":"transparent";if(a.style.cssText=o?`\n position: fixed; left: 0; right: 0; bottom: 0; z-index: 99998;\n display: flex; gap: 16px; align-items: flex-start; overflow-x: auto;\n padding: 14px 18px 16px 20px; scroll-padding-left: 20px;\n background: ${r}; backdrop-filter: blur(8px);\n box-shadow: 0 -4px 16px rgba(0,0,0,0.08); scrollbar-width: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n `:`\n display: flex; gap: 16px; align-items: flex-start; overflow-x: auto;\n padding: 12px 18px 12px 18px; scroll-padding-left: 18px;\n background: ${r}; ${t.branded?"border-radius: 16px;":""}\n scrollbar-width: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,t.groups.forEach((n,i)=>a.appendChild(function(e,t,n,i,o){var s;const a="rectangle"===t.thumbnailShape,r=n.title||(null==(s=n.frames[0])?void 0:s.title)||`Story ${i+1}`,c=function(e){if(e.cover_image_url)return{img:e.cover_image_url,index:0};const t=e.frames.findIndex(e=>e.image_url);return t>=0?{img:e.frames[t].image_url||null,index:t}:{img:null,index:0}}(n),d=c.img?e.sanitizeUrl(c.img):null,l=ie(i),p=document.createElement("button");if(p.type="button",p.setAttribute("aria-label",`Open ${r} (${n.frames.length} frames)`),p.style.cssText="flex: 0 0 auto; display: flex; flex-direction: column; align-items: center; gap: 5px; border: none; background: transparent; cursor: pointer; padding: 0;",a){const n=document.createElement("div");n.style.cssText=`\n width: 92px; height: 124px; border-radius: 14px; padding: 2.5px;\n background: ${t.ringBgLinear}; background-size: 220% 100%; background-position: 0% 50%;\n ${t.reduceMotion?"":"animation: aegisStoryShimmer 3s ease-in-out infinite;"}\n `;const o=document.createElement("div");if(o.style.cssText=`\n position: relative; width: 100%; height: 100%; border-radius: 12px; overflow: hidden;\n background: ${l}; display: flex; align-items: flex-end;\n `,d){const e=document.createElement("img");e.src=d,e.alt="",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",o.appendChild(e)}const s=document.createElement("div");s.style.cssText="position: absolute; inset: 0; background: linear-gradient(to top, rgba(0,0,0,0.6), rgba(0,0,0,0) 55%);",o.appendChild(s);const a=document.createElement("div");return a.textContent=r,a.style.cssText="position: relative; z-index: 1; padding: 7px 8px; color: #fff; font-size: 11px; font-weight: 700; line-height: 1.2; text-shadow: 0 1px 4px rgba(0,0,0,0.5);",o.appendChild(a),n.appendChild(o),p.appendChild(n),p.addEventListener("click",()=>ce(e,t,i,0)),p}const h=document.createElement("div");h.style.cssText="position: relative; width: 66px; height: 66px;";const u=document.createElement("div");u.style.cssText=`\n position: absolute; inset: 0; border-radius: 50%; background: ${t.ringBg};\n ${t.reduceMotion?"":"animation: aegisStoryRing 4s linear infinite;"}\n `,h.appendChild(u);const g=document.createElement("div");g.style.cssText=`position: absolute; inset: 3px; border-radius: 50%; background: ${t.branded?t.brand:"#fff"};`,h.appendChild(g);const m=document.createElement("div");if(m.style.cssText=`position: absolute; inset: 5px; border-radius: 50%; overflow: hidden; background: ${l}; display: flex; align-items: center; justify-content: center;`,d){const e=document.createElement("img");e.src=d,e.alt="",e.style.cssText="width: 100%; height: 100%; object-fit: cover;",m.appendChild(e)}else{const e=document.createElement("span");e.textContent=r.trim().charAt(0).toUpperCase(),e.style.cssText="color: #fff; font-weight: 800; font-size: 22px; text-shadow: 0 1px 4px rgba(0,0,0,0.25);",m.appendChild(e)}h.appendChild(m),p.appendChild(h);const f=document.createElement("span");return f.textContent=r,f.style.cssText=`max-width: 70px; font-size: 11px; color: ${o}; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`,p.appendChild(f),p.addEventListener("click",()=>ce(e,t,i,0)),p}(e,t,n,i,s))),o){const n=document.createElement("button");n.type="button",n.textContent="✕",n.setAttribute("aria-label","Dismiss stories"),n.style.cssText=`\n flex: 0 0 auto; align-self: center; margin-left: auto;\n width: 28px; height: 28px; border: none; border-radius: 999px;\n background: ${t.branded?"rgba(255,255,255,0.18)":"rgba(0,0,0,0.06)"};\n color: ${t.branded?"#fff":"#475569"}; font-size: 14px; cursor: pointer;\n `,n.addEventListener("click",()=>{e.trackEvent(i.id,"dismissed"),a.remove()}),a.appendChild(n)}n?n.appendChild(a):document.body.appendChild(a)}(e,n,t),!0)}function ce(e,t,n,i=0){const{campaign:o,trackEvent:s,sanitizeUrl:a,log:r}=e,{loop:c,autoplay:d,showProgress:l,defaultDuration:p,reduceMotion:h}=t,u=t.groups;if(0===u.length)return;let g=Math.max(0,Math.min(n,u.length-1)),m=u[g].frames;r(`stories viewer open @ group ${g}`);const f=document.createElement("div");f.className="aegis-in-app-stories-overlay",f.setAttribute("data-campaign-id",o.id),f.setAttribute("role","dialog"),f.setAttribute("aria-label",o.title||"Stories"),f.style.cssText='\n position: fixed; inset: 0; z-index: 100000; background: #000;\n display: flex; align-items: center; justify-content: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisFadeIn 0.25s ease;\n ';const x=document.createElement("div");x.style.cssText="position: relative; width: 100%; height: 100%; max-width: 440px; max-height: 100vh; background: #111; overflow: hidden;",f.appendChild(x);const y=document.createElement("div");y.style.cssText="position: absolute; inset: 0;",x.appendChild(y);const b=document.createElement("div");b.style.cssText="position: absolute; top: 0; left: 0; right: 0; z-index: 4; display: flex; gap: 4px; padding: 10px 10px 0;",x.appendChild(b);let v=[];const w=()=>{b.replaceChildren(),v=[],l&&m.forEach(()=>{const e=document.createElement("div");e.style.cssText="flex: 1; height: 2.5px; border-radius: 999px; background: rgba(255,255,255,0.32); overflow: hidden;";const t=document.createElement("div");t.style.cssText="width: 0%; height: 100%; background: #fff; border-radius: 999px;",e.appendChild(t),b.appendChild(e),v.push(t)})},_=document.createElement("button");_.type="button",_.textContent="✕",_.setAttribute("aria-label","Close"),_.style.cssText="position: absolute; top: 12px; right: 10px; z-index: 5; width: 34px; height: 34px; border: none; border-radius: 999px; background: rgba(0,0,0,0.32); color: #fff; font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center; line-height: 1;",x.appendChild(_);let C=i,k=null,E=null,S=0,T=0,$=!1,I=null;const z=new Set,A=()=>{k&&(clearTimeout(k),k=null),null!==E&&(cancelAnimationFrame(E),E=null)};let M=!1;const L=n=>{var i;A(),document.removeEventListener("keydown",W),"dismissed"===n?s(o.id,"dismissed"):M||(M=!0,null==(i=e.submitResponse)||i.call(e,"story_complete",{groups:t.groups.length})),f.remove()},R=e=>{var t;const n=Number(null==(t=m[e])?void 0:t.duration_ms);return n>=1e3?n:p},P=()=>{if(!l||$)return;const e=R(C),t=T+(Date.now()-S),n=Math.max(0,Math.min(100,t/e*100));v[C]&&(v[C].style.width=`${n}%`),n<100&&(E=requestAnimationFrame(P))},D=()=>{if(!d)return;const e=R(C)-T;S=Date.now(),k=setTimeout(()=>O(1),Math.max(0,e)),l&&!h?E=requestAnimationFrame(P):l&&v[C]&&(v[C].style.width="0%")},N=n=>{var i;A(),T=0,$=!1,C=n,i=n,l&&v.forEach((e,t)=>{e.style.width=t<i?"100%":"0%"}),(n=>{var i;const r=m[n];y.replaceChildren(),I=null;const c=r.video_url?a(r.video_url):null,d=r.image_url?a(r.image_url):null;if(c){const e=document.createElement("video");e.src=c,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",y.appendChild(e),I=e,null==(i=e.play)||i.call(e).catch(()=>{})}else if(d){const e=document.createElement("img");e.src=d,e.alt=r.title||"",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",y.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`position: absolute; inset: 0; background: ${t.branded?t.brand:ie(n)};`,y.appendChild(e)}const l=document.createElement("div");l.style.cssText="position: absolute; inset: 0; pointer-events: none; background: linear-gradient(to top, rgba(0,0,0,0.72) 0%, rgba(0,0,0,0.18) 38%, rgba(0,0,0,0) 60%);",y.appendChild(l);const p=document.createElement("div");if(p.style.cssText="position: absolute; left: 0; right: 0; bottom: 0; z-index: 3; padding: 20px 18px 30px; color: #fff; text-align: left;",r.title){const e=document.createElement("div");e.textContent=r.title,e.style.cssText="font-family: 'Inter Tight', Inter, system-ui, sans-serif; font-size: 21px; font-weight: 800; letter-spacing: -0.01em; line-height: 1.2; margin-bottom: 6px; text-shadow: 0 1px 8px rgba(0,0,0,0.4);",p.appendChild(e)}if(r.body){const e=document.createElement("div");e.textContent=r.body,e.style.cssText="font-size: 14px; line-height: 1.45; opacity: 0.92; text-shadow: 0 1px 6px rgba(0,0,0,0.4);",p.appendChild(e)}const h=r.cta_url?a(r.cta_url):null,u=r.cta_text||(h?"Learn more":"");if(u){const t=document.createElement("button");t.type="button",t.className="aegis-cta",t.textContent=u,t.style.cssText="margin-top: 14px; padding: 11px 22px; border: none; border-radius: 999px; background: #fff; color: #0f172a; font-size: 14px; font-weight: 700; cursor: pointer;",t.addEventListener("pointerdown",e=>e.stopPropagation()),t.addEventListener("click",t=>{t.stopPropagation(),s(o.id,"clicked",{stepId:`g${g}_f${n}`}),h&&(A(),e.navigate?e.navigate(h,`g${g}_f${n}`):window.location.href=h)}),p.appendChild(t)}y.appendChild(p);const f=`${g}_${n}`;z.has(f)||(z.add(f),s(o.id,"impression",{stepId:`g${g}_f${n}`}))})(n),D()},F=(e,t)=>{g=e,m=u[e].frames,w(),N(Math.max(0,Math.min(t,m.length-1)))};function O(e){const t=C+e;t<0?g>0?F(g-1,u[g-1].frames.length-1):N(0):t>=m.length?g+1<u.length?F(g+1,0):c?(z.clear(),F(0,0)):L("completed"):N(t)}const B=()=>{var e;$&&($=!1,null==(e=null==I?void 0:I.play)||e.call(I).catch(()=>{}),D())};let U=0,j=0;function W(e){"Escape"===e.key?L("dismissed"):"ArrowRight"===e.key?O(1):"ArrowLeft"===e.key&&O(-1)}x.addEventListener("pointerdown",e=>{var t;U=Date.now(),j=e.clientX,$||($=!0,k&&(clearTimeout(k),k=null),null!==E&&(cancelAnimationFrame(E),E=null),T+=Date.now()-S,null==(t=null==I?void 0:I.pause)||t.call(I))}),x.addEventListener("pointerup",()=>{if(Date.now()-U<=220){const e=x.getBoundingClientRect();O(j-e.left<e.width/3?-1:1)}else B()}),x.addEventListener("pointercancel",B),x.addEventListener("pointerleave",B),_.addEventListener("pointerdown",e=>e.stopPropagation()),_.addEventListener("click",e=>{e.stopPropagation(),L("dismissed")}),document.addEventListener("keydown",W),w(),document.body.appendChild(f),N(i)}function de(){if("undefined"==typeof document)return;if(document.getElementById("aegis-stories-styles"))return;const e=document.createElement("style");e.id="aegis-stories-styles",e.textContent="\n @keyframes aegisStoryRing { to { transform: rotate(360deg); } }\n @keyframes aegisStoryShimmer { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }\n .aegis-in-app-stories-tray::-webkit-scrollbar { display: none; }\n ",document.head.appendChild(e)}const le=(e,t)=>{const n=Number(e);return Number.isFinite(n)?n:t},pe=(e,t="")=>"string"==typeof e?e:t,he=e=>Array.isArray(e)?e:[];function ue(e,t,n=360){const{campaign:i,trackEvent:o,addAnimationStyles:s}=e;s(),function(){if("undefined"==typeof document||document.getElementById("aegis-game-styles"))return;if("undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;const e=document.createElement("style");e.id="aegis-game-styles",e.textContent="@keyframes aegisBoxRattle{0%,100%{transform:scale(1) rotate(0)}20%{transform:scale(1.05) rotate(-4deg)}40%{transform:scale(1.05) rotate(4deg)}60%{transform:scale(1.06) rotate(-3deg)}80%{transform:scale(1.06) rotate(3deg)}}@keyframes aegisStampIn{0%{transform:scale(2.4) rotate(-20deg);opacity:0}55%{transform:scale(0.82) rotate(7deg);opacity:1}100%{transform:scale(1) rotate(-6deg);opacity:1}}@keyframes aegisBadgePop{0%{transform:scale(0) rotate(-12deg);opacity:0}70%{transform:scale(1.18) rotate(4deg);opacity:1}100%{transform:scale(1) rotate(0);opacity:1}}",document.head.appendChild(e)}();const a=function(e){return e.sanitizeColor(e.campaign.background_color||"#4169e1")}(e),r="branded"===(i.interactive_config||{}).surface_style,c=r?a:"#ffffff",d=r?"#ffffff":"#0f172a",l=document.createElement("div");l.className=t,l.setAttribute("data-campaign-id",i.id),l.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(15,23,42,0.55);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:16px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;animation:aegisFadeIn 0.25s ease;';const p=document.createElement("div");p.style.cssText=`position:relative;width:100%;max-width:${n}px;max-height:88vh;overflow-y:auto;background:${c};color:${d};border-radius:20px;padding:24px 20px 20px;box-shadow:0 16px 48px rgba(0,0,0,0.22);animation:aegisScaleIn 0.3s ease;text-align:center;`;let h=!1;const u=(e=!1)=>{h||(h=!0,e&&o(i.id,"dismissed"),l.style.animation="aegisFadeOut 0.2s ease",setTimeout(()=>l.remove(),180))},g=document.createElement("button");if(g.type="button",g.textContent="✕",g.setAttribute("aria-label","Close"),g.style.cssText=`position:absolute;top:10px;right:10px;width:30px;height:30px;border:none;border-radius:999px;background:${r?"rgba(255,255,255,0.18)":"rgba(0,0,0,0.05)"};color:${r?"#fff":"#475569"};font-size:15px;cursor:pointer;z-index:1;`,g.addEventListener("click",()=>u(!0)),p.appendChild(g),l.addEventListener("click",e=>{e.target===l&&u(!0)}),i.title){const e=document.createElement("div");e.textContent=i.title,e.style.cssText="font-family:'Inter Tight',Inter,system-ui,sans-serif;font-size:18px;font-weight:800;letter-spacing:-0.01em;margin:2px 24px 4px;line-height:1.25;",p.appendChild(e)}if(i.body){const e=document.createElement("div");e.textContent=i.body,e.style.cssText="font-size:13px;opacity:0.72;margin:0 6px 12px;line-height:1.4;",p.appendChild(e)}const m=document.createElement("div");p.appendChild(m),l.appendChild(p),document.body.appendChild(l);return{overlay:l,card:p,content:m,accent:a,branded:r,dismiss:u,ctaButton:(t,n)=>{if(!t)return null;const s=document.createElement("button");return s.type="button",s.className="aegis-cta",s.textContent=t,s.style.cssText=`margin-top:16px;width:100%;padding:12px 20px;border:none;border-radius:999px;background:${r?"#fff":a};color:${r?a:"#fff"};font-size:14px;font-weight:700;cursor:pointer;`,s.addEventListener("click",()=>{o(i.id,"clicked"),n&&n();const t=pe(i.action_url);t&&(e.navigate?e.navigate(t,"cta"):window.location.href=t)}),p.appendChild(s),s}}}function ge(e,t,n){const i=document.createElement(e);return t&&(i.style.cssText=t),null!=n&&(i.textContent=n),i}function me(e,t,n=8){const i=ge("div",`height:${n}px;border-radius:999px;background:rgba(148,163,184,0.25);overflow:hidden;margin:10px 0`);return i.appendChild(ge("div",`height:100%;width:${Math.max(0,Math.min(100,t))}%;background:${e};border-radius:999px;transition:width .5s ease`)),i}let fe=null;function xe(){try{if("undefined"==typeof window)return;const e=window.AudioContext||window.webkitAudioContext;if(!e)return;fe||(fe=new e);const t=fe;"suspended"===t.state&&t.resume();const n=t.currentTime,i=t.createOscillator(),o=t.createGain();i.type="triangle",i.frequency.setValueAtTime(190,n),i.frequency.exponentialRampToValueAtTime(68,n+.12),o.gain.setValueAtTime(1e-4,n),o.gain.exponentialRampToValueAtTime(.22,n+.006),o.gain.exponentialRampToValueAtTime(1e-4,n+.16),i.connect(o),o.connect(t.destination),i.start(n),i.stop(n+.18)}catch{}}const ye={streak:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-streak"),i=le(t.streak_count,5),o=le(t.streak_goal,i+1),s=pe(t.streak_reward_text,"Come back tomorrow to keep it going."),a=["M","T","W","T","F","S","S"];n.content.appendChild(ge("div","font-size:44px;line-height:1","🔥")),n.content.appendChild(ge("div","font-size:22px;font-weight:800;margin:4px 0 2px",`${i}-day streak!`));const r=ge("div","display:flex;justify-content:center;gap:8px;margin:12px 0");for(let d=0;d<7;d++){const e=ge("div","display:inline-flex;flex-direction:column;align-items:center;gap:3px;font-size:11px;opacity:0.8");e.appendChild(ge("span","",a[d])),e.appendChild(ge("span","font-size:16px",d<i%7||i>=7&&d<7?"✅":d===i%7?"🔥":"⚪")),r.appendChild(e)}n.content.appendChild(r);const c=ge("div","font-size:13px;opacity:0.8");c.appendChild(document.createTextNode(s+" ")),c.appendChild(ge("b","",`Day ${o}`)),c.appendChild(document.createTextNode(" unlocks a reward.")),n.content.appendChild(c),n.ctaButton(pe(t.streak_cta_text,"Keep my streak"),()=>{var t,o,s;null==(t=e.haptic)||t.call(e,20),null==(o=e.playReaction)||o.call(e,n.card,"affirm"),null==(s=e.submitResponse)||s.call(e,"streak",{streak_count:i})})},milestone:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-milestone"),i=pe(t.milestone_unit,""),o=le(t.milestone_current,1200),s=le(t.milestone_target,2e3),a=he(t.milestone_steps),r=s>0?o/s*100:0;if(n.content.appendChild(ge("div","font-size:13px;opacity:0.8;margin-bottom:2px",`${i}${o} of ${i}${s}`)),n.content.appendChild(me(n.accent,r)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${i}${Math.max(0,s-o)} to go`)),a.length){const e=ge("div","display:flex;justify-content:space-between;margin-top:6px;font-size:10px;opacity:0.7");a.forEach(t=>{const n=ge("span","display:flex;flex-direction:column;text-align:center;max-width:64px");n.appendChild(ge("span","",`${i}${le(t.value,0)}`)),n.appendChild(ge("span","",pe(t.reward))),e.appendChild(n)}),n.content.appendChild(e)}n.ctaButton(pe(t.milestone_cta_text,"Shop now"))},challenge:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-challenge"),i=he(t.challenge_tasks),o=i.filter(e=>e.done).length,s=i.length?o/i.length*100:0;pe(t.challenge_deadline_text)&&n.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:8px",pe(t.challenge_deadline_text))),i.forEach(e=>{const t=ge("div","display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid rgba(148,163,184,0.18);font-size:13px;text-align:left");t.appendChild(ge("span","",e.done?"☑":"☐")),t.appendChild(ge("span","flex:1;"+(e.done?"opacity:0.6":""),pe(e.label))),e.points&&t.appendChild(ge("span","opacity:0.7;font-size:12px",`+${le(e.points,0)}`)),n.content.appendChild(t)}),n.content.appendChild(me(n.accent,s)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${o} of ${i.length} · ${pe(t.challenge_bonus_text,"finish all to earn a bonus")}`)),n.ctaButton(pe(t.challenge_cta_text,"Continue"))},achievements:function(e){var t,n;const i=e.campaign.interactive_config||{},o=ue(e,"aegis-in-app-achievements",380),s=he(i.achievements_items),a=s.filter(e=>e.unlocked).length,r="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,c=ge("div","display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:6px 0 10px");let d=0;s.forEach(e=>{const t=ge("div",`display:flex;flex-direction:column;align-items:center;gap:4px;padding:10px 6px;border-radius:12px;background:${e.unlocked?o.accent+"1f":"rgba(148,163,184,0.12)"};${e.unlocked?"":"opacity:0.55"}`),n=ge("span","font-size:24px;display:inline-block",e.unlocked?pe(e.icon,"🏅"):"🔒");t.appendChild(n),t.appendChild(ge("span","font-size:10.5px;line-height:1.15",pe(e.label))),e.unlocked&&!r&&(n.style.animation=`aegisBadgePop 0.5s cubic-bezier(0.2,1.4,0.4,1) ${.08*d}s both`,d++),c.appendChild(t)}),o.content.appendChild(c),o.content.appendChild(ge("div","font-size:13px;font-weight:600",`${a} of ${s.length} unlocked`)),pe(i.achievements_next_text)&&o.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-top:2px",pe(i.achievements_next_text))),a>0&&!r&&(null==(t=e.haptic)||t.call(e,12),null==(n=e.playReaction)||n.call(e,o.card,"affirm")),o.ctaButton(pe(e.campaign.button_text,""))},leaderboard:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-leaderboard"),i=he(t.leaderboard_rows),o=["🥇","🥈","🥉"];pe(t.leaderboard_period_text)&&n.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:6px",pe(t.leaderboard_period_text))),i.forEach((e,t)=>{const i=ge("div",`display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:10px;${e.you?`background:${n.accent}14;font-weight:700`:""};font-size:13px;text-align:left`);i.appendChild(ge("span","width:22px",t<3?o[t]:String(t+1))),i.appendChild(ge("span","flex:1",pe(e.name)+(e.you?" (You)":""))),i.appendChild(ge("span","",le(e.score,0).toLocaleString())),n.content.appendChild(i)}),pe(t.leaderboard_gap_text)&&n.content.appendChild(ge("div","font-size:12.5px;opacity:0.8;margin-top:10px",pe(t.leaderboard_gap_text))),n.ctaButton(pe(e.campaign.button_text,""))},check_in:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-checkin",380),i=he(t.checkin_days),o=ge("div","display:flex;gap:8px;overflow-x:auto;padding:6px 2px 10px;scrollbar-width:none");i.forEach(e=>{const t="today"===e.state,i=ge("div",`flex:0 0 auto;width:60px;display:flex;flex-direction:column;align-items:center;gap:3px;padding:8px 4px;border-radius:12px;background:${t?n.accent+"1a":"rgba(148,163,184,0.12)"};border:1.5px solid ${t?n.accent:"transparent"}`);i.appendChild(ge("span","font-size:11px;opacity:0.7",pe(e.label))),i.appendChild(ge("span","font-size:18px","claimed"===e.state?"✅":t?"🎁":"🔒")),i.appendChild(ge("span","font-size:11px;font-weight:700",pe(e.reward))),o.appendChild(i)}),n.content.appendChild(o);const s=i.find(e=>"today"===e.state);n.ctaButton(pe(t.checkin_cta_text,s?`Claim ${pe(s.label)} · ${pe(s.reward)}`:"Claim"),()=>{var i,o,a;null==(i=e.haptic)||i.call(e,[0,20,15,30]),null==(o=e.playReaction)||o.call(e,n.card,"celebrate","gift.json"),null==(a=e.submitResponse)||a.call(e,"check_in",{day:pe(null==s?void 0:s.label),reset:pe(t.checkin_reset)||"daily"})})},stamp_card:function(e){var t,n,i;const o=e.campaign.interactive_config||{},s=ue(e,"aegis-in-app-stamp",380),a=le(o.stamp_total,9),r=Math.min(a,le(o.stamp_filled,1)),c="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,d=pe(o.stamp_logo_url)||pe(e.campaign.image_url),l=d?e.sanitizeUrl(d):null,p=he(o.stamp_rewards),h=new Map,u=new Map;p.length?p.forEach(e=>{"number"==typeof e.at&&e.at>=1&&e.at<=a&&(h.set(e.at,pe(e.label)||pe(e.prize_value)||"Reward"),u.set(e.at,pe(e.icon)||"🎁"))}):(h.set(a,pe(null==(t=o.stamp_reward)?void 0:t.label)||pe(o.stamp_reward_text)||"Reward"),u.set(a,"🎁"));const g="#10b981",m=Math.min(a,3),f=document.createElement("div");f.style.cssText=`display:grid;grid-template-columns:repeat(${m},1fr);gap:16px;margin:14px auto 16px;max-width:${110*m}px`;const x=[];let y=0;for(let C=0;C<a;C++){const t=C+1,n=h.has(t),i=C<r,o=document.createElement("div");if(o.title=n?`Reward: ${h.get(t)}`:"",o.style.cssText="position:relative;width:100%;aspect-ratio:1;border-radius:50%;display:flex;align-items:center;justify-content:center;overflow:visible;"+(i?`border:2.5px solid ${g};background:${g}14;${n?`box-shadow:0 0 0 3px ${g}55;`:""}`:`border:2.5px dashed ${n?g+"aa":"rgba(148,163,184,0.5)"};background:${n?g+"10":"transparent"};`),i){const t=ge("div","width:92%;height:92%;border-radius:50%;overflow:hidden;display:flex;align-items:center;justify-content:center;");if(t.appendChild(ge("span",`font-size:32px;font-weight:900;color:${g};transform:rotate(-6deg)`,"✓")),t.style.transform="rotate(-6deg) scale(1.02)",!c){const n=.1*Math.min(y,9);t.style.opacity="0",t.style.animation=`aegisStampIn 0.45s cubic-bezier(0.2,1.3,0.4,1) ${n}s both`;const i=y;window.setTimeout(()=>{var t;xe(),null==(t=e.haptic)||t.call(e,14)},1e3*n+(0===i?80:0))}l&&x.push(t),y++,o.appendChild(t)}else n&&o.appendChild(ge("span","font-size:30px",u.get(t)||"🎁"));n&&i&&o.appendChild(ge("span","position:absolute;top:-3px;right:-3px;font-size:17px;line-height:1;filter:drop-shadow(0 1px 1px rgba(0,0,0,0.25))",u.get(t)||"🎁")),f.appendChild(o)}if(s.content.appendChild(f),l&&x.length){const e=new Image;e.onload=()=>{const t=e.naturalWidth||96,n=e.naturalHeight||96,i=Math.min(1,160/Math.max(t,n)),o=Math.max(1,Math.round(t*i)),s=Math.max(1,Math.round(n*i)),a=document.createElement("canvas");a.width=o,a.height=s;const r=a.getContext("2d");if(!r)return;r.drawImage(e,0,0,o,s);let c=!1;try{c=[[0,0],[o-1,0],[0,s-1],[o-1,s-1]].some(([e,t])=>r.getImageData(e,t,1,1).data[3]<16)}catch{c=/transparent/i.test(l||"")}c&&(r.globalCompositeOperation="source-in",r.fillStyle=g,r.fillRect(0,0,o,s)),x.forEach(e=>{const t=document.createElement("canvas");t.width=o,t.height=s,t.style.cssText="width:100%;height:100%;object-fit:contain;";const n=t.getContext("2d");n&&n.drawImage(a,0,0),e.replaceChildren(t)})},e.onerror=()=>{},e.src=l}const b=[...h.keys()].filter(e=>e>r).sort((e,t)=>e-t)[0],v=b?`${b-r} more → ${h.get(b)}`:"Card complete!",w=ge("div","font-size:13px;font-weight:600;margin-top:2px");w.appendChild(me(g,r/a*100)),w.appendChild(ge("div","",`${r} of ${a}`)),w.appendChild(ge("div","font-weight:400;opacity:0.82;margin-top:1px",pe(o.stamp_reward_text)||v)),s.content.appendChild(w),s.ctaButton(pe(o.stamp_cta_text,"Order & earn"),()=>{var t;null==(t=e.haptic)||t.call(e,12)});const _=o.stamp_just_unlocked;if(_&&"object"==typeof _){const t=ge("div",`margin-top:12px;padding:11px 12px;border-radius:14px;background:${g}14;border:1.5px solid ${g}55;text-align:center`);t.appendChild(ge("div","font-size:24px",pe(_.icon)||"🎁")),t.appendChild(ge("div",`font-size:13.5px;font-weight:800;color:${g}`,`Unlocked: ${pe(_.label)||"Reward"}`)),t.appendChild(ge("div","font-size:11.5px;opacity:0.8;margin-top:1px",_.coupon_code?`Coupon ${String(_.coupon_code)} added to your account`:"Added to your account")),s.content.appendChild(t),c||(null==(n=e.haptic)||n.call(e,[0,30,20,40]),null==(i=e.playReaction)||i.call(e,s.card,"celebrate","gift.json"))}},mystery_box:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-mystery"),i=he(t.mystery_boxes),o=i.length?i:[{prize:"10% OFF"},{prize:"Free shipping"},{prize:"50 points"}];if(pe(t.mystery_subtitle)){const e=document.createElement("div");e.textContent=pe(t.mystery_subtitle),e.style.cssText="font-size:12.5px;opacity:0.75;margin-bottom:8px",n.content.appendChild(e)}const s=document.createElement("div");s.style.cssText="display:flex;gap:12px;justify-content:center;margin:8px 0 4px";let a=!1;o.forEach((t,i)=>{const o=document.createElement("button");o.type="button",o.style.cssText=`flex:1;max-width:96px;aspect-ratio:3/4;border:none;border-radius:14px;background:${n.accent}1a;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;cursor:pointer;font-size:13px;font-weight:700;color:#0f172a;transition:transform .15s`,o.appendChild(ge("span","font-size:30px","🎁")),o.appendChild(ge("span","opacity:0.7",`Box ${String.fromCharCode(65+i)}`)),o.addEventListener("click",()=>{var r,c;if(a)return;a=!0,null==(r=e.haptic)||r.call(e,12),Array.from(s.children).forEach(e=>{e!==o&&(e.style.opacity="0.4",e.style.transform="scale(0.94)")}),o.style.animation="aegisBoxRattle 0.45s ease-in-out";const d=null==(c=e.submitResponse)?void 0:c.call(e,"mystery_box",{box_index:i,prize:pe(t.prize)});window.setTimeout(()=>{(async()=>{var i,s,a,r;o.style.animation="";let c=!0,l=pe(t.prize,"You won!");try{const e=await d,t=e?e.prize:null;t&&(c=!1!==t.win,t.prize_label&&(l=String(t.prize_label)))}catch{}o.style.background=c?`${n.accent}`:"rgba(148,163,184,0.22)",o.style.color=c?"#fff":"#475569",o.style.transform="scale(1.08)",o.replaceChildren(),o.appendChild(ge("span","font-size:28px",c?"🎉":"🙈")),o.appendChild(ge("span","",c?l:"Not this time")),c?(null==(i=e.haptic)||i.call(e,[0,30,20,40]),null==(s=e.playReaction)||s.call(e,n.card,"celebrate","gift.json")):(null==(a=e.haptic)||a.call(e,15),null==(r=e.playReaction)||r.call(e,n.card,"empathize"))})()},520)}),s.appendChild(o)}),n.content.appendChild(s),n.ctaButton(pe(t.mystery_cta_text,""))},tier_ladder:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-tier"),i=he(t.tiers),o=i.length?i:[{name:"Bronze",icon:"🥉"},{name:"Silver",icon:"🥈"},{name:"Gold",icon:"🥇"}],s=Math.min(o.length-1,le(t.tier_current_index,1)),a=le(t.tier_current_points,640),r=le(t.tier_next_points,1e3),c=r>0?a/r*100:0,d=he(t.tier_perks),l=o[Math.min(o.length-1,s+1)],p=ge("div","display:flex;align-items:flex-start;justify-content:center;margin:6px 0 12px");if(o.forEach((e,t)=>{t>0&&p.appendChild(ge("span","flex:1;height:2px;background:rgba(148,163,184,0.4);margin:12px 4px 0;align-self:flex-start"));const i=ge("div","display:flex;flex-direction:column;align-items:center;gap:3px;"+(t===s?"font-weight:800":"opacity:0.6"));i.appendChild(ge("span","font-size:24px",pe(e.icon,"◆"))),i.appendChild(ge("span","font-size:11px",pe(e.name))),t===s&&i.appendChild(ge("span",`font-size:9px;color:${n.accent}`,"▲ you")),p.appendChild(i)}),n.content.appendChild(p),n.content.appendChild(me(n.accent,c)),n.content.appendChild(ge("div","font-size:13px;font-weight:600",`${Math.max(0,r-a)} pts to ${pe(null==l?void 0:l.name,"next tier")}`)),d.length){const e=ge("div","text-align:left;margin-top:10px;font-size:12.5px;opacity:0.85");e.appendChild(ge("div","",`${pe(null==l?void 0:l.name,"Next")} unlocks:`)),d.forEach(t=>e.appendChild(ge("div","",`• ${pe(t)}`))),n.content.appendChild(e)}n.ctaButton(pe(t.tier_cta_text,""))},lucky_draw:function(e){var t;const n=e.campaign.interactive_config||{},i=ue(e,"aegis-in-app-draw"),o=le(n.draw_entries,6),s=he(n.draw_actions);pe(n.draw_deadline_text)&&i.content.appendChild(ge("div","font-size:12px;opacity:0.65;margin-bottom:6px",pe(n.draw_deadline_text))),i.content.appendChild(ge("div","font-size:30px","🎟️")),i.content.appendChild(ge("div","font-size:15px;font-weight:800;margin:2px 0 10px",`${o} entries`)),i.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-bottom:4px;text-align:left","Earn more entries:")),s.forEach(e=>{const t=ge("div","display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid rgba(148,163,184,0.18);font-size:13px;text-align:left");t.appendChild(ge("span","",e.done?"✅":"☐")),t.appendChild(ge("span","flex:1;"+(e.done?"opacity:0.6":""),pe(e.label))),t.appendChild(ge("span","opacity:0.7;font-size:12px",`+${le(e.entries,1)}`)),i.content.appendChild(t)}),pe(n.draw_pool_text)&&i.content.appendChild(ge("div","font-size:12px;opacity:0.7;margin-top:8px",pe(n.draw_pool_text))),null==(t=e.submitResponse)||t.call(e,"lucky_draw",{entries:o}),i.ctaButton(pe(n.draw_cta_text,"Get more entries"),()=>{var t;null==(t=e.haptic)||t.call(e,12)})},slot_machine:function(e){const t=e.campaign.interactive_config||{},n=ue(e,"aegis-in-app-slot",400),i=he(t.slot_symbols).filter(e=>"string"==typeof e&&e),o=i.length>=3?i:["🍒","7️⃣","🍋","⭐","🔔"],s=e=>Math.floor(Math.random()*e),a=document.createElement("div");a.style.cssText="display:flex;align-items:center;justify-content:center;gap:12px;margin:12px 0 6px";const r=document.createElement("div");r.style.cssText="position:relative;display:flex;gap:8px;padding:12px;border-radius:18px;background:linear-gradient(180deg,#1f2937,#0f172a);box-shadow:inset 0 3px 10px rgba(0,0,0,0.55),0 6px 16px rgba(0,0,0,0.25)";const c=[0,1,2].map(()=>function(e,t){const n="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,i=document.createElement("div");i.style.cssText=`position:relative;width:${t}px;height:${t}px;overflow:hidden;border-radius:10px;background:linear-gradient(180deg,#ffffff,#f1f5f9);box-shadow:inset 0 6px 8px -4px rgba(0,0,0,0.35),inset 0 -6px 8px -4px rgba(0,0,0,0.35)`;const o=e.length*t,s=8*e.length,a=document.createElement("div");a.style.cssText="position:absolute;left:0;top:0;width:100%;will-change:transform";for(let l=0;l<s;l++){const n=document.createElement("div");n.style.cssText=`height:${t}px;display:flex;align-items:center;justify-content:center;font-size:${Math.round(.55*t)}px`,n.textContent=e[l%e.length],a.appendChild(n)}i.appendChild(a);let r=0,c=null;const d=()=>{a.style.transform=`translateY(${-r%o}px)`};return d(),{el:i,startSpin:()=>{if(n)return;a.style.transition="",a.style.filter="blur(1.5px)";const e=()=>{r+=34,d(),c=requestAnimationFrame(e)};c=requestAnimationFrame(e)},stop:(i,s)=>{null!==c&&(cancelAnimationFrame(c),c=null);const l=Math.max(0,e.indexOf(i))%e.length*t,p=r%o;if(n)return r=l,a.style.filter="",d(),void s();const h=p+2*o+((l-p)%o+o)%o;a.style.filter="",a.style.transition="transform 0.9s cubic-bezier(0.18,0.86,0.28,1.12)",a.style.transform=`translateY(${-h}px)`;const u=()=>{a.removeEventListener("transitionend",u),r=l,a.style.transition="",d(),s()};a.addEventListener("transitionend",u)}}}(o,68));c.forEach(e=>r.appendChild(e.el));const d=document.createElement("div");d.style.cssText="position:absolute;left:8px;right:8px;top:50%;height:68px;transform:translateY(-50%);border:2.5px solid transparent;border-radius:12px;pointer-events:none;transition:border-color 0.3s,box-shadow 0.3s",r.appendChild(d);const l=function(e,t){const n=document.createElement("div");n.style.cssText="position:relative;width:26px;height:96px;display:flex;justify-content:center;cursor:pointer;user-select:none",n.setAttribute("role","button"),n.setAttribute("aria-label","Pull the lever");const i=document.createElement("div");i.style.cssText="position:absolute;top:10px;bottom:10px;width:6px;border-radius:3px;background:linear-gradient(180deg,#64748b,#334155)";const o=document.createElement("div");return o.style.cssText=`position:absolute;top:0;width:26px;height:26px;border-radius:50%;background:radial-gradient(circle at 34% 30%,#ffffff,${e});box-shadow:0 3px 7px rgba(0,0,0,0.45);z-index:1`,n.appendChild(i),n.appendChild(o),n.addEventListener("click",t),{el:n,pull:()=>{o.style.transition="transform 0.12s ease-in",o.style.transform="translateY(60px)",window.setTimeout(()=>{o.style.transition="transform 0.5s cubic-bezier(0.2,1.5,0.4,1)",o.style.transform="translateY(0)"},130)}}}(n.accent,()=>{m()});a.appendChild(r),a.appendChild(l.el),n.content.appendChild(a);const p=document.createElement("div");p.style.cssText="font-size:13px;font-weight:700;min-height:18px;margin-top:8px",n.content.appendChild(p);let h=!1;const u=n.ctaButton(pe(t.slot_cta_text,"PULL 🎰"),()=>{}),g=u?u.cloneNode(!0):null;u&&g&&(u.replaceWith(g),g.addEventListener("click",()=>{m()}));const m=async()=>{var i,a;if(h)return;h=!0,g&&(g.disabled=!0),l.pull(),null==(i=e.haptic)||i.call(e,18),p.textContent="",d.style.borderColor="transparent",d.style.boxShadow="none",c.forEach(e=>e.startSpin());const r=[o[s(o.length)],o[s(o.length)],o[s(o.length)]],u=r[0]===r[1]&&r[1]===r[2],m=null==(a=e.submitResponse)?void 0:a.call(e,"slot_machine",{win:u,symbols:r});let f=null;try{const e=await Promise.race([m??Promise.resolve(null),new Promise(e=>window.setTimeout(()=>e(null),1400))]);f=e?e.prize:null}catch{}const x=f?!1!==f.win:u,y=f&&f.prize_label?String(f.prize_label):pe(t.slot_win_text,"You win!");let b;if(f)if(x){const e=o[s(o.length)];b=[e,e,e]}else b=[o[s(o.length)],o[s(o.length)],o[s(o.length)]],b[0]===b[1]&&b[1]===b[2]&&(b[2]=o[(o.indexOf(b[2])+1)%o.length]);else b=r;const v=t=>{c[t].stop(b[t],()=>{var i;null==(i=e.haptic)||i.call(e,10),t<c.length-1?window.setTimeout(()=>v(t+1),t===c.length-2?560:320):(()=>{var t,i,o,s;p.textContent=x?`🎉 ${y}`:"So close — try again next time!",p.style.color=x?n.accent:"#94a3b8",x?(d.style.borderColor=n.accent,d.style.boxShadow=`0 0 14px ${n.accent}aa, inset 0 0 14px ${n.accent}55`,null==(t=e.haptic)||t.call(e,[0,30,20,40]),null==(i=e.playReaction)||i.call(e,n.card,"celebrate")):(null==(o=e.haptic)||o.call(e,15),null==(s=e.playReaction)||s.call(e,n.card,"empathize")),e.trackEvent(e.campaign.id,"clicked",{stepId:x?"win":"lose"}),h=!1})()})};window.setTimeout(()=>v(0),620)}}},be=Object.keys(ye);const ve={"16:9":"16 / 9","9:16":"9 / 16","1:1":"1 / 1","4:5":"4 / 5"};function we(e,t,n,i){var o;const{campaign:s,sanitizeUrl:a}=e,r=a((s.interactive_config||{}).video_url||s.video_url||""),c=s.image_url?a(s.image_url):null,d=document.createElement("div");if(d.style.cssText=`position:relative;width:100%;aspect-ratio:${ve[t]||ve["16:9"]};background:#0b1220;border-radius:14px;overflow:hidden;`,r){const t=document.createElement("video");t.src=r,t.muted=!0,t.loop=i,t.autoplay=n,t.playsInline=!0,t.setAttribute("playsinline",""),c&&(t.poster=c),t.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;",d.appendChild(t),n&&(null==(o=t.play)||o.call(t).catch(()=>{}));let s=!1;const a=()=>{var n;!s&&t.duration&&isFinite(t.duration)&&t.currentTime/t.duration>=.9&&(s=!0,null==(n=e.submitResponse)||n.call(e,"video_complete",{duration_s:Math.round(t.duration)}))};t.addEventListener("timeupdate",a),t.addEventListener("ended",()=>{var n;s||(s=!0,null==(n=e.submitResponse)||n.call(e,"video_complete",{duration_s:Math.round(t.duration||0)}))});const l=document.createElement("button");l.type="button",l.textContent="🔇",l.setAttribute("aria-label","Unmute"),l.style.cssText="position:absolute;bottom:10px;right:10px;z-index:2;width:34px;height:34px;border:none;border-radius:999px;background:rgba(0,0,0,0.45);color:#fff;font-size:14px;cursor:pointer;",l.addEventListener("click",e=>{var n;e.stopPropagation(),t.muted=!t.muted,l.textContent=t.muted?"🔇":"🔊",t.muted||null==(n=t.play)||n.call(t).catch(()=>{})}),d.appendChild(l)}else if(c){const e=document.createElement("img");e.src=c,e.alt="",e.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;",d.appendChild(e)}else d.style.background="linear-gradient(160deg,#1f2937,#0f172a)";return d}function _e(e,t,n){const{campaign:i}=e;if(!(i.title||i.body||i.button_text||i.action_url))return null;const o=document.createElement("div");if(o.style.cssText=n?"position:absolute;left:0;right:0;bottom:0;z-index:2;padding:18px 16px 16px;color:#fff;text-align:left;background:linear-gradient(to top,rgba(0,0,0,0.72),rgba(0,0,0,0) 80%);":"padding:14px 4px 2px;text-align:left;color:#0f172a;",i.title){const e=document.createElement("div");e.textContent=i.title,e.style.cssText="font-family:'Inter Tight',Inter,system-ui,sans-serif;font-size:17px;font-weight:800;letter-spacing:-0.01em;line-height:1.2;"+(n?"text-shadow:0 1px 8px rgba(0,0,0,0.4);":""),o.appendChild(e)}if(i.body){const e=document.createElement("div");e.textContent=i.body,e.style.cssText="font-size:13px;line-height:1.45;margin-top:3px;"+(n?"opacity:0.92;text-shadow:0 1px 6px rgba(0,0,0,0.4);":"opacity:0.7;"),o.appendChild(e)}const s=i.button_text||(i.action_url?"Watch now":"");if(s){const a=document.createElement("button");a.type="button",a.className="aegis-cta",a.textContent=s,a.style.cssText=`margin-top:12px;padding:10px 22px;border:none;border-radius:999px;background:${n?"#fff":t};color:${n?"#0f172a":"#fff"};font-size:13px;font-weight:700;cursor:pointer;`,a.addEventListener("click",t=>{t.stopPropagation(),e.trackEvent(i.id,"clicked");const n=i.action_url||"";n&&(e.navigate?e.navigate(n,"cta"):window.location.href=n)}),o.appendChild(a)}return o}function Ce(e){const t=e.campaign.interactive_config||{};return{accent:e.sanitizeColor(e.campaign.background_color||"#4169e1"),aspect:t.video_aspect||"16:9",overlayCaption:"below"!==t.video_caption,autoplay:!1!==t.video_autoplay,loop:!1!==t.video_loop}}function ke(e){const{campaign:t,trackEvent:n,addAnimationStyles:i}=e;i();const o=Ce(e),s=document.createElement("div");s.className="aegis-in-app-video-overlay",s.setAttribute("data-campaign-id",t.id),s.style.cssText='position:fixed;inset:0;z-index:100000;background:rgba(15,23,42,0.6);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;padding:16px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;animation:aegisFadeIn 0.25s ease;';const a=document.createElement("div");a.style.cssText=`position:relative;width:100%;max-width:${"9:16"===o.aspect?320:460}px;background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 16px 48px rgba(0,0,0,0.28);animation:aegisScaleIn 0.3s ease;`;const r=we(e,o.aspect,o.autoplay,o.loop);if(o.overlayCaption){const t=_e(e,o.accent,!0);t&&r.appendChild(t)}if(a.appendChild(r),!o.overlayCaption){const t=_e(e,o.accent,!1);t&&(t.style.padding="14px 16px 16px",a.appendChild(t))}const c=document.createElement("button");c.type="button",c.textContent="✕",c.setAttribute("aria-label","Close"),c.style.cssText="position:absolute;top:10px;left:10px;z-index:3;width:32px;height:32px;border:none;border-radius:999px;background:rgba(0,0,0,0.4);color:#fff;font-size:15px;cursor:pointer;",c.addEventListener("click",()=>{n(t.id,"dismissed"),s.remove()}),a.appendChild(c),s.addEventListener("click",e=>{e.target===s&&(n(t.id,"dismissed"),s.remove())}),s.appendChild(a),document.body.appendChild(s)}const Ee=/^#[0-9a-fA-F]{3,8}$/;const Se={none:"0",lg:"12px",xl:"16px","2xl":"20px"},Te={"16:9":"16 / 9","4:3":"4 / 3","21:9":"21 / 9"};function $e(e){return e.headline??e.title??""}function Ie(e){return e.subhead??e.body??""}function ze(e){return e.cta_label??e.cta_text??""}function Ae(e){if(e.cta_url)return e.cta_url;const t=e.cta_target;return t&&t.value?"category"===t.type?`?category=${encodeURIComponent(t.value)}`:t.value:""}function Me(e,t){const{campaign:n,sanitizeUrl:i,trackEvent:o}=e,s=n.interactive_config||{},a=Array.isArray(s.cards)?s.cards:[];if(0===a.length)return!1;const r=s.chrome||{},c=(d=r.accent&&"brand"!==r.accent?r.accent:n.background_color,l="#4169e1",d&&Ee.test(d)?d:l);var d,l;const p=Se[r.radius??"2xl"]??Se["2xl"];if("announcement_bar"===(r.variant??"hero_fullbleed")){const s=a[0],r=document.createElement("div");r.style.cssText=`display:flex;align-items:center;justify-content:center;gap:10px;background:${c};color:#fff;padding:8px 14px;font:600 13px/1.3 Inter,system-ui,sans-serif;text-align:center;`,r.textContent=[$e(s),Ie(s)].filter(Boolean).join(" · ");const d=i(Ae(s));if(d&&ze(s)){const t=document.createElement("span");t.style.cssText="text-decoration:underline;cursor:pointer;white-space:nowrap;",t.textContent=ze(s),t.addEventListener("click",()=>{var t;o(n.id,"clicked"),null==(t=e.navigate)||t.call(e,d)}),r.appendChild(t)}return t.appendChild(r),o(n.id,"impression"),!0}const h=document.createElement("div");h.style.cssText=`position:relative;width:100%;overflow:hidden;border-radius:${p};box-shadow:0 1px 2px rgba(16,24,40,0.06);${r.aspect_ratio&&Te[r.aspect_ratio]?`aspect-ratio:${Te[r.aspect_ratio]};`:"min-height:300px;"}`,h.setAttribute("data-campaign-id",n.id);const u=document.createElement("div");u.style.cssText="display:flex;height:100%;width:100%;transition:transform 0.5s ease;",h.appendChild(u);const g="none"===r.overlay?"":"full-scrim"===r.overlay?"background:linear-gradient(0deg,rgba(0,0,0,0.55),rgba(0,0,0,0.25));":"background:linear-gradient(to top right,rgba(0,0,0,0.7),rgba(0,0,0,0.25) 45%,transparent);",m="center"===r.text_position?"center":"flex-end",f="bottom-left"!==r.text_position&&r.text_position?"center":"flex-start";a.forEach((t,s)=>{const a=document.createElement("div");a.style.cssText="position:relative;flex:0 0 100%;width:100%;height:100%;min-height:inherit;background:#f1f5f9;";const d=i(t.video_url??""),l=!!d||"video"===t.media_type,p=l?d||i(t.media_url??""):i(t.image_url??t.media_url??"");if(p)if(l){const e=document.createElement("video");e.src=p,e.autoplay=!0,e.muted=!0,e.loop=!0,e.playsInline=!0,e.style.cssText="position:absolute;inset:0;width:100%;height:100%;object-fit:cover;",a.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`position:absolute;inset:0;background:url("${p}") center/cover no-repeat;`,a.appendChild(e)}if(g){const e=document.createElement("div");e.style.cssText=`position:absolute;inset:0;${g}`,a.appendChild(e)}const h=document.createElement("div");h.style.cssText=`position:absolute;inset:0;display:flex;flex-direction:column;justify-content:${m};align-items:${f};gap:6px;padding:24px;text-align:${"center"===f?"center":"left"};`;const x=$e(t);if(x){const e=document.createElement("h2");e.textContent=x,e.style.cssText="margin:0;color:#fff;font:800 24px/1.2 Inter Tight,Inter,system-ui,sans-serif;letter-spacing:-0.02em;text-shadow:0 1px 8px rgba(0,0,0,0.35);max-width:90%;",h.appendChild(e)}const y=Ie(t);if(y){const e=document.createElement("p");e.textContent=y,e.style.cssText="margin:0;color:rgba(255,255,255,0.92);font:500 14px/1.4 Inter,system-ui,sans-serif;text-shadow:0 1px 6px rgba(0,0,0,0.3);max-width:90%;",h.appendChild(e)}const b=ze(t),v=i(Ae(t));if(b&&"none"!==r.cta_style){const t=document.createElement("button");t.textContent=b,t.style.cssText="underline"===r.cta_style?"margin-top:6px;background:none;border:none;color:#fff;font:700 14px Inter,system-ui,sans-serif;text-decoration:underline;cursor:pointer;padding:0;":`margin-top:8px;background:${c};color:#fff;border:none;border-radius:999px;padding:9px 18px;font:700 13px Inter,system-ui,sans-serif;cursor:pointer;box-shadow:0 4px 12px rgba(0,0,0,0.2);`,t.addEventListener("click",()=>{var t;o(n.id,"clicked",{stepId:`card_${s}`}),v&&(null==(t=e.navigate)||t.call(e,v))}),h.appendChild(t)}a.appendChild(h),u.appendChild(a)});const x=[];let y=0;const b=e=>{y=(e%a.length+a.length)%a.length,u.style.transform=`translateX(-${100*y}%)`,x.forEach((e,t)=>{e.style.width=t===y?"18px":"6px",e.style.background=t===y?c:"rgba(255,255,255,0.7)"})},v=document.createElement("div");if(v.style.cssText="position:absolute;bottom:8px;left:50%;transform:translateX(-50%);display:flex;gap:6px;z-index:2;",a.length>1&&(a.forEach((e,t)=>{const n=document.createElement("span");n.style.cssText="width:6px;height:6px;border-radius:999px;background:rgba(255,255,255,0.7);transition:all 0.25s;cursor:pointer;",n.addEventListener("click",()=>b(t)),x.push(n),v.appendChild(n)}),h.appendChild(v)),t.appendChild(h),b(0),a.length>1&&!1!==r.loop){const e="number"==typeof r.autoplay_ms&&r.autoplay_ms>=1500?r.autoplay_ms:4e3;let t=window.setInterval(()=>b(y+1),e);h.addEventListener("mouseenter",()=>window.clearInterval(t)),h.addEventListener("mouseleave",()=>{t=window.setInterval(()=>b(y+1),e)})}return o(n.id,"impression"),!0}const Le="aegis-chat-styles";let Re=null;class Pe{constructor(e){this.sessionResumed=!1,this.open=!1,this.initialized=!1,this.unread=0,this.renderedIds=new Set,this.pendingEcho=[],this.hasInteracted=!1,this.writeKey=e.writeKey,this.apiHost=(e.apiHost??"").replace(/\/$/,""),this.contactId=e.contactId,this.channel=e.channel??"web",this.debugMode=e.debugMode??!1,this.title=e.title??"Shopping Assistant",this.greeting=e.greeting??"Hi! 👋 How can I help you today?",this.accent=e.accentColor??"#4169e1",this.icon=e.icon??"sparkle",this.logoUrl=e.logoUrl,this.position=e.position??"bottom-right",this.displayMode=e.displayMode??"bubble",this.agentPersona=e.agentPersona,this.quickReplies=e.quickReplies,this.onSessionStart=e.onSessionStart,this.onSessionEnd=e.onSessionEnd,this.onMessageSent=e.onMessageSent,this.anonymousId=this.readAnonId(),this.contactId=this.contactId??this.readStoredContactId()}initialize(){this.initialized||"undefined"==typeof document||(this.initialized=!0,this.injectStyles(),this.mount(),Re=this,"nav"!==this.displayMode&&this.scheduleAttention())}updateContactId(e){e&&e!==this.contactId&&(this.contactId=e)}openPanel(e){var t,n,i,o;if(this.panel||this.initialize(),!this.open){this.open=!0,this.hasInteracted=!0;try{null==(t=this.onSessionStart)||t.call(this)}catch{}this.dismissAttention(),null==(n=this.panel)||n.classList.add("aegis-chat-panel--open"),null==(i=this.bubble)||i.classList.add("aegis-chat-bubble--hidden"),this.clearUnread(),e&&this.input&&(this.input.value=e),this.resumeSession(),this.startPolling(),null==(o=this.input)||o.focus()}}closePanel(){var e,t,n;const i=this.open;if(this.open=!1,null==(e=this.panel)||e.classList.remove("aegis-chat-panel--open"),null==(t=this.bubble)||t.classList.remove("aegis-chat-bubble--hidden"),this.disconnectSSE(),this.stopPolling(),i)try{null==(n=this.onSessionEnd)||n.call(this)}catch{}}destroy(){var e;this.disconnectSSE(),this.stopPolling(),null==(e=this.root)||e.remove(),this.initialized=!1,Re===this&&(Re=null)}async send(e,t){var n;const i=e.trim();if(!i&&!t)return;const o=i||(t?"image"===t.type?"Sent a photo 📷":"Sent a file 📎":"");this.appendBubble({id:`local_${Date.now()}`,sender:"customer",role:"user",content:o,media_url:(null==t?void 0:t.url)??null,media_type:(null==t?void 0:t.type)??null}),this.pendingEcho.push(o),this.input&&(this.input.value="",this.input.style.height="auto"),this.showTyping();try{const e=await fetch(`${this.apiHost}/v1/chat/message`,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify({message_text:o,channel:this.channel,anonymous_id:this.anonymousId,contact_id:this.contactId,media_url:null==t?void 0:t.url,media_type:null==t?void 0:t.type,agent_persona:this.agentPersona}),keepalive:!0});if(!e.ok)return this.log("send failed",e.status),void this.appendSystem("Sorry — your message could not be delivered. Please try again.");const i=await e.json();try{null==(n=this.onMessageSent)||n.call(this)}catch{}this.contactId=i.contact_id,this.persistContactId(i.contact_id),this.sseTicket=i.sse_ticket,this.connectSSE(i.sse_ticket),this.refreshHistory()}catch(s){this.log("send error",s),this.appendSystem("Sorry — your message could not be delivered. Please try again.")}}async handleFile(e){var t;if(new Set(["image/jpeg","image/png","image/gif","image/webp","application/pdf"]).has(e.type))if(e.size>8388608)this.appendSystem("That file is too large (max 8 MB).");else try{const n=await this.fileToBase64(e),i=await fetch(`${this.apiHost}/v1/chat/upload`,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify({data:n,content_type:e.type,filename:e.name})});if(!i.ok)return this.log("upload failed",i.status),void this.appendSystem("Sorry — that attachment couldn’t be uploaded.");const o=await i.json();await this.send((null==(t=this.input)?void 0:t.value)??"",{url:o.media_url,type:o.media_type})}catch(n){this.log("upload error",n),this.appendSystem("Sorry — that attachment couldn’t be uploaded.")}else this.appendSystem("That file type isn’t supported (images or PDF only).")}fileToBase64(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>{const e=String(i.result||""),n=e.indexOf(",");t(n>=0?e.slice(n+1):e)},i.onerror=()=>n(i.error),i.readAsDataURL(e)})}connectSSE(e){if(!this.open)return;if("undefined"==typeof EventSource||!this.contactId)return;if(!e)return;this.disconnectSSE();const t=new URL("/v1/stream/realtime",this.apiHost||window.location.origin);t.searchParams.set("ticket",e),t.searchParams.set("mode","ephemeral");try{this.eventSource=new EventSource(t.toString()),this.eventSource.onopen=()=>{this.stopPolling(),this.log("SSE connected")},this.eventSource.addEventListener("chat.message",()=>{this.refreshHistory()}),this.eventSource.onerror=()=>{this.startPolling()}}catch(n){this.log("SSE connect failed",n),this.startPolling()}}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}startPolling(){this.open&&(this.pollTimer||(this.pollTimer=setInterval(()=>{this.refreshHistory()},5e3)))}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0)}async refreshHistory(){if(this.contactId&&this.sseTicket)try{const e=new URL("/v1/chat/history",this.apiHost||window.location.origin);e.searchParams.set("contact_id",this.contactId),e.searchParams.set("ticket",this.sseTicket),e.searchParams.set("channel",this.channel),e.searchParams.set("limit","50");const t=await fetch(e.toString(),{method:"GET",headers:{"X-Aegis-Write-Key":this.writeKey}});if(!t.ok)return;const n=await t.json();let i=!1;for(const o of n.messages||[])if(!this.renderedIds.has(o.id)){if("customer"===o.sender){const e=this.pendingEcho.indexOf(o.content||"");if(-1!==e){this.pendingEcho.splice(e,1),o.id&&this.renderedIds.add(o.id);continue}}"assistant"===o.sender&&this.hideTyping(),this.appendBubble(o),i=!0,"assistant"!==o.sender||this.open||this.bumpUnread()}i&&this.scrollToBottom()}catch(e){this.log("history fetch error",e)}}bubbleIconHtml(){if("chat"===this.icon)return'<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';if("logo"===this.icon&&this.logoUrl&&/^https?:\/\//i.test(this.logoUrl)){return`<img class="aegis-chat-bubble-logo" src="${this.logoUrl.replace(/"/g,""")}" alt="" />`}return'<svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2.3l1.85 5.0 5.0 1.85-5.0 1.85L12 16l-1.85-5.0L5.15 9.15l5.0-1.85L12 2.3z"/><path d="M18.7 14.3l.78 2.1 2.1.78-2.1.78-.78 2.1-.78-2.1-2.1-.78 2.1-.78.78-2.1z" opacity="0.85"/></svg>'}mount(){const e=document.createElement("div");e.className=`aegis-chat-root aegis-chat-root--${this.position}`,e.style.setProperty("--aegis-chat-accent",this.accent);const t=document.createElement("button");t.className="aegis-chat-bubble",t.setAttribute("aria-label",`Open ${this.title}`),t.innerHTML=this.bubbleIconHtml();const n=document.createElement("span");n.className="aegis-chat-badge",n.style.display="none",t.appendChild(n),t.addEventListener("click",()=>this.openPanel());const i=document.createElement("div");i.className="aegis-chat-panel",i.setAttribute("role","dialog"),i.setAttribute("aria-label",this.title);const o=document.createElement("div");o.className="aegis-chat-header";const s=document.createElement("span");s.className="aegis-chat-title",s.textContent=this.title;const a=document.createElement("button");a.className="aegis-chat-close",a.setAttribute("aria-label","Close chat"),a.textContent="✕",a.addEventListener("click",()=>this.closePanel()),o.appendChild(s),o.appendChild(a);const r=document.createElement("div");r.className="aegis-chat-thread";const c=document.createElement("form");c.className="aegis-chat-composer";const d=document.createElement("textarea");d.className="aegis-chat-input",d.rows=1,d.placeholder="Type a message…",d.addEventListener("keydown",e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.send(d.value))});const l=document.createElement("input");l.type="file",l.accept="image/*,application/pdf",l.className="aegis-chat-fileinput",l.addEventListener("change",()=>{const e=l.files&&l.files[0];e&&this.handleFile(e),l.value=""});const p=document.createElement("button");p.type="button",p.className="aegis-chat-attach",p.setAttribute("aria-label","Attach a file"),p.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',p.addEventListener("click",()=>l.click());const h=document.createElement("button");h.type="submit",h.className="aegis-chat-send",h.setAttribute("aria-label","Send message"),h.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>',c.addEventListener("submit",e=>{e.preventDefault(),this.send(d.value)}),c.appendChild(p),c.appendChild(d),c.appendChild(h),c.appendChild(l),i.appendChild(o),i.appendChild(r),i.appendChild(c);const u=document.createElement("div");u.className="aegis-chat-tip";const g=document.createElement("span");g.textContent=this.greeting||"Need help finding something? Ask me 👋";const m=document.createElement("button");m.className="aegis-chat-tip-close",m.setAttribute("aria-label","Dismiss"),m.textContent="✕",m.addEventListener("click",e=>{e.stopPropagation(),this.dismissAttention()}),u.appendChild(g),u.appendChild(m),u.addEventListener("click",()=>this.openPanel()),e.appendChild(i),"nav"!==this.displayMode&&(e.appendChild(u),e.appendChild(t)),document.body.appendChild(e),this.greetingTip=u,this.root=e,this.bubble=t,this.badge=n,this.panel=i,this.thread=r,this.input=d,this.appendSystemGreeting(this.greeting),this.renderQuickReplies()}renderQuickReplies(){var e;if(!this.thread||!(null==(e=this.quickReplies)?void 0:e.length))return;const t=document.createElement("div");t.className="aegis-chat-quickreplies";for(const n of this.quickReplies){if("string"!=typeof n||!n.trim())continue;const e=document.createElement("button");e.type="button",e.className="aegis-chat-chip",e.textContent=n,e.addEventListener("click",()=>{t.remove(),this.send(n)}),t.appendChild(e)}t.childElementCount>0&&this.thread.appendChild(t)}appendBubble(e){if(!this.thread)return;e.id&&this.renderedIds.add(e.id);const t=document.createElement("div");if(t.className=`aegis-chat-msg aegis-chat-msg--${e.sender}`,e.media_url)if("image"===e.media_type){const n=document.createElement("img");n.className="aegis-chat-media-img",n.src=e.media_url,n.alt="attachment",n.loading="lazy";const i=e.media_url;n.addEventListener("click",()=>window.open(i,"_blank","noopener")),t.appendChild(n)}else{const n=document.createElement("a");n.className="aegis-chat-media-file",n.href=e.media_url,n.target="_blank",n.rel="noopener noreferrer",n.textContent="📎 Attachment",t.appendChild(n)}if(e.content){const n=document.createElement("div");n.className="aegis-chat-bubbletext",n.textContent=e.content,t.appendChild(n)}if(e.interactive&&Array.isArray(e.interactive))for(const n of e.interactive){const e=this.renderInteractive(n);e&&t.appendChild(e)}this.thread.appendChild(t),this.scrollToBottom()}renderInteractive(e){if("product_carousel"!==(null==e?void 0:e.type))return null;const t=e.products||[];if(!t.length)return null;const n=document.createElement("div");n.className="aegis-chat-carousel";for(const i of t){const e=document.createElement("a");e.className="aegis-chat-card";const t=i.cta_url||"#";if(e.href=t,e.target="_blank",e.rel="noopener noreferrer",i.image_url){const t=document.createElement("img");t.className="aegis-chat-card-img",t.src=i.image_url,t.alt=i.name||"",t.loading="lazy",e.appendChild(t)}const o=document.createElement("div");if(o.className="aegis-chat-card-name",o.textContent=i.name||"",e.appendChild(o),null!=i.price){const t=document.createElement("div");t.className="aegis-chat-card-price",t.textContent=(i.price,String(i.price)),e.appendChild(t)}n.appendChild(e)}if("string"==typeof e.browse_all_url&&e.browse_all_url){const t=document.createElement("a");t.className="aegis-chat-card aegis-chat-card--more",t.href=e.browse_all_url,t.target="_blank",t.rel="noopener noreferrer",t.textContent="View all →",n.appendChild(t)}return n}appendSystem(e){this.appendBubble({id:`sys_${Date.now()}`,sender:"system",role:"system",content:e})}appendSystemGreeting(e){this.appendBubble({id:`greeting_${Date.now()}`,sender:"assistant",role:"bot",content:e})}bumpUnread(){this.unread+=1,this.badge&&(this.badge.textContent=String(this.unread),this.badge.style.display="flex")}clearUnread(){this.unread=0,this.badge&&(this.badge.style.display="none")}scrollToBottom(){this.thread&&(this.thread.scrollTop=this.thread.scrollHeight)}readAnonId(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}readStoredContactId(){if("undefined"!=typeof document)try{return(new l).get("aegis_chat_cid")??void 0}catch{return}}persistContactId(e){if(e&&"undefined"!=typeof document)try{(new l).set("aegis_chat_cid",e,365)}catch{}}async resumeSession(){if(this.sseTicket)this.refreshHistory();else if(!this.sessionResumed&&(this.sessionResumed=!0,this.contactId||this.anonymousId))try{const e=await fetch(`${this.apiHost}/v1/chat/session`,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify({anonymous_id:this.anonymousId,contact_id:this.contactId,channel:this.channel})});if(!e.ok)return;const t=await e.json();if(!t.contact_id||!t.sse_ticket)return;this.contactId=t.contact_id,this.sseTicket=t.sse_ticket,this.persistContactId(t.contact_id),await this.refreshHistory(),this.open&&this.connectSSE(t.sse_ticket)}catch(e){this.log("resume session failed",e)}}showTyping(){if(!this.thread||this.typingEl)return;const e=document.createElement("div");e.className="aegis-chat-msg aegis-chat-msg--assistant aegis-chat-typing",e.innerHTML='<div class="aegis-chat-bubbletext aegis-chat-typingdots"><span></span><span></span><span></span></div>',this.thread.appendChild(e),this.typingEl=e,this.scrollToBottom()}hideTyping(){this.typingEl&&(this.typingEl.remove(),this.typingEl=void 0)}scheduleAttention(){"undefined"!=typeof window&&(this.attentionTimer=setTimeout(()=>{var e,t;this.hasInteracted||this.open||(null==(e=this.bubble)||e.classList.add("aegis-chat-bubble--pulse"),null==(t=this.greetingTip)||t.classList.add("aegis-chat-tip--show"))},4500))}dismissAttention(){var e,t;this.attentionTimer&&(clearTimeout(this.attentionTimer),this.attentionTimer=void 0),null==(e=this.bubble)||e.classList.remove("aegis-chat-bubble--pulse"),null==(t=this.greetingTip)||t.classList.remove("aegis-chat-tip--show")}log(...e){this.debugMode&&console.log("[AegisChat]",...e)}injectStyles(){if("undefined"==typeof document||document.getElementById(Le))return;const e=document.createElement("style");e.id=Le,e.textContent=De,document.head.appendChild(e)}}const De='\n.aegis-chat-root{position:fixed;bottom:20px;right:20px;z-index:2147483000;font-family:Inter,system-ui,-apple-system,sans-serif}\n.aegis-chat-root--bottom-left{left:20px;right:auto}\n.aegis-chat-root--bottom-left .aegis-chat-panel{left:0;right:auto}\n.aegis-chat-bubble-logo{width:34px;height:34px;border-radius:9999px;object-fit:cover}\n.aegis-chat-bubble{width:60px;height:60px;border-radius:9999px;border:none;background:var(--aegis-chat-accent,#4169e1);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 8px 24px rgba(0,0,0,.18);transition:transform .18s ease,box-shadow .18s ease;position:relative;animation:aegis-chat-in .4s cubic-bezier(.16,1,.3,1)}\n.aegis-chat-bubble:hover{transform:translateY(-2px) scale(1.04);box-shadow:0 12px 28px rgba(0,0,0,.22)}\n.aegis-chat-bubble--hidden{display:none}\n/* Attention pulse — an expanding accent ring that draws the eye to a live, ready assistant. */\n.aegis-chat-bubble--pulse::before{content:"";position:absolute;inset:0;border-radius:9999px;background:var(--aegis-chat-accent,#4169e1);z-index:-1;animation:aegis-chat-pulse 1.8s ease-out infinite}\n.aegis-chat-bubble--pulse{animation:aegis-chat-in .4s cubic-bezier(.16,1,.3,1),aegis-chat-nudge 1.8s ease-in-out 2}\n@keyframes aegis-chat-in{from{opacity:0;transform:scale(.6)}to{opacity:1;transform:scale(1)}}\n@keyframes aegis-chat-pulse{0%{transform:scale(1);opacity:.55}100%{transform:scale(1.9);opacity:0}}\n@keyframes aegis-chat-nudge{0%,100%{transform:translateY(0)}25%{transform:translateY(-5px)}50%{transform:translateY(0)}}\n/* One-time greeting tooltip */\n.aegis-chat-tip{position:absolute;bottom:14px;right:74px;max-width:230px;background:#fff;color:#0f172a;border:1px solid #e2e8f0;border-radius:14px;border-bottom-right-radius:4px;box-shadow:0 10px 30px rgba(0,0,0,.16);padding:10px 30px 10px 13px;font-size:13.5px;line-height:1.4;cursor:pointer;opacity:0;transform:translateX(8px) scale(.92);transform-origin:bottom right;pointer-events:none;transition:opacity .25s ease,transform .25s ease}\n.aegis-chat-tip--show{opacity:1;transform:translateX(0) scale(1);pointer-events:auto}\n.aegis-chat-tip-close{position:absolute;top:5px;right:6px;width:18px;height:18px;border:none;background:transparent;color:#94a3b8;font-size:12px;line-height:1;cursor:pointer;border-radius:9999px}\n.aegis-chat-tip-close:hover{background:#f1f5f9;color:#475569}\n@media (prefers-reduced-motion:reduce){.aegis-chat-bubble,.aegis-chat-bubble--pulse{animation:none}.aegis-chat-bubble--pulse::before{animation:none;display:none}}\n.aegis-chat-badge{position:absolute;top:-2px;right:-2px;min-width:20px;height:20px;padding:0 5px;border-radius:9999px;background:#ef4444;color:#fff;font-size:12px;font-weight:600;display:flex;align-items:center;justify-content:center}\n.aegis-chat-panel{position:absolute;bottom:0;right:0;width:380px;max-width:calc(100vw - 32px);height:560px;max-height:calc(100vh - 48px);background:#fff;border-radius:16px;box-shadow:0 16px 48px rgba(0,0,0,.24);display:none;flex-direction:column;overflow:hidden}\n.aegis-chat-panel--open{display:flex}\n.aegis-chat-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;background:var(--aegis-chat-accent,#4169e1);color:#fff}\n.aegis-chat-title{font-weight:600;font-size:15px}\n.aegis-chat-close{background:transparent;border:none;color:#fff;font-size:16px;cursor:pointer;opacity:.85}\n.aegis-chat-close:hover{opacity:1}\n.aegis-chat-thread{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:10px;background:#f8fafc}\n.aegis-chat-msg{display:flex;flex-direction:column;max-width:85%}\n.aegis-chat-msg--customer{align-self:flex-end;align-items:flex-end}\n.aegis-chat-msg--assistant,.aegis-chat-msg--system{align-self:flex-start;align-items:flex-start}\n.aegis-chat-bubbletext{padding:9px 13px;border-radius:14px;font-size:14px;line-height:1.45;white-space:pre-wrap;word-break:break-word}\n.aegis-chat-msg--customer .aegis-chat-bubbletext{background:var(--aegis-chat-accent,#4169e1);color:#fff;border-bottom-right-radius:4px}\n.aegis-chat-msg--assistant .aegis-chat-bubbletext{background:#fff;color:#0f172a;border:1px solid #e2e8f0;border-bottom-left-radius:4px}\n.aegis-chat-quickreplies{display:flex;flex-wrap:wrap;gap:6px;padding:2px 4px 6px;justify-content:flex-start}\n.aegis-chat-chip{appearance:none;cursor:pointer;border:1px solid var(--aegis-chat-accent,#4169e1);background:#fff;color:var(--aegis-chat-accent,#4169e1);border-radius:9999px;padding:6px 12px;font-size:13px;line-height:1;font-family:inherit;transition:background .15s,color .15s}\n.aegis-chat-chip:hover{background:var(--aegis-chat-accent,#4169e1);color:#fff}\n.aegis-chat-msg--system .aegis-chat-bubbletext{background:#fef3c7;color:#92400e;font-size:13px}\n.aegis-chat-typingdots{display:flex;gap:4px;align-items:center;padding:12px 14px}\n.aegis-chat-typingdots span{width:7px;height:7px;border-radius:9999px;background:#94a3b8;display:inline-block;animation:aegis-chat-typing 1.2s infinite ease-in-out}\n.aegis-chat-typingdots span:nth-child(2){animation-delay:.18s}\n.aegis-chat-typingdots span:nth-child(3){animation-delay:.36s}\n@keyframes aegis-chat-typing{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}}\n.aegis-chat-carousel{display:flex;gap:10px;overflow-x:auto;padding:8px 0;max-width:320px;scroll-snap-type:x mandatory}\n.aegis-chat-card{flex:0 0 140px;scroll-snap-align:start;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:8px;text-decoration:none;color:#0f172a;display:flex;flex-direction:column;gap:4px;transition:box-shadow .15s ease}\n.aegis-chat-card:hover{box-shadow:0 6px 16px rgba(0,0,0,.1)}\n.aegis-chat-card-img{width:100%;height:96px;object-fit:cover;border-radius:8px}\n.aegis-chat-card-name{font-size:13px;font-weight:500;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}\n.aegis-chat-card-price{font-size:13px;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-card--more{align-items:center;justify-content:center;font-weight:600;color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-composer{display:flex;align-items:flex-end;gap:8px;padding:12px;border-top:1px solid #e2e8f0;background:#fff}\n.aegis-chat-input{flex:1;resize:none;border:1px solid #e2e8f0;border-radius:12px;padding:9px 12px;font-size:14px;font-family:inherit;max-height:96px;outline:none}\n.aegis-chat-input:focus{border-color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-send{width:40px;height:40px;border-radius:9999px;border:none;background:var(--aegis-chat-accent,#4169e1);color:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto}\n.aegis-chat-attach{width:38px;height:38px;border-radius:9999px;border:none;background:transparent;color:#64748b;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto;transition:background .15s ease,color .15s ease}\n.aegis-chat-attach:hover{background:#f1f5f9;color:var(--aegis-chat-accent,#4169e1)}\n.aegis-chat-fileinput{display:none}\n.aegis-chat-media-img{max-width:200px;max-height:200px;border-radius:12px;object-fit:cover;cursor:pointer;display:block}\n.aegis-chat-media-file{display:inline-flex;align-items:center;gap:6px;padding:8px 12px;border-radius:12px;background:#fff;border:1px solid #e2e8f0;font-size:13px;color:#0f172a;text-decoration:none;max-width:220px}\n.aegis-chat-msg--customer .aegis-chat-media-file{background:rgba(255,255,255,.18);border-color:transparent;color:#fff}\n/* Mobile: raise the bubble above the storefront\'s full-width cart bar so they\n never overlap; widen the panel and reduce the tooltip width. */\n@media (max-width:767px){\n .aegis-chat-root{bottom:84px;right:16px}\n /* Full-page chat on mobile — the open panel covers the whole viewport (incl.\n the bottom nav) like a native chat screen, instead of a floating card. */\n .aegis-chat-panel{position:fixed;inset:0;left:0;right:0;width:100vw;height:100vh;height:100dvh;max-width:none;max-height:none;border-radius:0}\n .aegis-chat-tip{max-width:200px}\n}\n';class Ne{constructor(){this.listeners=new Map,this.isStarted=!1,this.scrollDepthTargets=new Set,this.scrollDepthReached=new Set,this.timeOnPageTargets=new Map,this.exitIntentEnabled=!1,this.exitIntentFired=!1,this.inactivityTargets=new Map,this.lastActivityTime=Date.now(),this.scrollVelocityEnabled=!1,this.scrollVelocityFired=!1,this.scrollVelocityConfig={threshold:.5,minScrollPosition:100,cooldown:5e3},this.lastScrollY=0,this.lastScrollTime=Date.now(),this.visibilityChangeEnabled=!1,this.backButtonEnabled=!1,this.backButtonFired=!1,this.rageClickEnabled=!1,this.rageClickConfig={threshold:3,windowMs:1e3},this.rageClickBuffer=new Map,this.rageClickFiredInBurst=new Set,this.hoverEnabled=!1,this.hoverStartAt=new Map,this.hoverLastMs=new Map,this.hoverThresholds=new Map([["price",[1500]],["cta",[1500]]]),this.hoverThresholdsFired=new Map,this.hoverThresholdTimers=new Map,this.mouseVelEnabled=!1,this.mouseVelConfig={threshold:1.5,windowMs:400,cooldownMs:5e3},this.mouseSamples=[],this.mouseVelLast=0,this.mouseVelLastFiredAt=0,this.handleScroll=()=>{const e=window.pageYOffset||document.documentElement.scrollTop,t=document.documentElement.scrollHeight-window.innerHeight,n=t>0?e/t*100:0;for(const i of this.scrollDepthTargets)n>=i&&!this.scrollDepthReached.has(i)&&(this.scrollDepthReached.add(i),this.emit(`scroll_depth_${i}`,{depth_percent:i,actual_percent:n,scroll_top:e,scroll_height:t}))},this.handleExitIntent=e=>{this.exitIntentFired||e.clientY<10&&(this.exitIntentFired=!0,this.emit("exit_intent",{client_y:e.clientY,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleScrollVelocity=()=>{if(this.scrollVelocityFired)return;const e=window.scrollY||document.documentElement.scrollTop,t=Date.now(),n=t-this.lastScrollTime;if(n>100){const i=this.lastScrollY-e,o=Math.abs(i/n);i>0&&o>this.scrollVelocityConfig.threshold&&e>this.scrollVelocityConfig.minScrollPosition&&(this.scrollVelocityFired=!0,this.emit("mobile_exit_intent",{scroll_velocity:o,scroll_distance:i,current_position:e,page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}),this.scrollVelocityCooldownTimer=window.setTimeout(()=>{this.scrollVelocityFired=!1},this.scrollVelocityConfig.cooldown)),this.lastScrollY=e,this.lastScrollTime=t}},this.handleVisibilityChange=()=>{document.hidden?this.emit("visibility_hidden",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}):this.emit("visibility_visible",{page_url:window.location.href})},this.handleBackButton=()=>{this.backButtonFired||(this.backButtonFired=!0,window.history.pushState(null,"",window.location.href),this.emit("back_button",{page_url:window.location.href,time_on_page:this.pageLoadTime?(Date.now()-this.pageLoadTime)/1e3:0}))},this.handleActivity=()=>{this.lastActivityTime=Date.now()}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}registerScrollDepth(e){this.scrollDepthTargets.add(e)}registerTimeOnPage(e){if(!this.timeOnPageTargets.has(e)){const t=window.setTimeout(()=>{this.emit(`time_on_page_${e}`,{seconds:e,page_url:window.location.href}),this.timeOnPageTargets.delete(e)},1e3*e);this.timeOnPageTargets.set(e,t)}}registerExitIntent(){this.exitIntentEnabled=!0}registerInactivity(e){if(!this.inactivityTargets.has(e)){const t=window.setTimeout(()=>{const t=(Date.now()-this.lastActivityTime)/1e3;t>=e&&this.emit(`inactivity_${e}`,{idle_seconds:e,actual_idle_time:t}),this.inactivityTargets.delete(e)},1e3*e);this.inactivityTargets.set(e,t)}}registerScrollVelocity(e){this.scrollVelocityEnabled=!0,e&&(this.scrollVelocityConfig={threshold:e.threshold??this.scrollVelocityConfig.threshold,minScrollPosition:e.minScrollPosition??this.scrollVelocityConfig.minScrollPosition,cooldown:e.cooldown??this.scrollVelocityConfig.cooldown})}registerVisibilityChange(){this.visibilityChangeEnabled=!0}registerBackButton(){this.backButtonEnabled=!0}registerRageClick(e){this.rageClickEnabled=!0,e&&(this.rageClickConfig={threshold:e.threshold??this.rageClickConfig.threshold,windowMs:e.windowMs??this.rageClickConfig.windowMs})}noteClick(e,t=Date.now()){if(!this.rageClickEnabled)return 0;const n=this.rageClickBuffer.get(e)??[],i=t-this.rageClickConfig.windowMs;let o=0;for(;o<n.length&&n[o]<i;)o++;const s=0===o?n:n.slice(o);return s.push(t),this.rageClickBuffer.set(e,s),s.length<this.rageClickConfig.threshold&&this.rageClickFiredInBurst.delete(e),s.length>=this.rageClickConfig.threshold&&!this.rageClickFiredInBurst.has(e)&&(this.rageClickFiredInBurst.add(e),this.emit("rage_click",{intent:e,count:s.length,window_ms:this.rageClickConfig.windowMs})),s.length}getRageClickCount(e){if(!this.rageClickEnabled)return 0;const t=this.rageClickBuffer.get(e);if(!t)return 0;const n=Date.now()-this.rageClickConfig.windowMs;let i=0;for(const o of t)o>=n&&i++;return i}registerHoverDwell(e){if(this.hoverEnabled=!0,null==e?void 0:e.thresholdsByIntent)for(const[t,n]of Object.entries(e.thresholdsByIntent))n&&this.hoverThresholds.set(t,n)}noteHoverStart(e,t=Date.now()){if(!this.hoverEnabled)return;this.hoverStartAt.has(e)&&this.noteHoverEnd(e,t),this.hoverStartAt.set(e,t),this.hoverThresholdsFired.set(e,new Set);const n=this.hoverThresholds.get(e);if(n){const i=[];for(const o of n){const n=setTimeout(()=>{if(!this.hoverStartAt.has(e))return;const n=this.hoverThresholdsFired.get(e);(null==n?void 0:n.has(o))||(null==n||n.add(o),this.emit(`${e}_hover_dwell_${o}`,{intent:e,threshold_ms:o,actual_ms:Date.now()-t}))},o);i.push(n)}this.hoverThresholdTimers.set(e,i)}}noteHoverEnd(e,t=Date.now()){if(!this.hoverEnabled)return;const n=this.hoverStartAt.get(e);if(void 0===n)return;const i=Math.max(0,t-n);this.hoverLastMs.set(e,i),this.hoverStartAt.delete(e);const o=this.hoverThresholdTimers.get(e);if(o){for(const e of o)clearTimeout(e);this.hoverThresholdTimers.delete(e)}this.hoverThresholdsFired.delete(e)}registerMouseVelocityToTop(e){this.mouseVelEnabled=!0,e&&(this.mouseVelConfig={threshold:e.threshold??this.mouseVelConfig.threshold,windowMs:e.windowMs??this.mouseVelConfig.windowMs,cooldownMs:e.cooldownMs??this.mouseVelConfig.cooldownMs})}noteMousePosition(e,t,n=Date.now()){if(!this.mouseVelEnabled)return 0;const i=n-this.mouseVelConfig.windowMs;let o=0;for(;o<this.mouseSamples.length&&this.mouseSamples[o].ts<i;)o++;if(o>0&&(this.mouseSamples=this.mouseSamples.slice(o)),this.mouseSamples.push({x:e,y:t,ts:n}),this.mouseSamples.length<2)return this.mouseVelLast=0,0;const s=this.mouseSamples[0],a=this.mouseSamples[this.mouseSamples.length-1],r=a.ts-s.ts;if(r<=0)return this.mouseVelLast=0,0;const c=-(a.y-s.y)/r;this.mouseVelLast=c;const d=0===this.mouseVelLastFiredAt||n-this.mouseVelLastFiredAt>=this.mouseVelConfig.cooldownMs;return c>=this.mouseVelConfig.threshold&&d&&(this.mouseVelLastFiredAt=n,this.emit("mouse_velocity_to_top",{velocity:c,threshold:this.mouseVelConfig.threshold,window_ms:this.mouseVelConfig.windowMs,samples:this.mouseSamples.length})),c}getMouseVelocityToTop(){return this.mouseVelEnabled?this.mouseVelLast:0}getHoverMs(e){if(!this.hoverEnabled)return 0;const t=this.hoverStartAt.get(e);return void 0!==t?Math.max(0,Date.now()-t):this.hoverLastMs.get(e)??0}start(){this.isStarted||(this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollDepthTargets.size>0&&this.attachScrollListener(),this.exitIntentEnabled&&this.attachExitIntentListener(),this.scrollVelocityEnabled&&this.attachScrollVelocityListener(),this.visibilityChangeEnabled&&this.attachVisibilityChangeListener(),this.backButtonEnabled&&this.attachBackButtonListener(),this.attachActivityListeners(),this.startInactivityCheck(),this.isStarted=!0)}stop(){this.isStarted&&(this.removeScrollListener(),this.removeExitIntentListener(),this.removeScrollVelocityListener(),this.removeVisibilityChangeListener(),this.removeBackButtonListener(),this.removeActivityListeners(),this.timeOnPageTargets.forEach(e=>clearTimeout(e)),this.timeOnPageTargets.clear(),this.inactivityTargets.forEach(e=>clearTimeout(e)),this.inactivityTargets.clear(),this.inactivityCheckInterval&&(clearInterval(this.inactivityCheckInterval),this.inactivityCheckInterval=void 0),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0),this.isStarted=!1)}reset(){this.scrollDepthReached.clear(),this.exitIntentFired=!1,this.scrollVelocityFired=!1,this.backButtonFired=!1,this.pageLoadTime=Date.now(),this.lastActivityTime=Date.now(),this.lastScrollY=window.scrollY||0,this.lastScrollTime=Date.now(),this.scrollVelocityCooldownTimer&&(clearTimeout(this.scrollVelocityCooldownTimer),this.scrollVelocityCooldownTimer=void 0)}attachScrollListener(){window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.handleScroll()}removeScrollListener(){window.removeEventListener("scroll",this.handleScroll)}attachExitIntentListener(){document.addEventListener("mouseleave",this.handleExitIntent)}removeExitIntentListener(){document.removeEventListener("mouseleave",this.handleExitIntent)}attachScrollVelocityListener(){window.addEventListener("scroll",this.handleScrollVelocity,{passive:!0})}removeScrollVelocityListener(){window.removeEventListener("scroll",this.handleScrollVelocity)}attachVisibilityChangeListener(){document.addEventListener("visibilitychange",this.handleVisibilityChange)}removeVisibilityChangeListener(){document.removeEventListener("visibilitychange",this.handleVisibilityChange)}attachBackButtonListener(){"undefined"!=typeof window&&window.history&&(window.history.pushState(null,"",window.location.href),window.addEventListener("popstate",this.handleBackButton))}removeBackButtonListener(){window.removeEventListener("popstate",this.handleBackButton)}attachActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.addEventListener(e,this.handleActivity,{passive:!0})})}removeActivityListeners(){["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{document.removeEventListener(e,this.handleActivity)})}startInactivityCheck(){this.inactivityCheckInterval=window.setInterval(()=>{const e=(Date.now()-this.lastActivityTime)/1e3;for(const[t]of this.inactivityTargets)if(e>=t){this.emit(`inactivity_${t}`,{idle_seconds:t,actual_idle_time:e});const n=this.inactivityTargets.get(t);n&&(clearTimeout(n),this.inactivityTargets.delete(t))}},1e3)}emit(e,t){const n={type:e,data:t,timestamp:Date.now()},i=this.listeners.get(e);i&&i.forEach(t=>{try{t(n)}catch(i){console.error(`Error in trigger callback for ${e}:`,i)}});const o=this.listeners.get("*");o&&o.forEach(e=>{try{e(n)}catch(t){console.error("Error in wildcard trigger callback:",t)}})}}let Fe=null,Oe=null;function Be(e){return"string"==typeof e&&e.length>0?e:void 0}function Ue(e){try{const t=(new DOMParser).parseFromString(e,"image/svg+xml").documentElement;return!t||t.getElementsByTagName("parsererror").length>0?null:document.importNode(t,!0)}catch{return null}}const je=class e{constructor(e){this.campaigns=[],this.displayedCampaigns=new Set,this._displaySizeMul=1,this.suppressedUntil=new Map,this.isInitialized=!1,this.reconnectAttempts=0,this.maxReconnectAttempts=5,this.hooks=new Map,this.ready=new Promise(e=>{this.readyResolve=e}),this.currentSurface=null,this.currentScreen=null,this.currentLocationId=null,this.filledSlots=new WeakSet,this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.propertyId=e.propertyId,this.debugMode=e.debugMode||!1,this.enableSSE=!0===e.enableSSE,this.onInteractiveCampaign=e.onInteractiveCampaign,this.getWorkspaceId=e.getWorkspaceId,this.getCartState=e.getCartState}emit(e,t){const n=this.hooks.get(e);if(!n||0===n.size)return!0;let i=!0;for(const s of n)try{!1===s(t)&&(i=!1)}catch(o){this.emitError(o,{event:e})}return i}emitError(e,t){const n=this.hooks.get("error");if(n&&0!==n.size)for(const i of n)try{i({message:e instanceof Error?e.message:String(e),error:e,context:t??{}})}catch{}else this.log(`Active Reach SDK error: ${e instanceof Error?e.message:String(e)}`,"error")}register(e,t){return this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add(t),()=>{var n;null==(n=this.hooks.get(e))||n.delete(t)}}on(e,t){return this.register(e,t)}onCampaignsLoaded(e){return this.register("campaigns-loaded",e)}onCampaignWillShow(e){return this.register("campaign-will-show",e)}onCampaignShown(e){return this.register("campaign-shown",e)}onCampaignClick(e){return this.register("campaign-click",e)}onCampaignDismiss(e){return this.register("campaign-dismiss",e)}onError(e){return this.register("error",e)}async initialize(){this.isInitialized?this.log("AegisInApp already initialized"):("undefined"!=typeof localStorage&&localStorage.setItem("aegis_returning_user","1"),await this.refreshCampaigns(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.isInitialized=!0,this.log("AegisInApp initialized successfully"))}updateUserId(e){this.userId=e,this.refreshCampaigns()}updateContactId(e){var t;this.contactId=e,null==(t=this.activeWebChat)||t.updateContactId(e),this.disconnectSSE(),this.enableSSE&&this.organizationId&&this.connectSSE(),this.refreshCampaigns()}refreshOnEvent(t,n=!1){this.isInitialized?(t&&e.KNOWN_SURFACES.has(t)&&(this.currentSurface=t),n&&t&&"page_view"!==t&&(this.currentScreen=t),this.refreshDebounceTimer&&clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=setTimeout(()=>{this.refreshDebounceTimer=void 0,this.log(`refreshOnEvent(${t}) — firing refreshCampaigns()`),this.refreshCampaigns()},e.REFRESH_DEBOUNCE_MS)):this.log(`refreshOnEvent(${t}) before initialize — ignored`)}setLocation(t){const n=t||null;n!==this.currentLocationId&&(this.currentLocationId=n,this.isInitialized&&(this.refreshDebounceTimer&&clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=setTimeout(()=>{this.refreshDebounceTimer=void 0,this.log(`setLocation(${n}) — firing refreshCampaigns()`),this.refreshCampaigns()},e.REFRESH_DEBOUNCE_MS)))}notifyConversion(t){if(!t)return void this.log("notifyConversion called with empty goalName; ignored","warn");const n=Date.now();if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem(`${e.CONVERSION_STORAGE_PREFIX}${t}`,JSON.stringify({ts:n}))}catch{}this.applySuppressionFromCampaigns(n),this.log(`notifyConversion: ${t} — suppressing ${this.suppressedUntil.size} armed campaigns`)}applySuppressionFromCampaigns(e){var t,n;for(const i of this.campaigns){const o=null==(t=i.frequency)?void 0:t.suppress_after_conversion_seconds;if("number"!=typeof o||o<=0)continue;const s=(null==(n=i.frequency)?void 0:n.scope)??"session";"session"!==s&&this.log(`applySuppressionFromCampaigns: scope=${s} not implemented; degrading to session for campaign ${i.id}`,"warn");const a=e+1e3*o,r=this.suppressedUntil.get(i.id);(void 0===r||r<a)&&this.suppressedUntil.set(i.id,a)}}rehydrateSuppressionFromStorage(){if("undefined"==typeof sessionStorage)return;let t=null;try{for(let n=0;n<sessionStorage.length;n++){const i=sessionStorage.key(n);if(!i||!i.startsWith(e.CONVERSION_STORAGE_PREFIX))continue;const o=sessionStorage.getItem(i);if(!o)continue;const s=JSON.parse(o);"number"==typeof s.ts&&(t=null===t?s.ts:Math.min(t,s.ts))}}catch{return}null!==t&&this.applySuppressionFromCampaigns(t)}isSuppressed(e){const t=this.suppressedUntil.get(e);return void 0!==t&&(!(Date.now()>=t)||(this.suppressedUntil.delete(e),!1))}connectSSE(){if(this.eventSource&&this.disconnectSSE(),!this.organizationId)return void this.log("Cannot connect SSE without organization ID","warn");const e=new URL("/v1/stream/realtime",this.apiHost),t={"X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(t["X-Contact-ID"]=this.contactId);const n=new URLSearchParams;Object.entries(t).forEach(([e,t])=>{n.append(e,t)}),this.eventSource=new EventSource(`${e}?${n.toString()}`),this.eventSource.addEventListener("open",()=>{this.log("SSE connection established"),this.reconnectAttempts=0}),this.eventSource.addEventListener("in_app_campaign_updated",e=>{try{const t=JSON.parse(e.data);this.log(`Received in-app campaign update: ${t.campaign_id}`),this.refreshCampaigns()}catch(t){this.log(`Error parsing SSE event: ${t}`,"error")}}),this.eventSource.addEventListener("heartbeat",()=>{this.log("SSE heartbeat received")}),this.eventSource.addEventListener("error",()=>{var e;this.log("SSE connection error","error"),(null==(e=this.eventSource)?void 0:e.readyState)===EventSource.CLOSED&&this.attemptReconnect()})}disconnectSSE(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0,this.log("SSE connection closed"))}attemptReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.log("Max reconnect attempts reached, giving up","warn");this.reconnectAttempts++;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempts),3e4);this.log(`Reconnecting SSE in ${e}ms (attempt ${this.reconnectAttempts})`),setTimeout(()=>{this.isInitialized&&this.enableSSE&&this.organizationId&&this.connectSSE()},e)}async refreshCampaigns(){try{const e=new URLSearchParams({device_type:this.detectDeviceType(),page_url:"undefined"!=typeof window?window.location.pathname:"/"});e.set("is_new_user",this.isNewUser()?"true":"false"),this.currentSurface&&e.set("current_surface",this.currentSurface),this.currentScreen&&e.set("current_screen",this.currentScreen),this.currentLocationId&&e.set("location_id",this.currentLocationId);const t=`${this.apiHost}/v1/in-app/active?${e.toString()}`,n={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};this.userId&&(n["X-User-ID"]=this.userId),this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId),this.propertyId&&(n["X-Property-Id"]=this.propertyId);const i=this.getABAssignments();Object.keys(i).length>0&&(n["X-AB-Assignments"]=btoa(JSON.stringify(i)));const o=await fetch(t,{method:"GET",headers:n,credentials:"include"});if(!o.ok)throw new Error(`Failed to fetch campaigns: ${o.status}`);const s=await o.json();this.campaigns=Array.isArray(s)?s:[],this.processABAssignments(this.campaigns),this.rehydrateSuppressionFromStorage(),this.log(`Fetched ${this.campaigns.length} campaigns`),this.emitServedEvents(this.campaigns),this.emit("campaigns-loaded",this.campaigns),this.readyResolve(),this.tryDisplayNextCampaign(),this.renderIntoSlots(),this.renderIntoAnchors(),this.renderTokenAnchors()}catch(e){this.emitError(e,{stage:"refresh-campaigns"}),this.log(`Error refreshing campaigns: ${e}`,"error")}}emitServedEvents(t){if("undefined"!=typeof sessionStorage)for(const n of t){const t=e.SERVED_DEDUP_PREFIX+n.id;if(!sessionStorage.getItem(t)){try{sessionStorage.setItem(t,"1")}catch{}this.trackEvent(n.id,"served")}}else for(const e of t)this.trackEvent(e.id,"served")}detectDeviceType(){if("undefined"==typeof navigator)return"desktop";const e=navigator.userAgent;return/Mobi|Android/i.test(e)?"mobile":/iPad|Tablet/i.test(e)?"tablet":"desktop"}isNewUser(){return"undefined"==typeof localStorage||!localStorage.getItem("aegis_returning_user")}getABAssignments(){if("undefined"==typeof localStorage)return{};try{return JSON.parse(localStorage.getItem("aegis_ab_assignments")||"{}")}catch{return{}}}processABAssignments(e){if("undefined"==typeof localStorage)return;const t=this.getABAssignments();for(const n of e)n.assigned_variant_id&&(t[n.id]=n.assigned_variant_id);localStorage.setItem("aegis_ab_assignments",JSON.stringify(t))}getVariantId(e){return this.getABAssignments()[e]??void 0}tryDisplayNextCampaign(){const e=this.campaigns.find(e=>!this.displayedCampaigns.has(e.id)&&!e.client_trigger&&!this.isSuppressed(e.id));e&&this.displayCampaign(e)}matchesCurrentSurface(e){return!e.surface||0===e.surface.length||(null===this.currentSurface||e.surface.includes(this.currentSurface))}matchesCurrentScreenOrSurface(e){const t=e.target_screens;if(!t||0===t.length)return this.matchesCurrentSurface(e);const n=null!==this.currentScreen&&t.includes(this.currentScreen);return e.surface&&0!==e.surface.length?n||this.matchesCurrentSurface(e):n}renderIntoSlots(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-slot]");if(0===e.length)return;const t=new Map;for(const n of this.campaigns){if(!this.matchesCurrentScreenOrSurface(n))continue;const e=n.delivery_modes,i=n.widget_category;if(!e||!e.includes("embedded_card"))continue;if(!i)continue;const o=t.get(i);o?o.push(n):t.set(i,[n])}0!==t.size&&e.forEach(e=>{if(this.filledSlots.has(e))return;const n=e.getAttribute("data-aegis-slot");if(!n)return;const i=t.get(n);if(!i||0===i.length)return;e.querySelectorAll(":scope > [data-aegis-slot-default]").forEach(e=>e.remove());const o=parseInt(e.getAttribute("data-aegis-slot-rotate")||"0",10),s=i.reduce((e,t)=>{var n;const i=Number(null==(n=t.interactive_config)?void 0:n.slot_rotate_ms);return Number.isFinite(i)&&i>e?i:e},0),a=o>0?o:s;a>0&&i.length>1?this.renderRotatingSlot(e,i,a):this.renderCampaignIntoSlot(i[0],e),this.filledSlots.add(e)})}renderRotatingSlot(e,t,n){const i=[];for(const c of t){const t=document.createElement("div");t.setAttribute("data-aegis-rotate-pane",c.id),t.style.display="none",e.appendChild(t),this.renderCampaignIntoSlot(c,t,{deferImpression:!0}),t.childElementCount>0?i.push({el:t,campaign:c}):t.remove()}if(0===i.length)return;const o=new Set,s=e=>{o.has(e.id)||(o.add(e.id),this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))};let a=0;if(i[0].el.style.display="",s(i[0].campaign),1===i.length)return;const r=setInterval(()=>{i[a].el.style.display="none",a=(a+1)%i.length,i[a].el.style.display="",s(i[a].campaign)},n);"undefined"!=typeof window&&window.addEventListener("beforeunload",()=>clearInterval(r),{once:!0})}renderIntoAnchors(){var e;if("undefined"!=typeof document)for(const t of this.campaigns){if(!this.matchesCurrentScreenOrSurface(t))continue;const n=t.delivery_modes;if(!n||!n.includes("embedded_card"))continue;const i=t.interactive_config,o=null==i?void 0:i.anchor,s=null==o?void 0:o.element_selector;if(!s)continue;let a=null;try{a=document.querySelector(s)}catch{a=null}if(!a){this.trackEvent(t.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:s,widget_type:t.sub_type}});continue}const r=(null==o?void 0:o.position)||"inside";let c;"before"===r||"after"===r?(c=document.createElement("div"),c.setAttribute("data-aegis-anchor-wrapper",t.id),null==(e=a.parentNode)||e.insertBefore(c,"before"===r?a:a.nextSibling)):(c=a,"replace"===r&&c.querySelectorAll(":scope > [data-aegis-slot-default]").forEach(e=>e.remove())),this.filledSlots.has(c)||(this.renderCampaignIntoSlot(t,c),this.filledSlots.add(c))}}renderTokenAnchors(){if("undefined"==typeof document)return;const e=document.querySelectorAll("[data-aegis-token-data]");0!==e.length&&e.forEach(e=>{if(this.filledSlots.has(e))return;const t=e.getAttribute("data-aegis-token-data");if(!t)return;let n=null;try{n=JSON.parse(t)}catch(i){return this.log(`data-aegis-token-data: invalid JSON, skipping anchor (${i})`,"warn"),void this.filledSlots.add(e)}if(!n||!n.campaign||!n.campaign.id)return this.log("data-aegis-token-data: missing `campaign` in payload, skipping","warn"),void this.filledSlots.add(e);this.renderCampaignIntoSlot(n.campaign,e,{submitUrl:n.submit_url}),this.filledSlots.add(e)})}renderCampaignIntoSlot(e,t,n){if(!this.emit("campaign-will-show",e))return void this.log(`slot campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id),this.addAnimationStyles();const i=e.interactive_config||{},o=this._sizeMul(i);if(1!==o){const e=document.createElement("div");e.style.cssText=`transform: scale(${o}); transform-origin: top center;`,t.appendChild(e),t=e}const{bg:s,text:a}=this._surfacePalette(e),r=null==n?void 0:n.submitUrl,c=Array.isArray(i.form_fields)?i.form_fields:null;let d=!1;if(c&&c.length>0)return d=this.renderFormSlot(e,c,s,a,t),d?void((null==n?void 0:n.deferImpression)||(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e))):void this.displayedCampaigns.delete(e.id);if("hero"===e.widget_category)d=Me(this.buildRenderContext(e),t);else switch(e.sub_type){case"star_rating":d=this.renderStarRatingSlot(e,i,s,a,t,r);break;case"nps_survey":d=this.renderNPSSurveySlot(e,i,s,a,t,r);break;case"spin_wheel":d=this.renderSpinWheelSlot(e,i,s,a,t);break;case"quick_poll":d=this.renderQuickPollSlot(e,i,s,a,t);break;case"carousel_cards":d=this.renderCarouselCardsSlot(e,i,s,a,t);break;case"countdown_offer":d=this.renderCountdownSlot(e,i,s,a,t);break;case"scratch_card":d=this.renderScratchCardSlot(e,i,s,a,t);break;case"custom_html":d=this.renderCustomHtmlSlot(e,i,s,a,t);break;case"stories":d=re(this.buildRenderContext(e),t);break;case"video":d=function(e,t){if(!t)return ke(e),!0;e.addAnimationStyles();const n=Ce(e),i=document.createElement("div");i.className="aegis-in-app-video-banner",i.setAttribute("data-campaign-id",e.campaign.id),i.style.cssText='width:100%;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;';const o=we(e,n.aspect,n.autoplay,n.loop);if(n.overlayCaption){const t=_e(e,n.accent,!0);t&&o.appendChild(t)}if(i.appendChild(o),!n.overlayCaption){const t=_e(e,n.accent,!1);t&&i.appendChild(t)}return t.appendChild(i),!0}(this.buildRenderContext(e),t);break;case"progress_bar":d=function(e,t){const n=J(e,!0);return!!n&&(t.appendChild(n),!0)}(this.buildRenderContext(e),t);break;case"quiz":d=this.renderQuizSlot(e,i,s,a,t),d||(d=this.renderGenericCardSlot(e,i,s,a,t));break;default:d=this.renderGenericCardSlot(e,i,s,a,t)}d&&((null==n?void 0:n.deferImpression)||(this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)))}renderStarRatingSlot(e,t,n,i,o,s){const a=this._slotStyle(e),r=this._wrapInSlotCard("aegis-in-app-rating-card",e.id,n,i,a.radius);return r.appendChild(this._buildStarRatingBody(e,t,i,"slot",s,a)),o.appendChild(r),!0}renderNPSSurveySlot(e,t,n,i,o,s){const a=this._slotStyle(e),r=this._wrapInSlotCard("aegis-in-app-nps-card",e.id,n,i,a.radius);return r.appendChild(this._buildNPSSurveyBody(e,t,i,"slot",s,a)),o.appendChild(r),!0}renderGenericCardSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-generic-card",e.id,n,i,s.radius),r=e,c="string"==typeof r.image_url?r.image_url:"",d="string"==typeof t.coupon_code?t.coupon_code:"",l="string"==typeof r.button_text?r.button_text:"",p="string"==typeof r.action_url?r.action_url:"";if(c){const e=document.createElement("img");e.src=c,e.alt="",e.style.cssText="width: 100%; height: 96px; object-fit: cover; display: block;",a.appendChild(e)}const h=document.createElement("div");if(h.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 6px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,h.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 11px; opacity: 0.85; line-height: 1.35;",t.textContent=e.body,h.appendChild(t)}if(d){const e=document.createElement("span");e.style.cssText=`align-self: flex-start; border: 1px dashed ${i}66; border-radius: 6px; padding: 2px 8px; font-family: monospace; font-size: 11px; letter-spacing: 0.04em;`,e.textContent=d,h.appendChild(e)}if(l){const t=document.createElement("button");t.textContent=l,t.style.cssText=`margin-top: 2px; align-self: flex-start; padding: 8px 14px; border-radius: ${s.btnRadius??9}px; border: none; background: ${i}; color: ${n}; font-size: 13px; font-weight: 600; cursor: pointer;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),p&&window.open(p,"_blank","noopener")}),h.appendChild(t)}return a.appendChild(h),o.appendChild(a),!0}renderFormSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-form-card",e.id,n,i,s.radius);return a.appendChild(this._buildFormBody(e,t,n,i,s)),o.appendChild(a),!0}_buildFormBody(e,t,n,i,o){const s=document.createElement("div");if(s.style.cssText=`padding: ${(null==o?void 0:o.padY)??16}px ${(null==o?void 0:o.padX)??16}px; display: flex; flex-direction: column; gap: 10px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 14px; font-weight: ${(null==o?void 0:o.weight)??"700"};`,t.textContent=e.title,s.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 12px; opacity: 0.8; margin-top: -4px;",t.textContent=e.body,s.appendChild(t)}const a=new Map,r=new Set,c=`padding: 9px 11px; border-radius: 9px; border: 1px solid ${i}33; background: ${i}0d; color: ${i}; font-size: 13px; width: 100%; box-sizing: border-box; font-family: inherit;`;for(const p of t){const e="string"==typeof p.key?p.key:null;if(!e)continue;const t="string"==typeof p.type?p.type:"text",n="string"==typeof p.label&&p.label||e,o=!0===p.required;o&&r.add(e);const d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 4px;";const l=document.createElement("label");let h;if(l.textContent=n+(o?" *":""),l.style.cssText=`font-size: 11px; font-weight: 600; opacity: 0.8; color: ${i};`,d.appendChild(l),"select"===t){const e=document.createElement("select");e.style.cssText=c;const t=document.createElement("option");t.value="",t.textContent="string"==typeof p.placeholder&&p.placeholder||"Select…",e.appendChild(t),(Array.isArray(p.options)?p.options:[]).forEach(t=>{const n=document.createElement("option");n.value=t,n.textContent=t,e.appendChild(n)}),h=e}else if("textarea"===t){const e=document.createElement("textarea");e.className="aegis-field",e.rows=3,e.placeholder="string"==typeof p.placeholder&&p.placeholder||n,e.style.cssText=`${c} resize: vertical;`,h=e}else{const e=document.createElement("input");e.className="aegis-field",e.type="email"===t?"email":"date"===t?"date":"tel"===t?"tel":"number"===t?"number":"text",e.placeholder="string"==typeof p.placeholder&&p.placeholder||n,e.style.cssText=c,h=e}o&&(h.required=!0),a.set(e,h),d.appendChild(h),s.appendChild(d)}const d=document.createElement("button"),l=e;return d.textContent="string"==typeof l.button_text&&l.button_text||"Save",d.style.cssText=`margin-top: 4px; padding: 10px 16px; border-radius: ${(null==o?void 0:o.btnRadius)??10}px; border: none; background: ${i}; color: ${n}; font-size: 14px; font-weight: 600; cursor: pointer;`,d.addEventListener("click",()=>{var t;const n={};let o=!0;for(const[e,s]of a){const t=(s.value||"").trim();r.has(e)&&!t?(o=!1,s.style.borderColor="#e11d48"):s.style.borderColor=`${i}33`,t&&(n[e]=t)}if(!o||0===Object.keys(n).length)return;for(this.submitFormResponse(e,n),this.trackEvent(e.id,"clicked",{meta:{fields:Object.keys(n)}});s.firstChild;)s.removeChild(s.firstChild);const c=s.parentElement;c&&(c.style.overflow="visible"),s.style.position="relative",s.style.minHeight="176px",s.style.alignItems="center",s.style.justifyContent="center";const d=document.createElement("div");d.style.cssText="padding: 8px 0; font-size: 13px; font-weight: 600; text-align: center;",d.textContent="string"==typeof(null==(t=e.interactive_config)?void 0:t.thank_you_message)?e.interactive_config.thank_you_message:"✓ Thanks — your details are saved.",s.appendChild(d),this._playReaction(s,"affirm","check.json",e.interactive_config)}),s.appendChild(d),s}async submitFormResponse(e,t){if(this.organizationId)try{const n={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(n["X-Contact-ID"]=this.contactId);const i=e.assigned_variant_id,o=await fetch(`${this.apiHost}/v1/in-app/responses`,{method:"POST",headers:n,keepalive:!0,body:JSON.stringify({campaign_id:e.id,response_type:"form",contact_id:this.contactId,user_id:this.userId,variant_id:i,platform:"web",payload:{fields:t}})});o.ok||this.log(`submitFormResponse failed (${o.status})`,"warn")}catch(n){this.log(`submitFormResponse error: ${n}`,"warn")}else this.log("submitFormResponse: no organizationId — cannot submit","warn")}async submitWidgetResponse(e,t,n){if(!this.organizationId)return null;try{const i={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey,"X-Organization-ID":this.organizationId};this.contactId&&(i["X-Contact-ID"]=this.contactId);const o=e.assigned_variant_id,s=await fetch(`${this.apiHost}/v1/in-app/responses`,{method:"POST",headers:i,keepalive:!0,body:JSON.stringify({campaign_id:e.id,response_type:t,contact_id:this.contactId,user_id:this.userId,variant_id:o,platform:"web",payload:n})});return s.ok?await s.json().catch(()=>null):(this.log(`submitWidgetResponse ${t} failed (${s.status})`,"warn"),null)}catch(i){return this.log(`submitWidgetResponse ${t} error: ${i}`,"warn"),null}}renderSpinWheelSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-spin-card",e.id,n,i,s.radius),r=(Array.isArray(t.segments)?t.segments:[]).filter(e=>"string"==typeof e.label&&e.label),c=r.map(e=>e.label),d=c.length>=2?c.length:8,l=e=>!!r[e]&&"no_prize"===String(r[e].prize_type||"").toLowerCase(),p=t.already_won&&"object"==typeof t.already_won?t.already_won:null,h=Array.from({length:d},(e,t)=>{const n=r[t]&&"number"==typeof r[t].probability?r[t].probability:NaN;return Number.isFinite(n)&&n>0?n:0}),u=h.reduce((e,t)=>e+t,0),g=u>0?h:Array.from({length:d},()=>1),m=u>0?u:d,f="equal"===("string"==typeof t.spin_slice_sizing?t.spin_slice_sizing:"proportional")?Array.from({length:d},()=>360/d):g.map(e=>e/m*360),x=[];f.reduce((e,t,n)=>(x[n]=e,e+t),0);const y=e=>x[e]+f[e]/2,b=Array.from({length:d},(e,t)=>`${(e=>(r[e]&&"string"==typeof r[e].color?r[e].color:"")||(e%2==0?i:`${i}40`))(t)} ${x[t]}deg ${x[t]+f[t]}deg`).join(", "),v=e=>"string"==typeof t[e]?t[e]:"",w=v("spin_mode")||"both",_=v("spin_idle_animation")||"shimmer",C=v("spin_win_reveal")||"inline",k=!1!==t.spin_haptics_enabled;let E=!1!==t.spin_sound_enabled;const S=v("spin_pointer_color")||"#ffffff",T=v("spin_hub_image_url"),$=v("wheel_background_url"),I=v("pointer_image_url"),z="center"===(v("spin_pointer_position")||"top"),A=z?"translate(-50%, -100%)":"translateX(-50%)",M=e=>/^https?:\/\//i.test(e),L=()=>"undefined"!=typeof performance&&performance.now?performance.now():Date.now();let R=0;if("undefined"!=typeof document&&!document.getElementById("aegis-spin-kf")){const e=document.createElement("style");e.id="aegis-spin-kf",e.textContent="@keyframes aegisSpinWobble{0%,100%{transform:rotate(-5deg)}50%{transform:rotate(5deg)}}@keyframes aegisSpinSheen{0%{transform:translateX(-130%)}100%{transform:translateX(360%)}}@keyframes aegisSpinRevealIn{0%{opacity:0;transform:scale(0.86)}100%{opacity:1;transform:scale(1)}}",document.head.appendChild(e)}let P=null;const D=()=>{if(!E)return null;try{if(!P){const e=window.AudioContext||window.webkitAudioContext;if(!e)return null;P=new e}return"suspended"===P.state&&P.resume(),P}catch{return null}},N=(e,t,n="triangle",i=.06)=>{const o=D();if(!o)return;const s=o.createOscillator(),a=o.createGain();s.type=n,s.frequency.value=e,a.gain.setValueAtTime(i,o.currentTime),a.gain.exponentialRampToValueAtTime(1e-4,o.currentTime+t/1e3),s.connect(a),a.connect(o.destination),s.start(),s.stop(o.currentTime+t/1e3)},F=e=>{var t;if(k)try{null==(t=navigator.vibrate)||t.call(navigator,e)}catch{}},O=document.createElement("div");if(O.style.cssText=`padding: ${s.padY??22}px ${s.padX??20}px 20px; display: flex; flex-direction: column; align-items: center; gap: 10px;`,e.title){const t=document.createElement("div");t.style.cssText="font-size: 18px; font-weight: 800; letter-spacing: -0.01em; text-align: center; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;",t.textContent=e.title,O.appendChild(t)}if(e.body){const t=document.createElement("div");t.style.cssText="font-size: 12.5px; opacity: 0.82; text-align: center; margin-top: -8px; line-height: 1.35;",t.textContent=e.body,O.appendChild(t)}const B=document.createElement("div");B.style.cssText="position: relative; width: 172px; height: 172px; filter: drop-shadow(0 10px 22px rgba(0,0,0,0.30));";const U=document.createElement("div");if(z){const e=Math.round(36.12);if(U.style.cssText=`position: absolute; left: 50%; top: 50%; width: 20px; height: ${e}px; transform: ${A}; transform-origin: 50% 100%; z-index: 6; pointer-events: none;`,I){const e=document.createElement("img");e.src=I,e.alt="",e.style.cssText="width: 100%; height: 100%; object-fit: contain; object-position: top; display: block; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.4));",U.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`position: absolute; left: 50%; bottom: 0; transform: translateX(-50%); width: 4px; height: 100%; background: ${S}; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.35);`;const t=document.createElement("div");t.style.cssText=`position: absolute; left: 50%; top: -1px; transform: translateX(-50%); width: 0; height: 0; border-left: 8px solid transparent; border-right: 8px solid transparent; border-bottom: 14px solid ${S}; filter: drop-shadow(0 1px 1px rgba(0,0,0,0.4));`,U.appendChild(e),U.appendChild(t)}}else if(I){U.style.cssText=`position: absolute; left: 50%; top: -12px; transform: ${A}; transform-origin: 50% 0; width: 30px; height: 34px; z-index: 5;`;const e=document.createElement("img");e.src=I,e.alt="",e.style.cssText="width: 100%; height: 100%; object-fit: contain; display: block; filter: drop-shadow(0 2px 2px rgba(0,0,0,0.35));",U.appendChild(e)}else U.style.cssText=`position: absolute; left: 50%; top: -7px; transform: ${A}; transform-origin: 50% 0; width: 0; height: 0; border-left: 9px solid transparent; border-right: 9px solid transparent; border-top: 16px solid ${S}; z-index: 5; filter: drop-shadow(0 2px 2px rgba(0,0,0,0.35));`;const j=document.createElement("div"),W=$?`center / cover no-repeat url("${$}")`:`conic-gradient(${b})`,q=$?"0":"5px solid #ffffff",H=$?`0 0 0 2px ${i}2e`:`0 0 0 2px ${i}2e, inset 0 0 22px rgba(0,0,0,0.20)`;j.style.cssText=`position: relative; width: 172px; height: 172px; border-radius: 50%; border: ${q}; box-shadow: ${H}; background: ${W}; overflow: hidden; will-change: transform; touch-action: none; cursor: ${"button"===w?"default":"grab"};`,"wobble"===_&&(j.style.animation="aegisSpinWobble 3s ease-in-out infinite");const V=Math.max(40,Math.min(100,Number(t.spin_slice_image_size)||100))/100;$||r.forEach((e,t)=>{const n="string"==typeof e.image_url?e.image_url:"";if(!n||!M(n))return;const i=["50% 50%"],o=Math.max(2,Math.ceil(f[t]/6));for(let a=0;a<=o;a++){const e=(x[t]+f[t]*a/o)*Math.PI/180,n=50+50*V*Math.sin(e),s=50-50*V*Math.cos(e);i.push(`${n.toFixed(2)}% ${s.toFixed(2)}%`)}const s=document.createElement("div");s.style.cssText=`position: absolute; inset: 0; background: center / cover no-repeat url("${n}"); clip-path: polygon(${i.join(",")}); pointer-events: none;`,j.appendChild(s)}),$||x.forEach(e=>{const t=document.createElement("div");t.style.cssText=`position: absolute; left: 50%; top: 0; width: 1.5px; height: 50%; background: rgba(255,255,255,0.55); transform-origin: bottom center; transform: translateX(-50%) rotate(${e}deg); pointer-events: none;`,j.appendChild(t)});$||c.forEach((e,t)=>{const n=y(t),i=r[t]&&"string"==typeof r[t].icon?r[t].icon:"",o=.6*(100*Math.sin(f[t]*Math.PI/180/2)),s=56/Math.max(4,.62*e.length+(i?1.6:0)),a=Math.max(7,Math.min(13,Math.floor(Math.min(o,s)))),c=n>180&&n<360,d=c?90:-90,l=document.createElement("div");if(l.style.cssText=`position: absolute; left: 50%; top: 50%; width: 56px; transform: translate(-50%, -50%) rotate(${n}deg) translateY(-50px) rotate(${d}deg); display: flex; flex-direction: ${c?"row-reverse":"row"}; align-items: center; justify-content: center; gap: 4px; white-space: nowrap; pointer-events: none;`,i)if(M(i)){const e=document.createElement("img");e.src=i,e.alt="",e.style.cssText=`width: ${a+6}px; height: ${a+6}px; object-fit: contain; flex: 0 0 auto; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.5));`,l.appendChild(e)}else{const e=document.createElement("span");e.textContent=i,e.style.cssText=`font-size: ${a+4}px; line-height: 1; flex: 0 0 auto;`,l.appendChild(e)}const p=document.createElement("span");p.textContent=e,p.style.cssText=`white-space: nowrap; line-height: 1.05; font-size: ${a}px; font-weight: 900; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif; letter-spacing: 0.2px; text-transform: uppercase; color: #fff; text-shadow: 0 1px 3px rgba(0,0,0,0.65), 0 0 1px rgba(0,0,0,0.9); -webkit-font-smoothing: antialiased;`,l.appendChild(p),j.appendChild(l)});const X=document.createElement("div");X.style.cssText="position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 2; background: radial-gradient(circle at 50% 22%, rgba(255,255,255,0.30), rgba(255,255,255,0.04) 42%, transparent 62%);";let K=null;if("shimmer"===_){const e=document.createElement("div");e.style.cssText="position: absolute; inset: 0; border-radius: 50%; overflow: hidden; pointer-events: none; z-index: 3;";const t=document.createElement("div");t.style.cssText="position: absolute; top: -25%; left: 0; width: 36%; height: 150%; transform: skewX(-12deg); background: linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent); animation: aegisSpinSheen 2.8s ease-in-out infinite; animation-delay: 0.5s;",e.appendChild(t),K=e}const Y=document.createElement("div");if(Y.style.cssText="position: absolute; left: 50%; top: 50%; width: 40px; height: 40px; transform: translate(-50%, -50%); border-radius: 50%; background: radial-gradient(circle at 35% 30%, #ffffff, #e9edf5); border: 3px solid #fff; box-shadow: 0 3px 8px rgba(0,0,0,0.30); z-index: 4; overflow: hidden; display: flex; align-items: center; justify-content: center;",T){Y.style.border="none",Y.style.background="transparent";const e=document.createElement("img");e.src=T,e.alt="",e.style.cssText="width: 100%; height: 100%; object-fit: cover; border-radius: 50%; display: block;",Y.appendChild(e)}else{const e=document.createElement("div");e.style.cssText=`width: 11px; height: 11px; border-radius: 50%; background: ${n};`,Y.appendChild(e)}B.appendChild(U),B.appendChild(j),B.appendChild(X),K&&B.appendChild(K),B.appendChild(Y),O.appendChild(B),a.style.position||(a.style.position="relative");const Q=document.createElement("div");if(Q.style.cssText="font-size: 14px; font-weight: 800; min-height: 0; text-align: center; letter-spacing: 0.2px;",!1!==t.spin_sound_enabled){const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Toggle sound"),e.textContent=E?"🔊":"🔇",e.style.cssText="position: absolute; top: 10px; left: 12px; background: transparent; border: none; font-size: 15px; cursor: pointer; opacity: 0.65; z-index: 6; line-height: 1;",e.addEventListener("click",()=>{E=!E,e.textContent=E?"🔊":"🔇"}),a.appendChild(e)}const G=document.createElement("button");G.textContent=e.button_text||"Spin the wheel",G.style.cssText=`padding: 9px 22px; border-radius: 999px; border: none; background: ${i}; color: ${n}; font-size: 13px; font-weight: 700; letter-spacing: 0.2px; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.20); transition: transform 0.15s, box-shadow 0.15s; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;`,G.addEventListener("mouseenter",()=>{G.disabled||(G.style.transform="translateY(-1px)",G.style.boxShadow="0 9px 22px rgba(0,0,0,0.28)")}),G.addEventListener("mouseleave",()=>{G.disabled||(G.style.transform="translateY(0)",G.style.boxShadow="0 6px 16px rgba(0,0,0,0.22)")});let J=!1,Z=!1,ee=-1;const te=()=>{try{null==K||K.remove()}catch{}j.style.animation=""};let ne=0,ie=0,oe=0,se=0;const ae=()=>{oe+=.18*-ie,oe*=.7,ie+=oe,Math.abs(ie)>.06||Math.abs(oe)>.06?(U.style.transform=`${A} rotate(${ie.toFixed(2)}deg)`,se=requestAnimationFrame(ae)):(ie=0,oe=0,U.style.transform=`${A} rotate(0deg)`,se=0)},re=e=>{const t=(e=>{const t=(e%360+360)%360;for(let n=0;n<d;n++)if(t>=x[n]&&t<x[n]+f[n])return n;return d-1})(((360-e%360)%360+360)%360);t!==ee&&(ee=t,N(1180,26,"square",.035),F(5),oe+=Math.min(9,1.4+.5*ne),se||(se=requestAnimationFrame(ae)))},ce=(e,t,n)=>{const i=R,o=e-i,s=L();let a=i;const r=()=>{const c=Math.min(1,(L()-s)/t);R=i+o*(e=>1-Math.pow(1-e,3))(c),ne=Math.abs(R-a),a=R,j.style.transform=`rotate(${R}deg)`,re(R),c<1?requestAnimationFrame(r):(j.style.transition="transform 0.18s ease-out",j.style.transform=`rotate(${e-2}deg)`,window.setTimeout(()=>{j.style.transform=`rotate(${e}deg)`,R=e,window.setTimeout(()=>{j.style.transition="",n()},180)},70))};requestAnimationFrame(r)},de=t=>{const o=document.createElement("div");o.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; padding: 22px; text-align: center; background: ${n}; color: ${i}; border-radius: inherit; animation: aegisSpinRevealIn 0.4s cubic-bezier(0.16,0.86,0.28,1); z-index: 7;`;const s=document.createElement("div");s.textContent="🎉 You won",s.style.cssText="font-size: 13px; font-weight: 700; letter-spacing: 0.3px; opacity: 0.8;";const r=document.createElement("div");if(r.textContent=t.label,r.style.cssText="font-size: 24px; font-weight: 900; letter-spacing: -0.02em; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;",o.appendChild(s),o.appendChild(r),t.code){const e=document.createElement("button");e.type="button",e.textContent=`${t.code} ⧉`,e.style.cssText=`margin-top: 4px; padding: 9px 16px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 14px; letter-spacing: 1px; cursor: pointer;`,e.addEventListener("click",()=>{var n;try{null==(n=navigator.clipboard)||n.writeText(t.code),e.textContent="Copied ✓"}catch{}}),o.appendChild(e)}else if("freebie"===t.kind){const e=document.createElement("div");e.textContent="🎟️ Show this screen to claim",e.style.cssText="margin-top: 2px; font-size: 12.5px; font-weight: 600; opacity: 0.85;",o.appendChild(e)}const c=document.createElement("button");c.type="button",c.textContent="Awesome!",c.style.cssText=`margin-top: 6px; padding: 11px 28px; border-radius: 999px; border: none; background: ${i}; color: ${n}; font-weight: 800; font-size: 14px; cursor: pointer;`,c.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),o.style.transition="opacity 0.25s ease",o.style.opacity="0",window.setTimeout(()=>o.remove(),250)}),o.appendChild(c),a.appendChild(o)},le=e=>{if(Z=!0,e.won?([523,659,784,1047].forEach((e,t)=>window.setTimeout(()=>N(e,170,"sine",.07),105*t)),F([0,35,25,35,25,90]),this._playReaction(a,"celebrate",void 0,t)):(N(320,220,"sine",.05),F(18),this._playReaction(a,"empathize",void 0,t)),"takeover"===C&&e.won)de(e);else if(e.label&&e.code){Q.textContent="";const t=document.createElement("span");t.textContent=`${e.label} — `;const n=document.createElement("button");n.type="button",n.textContent=`${e.code} ⧉`,n.style.cssText=`padding: 2px 8px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 12px; letter-spacing: 0.5px; cursor: pointer;`,n.addEventListener("click",()=>{var t;try{null==(t=navigator.clipboard)||t.writeText(e.code),n.textContent="Copied ✓"}catch{}}),Q.appendChild(t),Q.appendChild(n)}else Q.textContent=e.label||"Thanks for playing!";G.style.transition="opacity 0.3s ease",G.style.opacity="0",G.style.pointerEvents="none",window.setTimeout(()=>{G.style.display="none"},320)},pe=t=>{if(J||Z)return;J=!0,te(),G.disabled=!0,G.style.opacity="0.6",G.style.transform="scale(0.97)",Q.textContent="",this.trackEvent(e.id,"clicked"),D();const n=Math.min(2.4,Math.max(.25,t||.6)),i=Math.round(3+2*n),o=Math.floor(Math.random()*d),s=.5+.35*n;let a=!0,p=!1,h=L();const u=()=>{if(!a)return;const e=L(),t=s*(e-h);h=e,R+=t,ne=t,j.style.transform=`rotate(${R}deg)`,re(R),requestAnimationFrame(u)};requestAnimationFrame(u);const g=(e,t)=>{if(p)return;p=!0,a=!1;const n=y(e);let o=R-(R%360+360)%360+((360-n)%360+360)%360+360*i;o<=R+360&&(o+=360);const r=3*(o-R)/Math.max(.05,s),c=Math.min(4200,Math.max(2300,r));ce(o,c,()=>{J=!1,le(t)})};this.submitWidgetResponse(e,"spin",{segment_index:o}).then(e=>{const t=e&&e.prize?e.prize:null;let n=o;t&&"number"==typeof t.segment_index&&(n=t.segment_index%d);const i=t&&"string"==typeof t.prize_label?t.prize_label:c[n]||"",s=t&&"string"==typeof t.coupon_code?t.coupon_code:"",a=t&&"string"==typeof t.prize_type?t.prize_type.toLowerCase():r[n]&&"string"==typeof r[n].prize_type?String(r[n].prize_type).toLowerCase():"",p=t?"no_prize"===String(t.prize_type||"").toLowerCase():l(n);g(n,{label:i,code:s,won:!!i&&!p,kind:a})}).catch(()=>{}),window.setTimeout(()=>{if(p)return;const e=(()=>{for(let e=0;e<d;e++)if(l(e))return e;return o})();g(e,{label:c[e]||"",code:"",won:!1,kind:r[e]&&"string"==typeof r[e].prize_type?String(r[e].prize_type).toLowerCase():"no_prize"})},8e3)};if("button"===w||"both"===w?G.addEventListener("click",()=>pe(.7)):G.style.display="none","drag"===w||"both"===w){let e=!1,t=0,n=0,i=0,o=0,s=0;const a=e=>{const t=j.getBoundingClientRect(),n=t.left+t.width/2,i=t.top+t.height/2;return 180*Math.atan2(e.clientY-i,e.clientX-n)/Math.PI};j.addEventListener("pointerdown",r=>{if(!J&&!Z){e=!0,t=a(r),n=R,i=t,o=L(),s=0,j.style.cursor="grabbing",te();try{j.setPointerCapture(r.pointerId)}catch{}}}),j.addEventListener("pointermove",r=>{if(!e)return;const c=a(r),d=R;R=n+(c-t),ne=Math.abs(R-d),j.style.transform=`rotate(${R}deg)`,re(R);const l=L(),p=l-o;if(p>0){let e=c-i;e>180&&(e-=360),e<-180&&(e+=360),s=e/p,i=c,o=l}});const r=t=>{if(!e)return;e=!1,j.style.cursor="grab";try{j.releasePointerCapture(t.pointerId)}catch{}const n=Math.abs(s);n>.15&&pe(n)};j.addEventListener("pointerup",r),j.addEventListener("pointercancel",r)}if(O.appendChild(Q),O.appendChild(G),a.appendChild(O),o.appendChild(a),p){te();const e=String(p.prize_type||"").toLowerCase();le({label:String(p.label||""),code:String(p.coupon_code||""),won:"no_prize"!==e,kind:e})}return!0}renderQuickPollSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-poll-card",e.id,n,i,s.radius),r=Array.isArray(t.poll_options)?t.poll_options.filter(e=>"string"==typeof e):[],c=document.createElement("div");if(c.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 6px;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,c.appendChild(t)}const d=[];return r.forEach((n,o)=>{const l=document.createElement("button");l.style.cssText=`position: relative; overflow: hidden; text-align: left; padding: 8px 10px; border-radius: ${s.btnRadius??8}px; border: 1px solid ${i}40; background: transparent; color: ${i}; font-size: 12px; cursor: pointer; transition: border-color 0.2s ease;`;const p=document.createElement("span");p.style.cssText="position: relative; z-index: 1; display: flex; justify-content: space-between; gap: 8px;";const h=document.createElement("span");h.textContent=n;const u=document.createElement("span");u.style.cssText="font-weight: 700; opacity: 0; transition: opacity 0.3s ease;",p.appendChild(h),p.appendChild(u),l.appendChild(p),l.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),d.forEach(e=>e.disabled=!0),this._paintPollResult(d,r,o,null,i),this.addAnimationStyles(),this.submitWidgetResponse(e,"poll",{option_index:o,option_label:n}).then(e=>{const t=this._readPollDistribution(e,r.length);t&&this._paintPollResult(d,r,o,t,i)}),this._playReaction(a,"affirm","check.json",t)}),d.push(l),c.appendChild(l)}),a.appendChild(c),o.appendChild(a),!0}_readPollDistribution(e,t){if(!e)return null;const n=e.results??e.distribution??e.tallies;if(!Array.isArray(n)||n.length!==t)return null;const i=n.map(e=>"number"==typeof e&&isFinite(e)&&e>=0?e:0);return i.some(e=>e>0)?i:null}_paintPollResult(e,t,n,i,o){const s=i&&i.reduce((e,t)=>e+t,0)||1;e.forEach((e,t)=>{const a=i?Math.round(i[t]/s*100):t===n?100:0;let r=e.querySelector(".aegis-poll-fill");r||(r=document.createElement("span"),r.className="aegis-poll-fill",r.style.cssText=`position: absolute; inset: 0 auto 0 0; z-index: 0; background: ${t===n?o:o+"22"}; opacity: ${t===n?"0.16":"0.1"};`,e.insertBefore(r,e.firstChild)),r.style.setProperty("--pct",`${a}%`),r.style.animation="aegisPollFill 0.5s ease forwards",t===n&&(e.style.borderColor=o);const c=e.querySelector("span > span:last-child");c&&i?(c.textContent=`${a}%`,c.style.opacity="0.8"):c&&t===n&&(c.textContent="✓",c.style.opacity="0.8")})}renderCarouselCardsSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-carousel-card",e.id,n,i,s.radius),r=Array.isArray(t.cards)?t.cards:[];if(e.title){const t=document.createElement("div");t.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px 0; font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,a.appendChild(t)}const c=document.createElement("div");return c.style.cssText=`display: flex; gap: 8px; overflow-x: auto; scroll-snap-type: x mandatory; padding: ${s.padY??12}px ${s.padX??12}px;`,r.forEach((t,o)=>{const a=document.createElement("div"),r="string"==typeof t.cta_url?t.cta_url:"";a.style.cssText=`flex: 0 0 auto; width: 150px; scroll-snap-align: start; background: ${i}0a; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; gap: 6px; cursor: ${r?"pointer":"default"};`;const d="string"==typeof t.video_url?t.video_url:"",l="string"==typeof t.image_url?t.image_url:"";if(d){const e=document.createElement("video");e.src=d,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="width: 100%; height: 90px; object-fit: cover; display: block;",a.appendChild(e)}else if(l){const e=document.createElement("img");e.src=l,e.alt="",e.loading="lazy",e.style.cssText="width: 100%; height: 90px; object-fit: cover; display: block;",a.appendChild(e)}const p=document.createElement("div");if(p.style.cssText="padding: 0 8px 8px; display: flex; flex-direction: column; gap: 4px;","string"==typeof t.title&&t.title){const e=document.createElement("div");e.style.cssText="font-size: 12px; font-weight: 600; line-height: 1.3;",e.textContent=t.title,p.appendChild(e)}if("string"==typeof t.body&&t.body){const e=document.createElement("div");e.style.cssText="font-size: 10.5px; opacity: 0.72; line-height: 1.3;",e.textContent=t.body,p.appendChild(e)}const h="string"==typeof t.cta_text?t.cta_text:"";if(h&&r){const t=document.createElement("button");t.textContent=h,t.style.cssText=`margin-top: auto; align-self: flex-start; background: ${i}; color: ${n}; border: none; padding: 5px 10px; border-radius: ${s.btnRadius??999}px; font-size: 11px; font-weight: 600; cursor: pointer;`;const c=t=>{t.stopPropagation(),this.trackEvent(e.id,"clicked",{stepId:`card_${o}`}),window.open(r,"_blank","noopener")};t.addEventListener("click",c),a.addEventListener("click",c),p.appendChild(t)}a.appendChild(p),c.appendChild(a)}),a.appendChild(c),o.appendChild(a),!0}renderCountdownSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-countdown-card",e.id,n,i,s.radius),r=document.createElement("div");if(r.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 8px; align-items: center; text-align: center;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,r.appendChild(t)}const c=document.createElement("div");c.style.cssText="font-size: 11px; opacity: 0.75;",c.textContent=t.countdown_label||"Ends in",r.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 6px; justify-content: center;";const l=()=>{const e=document.createElement("span");return e.style.cssText=`padding: 6px 9px; border-radius: 8px; font-size: 18px; font-weight: 700; font-family: ui-monospace, monospace; background: ${i}1a; transition: background 0.3s ease, color 0.3s ease;`,e.textContent="00",e},p=l(),h=l(),u=l();[p,":",h,":",u].forEach(e=>{if(":"===e){const e=document.createElement("span");e.style.cssText="font-size: 18px; font-weight: 700; align-self: center;",e.textContent=":",d.appendChild(e)}else d.appendChild(e)}),r.appendChild(d);const g=t.countdown_target,m=g?new Date(g).getTime():Date.now()+6e5;let f=!1;const x=()=>{if(!document.body.contains(a))return;const n=Math.max(0,m-Date.now()),i=Math.floor(n/36e5),o=Math.floor(n%36e5/6e4),s=Math.floor(n%6e4/1e3);p.textContent=String(i).padStart(2,"0"),h.textContent=String(o).padStart(2,"0"),u.textContent=String(s).padStart(2,"0"),n>0&&n<=6e4&&!f&&(f=!0,[p,h,u].forEach(e=>{e.style.boxShadow="0 0 0 2px #ef4444",e.style.animation="aegisUrgencyPulse 1s ease-in-out infinite"})),n>0?requestAnimationFrame(x):y||(y=!0,this.submitWidgetResponse(e,"countdown",{state:"expired"}),this._playReaction(a,"celebrate","alarm-clock.json",t))};let y=!1;if(this.addAnimationStyles(),x(),e.body){const t=document.createElement("div");t.style.cssText="font-size: 11px; opacity: 0.8;",t.textContent=e.body,r.appendChild(t)}if(e.button_text){const t=document.createElement("button");t.textContent=e.button_text,t.style.cssText=`margin-top: 2px; background: ${i}; color: ${n}; border: none; padding: 7px 14px; border-radius: ${s.btnRadius??999}px; font-size: 12px; font-weight: 600; cursor: pointer;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),this.submitWidgetResponse(e,"countdown",{state:"engaged"});const t=e.action_url;t&&window.open(t,"_blank","noopener")}),r.appendChild(t)}return a.appendChild(r),o.appendChild(a),!0}_scratchFoilPalette(e){const t=(e||"").trim().replace(/^#/,"");if(!/^[0-9a-fA-F]{6}$/.test(t))return{g0:"#d7dbe2",g1:"#b4bac4",g2:"#c9cdd6",ink:"#6b7280"};const n=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),o=parseInt(t.slice(4,6),16),s=e=>{const t=t=>Math.round(t+(255-t)*e);return`rgb(${t(n)}, ${t(i)}, ${t(o)})`},a=(.299*n+.587*i+.114*o)/255;return{g0:s(.34),g1:`#${t}`,g2:s(.18),ink:a>.62?"#5b6270":"rgba(255,255,255,0.92)"}}renderScratchCardSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-scratch-card",e.id,n,i,s.radius);a.style.position||(a.style.position="relative");const r=(e,n)=>"number"==typeof t[e]?t[e]:n,c=e=>"string"==typeof t[e]?t[e]:"",d=Math.min(1,Math.max(.1,r("scratch_threshold_pct",.5))),l=Math.min(60,Math.max(8,r("scratch_brush_radius",22))),p=!1!==t.scratch_idle_shimmer,h=c("scratch_win_reveal")||"inline",u=!1!==t.scratch_haptics_enabled;let g=!1!==t.scratch_sound_enabled;const m=c("reveal_image_url"),f=c("scratch_foil_image_url"),x=this._scratchFoilPalette(c("scratch_foil_color")),y=Array.isArray(t.prize_pool)?t.prize_pool:[],b=e=>/^https?:\/\//i.test(e),v=y.find(e=>"string"==typeof e.prize_type&&"no_prize"!==e.prize_type.toLowerCase())||null;if("undefined"!=typeof document&&!document.getElementById("aegis-scratch-kf")){const e=document.createElement("style");e.id="aegis-scratch-kf",e.textContent="@keyframes aegisScratchSheen{0%{transform:translateX(-140%) skewX(-12deg)}100%{transform:translateX(260%) skewX(-12deg)}}@keyframes aegisScratchPop{0%{opacity:0;transform:scale(0.8)}100%{opacity:1;transform:scale(1)}}@keyframes aegisScratchDust{0%{opacity:0.9;transform:translate(0,0) scale(1)}100%{opacity:0;transform:translate(var(--dx),var(--dy)) scale(0.4)}}",document.head.appendChild(e)}let w=null;const _=()=>{if(!g)return null;try{if(!w){const e=window.AudioContext||window.webkitAudioContext;if(!e)return null;w=new e}return"suspended"===w.state&&w.resume(),w}catch{return null}};let C=0;const k=(e,t)=>{const n=_();n&&e.forEach((e,i)=>window.setTimeout(()=>{const i=n.createOscillator(),o=n.createGain();i.type="sine",i.frequency.value=e,o.gain.setValueAtTime(t,n.currentTime),o.gain.exponentialRampToValueAtTime(1e-4,n.currentTime+.22),i.connect(o),o.connect(n.destination),i.start(),i.stop(n.currentTime+.22)},100*i))},E=document.createElement("div");if(E.style.cssText=`padding: ${s.padY??12}px ${s.padX??12}px; display: flex; flex-direction: column; gap: 8px; align-items: center; text-align: center;`,e.title){const t=document.createElement("div");t.style.cssText=`font-size: 13px; font-weight: ${s.weight??"700"};`,t.textContent=e.title,E.appendChild(t)}const S=document.createElement("div");if(S.style.cssText="font-size: 11px; opacity: 0.7;",S.textContent=c("scratch_hint")||"Scratch to reveal your prize",E.appendChild(S),!1!==t.scratch_sound_enabled){const e=document.createElement("button");e.type="button",e.setAttribute("aria-label","Toggle sound"),e.textContent=g?"🔊":"🔇",e.style.cssText="position: absolute; top: 10px; left: 12px; background: transparent; border: none; font-size: 15px; cursor: pointer; opacity: 0.65; z-index: 6; line-height: 1;",e.addEventListener("click",()=>{g=!g,e.textContent=g?"🔊":"🔇"}),a.appendChild(e)}let T=!1,$=!1,I=0;const z=document.createElement("div");z.style.cssText="position: relative; width: 280px; max-width: 100%; aspect-ratio: 3 / 2; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 14px rgba(0,0,0,0.12);";const A=document.createElement("div");A.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 12px; text-align: center; font-size: 20px; font-weight: 800; color: ${i}; `+(m?`background: ${i}0f center/cover no-repeat;`:`background: ${i}0f;`),m&&(A.style.backgroundImage=`url("${m.replace(/"/g,"%22")}")`);const M=document.createElement("div"),L=v&&"string"==typeof v.icon?v.icon:"",R=v&&"string"==typeof v.label?v.label:"";M.textContent=R?L&&!b(L)?`${L} ${R}`:R:"🎁",A.appendChild(M),z.appendChild(A);const P=document.createElement("canvas");P.width=300,P.height=200,P.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; cursor: grab; touch-action: none;",z.appendChild(P);const D=P.getContext("2d"),N=P.width,F=P.height,O=e=>{if(!D)return;D.globalCompositeOperation="source-over";const t=D.createLinearGradient(0,0,N,F);if(t.addColorStop(0,x.g0),t.addColorStop(.5,x.g1),t.addColorStop(1,x.g2),D.fillStyle=t,D.fillRect(0,0,N,F),D.textAlign="center",D.textBaseline="middle",e)D.globalAlpha=.6,D.drawImage(e,(N-e.width)/2,.42*F-e.height/2,e.width,e.height),D.globalAlpha=1,D.fillStyle=x.ink,D.font="700 12px system-ui, sans-serif",D.fillText("SCRATCH HERE",N/2,.84*F);else{D.globalAlpha=.22,D.fillStyle=x.ink,D.font="12px system-ui, sans-serif";for(let e=18;e<F;e+=30){for(let t=16+((e/30|0)%2?16:0);t<N;t+=32)D.fillText("✦",t,e)}D.globalAlpha=1,D.fillStyle=x.ink,D.font="700 13px system-ui, sans-serif",D.fillText("SCRATCH HERE",N/2,F/2)}D.globalCompositeOperation="destination-out"};if(D&&(O(null),f)){const e=new Image;e.crossOrigin="anonymous",e.onload=()=>{if(T||!D)return;const t=.52*N,n=.42*F,i=e.width/e.height||1;let o=t,s=t/i;s>n&&(s=n,o=n*i);const a=document.createElement("canvas");a.width=Math.max(1,Math.round(o)),a.height=Math.max(1,Math.round(s));const r=a.getContext("2d");r&&(r.drawImage(e,0,0,a.width,a.height),r.globalCompositeOperation="source-in",r.fillStyle=x.ink,r.fillRect(0,0,a.width,a.height),O(a))},e.onerror=()=>{},e.src=f}const B=new Uint8Array(600);let U=0;let j=null;if(p){const e=document.createElement("div");e.style.cssText="position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 2;";const t=document.createElement("div");t.style.cssText="position: absolute; top: -20%; left: 0; width: 34%; height: 140%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.55), transparent); animation: aegisScratchSheen 2.6s ease-in-out infinite; animation-delay: 0.4s;",e.appendChild(t),j=e,z.appendChild(e)}const W=document.createElement("div");W.style.cssText="position: absolute; inset: 0; pointer-events: none; z-index: 3;",z.appendChild(W);const q=e=>{const t=e&&e.prize||null,n=t&&"number"==typeof t.segment_index?t.segment_index:-1;if(n>=0&&y[n])return y[n];const i=this._extractPrizeLabel(e);return y.find(e=>e.label===i)||v||null},H=(e,o,s)=>{if("takeover"===h){const t=document.createElement("div");if(t.style.cssText=`position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 22px; text-align: center; background: ${n}; color: ${i}; border-radius: inherit; animation: aegisScratchPop 0.4s cubic-bezier(0.16,0.86,0.28,1); z-index: 7;`,s){const e=document.createElement(b(s)?"img":"div");b(s)?(e.src=s,e.style.cssText="width: 42px; height: 42px; object-fit: contain;"):(e.textContent=s,e.style.cssText="font-size: 36px; line-height: 1;"),t.appendChild(e)}const r=document.createElement("div");r.textContent="You won",r.style.cssText="font-size: 12px; font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; opacity: 0.7;";const c=document.createElement("div");if(c.textContent=e,c.style.cssText="font-size: 22px; font-weight: 900; letter-spacing: -0.02em; font-family: 'Inter Tight', Inter, system-ui, sans-serif;",t.appendChild(r),t.appendChild(c),o){const e=document.createElement("button");e.type="button",e.textContent=`${o} ⧉`,e.style.cssText=`margin-top: 4px; padding: 8px 14px; border-radius: 999px; border: 1.5px dashed ${i}66; background: transparent; color: ${i}; font-weight: 800; font-size: 13px; letter-spacing: 1px; cursor: pointer;`,e.addEventListener("click",()=>{var t;try{null==(t=navigator.clipboard)||t.writeText(o),e.textContent="Copied ✓"}catch{}}),t.appendChild(e)}a.appendChild(t);try{this._fireConfetti(t)}catch{}}else{if(M.textContent=s&&!b(s)?`${s} ${e}`:e,o){const e=document.createElement("div");e.style.cssText=`margin-top: 6px; font-family: ui-monospace, monospace; font-size: 12px; font-weight: 700; padding: 4px 8px; border-radius: 6px; background: ${i}14; color: ${i};`,e.textContent=o,E.appendChild(e)}this._playReaction(E,"celebrate","gift.json",t)}},V=()=>{if(!T){T=!0;try{null==j||j.remove()}catch{}P.style.transition="opacity 0.4s ease",P.style.opacity="0",this.addAnimationStyles(),this.trackEvent(e.id,"clicked"),this.submitWidgetResponse(e,"scratch",{state:"revealed"}).then(e=>{var n;const i=e&&(!0===e.won||!0===(null==(n=e.reward)?void 0:n.granted)),o=v&&"string"==typeof v.label?v.label:"",s=this._extractPrizeLabel(e)||o||t.scratch_prize_label||"You won!",a=this._extractCouponCode(e)||"",r=q(e),c=r&&"string"==typeof r.icon?r.icon:"",d=r&&"string"==typeof r.prize_type?r.prize_type.toLowerCase():"";if(!1===i)(()=>{var e;if(k([392,330],.05),u)try{null==(e=navigator.vibrate)||e.call(navigator,18)}catch{}})(),M.textContent="Better luck next time",this._playReaction(E,"empathize",void 0,t);else if((()=>{var e;if(k([523,659,784,1047],.07),u)try{null==(e=navigator.vibrate)||e.call(navigator,[0,35,25,60])}catch{}})(),H(s,a,c),!a&&"freebie"===d&&"takeover"!==h){const e=document.createElement("div");e.textContent="🎟️ Show this screen to claim",e.style.cssText="margin-top: 4px; font-size: 12px; font-weight: 600; opacity: 0.85;",E.appendChild(e)}})}},X=(e,t)=>{if(!T){if(!D)return V();I+=1,D.beginPath(),D.arc(e,t,l,0,2*Math.PI),D.fill(),((e,t)=>{const n=N/30,i=F/20,o=l,s=Math.max(0,Math.floor((e-o)/n)),a=Math.min(29,Math.floor((e+o)/n)),r=Math.max(0,Math.floor((t-o)/i)),c=Math.min(19,Math.floor((t+o)/i));for(let d=r;d<=c;d++)for(let r=s;r<=a;r++){const s=30*d+r;if(B[s])continue;const a=(r+.5)*n-e,c=(d+.5)*i-t;a*a+c*c<=o*o&&(B[s]=1,U++)}})(e,t),I%2==0&&((()=>{var e;const t=_(),n="undefined"!=typeof performance?performance.now():Date.now();if(t&&n-C>45){C=n;const e=.05,i=t.createBuffer(1,Math.floor(t.sampleRate*e),t.sampleRate),o=i.getChannelData(0);for(let t=0;t<o.length;t++)o[t]=43758.5453*Math.sin(12.9898*t)%1*2-1;const s=t.createBufferSource();s.buffer=i;const a=t.createBiquadFilter();a.type="highpass",a.frequency.value=2200;const r=t.createGain();r.gain.setValueAtTime(.05,t.currentTime),r.gain.exponentialRampToValueAtTime(1e-4,t.currentTime+e),s.connect(a),a.connect(r),r.connect(t.destination),s.start()}if(u)try{null==(e=navigator.vibrate)||e.call(navigator,4)}catch{}})(),((e,t)=>{const n=e/P.width*100,i=t/P.height*100;for(let o=0;o<2;o++){const e=document.createElement("div"),t=(53*o+17*I)%30-15,s=8+13*I%14;e.style.cssText=`position: absolute; left: ${n}%; top: ${i}%; width: 3px; height: 3px; border-radius: 50%; background: #b4bac4; --dx:${t}px; --dy:${s}px; animation: aegisScratchDust 0.5s ease-out forwards;`,W.appendChild(e),window.setTimeout(()=>e.remove(),520)}})(e,t)),U/600>d&&V()}},K=e=>{const t=P.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*P.width,y:(e.clientY-t.top)/t.height*P.height}};P.addEventListener("pointerdown",e=>{if(T)return;$=!0;try{P.setPointerCapture(e.pointerId)}catch{}const t=K(e);X(t.x,t.y)}),P.addEventListener("pointermove",e=>{if(!$)return;const t=K(e);X(t.x,t.y)});const Y=()=>{$=!1};return P.addEventListener("pointerup",Y),P.addEventListener("pointercancel",Y),P.addEventListener("pointerleave",Y),E.appendChild(z),a.appendChild(E),o.appendChild(a),!0}_extractPrizeLabel(e){var t;if(!e)return null;const n=e.reward,i=[e.prize_label,e.label,null==n?void 0:n.label,null==(t=e.prize)?void 0:t.prize_label];for(const o of i)if("string"==typeof o&&o)return o;return null}_extractCouponCode(e){if(!e)return null;const t=e.reward,n=[e.coupon_code,null==t?void 0:t.coupon_code];for(const i of n)if("string"==typeof i&&i)return i;return null}_submitTokenResponse(e,t){e&&fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({response:t}),keepalive:!0}).catch(e=>{this.log(`token submit failed: ${e}`,"warn")})}_slotStyle(e){const t=e.interactive_config||{},n=(e,t,n)=>{if(null==e||""===e)return;const i=Number(e);return Number.isFinite(i)?Math.max(t,Math.min(n,i)):void 0},i=null!=t.heading_font_weight?String(t.heading_font_weight):"",o=this._surfacePalette(e);return{bg:o.bg,text:o.text,radius:n(t.border_radius,0,24)??12,padX:n(t.padding_x,0,32),padY:n(t.padding_y,0,24),btnRadius:n(t.button_radius,0,999),weight:["400","500","600","700"].includes(i)?i:void 0}}_wrapInSlotCard(e,t,n,i,o=12){const s=document.createElement("div");return s.className=e,s.setAttribute("data-campaign-id",t),s.style.cssText=`\n width: 100%; border-radius: ${o}px; overflow: hidden;\n background: ${n}; color: ${i};\n box-shadow: 0 4px 12px rgba(0,0,0,0.06);\n `,s}_appendHeaderImage(e,t){const n=t.header_image_url;if(!n)return;const i=this.sanitizeUrl(n);if(!i)return;const o=document.createElement("img");o.src=i,o.alt="",o.style.cssText="display: block; max-height: 72px; max-width: 60%; margin: 0 auto 14px; object-fit: contain;",e.appendChild(o)}_buildStarRatingBody(e,t,n,i,o,s){const a="overlay"===i,r=a?"24px":`${(null==s?void 0:s.padY)??20}px ${(null==s?void 0:s.padX)??20}px`,c=a?"18px":"16px",d=a?"700":(null==s?void 0:s.weight)??"600",l=a?"16px":"12px",p=a?"32px":"28px",h=a?"16px":"0",u=a?"1.2":"1.15",g=document.createElement("div");g.style.cssText=`padding: ${r}; text-align: center;`,this._appendHeaderImage(g,t);const m=document.createElement("div");m.style.cssText=`font-size: ${c}; font-weight: ${d}; margin-bottom: ${l};`,m.textContent=e.title||"Rate your experience",g.appendChild(m);const f=document.createElement("div");f.style.cssText="display: flex; gap: 8px; justify-content: center;"+("0"!==h?` margin-bottom: ${h};`:"");const x=t.rating_scale||5,y=t.rating_icon||"star",b=["😞","🙁","😐","🙂","😀","🤩"],v=(e,t)=>"emoji"===y?(e=>{const t=x<=1?b.length-1:Math.round(e/(x-1)*(b.length-1));return b[Math.max(0,Math.min(b.length-1,t))]})(t):"heart"===y?e?"♥":"♡":e?"★":"☆",w=Array.isArray(t.rating_labels)?t.rating_labels:null;let _=null;w&&w.length>0&&(_=document.createElement("div"),_.style.cssText=`font-size: 12px; opacity: 0.7; margin-top: 8px; min-height: 16px; color: ${n||"inherit"};`);const C=[];let k=0;const E=e=>{if(C.forEach((t,i)=>{const o=i<e;t.textContent=v(o,i),"emoji"===y?(t.style.opacity=o||0===e?"1":"0.3",t.style.color="inherit"):t.style.color=o?"#fbbf24":n||"inherit",t.style.transform=o&&i===e-1?`scale(${u})`:"scale(1)"}),_&&w){const t=e>0?w[Math.min(e-1,w.length-1)]:"";_.textContent=t||""}};for(let S=1;S<=x;S++){const i=document.createElement("span");i.style.cssText=`font-size: ${p}; cursor: pointer; transition: transform 0.12s, color 0.12s, opacity 0.12s; user-select: none;`+("emoji"!==y&&n?` color: ${n};`:"")+("emoji"===y?" opacity: 0.3;":""),i.setAttribute("role","button"),i.setAttribute("aria-label",`${S} ${"heart"===y?"heart":"star"}${S>1?"s":""}`),i.textContent=v(!1,S-1);const s=S;i.addEventListener("mouseenter",()=>E(s)),i.addEventListener("mouseleave",()=>E(k)),i.addEventListener("click",()=>{k=s,E(k),i.style.transform="scale(1.28)",setTimeout(()=>E(k),160),this.trackEvent(e.id,"clicked"),this._onStarRatingPicked(e,t,g,s,x,n,a,o)}),C.push(i),f.appendChild(i)}return g.appendChild(f),_&&g.appendChild(_),g}_onStarRatingPicked(e,t,n,i,o,s,a,r){r&&this._submitTokenResponse(r,{sub_type:"star_rating",value:i});const c=a&&!1!==t.rating_followup_enabled,d=i>=(t.rating_followup_threshold||Math.ceil(.8*o));if(a)return c?void(d?(this.submitWidgetResponse(e,"rating",{stars:i}),this._renderRatingThankYou(e,t,n,!0)):this._renderRatingLowFollowup(e,t,n,i,s)):(this.submitWidgetResponse(e,"rating",{stars:i}),void this._renderRatingThankYou(e,t,n,d));d?this._playReaction(n,"affirm",void 0,t):i<=Math.max(1,Math.floor(.4*o))?this._playReaction(n,"empathize",void 0,t):this._playReaction(n,"acknowledge",void 0,t)}_renderRatingThankYou(e,t,n,i){for(;n.firstChild;)n.removeChild(n.firstChild);const o=n.parentElement;o&&(o.style.overflow="visible"),n.style.position="relative",n.style.minHeight="176px",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center";const s=document.createElement("div");s.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 8px;",s.textContent=i?t.rating_high_prompt||"Thanks — glad you loved it!":t.thank_you_message||"Thanks for your feedback!",n.appendChild(s);const a=t.rating_review_url;if(i&&a){const t=document.createElement("div");t.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 14px;",t.textContent="Would you share that with others?",n.appendChild(t);const i=this.inAppStyle(e),o=document.createElement("button");o.type="button",o.textContent=e.button_text||"Leave a review",o.style.cssText=`padding: 10px 24px; border-radius: 999px; border: none; background: ${i.btnBg}; color: ${i.btnText}; font-weight: 800; font-size: 13.5px; cursor: pointer;`,o.addEventListener("click",()=>{this.trackEvent(e.id,"clicked",{meta:{action:"review_redirect"}});const t=this.sanitizeUrl(a);t&&this.navigateToCampaignAction(e,t)}),n.appendChild(o)}else this._playReaction(n,i?"affirm":"acknowledge",void 0,t)}_renderRatingLowFollowup(e,t,n,i,o){for(this.addAnimationStyles();n.firstChild;)n.removeChild(n.firstChild);const s=document.createElement("div");s.style.cssText="font-size: 15px; font-weight: 700; margin-bottom: 10px;",s.textContent=t.rating_low_prompt||"Sorry to hear that. What went wrong?",n.appendChild(s);const a=document.createElement("textarea");a.className="aegis-rating-comment",a.rows=3,a.placeholder="Tell us how we can do better…",a.style.cssText=`width: 100%; box-sizing: border-box; padding: 10px; border-radius: 10px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 13px; resize: vertical; margin-bottom: 12px; font-family: inherit;`,n.appendChild(a);const r=this.inAppStyle(e),c=document.createElement("div");c.style.cssText="display: flex; gap: 8px; justify-content: center;";let d=!1;const l=o=>{if(d)return;d=!0;const s=o?a.value.trim():"";this.submitWidgetResponse(e,"rating",s?{stars:i,comment:s}:{stars:i}),this._renderRatingThankYou(e,t,n,!1)},p=document.createElement("button");p.type="button",p.textContent="Send feedback",p.style.cssText=`padding: 9px 20px; border-radius: 999px; border: none; background: ${r.btnBg}; color: ${r.btnText}; font-weight: 800; font-size: 13px; cursor: pointer;`,p.addEventListener("click",()=>l(!0));const h=document.createElement("button");h.type="button",h.textContent="Skip",h.style.cssText=`padding: 9px 16px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-weight: 600; font-size: 13px; cursor: pointer;`,h.addEventListener("click",()=>l(!1)),c.appendChild(p),c.appendChild(h),n.appendChild(c),a.focus()}_buildNPSSurveyBody(e,t,n,i,o,s){const a="overlay"===i,r=a?"24px":`${(null==s?void 0:s.padY)??20}px ${(null==s?void 0:s.padX)??20}px`,c=document.createElement("div");c.style.cssText=`padding: ${r};`+(a?" text-align: center;":""),this._appendHeaderImage(c,t);const d=document.createElement("div");d.style.cssText=`font-size: 16px; font-weight: ${a?"700":(null==s?void 0:s.weight)??"600"}; margin-bottom: ${a?"16px":"12px"}; text-align: center;`,d.textContent=t.nps_question||e.title||"How likely are you to recommend us?",c.appendChild(d);const l=e=>e<=6?"#ef4444":e<=8?"#f59e0b":"#10b981",p=document.createElement("div");p.style.cssText=a?"display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-bottom: 12px;":"display: grid; grid-template-columns: repeat(11, 1fr); gap: 4px;";const h=i=>{this.trackEvent(e.id,"clicked"),o&&this._submitTokenResponse(o,{sub_type:"nps_survey",value:i});if(a&&!1!==t.nps_followup_enabled)return void this._renderNpsReasonFollowup(e,t,c,i,n);this.submitWidgetResponse(e,"nps",{score:i}),this.addAnimationStyles();const s=document.createElement("div");s.style.cssText=`font-size: 14px; font-weight: 600; padding: 8px 0; text-align: center; color: ${n};`,s.textContent=i>=9?"Thanks! We are glad you love it.":i<=6?"Thanks for the honest feedback — we will do better.":"Thank you for your feedback!",p.replaceWith(s),null==u||u.remove(),i>=9?this._playReaction(c,"affirm",void 0,t):i<=6?this._playReaction(c,"empathize",void 0,t):this._playReaction(c,"acknowledge",void 0,t)};for(let g=0;g<=10;g++){const e=l(g),t=g;if(a){const n=document.createElement("span");n.style.cssText=`\n width: 28px; height: 28px; border-radius: 6px; display: flex;\n align-items: center; justify-content: center; font-size: 12px;\n font-weight: 700; cursor: pointer; background: ${e}; color: #fff;\n opacity: 0.85; transition: transform 0.1s, opacity 0.15s;\n `,n.textContent=String(g),n.addEventListener("mouseenter",()=>{n.style.opacity="1",n.style.transform="translateY(-1px)"}),n.addEventListener("mouseleave",()=>{n.style.opacity="0.85",n.style.transform="translateY(0)"}),n.addEventListener("click",()=>h(t)),p.appendChild(n)}else{const n=document.createElement("button");n.style.cssText=`\n padding: 8px 0; border-radius: 6px; border: 1px solid ${e}88;\n background: ${e}14; color: ${e}; font-size: 13px; font-weight: 700;\n cursor: pointer; transition: transform 0.12s, background 0.15s;\n `,n.textContent=String(g),n.addEventListener("mouseenter",()=>{n.style.background=e,n.style.color="#fff",n.style.transform="translateY(-1px)"}),n.addEventListener("mouseleave",()=>{n.style.background=`${e}14`,n.style.color=e,n.style.transform="translateY(0)"}),n.addEventListener("click",()=>h(t)),p.appendChild(n)}}c.appendChild(p);let u=null;if(a){u=document.createElement("div"),u.style.cssText="display: flex; justify-content: space-between; font-size: 11px; opacity: 0.6; margin-bottom: 16px;";const e=document.createElement("span");e.textContent="Not likely";const t=document.createElement("span");t.textContent="Very likely",u.appendChild(e),u.appendChild(t),c.appendChild(u)}return c}_renderNpsReasonFollowup(e,t,n,i,o){this.addAnimationStyles();const s=t.nps_promoter_threshold||9,a=i>=s?t.nps_follow_up_promoter||"What do you love most about us?":i<=6?t.nps_follow_up_detractor||"How can we improve?":t.nps_follow_up_passive||"What would make us a 10?";for(;n.firstChild;)n.removeChild(n.firstChild);const r=document.createElement("div");r.style.cssText="font-size: 15px; font-weight: 700; margin-bottom: 10px; text-align: center;",r.textContent=a,n.appendChild(r);const c=document.createElement("textarea"),d=Array.isArray(t.nps_reason_chips)?t.nps_reason_chips:[];if(d.length){const e=document.createElement("div");e.style.cssText="display: flex; flex-wrap: wrap; gap: 6px; justify-content: center; margin-bottom: 10px;",d.slice(0,8).forEach(t=>{const n=document.createElement("button");n.type="button",n.textContent=t,n.style.cssText=`padding: 5px 11px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 12px; cursor: pointer;`,n.addEventListener("click",()=>{c.value=c.value?`${c.value}, ${t}`:t,c.focus()}),e.appendChild(n)}),n.appendChild(e)}c.className="aegis-rating-comment",c.rows=3,c.placeholder="Share a little more…",c.style.cssText=`width: 100%; box-sizing: border-box; padding: 10px; border-radius: 10px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-size: 13px; resize: vertical; margin-bottom: 12px; font-family: inherit;`,n.appendChild(c);const l=this.inAppStyle(e),p=document.createElement("div");p.style.cssText="display: flex; gap: 8px; justify-content: center;";let h=!1;const u=o=>{if(h)return;h=!0;const a=o?c.value.trim():"";this.submitWidgetResponse(e,"nps",a?{score:i,comment:a}:{score:i}),this._renderNpsThankYou(e,t,n,i>=s)},g=document.createElement("button");g.type="button",g.textContent="Send",g.style.cssText=`padding: 9px 20px; border-radius: 999px; border: none; background: ${l.btnBg}; color: ${l.btnText}; font-weight: 800; font-size: 13px; cursor: pointer;`,g.addEventListener("click",()=>u(!0));const m=document.createElement("button");m.type="button",m.textContent="Skip",m.style.cssText=`padding: 9px 16px; border-radius: 999px; border: 1px solid ${o}33; background: transparent; color: ${o||"inherit"}; font-weight: 600; font-size: 13px; cursor: pointer;`,m.addEventListener("click",()=>u(!1)),p.appendChild(g),p.appendChild(m),n.appendChild(p),c.focus()}_renderNpsThankYou(e,t,n,i){for(;n.firstChild;)n.removeChild(n.firstChild);const o=n.parentElement;o&&(o.style.overflow="visible"),n.style.position="relative",n.style.minHeight="176px",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="center",n.style.justifyContent="center";const s=document.createElement("div");s.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 8px; text-align: center;",s.textContent=t.thank_you_message||(i?"Thanks — glad you love it!":"Thanks for your feedback!"),n.appendChild(s);const a=t.nps_promoter_url;if(i&&a){const t=document.createElement("div");t.style.cssText="font-size: 13px; opacity: 0.8; margin-bottom: 14px; text-align: center;",t.textContent="Would you share that with others?",n.appendChild(t);const i=this.inAppStyle(e),o=document.createElement("button");o.type="button",o.textContent=e.button_text||"Leave a review",o.style.cssText=`padding: 10px 24px; border-radius: 999px; border: none; background: ${i.btnBg}; color: ${i.btnText}; font-weight: 800; font-size: 13.5px; cursor: pointer;`,o.addEventListener("click",()=>{this.trackEvent(e.id,"clicked",{meta:{action:"nps_review_redirect"}});const t=this.sanitizeUrl(a);t&&this.navigateToCampaignAction(e,t)}),n.appendChild(o)}else this._playReaction(n,i?"affirm":"acknowledge",void 0,t)}onClientEvent(e,t={}){for(const n of this.campaigns)this.displayedCampaigns.has(n.id)||n.client_trigger&&(this.isSuppressed(n.id)||this.matchesClientTrigger(n.client_trigger,e,t)&&this.displayCampaign(n))}matchesClientTrigger(e,t,n){var i;const o=e.config||{};switch(e.type){case"custom_event":return"string"==typeof o.event&&o.event===t;case"product_match":{if("product_viewed"!==t&&"product_view"!==t)return!1;const e=o.product_id,s=Array.isArray(e)?e:"string"==typeof e?[e]:[];if(0===s.length)return!1;const a=String(n.product_id??n.productId??(null==(i=n.product)?void 0:i.id)??"");return s.includes(a)}default:return!1}}displayCampaign(e){if(!this.emit("campaign-will-show",e))return void this.log(`campaign ${e.id} suppressed by campaign-will-show handler`);this.displayedCampaigns.add(e.id),this._displaySizeMul=this._sizeMul(e.interactive_config);const t=new Set(["spin_wheel","scratch_card","nps_survey","quiz","countdown_offer","star_rating","quick_poll","multi_step_form","push_primer",...be]);if(e.sub_type&&t.has(e.sub_type))return this.renderInteractive(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);switch(e.type){case"custom_html":return this.renderCustomHtml(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"modal":this.renderModal(e);break;case"banner":this.renderBanner(e);break;case"full_screen":this.renderFullScreen(e);break;case"half_interstitial":this.renderHalfInterstitial(e);break;case"alert":this.renderAlert(e);break;case"pip":this.renderPIP(e);break;case"tooltip":this.renderTooltip(e);break;case"carousel_cards":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c=(Array.isArray(r.cards)?r.cards:[]).slice(0,10);if(0===c.length)return void s("carousel_cards rendered with zero cards — skipping","warn");const d=Number(r.autoplay_ms)||0,l=!1!==r.loop;a();const p="#0f172a",h=o(t.background_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-carousel-overlay",u.setAttribute("data-campaign-id",t.id),u.style.cssText='\n position: fixed; left: 0; right: 0; bottom: 0;\n z-index: 99999; padding: 12px 12px 20px;\n background: rgba(0,0,0,0.12); backdrop-filter: blur(8px);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n ';const g=document.createElement("div");g.style.cssText=`\n background: #ffffff; color: ${p}; border-radius: 16px;\n box-shadow: 0 8px 20px rgba(0,0,0,0.08); padding: 16px;\n max-width: 520px; margin: 0 auto; position: relative;\n `;const m=document.createElement("div");m.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 12px;";const f=document.createElement("div"),x=document.createElement("div");x.textContent=t.title,x.style.cssText="font-weight: 700; font-size: 15px; margin-bottom: 2px;";const y=document.createElement("div");y.textContent=t.body,y.style.cssText="font-size: 13px; opacity: 0.75;",f.appendChild(x),f.appendChild(y),m.appendChild(f);const b=document.createElement("button");b.textContent="✕",b.setAttribute("aria-label","Close"),b.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; opacity: 0.6; padding: 2px 6px;\n ",b.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),m.appendChild(b),g.appendChild(m);const v=document.createElement("div");v.style.cssText="\n display: flex; gap: 10px; overflow-x: auto; scroll-snap-type: x proximity;\n scroll-padding-left: 0; scrollbar-width: none; -ms-overflow-style: none;\n padding-bottom: 4px; -webkit-overflow-scrolling: touch;\n ",v.style.msOverflowStyle="none",c.forEach((e,o)=>{const s=document.createElement("div");s.setAttribute("data-card-index",String(o)),s.style.cssText=`\n flex: 0 0 auto; width: 140px; scroll-snap-align: start;\n background: ${p}0a; border-radius: 12px; padding: 10px;\n display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n `;const a=e.video_url?i(e.video_url):"";if(a){const e=document.createElement("video");e.src=a,e.muted=!0,e.loop=!0,e.autoplay=!0,e.playsInline=!0,e.setAttribute("playsinline",""),e.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",s.appendChild(e)}else if(e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; height: 96px; border-radius: 8px; object-fit: cover;",s.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",s.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",s.appendChild(t)}if(e.cta_text&&e.cta_url){const a=document.createElement("button");a.className="aegis-cta",a.textContent=e.cta_text,a.style.cssText=`\n margin-top: auto; background: ${h}; color: #fff;\n border: none; padding: 6px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const r=s=>{s.stopPropagation(),n(t.id,"clicked",{stepId:`card_${o}`});const a=i(e.cta_url);a&&(window.location.href=a)};a.addEventListener("click",r),s.appendChild(a),s.addEventListener("click",r)}v.appendChild(s)}),g.appendChild(v);const w=document.createElement("div");w.style.cssText="display: flex; justify-content: center; gap: 6px; margin-top: 10px;";const _=[];c.forEach(()=>{const e=document.createElement("span");e.style.cssText=`\n width: 6px; height: 6px; border-radius: 999px; background: ${p};\n opacity: 0.25; transition: opacity 0.2s;\n `,_.push(e),w.appendChild(e)}),g.appendChild(w);const C=new Set,k=e=>{_.forEach((t,n)=>{t.style.opacity=n===e?"1":"0.25",t.style.background=n===e?h:p}),C.has(e)||(C.add(e),n(t.id,"impression",{stepId:`card_${e}`}))};k(0);let E=0;const S=v.querySelectorAll("[data-card-index]"),T=e=>{E=(e%c.length+c.length)%c.length;const t=S[E];if(t){const e=t.getBoundingClientRect().left-v.getBoundingClientRect().left;v.scrollTo({left:v.scrollLeft+e,behavior:"smooth"}),k(E)}};if(c.length>1){const e=(e,t,n)=>{const i=document.createElement("button");return i.type="button",i.textContent=e,i.setAttribute("aria-label",t),i.style.cssText=`background: transparent; border: none; color: ${p}; opacity: 0.55; font-size: 18px; line-height: 1; cursor: pointer; padding: 0 4px;`,i.addEventListener("click",()=>{I(),T(E+n)}),i};w.style.alignItems="center",w.insertBefore(e("‹","Previous",-1),w.firstChild),w.appendChild(e("›","Next",1))}let $=null;const I=()=>{$&&(clearInterval($),$=null)};d>0&&c.length>1&&($=setInterval(()=>{if(!document.body.contains(u))return void I();const e=E+1;e>=c.length&&!l?I():T(e)},d)),["pointerdown","wheel","touchstart"].forEach(e=>v.addEventListener(e,I,{passive:!0})),v.addEventListener("scroll",()=>{const e=Math.round(v.scrollLeft/150);e!==E&&e>=0&&e<c.length&&(E=e,k(E))}),u.appendChild(g),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"sticky_bar":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c="top"===r.sticky_position?"top":"bottom",d=!1!==r.sticky_dismissible,l=Number(r.sticky_auto_hide_ms)||0;try{if("undefined"!=typeof localStorage&&localStorage.getItem(G+t.id))return void s(`sticky_bar ${t.id} suppressed — user dismissed earlier`)}catch{}a();const p=o(r.sticky_bg_color||t.background_color||"#4169e1"),h=o(t.text_color||"#ffffff"),u=document.createElement("div");u.className="aegis-in-app-sticky-bar",u.setAttribute("data-campaign-id",t.id);const g="top"===c?"top: 0; left: 0; right: 0; animation: aegisSlideDown 0.3s ease-out;":"bottom: 0; left: 0; right: 0; animation: aegisSlideInFromBottom 0.3s ease-out;";u.style.cssText=`\n position: fixed; ${g}\n background: ${p}; color: ${h};\n padding: 10px 14px; z-index: 999998;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex; align-items: center; gap: 12px; justify-content: center;\n box-shadow: 0 ${"top"===c?"2px":"-2px"} 8px rgba(0,0,0,0.08);\n `;const m=document.createElement("div");m.style.cssText="flex: 0 1 auto; font-size: 13px; font-weight: 500; text-align: center;";const f=document.createElement("strong");f.textContent=t.title,f.style.cssText="margin-right: 6px; font-weight: 700;",m.appendChild(f),m.appendChild(document.createTextNode(t.body)),u.appendChild(m);const x=t.button_text||(t.action_url?"Shop now":"");if(x){const e=document.createElement("button");e.className="aegis-cta",e.textContent=x,e.style.cssText=`\n background: ${h}; color: ${p};\n border: none; padding: 6px 14px; border-radius: 999px;\n font-size: 12px; font-weight: 700; cursor: pointer; white-space: nowrap;\n `,e.addEventListener("click",()=>{if(n(t.id,"clicked"),t.action_url){const e=i(t.action_url);e&&(window.location.href=e)}}),u.appendChild(e)}let y=null;const b=e=>{if(y&&clearTimeout(y),e)try{"undefined"!=typeof localStorage&&localStorage.setItem(G+t.id,"1")}catch{}u.remove()};if(d){const e=document.createElement("button");e.textContent="✕",e.setAttribute("aria-label","Dismiss"),e.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 16px; cursor: pointer; padding: 0 4px; opacity: 0.75;\n ",e.addEventListener("click",()=>{n(t.id,"dismissed"),b(!0)}),u.appendChild(e)}l>0&&(y=setTimeout(()=>b(!1),l)),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"progress_bar":return function(e){const t=J(e,!1);t&&document.body.appendChild(t)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"coachmark_tour":return te(this.buildRenderContext(e)),void this.emit("campaign-shown",e);case"product_recommendation":return function(e){const{campaign:t,trackEvent:n,sanitizeUrl:i,sanitizeColor:o,log:s,addAnimationStyles:a}=e,r=t.interactive_config||{},c=(Array.isArray(r.cards)?r.cards:[]).slice(0,24);if(0===c.length)return void s("product_recommendation rendered with zero products — skipping","warn");const d=r.rec_layout||"grid",l=r.rec_cta_text||"Shop now";a();const p="#0f172a",h=o(t.background_color||"#4169e1"),u=document.createElement("div");u.className="aegis-in-app-product-rec",u.setAttribute("data-campaign-id",t.id),u.style.cssText="\n position: fixed; inset: 0;\n background: rgba(15,23,42,0.55); backdrop-filter: blur(4px);\n display: flex; align-items: flex-end; justify-content: center;\n z-index: 99999; animation: aegisFadeIn 0.25s ease;\n ";const g=document.createElement("div");g.style.cssText=`\n background: #ffffff; color: ${p};\n max-width: 560px; width: 100%; max-height: 80vh; overflow-y: auto;\n border-radius: 20px 20px 0 0;\n padding: 18px 16px 22px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisSlideInFromBottom 0.3s ease-out;\n box-shadow: 0 -12px 30px rgba(0,0,0,0.12);\n `;const m=document.createElement("div");m.style.cssText=`\n width: 36px; height: 4px; border-radius: 999px; background: ${p}1f;\n margin: 0 auto 12px;\n `,g.appendChild(m);const f=document.createElement("div");f.style.cssText="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;";const x=document.createElement("div"),y=document.createElement("div");y.textContent=t.title,y.style.cssText="font-weight: 700; font-size: 16px; margin-bottom: 2px;";const b=document.createElement("div");b.textContent=t.body,b.style.cssText="font-size: 13px; opacity: 0.7; line-height: 1.4;",x.appendChild(y),x.appendChild(b),f.appendChild(x);const v=document.createElement("button");v.textContent="✕",v.setAttribute("aria-label","Close"),v.style.cssText="\n background: transparent; border: none; color: inherit;\n font-size: 18px; cursor: pointer; padding: 4px 8px; opacity: 0.7;\n ",v.addEventListener("click",()=>{n(t.id,"dismissed"),u.remove()}),f.appendChild(v),g.appendChild(f);const w=document.createElement("div");w.style.cssText="row"===d?"\n display: flex; gap: 10px; overflow-x: auto;\n scroll-snap-type: x mandatory; padding: 14px 0 4px;\n ":"\n display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;\n padding-top: 14px;\n ",c.forEach(e=>{const o=document.createElement("div"),s="row"===d;if(o.style.cssText=`\n background: ${p}08; border-radius: 12px;\n padding: 10px; display: flex; flex-direction: column; gap: 6px;\n cursor: ${e.cta_url?"pointer":"default"};\n ${s?"flex: 0 0 150px; scroll-snap-align: start;":""}\n transition: transform 0.15s ease;\n `,e.image_url){const t=document.createElement("img"),n=i(e.image_url);n&&(t.src=n,t.alt="",t.loading="lazy",t.style.cssText="width: 100%; aspect-ratio: 1 / 1; border-radius: 8px; object-fit: cover;",o.appendChild(t))}if(e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-weight: 600; font-size: 13px; line-height: 1.3;",o.appendChild(t)}const a=e.metadata&&"object"==typeof e.metadata?e.metadata:{},r=a.price,c=a.compare_at_price??a.compare_at??a.original_price;if(void 0!==r){const e=document.createElement("div");e.style.cssText="display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap;";const t=document.createElement("span");t.textContent=String(r),t.style.cssText=`color: ${h}; font-weight: 700; font-size: 13px;`,e.appendChild(t);const n=parseFloat(String(r).replace(/[^0-9.]/g,"")),i=void 0!==c?parseFloat(String(c).replace(/[^0-9.]/g,"")):NaN;if(isFinite(i)&&isFinite(n)&&i>n){const t=document.createElement("span");t.textContent=String(c),t.style.cssText="text-decoration: line-through; opacity: 0.5; font-size: 11px;",e.appendChild(t);const o=document.createElement("span");o.textContent=`-${Math.round(100*(1-n/i))}%`,o.style.cssText="background: #ef444422; color: #ef4444; font-weight: 700; font-size: 10px; padding: 1px 5px; border-radius: 999px;",e.appendChild(o)}o.appendChild(e)}else if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 11.5px; opacity: 0.72; line-height: 1.3;",o.appendChild(t)}const u=document.createElement("button");u.className="aegis-cta",u.textContent=e.cta_text||l,u.style.cssText=`\n margin-top: auto;\n background: ${h}; color: #fff;\n border: none; padding: 7px 10px; border-radius: 999px;\n font-size: 12px; font-weight: 600; cursor: pointer;\n `;const g=o=>{if(o.stopPropagation(),n(t.id,"clicked"),e.cta_url){const t=i(e.cta_url);t&&(window.location.href=t)}};u.addEventListener("click",g),o.appendChild(u),e.cta_url&&o.addEventListener("click",g),w.appendChild(o)}),g.appendChild(w),u.appendChild(g),u.addEventListener("click",e=>{e.target===u&&(n(t.id,"dismissed"),u.remove())}),document.body.appendChild(u)}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"stories":return function(e){const t=ae(e);t&&(e.addAnimationStyles(),de(),ce(e,t,0,0))}(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"video":return ke(this.buildRenderContext(e)),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e);case"active_web_chat":return this.renderActiveWebChatLauncher(e),this.trackEvent(e.id,"impression"),void this.emit("campaign-shown",e)}this.trackEvent(e.id,"impression"),this.emit("campaign-shown",e)}renderActiveWebChatLauncher(e){if(this.activeWebChat)return;const t=function(e,t){if("undefined"==typeof document)return null;if(Fe)return Fe;const n=e.campaign.interactive_config||{},i=Be(n.chat_accent_color),o=Be(n.chat_logo_url),s=Be(n.chat_icon),a={writeKey:t.writeKey,apiHost:t.apiHost,contactId:t.contactId,channel:t.channel??"web",title:Be(n.chat_title),greeting:Be(n.chat_greeting),accentColor:i?e.sanitizeColor(i):void 0,icon:"sparkle"===s||"chat"===s||"logo"===s?s:void 0,logoUrl:o?e.sanitizeUrl(o)??void 0:void 0,position:"bottom-left"===n.chat_position?"bottom-left":void 0,displayMode:"nav"===n.chat_display_mode?"nav":void 0,agentPersona:Be(n.chat_agent_persona),quickReplies:Array.isArray(n.chat_quick_replies)?n.chat_quick_replies.filter(e=>"string"==typeof e):void 0,onSessionStart:()=>e.trackEvent(e.campaign.id,"clicked",{meta:{action:"session_start"}}),onSessionEnd:()=>e.trackEvent(e.campaign.id,"dismissed",{meta:{action:"session_end"}}),onMessageSent:()=>e.trackEvent(e.campaign.id,"clicked",{meta:{action:"message_sent"}})},r=new Pe(a);r.initialize(),Fe=r;const c=n.chat_proactive||{},d=!0===c.exit_intent,l=!0===c.cart_idle;if(d||l){const e=new Ne;d&&(e.registerExitIntent(),e.on("exit_intent",()=>r.openPanel())),l&&(e.registerInactivity(60),e.on("inactivity_60",()=>r.openPanel())),e.start(),Oe=e}return r}(this.buildRenderContext(e),{writeKey:this.writeKey,apiHost:this.apiHost,contactId:this.contactId,channel:"web"});t&&(this.activeWebChat=t)}buildRenderContext(e){return{campaign:e,getCartState:this.getCartState,trackEvent:(e,t,n)=>{this.trackEvent(e,t,n)},sanitizeUrl:e=>this.sanitizeUrl(e),navigate:(t,n)=>this.navigateToCampaignAction(e,t,n),submitResponse:(t,n)=>this.submitWidgetResponse(e,t,n),playReaction:(t,n,i)=>this._playReaction(t,n,i,e.interactive_config),haptic:e=>{try{"undefined"!=typeof navigator&&"function"==typeof navigator.vibrate&&navigator.vibrate(e)}catch{}},sanitizeColor:e=>this.sanitizeColor(e),log:(e,t)=>this.log(e,t),addAnimationStyles:()=>this.addAnimationStyles()}}renderInteractive(e){const t=e.interactive_config||{},{bg:n,text:i}=this._surfacePalette(e);if(!e.sub_type||!function(e,t){const n=ye[t];return!!n&&(n(e),!0)}(this.buildRenderContext(e),e.sub_type))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"multi_step_form":this.renderMultiStepForm(e,t,n,i);break;case"push_primer":this.renderPushPrimer(e,t,n,i);break;case"spin_wheel":case"scratch_card":this.onInteractiveCampaign?this.onInteractiveCampaign(e):this.renderGamificationOverlay(e,t,n,i);break;default:this.log(`Unknown interactive sub_type: ${e.sub_type}`,"warn"),this.renderModal(e)}}_sizeMul(e){const t=e&&"string"==typeof e.display_size?e.display_size:"medium";return"small"===t?.82:"large"===t?1.18:1}renderGamificationOverlay(e,t,n,i){const o=this.createOverlay(`aegis-in-app-${e.sub_type}-overlay`),s=document.createElement("div");s.style.cssText=`\n position: relative; max-width: 340px; width: 90%; border-radius: 20px;\n overflow: hidden; background: ${n}; color: ${i};\n animation: aegisScaleIn 0.3s ease; box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n `,"scratch_card"===e.sub_type?this.renderScratchCardSlot(e,t,n,i,s):this.renderSpinWheelSlot(e,t,n,i,s),this._addCornerClose(s,o,e.id,i);const a=this._sizeMul(t),r=document.createElement("div");r.style.cssText=`display: flex; justify-content: center; align-items: center; width: 100%; transform: scale(${a}); transform-origin: center;`,r.appendChild(s),o.appendChild(r),this.addAnimationStyles(),document.body.appendChild(o)}_addCornerClose(e,t,n,i){const o=document.createElement("button");o.setAttribute("aria-label","Close");const s=Ue('<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>');s?o.appendChild(s):o.textContent="✕",o.style.cssText=`\n position: absolute; top: 12px; right: 12px; z-index: 4; width: 28px; height: 28px;\n display: flex; align-items: center; justify-content: center; border: none;\n border-radius: 50%; cursor: pointer; color: ${i};\n background: ${i}1f; backdrop-filter: blur(4px); transition: background 0.15s, transform 0.15s;\n `,o.addEventListener("mouseenter",()=>{o.style.background=`${i}33`,o.style.transform="scale(1.08)"}),o.addEventListener("mouseleave",()=>{o.style.background=`${i}1f`,o.style.transform="scale(1)"}),o.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(o)}renderCustomHtml(e){const t=e.interactive_config||{},n=this.createOverlay("aegis-in-app-custom-html-overlay"),i=document.createElement("div");i.style.cssText="position: relative; max-width: 420px; width: 92%; border-radius: 16px; overflow: hidden; background: #ffffff; box-shadow: 0 16px 48px rgba(0,0,0,0.22); animation: aegisScaleIn 0.3s ease;",i.appendChild(this._buildCustomHtmlFrame(e,t,n)),this._addCornerClose(i,n,e.id,"#111827"),n.appendChild(i),this.addAnimationStyles(),document.body.appendChild(n)}_buildCustomHtmlFrame(e,t,n){const i="string"==typeof t.html?t.html:"",o="number"==typeof t.html_height?t.html_height:360,s=this.inAppStyle(e),a=`:root{--aegis-bg:${s.bg};--aegis-text:${s.text};--aegis-primary:${s.btnBg};--aegis-on-primary:${s.btnText};}`,r=document.createElement("iframe");r.setAttribute("sandbox","allow-scripts"),r.setAttribute("referrerpolicy","no-referrer"),r.style.cssText=`width: 100%; height: ${o}px; border: none; display: block; background: #fff; transform: translateZ(0); backface-visibility: hidden;`,r.title=e.title||"In-app content";r.srcdoc='<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>'+a+"html,body{margin:0;padding:0;font-family:system-ui,-apple-system,sans-serif;}</style><script>window.aegis={close:function(){parent.postMessage({__aegis:'close'},'*')},track:function(e,p){parent.postMessage({__aegis:'track',event:e,payload:p},'*')},cta:function(u){parent.postMessage({__aegis:'cta',url:u},'*')},resize:function(h){parent.postMessage({__aegis:'resize',height:h},'*')}};<\/script></head><body>"+i+"</body></html>";const c=t=>{if(t.source!==r.contentWindow)return;const i=t.data;if(i&&"string"==typeof i.__aegis)switch(i.__aegis){case"close":window.removeEventListener("message",c),this.trackEvent(e.id,"dismissed"),this.removeModal(n);break;case"track":this.trackEvent(e.id,"clicked");break;case"cta":{this.trackEvent(e.id,"clicked");const t="string"==typeof i.url?this.sanitizeUrl(i.url):null;if(t){const n=new CustomEvent("aegis:campaign-click",{detail:{campaign:e,url:t},cancelable:!0});window.dispatchEvent(n)&&window.open(t,"_blank","noopener")}break}case"resize":"number"==typeof i.height&&i.height>=40&&i.height<=2e3&&(r.style.height=`${i.height}px`)}};return window.addEventListener("message",c),r}renderCustomHtmlSlot(e,t,n,i,o){const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-custom-html-card",e.id,n,i,s.radius);return a.appendChild(this._buildCustomHtmlFrame(e,t,a)),o.appendChild(a),!0}renderNPSSurvey(e,t,n,i){const o=this.createOverlay("aegis-in-app-nps-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=this._buildNPSSurveyBody(e,t,i,"overlay");this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderCountdownOffer(e,t,n,i){const o=this.createOverlay("aegis-in-app-countdown-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\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=t.countdown_target,l=d?new Date(d).getTime():Date.now()+6e5,p=l-Date.now()>=864e5,h=p?[["d","Days"],["h","Hrs"],["m","Min"],["s","Sec"]]:[["h","Hrs"],["m","Min"],["s","Sec"]],u={},g=document.createElement("div");g.style.cssText="display: flex; gap: 10px; justify-content: center; margin-bottom: 16px;";for(const[b,v]of h){const e=document.createElement("div");e.style.cssText="display: flex; flex-direction: column; align-items: center; gap: 4px;";const t=document.createElement("div");t.style.cssText=`min-width: 46px; padding: 8px 6px; border-radius: 8px; font-size: 24px; font-weight: 700; font-family: monospace; background: ${i}22; color: ${i}; transition: background 0.2s, color 0.2s;`,t.textContent="00";const n=document.createElement("div");n.style.cssText="font-size: 10px; opacity: 0.6; text-transform: uppercase; letter-spacing: 0.5px;",n.textContent=v,e.appendChild(t),e.appendChild(n),u[b]=t,g.appendChild(e)}a.appendChild(g);const m=e=>String(e).padStart(2,"0");let f=!1,x=!1;const y=()=>{const n=Math.max(0,l-Date.now()),i=Math.floor(n/864e5),o=Math.floor(n%864e5/36e5),s=Math.floor(n%36e5/6e4),r=Math.floor(n%6e4/1e3);u.d&&(u.d.textContent=m(i)),u.h&&(u.h.textContent=m(p?o:Math.floor(n/36e5))),u.m&&(u.m.textContent=m(s)),u.s&&(u.s.textContent=m(r)),!x&&n>0&&n<=6e4&&(x=!0,Object.values(u).forEach(e=>{e&&(e.style.boxShadow="0 0 0 2px #ef4444")}),g.style.animation="aegisCountdownPulse 1.1s ease-in-out infinite"),n>0?requestAnimationFrame(y):f||(f=!0,this.submitWidgetResponse(e,"countdown",{state:"expired"}),this._playReaction(a,"celebrate","alarm-clock.json",t))};if(y(),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,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderStarRating(e,t,n,i){const o=this.createOverlay("aegis-in-app-rating-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=this._buildStarRatingBody(e,t,i,"overlay");this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderQuickPoll(e,t,n,i){const o=this.createOverlay("aegis-in-app-poll-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");if(r.style.cssText=`font-size: 16px; font-weight: 700; margin-bottom: ${e.body?"6px":"16px"};`,r.textContent=e.title||"Quick question",a.appendChild(r),e.body){const t=document.createElement("div");t.style.cssText=`font-size: 13px; opacity: 0.8; margin-bottom: 16px; color: ${i};`,t.textContent=e.body,a.appendChild(t)}const c=t.poll_options||[],d=document.createElement("div");d.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;";const l=[];c.forEach((n,o)=>{const s=document.createElement("button");s.style.cssText=`\n position: relative; overflow: hidden;\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: border-color 0.2s ease;\n `;const r=document.createElement("span");r.style.cssText="position: relative; z-index: 1; display: flex; justify-content: space-between; gap: 8px;";const p=document.createElement("span");p.textContent=n;const h=document.createElement("span");h.style.cssText="font-weight: 700; opacity: 0; transition: opacity 0.3s ease;",r.appendChild(p),r.appendChild(h),s.appendChild(r),s.addEventListener("click",()=>{this.trackEvent(e.id,"clicked"),l.forEach(e=>e.disabled=!0),this._paintPollResult(l,c,o,null,i),this.submitWidgetResponse(e,"poll",{option_index:o,option_label:n}).then(e=>{const t=this._readPollDistribution(e,c.length);t&&this._paintPollResult(l,c,o,t,i)});const s=a.parentElement;s&&(s.style.overflow="visible"),this._playReaction(a,"affirm","check.json",t)}),l.push(s),d.appendChild(s)}),a.appendChild(d),this.addCloseButton(a,o,e.id),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderMultiStepForm(e,t,n,i){const o=this.createOverlay("aegis-in-app-multistep-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=Array.isArray(t.form_fields)?t.form_fields:null;if(a&&a.length>0){const t=this._buildFormBody(e,a,n,i);return this.addCloseButton(t,o,e.id),s.appendChild(t),o.appendChild(s),this.addAnimationStyles(),void document.body.appendChild(o)}const r=document.createElement("div");r.style.cssText="padding: 24px;";const c=Array.isArray(t.steps)?t.steps:[],d=c.length>0?c:[{question:e.title||"Tell us more",options:[]}],l=d.length;let p=0;const h=new Array(l).fill(null),u=document.createElement("div");u.style.cssText=`height: 4px; border-radius: 2px; background: ${i}22; margin-bottom: 16px; overflow: hidden;`;const g=document.createElement("div");g.style.cssText=`height: 100%; background: ${i}; transition: width 0.2s ease; width: 0%;`,u.appendChild(g),r.appendChild(u);const m=document.createElement("div");m.style.cssText="font-size: 11px; opacity: 0.7; margin-bottom: 6px;",r.appendChild(m);const f=document.createElement("div");f.style.cssText="font-size: 16px; font-weight: 700; margin-bottom: 14px;",r.appendChild(f);const x=document.createElement("div");x.style.cssText="display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px;",r.appendChild(x);const y=document.createElement("div");y.style.cssText="display: flex; gap: 8px; justify-content: space-between;";const b=document.createElement("button");b.textContent="Back",b.style.cssText=`padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33; background: transparent; color: ${i}; font-size: 14px; cursor: pointer;`;const v=document.createElement("button");v.style.cssText=`padding: 10px 16px; border-radius: 10px; border: none; background: ${i}; color: ${n}; font-size: 14px; font-weight: 600; cursor: pointer; flex: 1;`,y.appendChild(b),y.appendChild(v),r.appendChild(y);const w=()=>{const e=d[p]||{},t=e.question||e.label||`Step ${p+1}`,n=Array.isArray(e.options)?e.options:[];for(g.style.width=`${Math.round(p/l*100)}%`,m.textContent=`Step ${p+1} of ${l}`,f.textContent=t;x.firstChild;)x.removeChild(x.firstChild);n.forEach(e=>{const t=document.createElement("button");t.textContent=e;const n=h[p]===e;t.style.cssText=`padding: 10px 16px; border-radius: 10px; border: 1px solid ${i}33; background: ${n?i+"22":"transparent"}; color: ${i}; font-size: 14px; cursor: pointer; text-align: left;`,t.addEventListener("click",()=>{h[p]=e,w()}),x.appendChild(t)}),b.style.visibility=0===p?"hidden":"visible",v.textContent=p===l-1?"Submit":"Next";const o=n.length>0&&null==h[p];v.disabled=o,v.style.opacity=o?"0.5":"1",v.style.cursor=o?"not-allowed":"pointer"};b.addEventListener("click",()=>{p>0&&(p-=1,w())}),v.addEventListener("click",()=>{p<l-1?(p+=1,w()):(g.style.width="100%",this.trackEvent(e.id,"clicked",{meta:{answers:h}}),this.submitWidgetResponse(e,"form",{answers:h}),this._playReaction(r,"affirm","check.json",t),window.setTimeout(()=>{o.parentNode&&document.body.removeChild(o)},2300))}),w(),this.addCloseButton(r,o,e.id),s.appendChild(r),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderPushPrimer(e,t,n,i){const o=this.createOverlay("aegis-in-app-push-primer-overlay"),s=document.createElement("div");s.style.cssText=`\n max-width: 340px; width: 90%; border-radius: 16px; overflow: hidden;\n background: ${n}; color: ${i}; animation: aegisScaleIn 0.3s ease;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 24px; text-align: center;";const r=document.createElement("div");r.style.cssText="font-size: 36px; margin-bottom: 8px;",r.textContent=t.icon||"🔔",a.appendChild(r);const c=document.createElement("div");c.style.cssText="font-size: 18px; font-weight: 700; margin-bottom: 8px;",c.textContent=e.title||"Stay in the loop",a.appendChild(c);const d=document.createElement("div");d.style.cssText="font-size: 14px; opacity: 0.85; margin-bottom: 18px;",d.textContent=e.body||"Enable notifications so you never miss an offer.",a.appendChild(d);const l="undefined"!=typeof Notification&&"function"==typeof Notification.requestPermission,p=document.createElement("button");p.textContent=t.allow_text||"Enable notifications",p.style.cssText=`width: 100%; padding: 12px 16px; border-radius: 10px; border: none; background: ${i}; color: ${n}; font-size: 15px; font-weight: 600; cursor: pointer; margin-bottom: 8px;`,p.addEventListener("click",()=>{if(!l)return this.trackEvent(e.id,"dismissed",{meta:{reason:"unsupported"}}),void(o.parentNode&&document.body.removeChild(o));Promise.resolve(Notification.requestPermission()).then(t=>{this.trackEvent(e.id,"clicked",{meta:{permission:t}}),o.parentNode&&document.body.removeChild(o)})}),a.appendChild(p);const h=document.createElement("button");h.textContent=t.dismiss_text||"Not now",h.style.cssText=`width: 100%; padding: 10px 16px; border-radius: 10px; border: none; background: transparent; color: ${i}; opacity: 0.7; font-size: 14px; cursor: pointer;`,h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),o.parentNode&&document.body.removeChild(o)}),a.appendChild(h),s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o)}renderQuiz(e,t,n,i){const o=this.createOverlay("aegis-in-app-quiz-overlay"),s=document.createElement("div");s.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 16px 48px rgba(0,0,0,0.22);\n `;const a=document.createElement("div");a.style.cssText="padding: 22px; text-align: center;",s.appendChild(a),o.appendChild(s),this.addAnimationStyles(),document.body.appendChild(o),this._runQuizFlow(e,t,n,i,a,o)}renderQuizSlot(e,t,n,i,o){if(0===(Array.isArray(t.questions)?t.questions:[]).length)return!1;const s=this._slotStyle(e),a=this._wrapInSlotCard("aegis-in-app-quiz-card",e.id,n,i,s.radius),r=document.createElement("div");return r.style.cssText=`padding: ${s.padY??18}px ${s.padX??18}px; text-align: center;`,a.appendChild(r),o.appendChild(a),this._runQuizFlow(e,t,n,i,r,null),!0}_runQuizFlow(e,t,n,i,o,s){const a=Array.isArray(t.questions)?t.questions:[],r=Array.isArray(t.result_mapping)?t.result_mapping:[],c="knowledge"===t.quiz_type,d=a.length,l=[],p={},h=c?a.reduce((e,t)=>e+("number"==typeof t.points?t.points:1),0):0;let u=0,g=0;const m=()=>{for(;o.firstChild;)o.removeChild(o.firstChild)},f=(e,t=!1)=>{const n=document.createElement("div");return n.style.cssText=`font-size: ${t?19:14}px; font-weight: ${t?800:600}; letter-spacing: -0.01em; line-height: 1.3; margin-bottom: ${t?6:14}px; font-family: 'Inter Tight', Inter, system-ui, -apple-system, sans-serif;`,n.textContent=e,n},x=()=>{m();let a=null,d=u;if(c)a=r.find(e=>{const t="number"==typeof e.min_score?e.min_score:-1/0,n="number"==typeof e.max_score?e.max_score:1/0;return u>=t&&u<=n})||r[r.length-1]||null;else{let e=-1;for(const t of r){const n="string"==typeof t.id?t.id:"",i=n&&p[n]||0;i>e&&(e=i,a=t)}d=e<0?0:e,a=a||r[0]||null}const g=a&&"string"==typeof a.title?a.title:c&&h?`You scored ${u} of ${h}`:"Your result",x=a&&"string"==typeof a.body?a.body:t.thank_you_message||"Thanks for completing the quiz!";o.appendChild(f(g,!0));const y=document.createElement("div");y.style.cssText="font-size: 13.5px; opacity: 0.85; line-height: 1.45; margin: 2px 0 14px;",y.textContent=x,o.appendChild(y);const b=a&&"string"==typeof a.action_url?a.action_url:"";if(b){const t=document.createElement("button");t.type="button",t.textContent=e.button_text||"Continue",t.style.cssText=`padding: 11px 28px; border-radius: 999px; border: none; background: ${i}; color: ${n}; font-weight: 800; font-size: 14px; cursor: pointer; margin-top: 2px;`,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked");const t=this.sanitizeUrl(b);t&&this.navigateToCampaignAction(e,t)}),o.appendChild(t)}this._playReaction(o,"affirm","check.json",t),s&&this.addCloseButton(o,s,e.id),this.submitWidgetResponse(e,"quiz",{answers:l,score:d,result_title:g,result_id:a&&"string"==typeof a.id?a.id:void 0,quiz_type:c?"knowledge":"personality"})},y=()=>{if(g>=d)return void x();m();const t=a[g];if(e.title){const t=document.createElement("div");t.style.cssText="font-size: 11px; font-weight: 700; letter-spacing: 0.3px; text-transform: uppercase; opacity: 0.55; margin-bottom: 10px;",t.textContent=e.title,o.appendChild(t)}const n=document.createElement("div");n.style.cssText=`height: 4px; border-radius: 999px; background: ${i}1f; overflow: hidden; margin-bottom: 8px;`;const r=document.createElement("div");r.style.cssText=`height: 100%; width: ${d?Math.round(g/d*100):0}%; background: ${i}; border-radius: 999px; transition: width 0.3s ease;`,n.appendChild(r),o.appendChild(n);const h=document.createElement("div");h.style.cssText="font-size: 11.5px; opacity: 0.6; margin-bottom: 12px; font-weight: 600;",h.textContent=`Question ${g+1} of ${d}`,o.appendChild(h);const b=t.image_url;if("string"==typeof b&&/^https?:\/\//i.test(b)){const e=document.createElement("img");e.src=b,e.alt="",e.style.cssText="width: 100%; max-height: 140px; object-fit: cover; border-radius: 10px; margin-bottom: 12px;",o.appendChild(e)}o.appendChild(f("string"==typeof t.question?t.question:""));const v=Array.isArray(t.options)?t.options.filter(e=>"string"==typeof e):[],w="number"==typeof t.correct_index?t.correct_index:-1,_="number"==typeof t.points?t.points:1,C=document.createElement("div");C.style.cssText="display: flex; flex-direction: column; gap: 8px;";const k=[];v.forEach((e,n)=>{const o=document.createElement("button");o.type="button",o.style.cssText=`padding: 11px 14px; border-radius: 10px; border: 1.5px solid ${i}2e; background: transparent; color: ${i}; font-size: 14px; cursor: pointer; text-align: left; transition: all 0.15s; font-weight: 600;`,o.textContent=e,o.addEventListener("click",()=>{if(o.disabled)return;k.forEach(e=>{e.disabled=!0}),l.push(n);let e=280;if(c){if(n===w&&(u+=_),w>=0){const t=n===w;o.style.borderColor=t?"#10b981":"#ef4444",o.style.background=(t?"#10b981":"#ef4444")+"22",!t&&k[w]&&(k[w].style.borderColor="#10b981",k[w].style.background="#10b98114"),e=680}}else{const e=(Array.isArray(t.option_results)?t.option_results:[])[n];"string"==typeof e&&e&&(p[e]=(p[e]||0)+1),o.style.borderColor=i,o.style.background=`${i}14`}window.setTimeout(()=>{g+=1,y()},e)}),C.appendChild(o),k.push(o)}),o.appendChild(C),s&&this.addCloseButton(o,s,e.id)};y()}createOverlay(e){const t=document.createElement("div");if(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 ",1!==this._displaySizeMul){const e=this._displaySizeMul;queueMicrotask(()=>{const n=t.firstElementChild;if(!n||n.dataset.aegisSized)return;n.dataset.aegisSized="1";const i=document.createElement("div");i.style.cssText=`display: flex; align-items: center; justify-content: center; transform: scale(${e}); transform-origin: center;`,t.insertBefore(i,n),i.appendChild(n)})}return t}_wrapScaled(e){if(1===this._displaySizeMul)return e;const t=document.createElement("div");return t.style.cssText=`display: flex; align-items: center; justify-content: center; transform: scale(${this._displaySizeMul}); transform-origin: center;`,t.appendChild(e),t}createCTAButton(e,t,n){const i=document.createElement("button");return i.className="aegis-cta",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&&this.navigateToCampaignAction(e,t)}}),i}addCloseButton(e,t,n){const i=document.createElement("div");i.style.cssText="margin-top: 12px; font-size: 12px; opacity: 0.6; cursor: pointer;",i.textContent="Close",i.addEventListener("click",()=>{this.trackEvent(n,"dismissed"),this.removeModal(t)}),e.appendChild(i)}navigateToCampaignAction(e,t,n="cta"){if("undefined"==typeof window)return;if(t.startsWith("aegis://"))return void this.runCampaignActionVerb(e,t);let i=!1;const o={campaign:e,action_url:t,button_id:n,preventDefault:()=>{i=!0,o.defaultPrevented=!0},defaultPrevented:!1},s=this.emit("campaign-click",o),a=new CustomEvent("aegis:campaign-click",{detail:{campaign_id:e.id,campaign_type:e.type,action_url:t,button_id:n},cancelable:!0}),r=window.dispatchEvent(a);!s||i||!r||a.defaultPrevented||(window.location.href=t)}runCampaignActionVerb(e,t){const n=t.slice(8),[i,o]=n.split("?"),s=new URLSearchParams(o||"");switch(i){case"dismiss":this.trackEvent(e.id,"dismissed",{meta:{reason:"cta"}}),this.removeCampaignEl(e.id);break;case"request-push":this.trackEvent(e.id,"clicked",{meta:{verb:"request-push"}}),"undefined"!=typeof Notification&&"function"==typeof Notification.requestPermission&&Promise.resolve(Notification.requestPermission()).then(t=>{this.trackEvent(e.id,"clicked",{meta:{permission:t}})}),this.removeCampaignEl(e.id);break;case"cart-add":{const t=s.get("sku")||"";this.trackEvent(e.id,"clicked",{meta:{verb:"cart-add",sku:t}});const n=new CustomEvent("aegis:cart-add",{detail:{sku:t,qty:1,campaign_id:e.id},cancelable:!0});window.dispatchEvent(n)&&!n.defaultPrevented&&t&&(window.location.href=`/p/${encodeURIComponent(t)}`);break}default:this.log(`Unknown campaign action verb: ${i}`,"warn")}}removeCampaignEl(e){"undefined"!=typeof document&&document.querySelectorAll(`[data-campaign-id="${e}"]`).forEach(e=>{var t;return null==(t=e.parentNode)?void 0:t.removeChild(e)})}_contrastText(e){const t=/^#?([0-9a-fA-F]{6})$/.exec(this.sanitizeColor(e));if(!t)return"#ffffff";const n=parseInt(t[1],16);return(.299*(n>>16&255)+.587*(n>>8&255)+.114*(255&n))/255>.62?"#0f172a":"#ffffff"}_surfacePalette(e){const t=e.interactive_config||{},n=this.sanitizeColor(e.background_color||"#4169e1");if("branded"===t.surface_style){const t=n,i=e.text_color?this.sanitizeColor(e.text_color):"#ffffff";return{bg:t,text:i,btnBg:i,btnText:t,accent:i,branded:!0}}return{bg:"#ffffff",text:"#0f172a",btnBg:n,btnText:this._contrastText(n),accent:n,branded:!1}}inAppStyle(e){const t=e.interactive_config||{},n=(e,t)=>{const n=Number(e);return Number.isFinite(n)?n:t},i=this._surfacePalette(e);return{bg:i.bg,text:i.text,btnBg:i.btnBg,btnText:i.btnText,accent:i.accent,radius:n(t.border_radius,16),btnRadius:n(t.button_radius,999),padX:n(t.padding_x,24),padY:n(t.padding_y,24),weight:String(t.heading_font_weight||"700"),mediaHeight:n(t.media_height,160),overlay:n(t.overlay_opacity,50)/100}}renderBanner(e){const t=document.createElement("div");t.className="aegis-in-app-banner",t.setAttribute("data-campaign-id",e.id);const n=this.inAppStyle(e),i=n.padY,o=n.padX,s=e.interactive_config||{},a="bottom"===s.banner_position;t.style.cssText=`\n position: fixed;\n ${a?"bottom: 0;":"top: 0;"}\n left: 0;\n right: 0;\n background: ${n.bg};\n color: ${n.text};\n padding: ${i}px ${o}px;\n z-index: 999999;\n box-shadow: 0 ${a?"-2px":"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: ${a?"aegisSlideInFromBottom":"aegisSlideDown"} 0.3s ease-out;\n `,t.setAttribute("data-banner-position",a?"bottom":"top");const r=document.createElement("div");if(r.style.cssText="flex: 1; display: flex; align-items: center; gap: 12px;",e.image_url){const t=document.createElement("img"),n=this.sanitizeUrl(e.image_url);n&&(t.src=n,t.alt="",t.style.cssText="width: 40px; height: 40px; border-radius: 4px; object-fit: cover;",r.appendChild(t))}const c=document.createElement("div");c.style.cssText="flex: 1;";const d=document.createElement("div");d.textContent=e.title,d.style.cssText=`font-weight: ${n.weight}; font-size: 14px; margin-bottom: 4px;`,c.appendChild(d);const l=document.createElement("div");l.textContent=e.body,l.style.cssText="font-size: 13px; opacity: 0.9;",c.appendChild(l),r.appendChild(c);const p=document.createElement("div");p.style.cssText="display: flex; align-items: center; gap: 12px; margin-left: 16px;";const h=e.button_text||(e.action_url?"Learn more":"");if(h){const i=document.createElement("button");i.className="aegis-cta",i.textContent=h,i.style.cssText=`\n background: ${n.btnBg};\n color: ${n.btnText};\n border: none;\n padding: 8px 16px;\n border-radius: ${n.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 13px;\n white-space: nowrap;\n `,i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeBanner(t)}),p.appendChild(i)}const u=document.createElement("button");u.textContent="✕",u.setAttribute("aria-label","Close"),u.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 ",u.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeBanner(t)}),p.appendChild(u),t.appendChild(r),t.appendChild(p),this.addAnimationStyles(),document.body.appendChild(t);const g=Number(s.banner_auto_dismiss_ms)||0;g>0&&window.setTimeout(()=>{t.parentNode&&this.removeBanner(t)},g)}renderModal(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=document.createElement("div");o.className="aegis-in-app-modal-overlay",o.setAttribute("data-campaign-id",e.id),o.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n `;const s=document.createElement("div");if(s.className="aegis-in-app-modal",s.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow: auto;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n animation: aegisScaleIn 0.3s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,i){const n=document.createElement("div");n.style.cssText=`position: relative; width: 100%; height: ${t.mediaHeight}px; overflow: hidden; border-radius: ${t.radius}px ${t.radius}px 0 0; background: #000;`,this._heroVideo(i,e.image_url,n,"bottom-left"),s.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%; height: ${t.mediaHeight}px; object-fit: cover; border-radius: ${t.radius}px ${t.radius}px 0 0;`,s.appendChild(n))}const a=document.createElement("div");a.style.cssText=`padding: ${t.padY}px ${t.padX}px;`;const r=document.createElement("h2");r.textContent=e.title,r.style.cssText=`margin: 0 0 12px 0; font-size: 20px; font-weight: ${t.weight}; color: ${t.text};`,a.appendChild(r);const c=document.createElement("p");c.textContent=e.body,c.style.cssText=`margin: 0 0 20px 0; font-size: 15px; line-height: 1.5; color: ${t.text}; opacity: 0.9;`,a.appendChild(c);const d=document.createElement("div");d.style.cssText="display: flex; gap: 12px; justify-content: flex-end; align-items: center;";const l=n.modal_secondary_text;if(l){const i=n.modal_secondary_url,s=document.createElement("button");s.type="button",s.textContent=l,s.style.cssText=`background: transparent; border: 1px solid ${t.text}55; color: ${t.text}; opacity: 0.8; padding: 10px 24px; border-radius: ${t.btnRadius}px; font-weight: 600; cursor: pointer; font-size: 14px;`,s.addEventListener("click",()=>{if(i){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const t=this.sanitizeUrl(i);if(t)return this.navigateToCampaignAction(e,t),void this.removeModal(o)}this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),d.appendChild(s)}const p=e.button_text||(e.action_url?"Continue":"");if(p){const n=document.createElement("button");n.className="aegis-cta",n.textContent=p,n.style.cssText=`\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n padding: 10px 24px;\n border-radius: ${t.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(o)}),d.appendChild(n)}const h=document.createElement("button");h.textContent="Close",h.style.cssText=`\n background: transparent;\n border: 1px solid ${t.text}55;\n color: ${t.text};\n opacity: 0.8;\n padding: 10px 24px;\n border-radius: ${t.btnRadius}px;\n font-weight: 600;\n cursor: pointer;\n font-size: 14px;\n `,h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),d.appendChild(h),a.appendChild(d),s.appendChild(a),o.appendChild(this._wrapScaled(s)),!1!==n.modal_dismiss_on_overlay&&o.addEventListener("click",t=>{t.target===o&&(this.trackEvent(e.id,"dismissed"),this.removeModal(o))}),this.addAnimationStyles(),document.body.appendChild(o)}_heroVideo(e,t,n,i){const o=this.sanitizeUrl(e);if(!o)return null;const s=document.createElement("video");if(s.src=o,s.muted=!0,s.loop=!0,s.autoplay=!0,s.playsInline=!0,s.setAttribute("playsinline",""),s.setAttribute("webkit-playsinline",""),s.controls=!1,t){const e=this.sanitizeUrl(t);e&&(s.poster=e)}s.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; background: #000;",n.appendChild(s);const a=document.createElement("button");a.type="button";const r=()=>{a.replaceChildren();const e=document.createElement("span");if(e.style.fontSize="13px",e.textContent=s.muted?"🔇":"🔊",a.appendChild(e),s.muted){const e=document.createElement("span");e.textContent="Tap for sound",a.appendChild(e)}};return a.style.cssText=`position: absolute; ${"top-left"===i?"top: 16px; left: 16px;":"bottom: 16px; left: 16px;"} display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,0.6); color: #fff; border: none; border-radius: 999px; padding: 6px 11px; font-size: 11.5px; font-weight: 700; cursor: pointer; z-index: 3; backdrop-filter: blur(3px);`,a.setAttribute("aria-label","Toggle sound"),a.addEventListener("click",e=>{e.stopPropagation(),s.muted=!s.muted,!s.muted&&s.paused&&s.play().catch(()=>{}),r()}),s.addEventListener("volumechange",r),r(),n.appendChild(a),s.play().catch(()=>{}),s}renderFullScreen(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=!(!i&&!e.image_url),s="background"===(n.fullscreen_layout||(o?"background":"centered"))&&o,a=s?"#ffffff":t.text,r=document.createElement("div");if(r.className="aegis-in-app-fullscreen-overlay",r.setAttribute("data-campaign-id",e.id),r.style.cssText=`\n position: fixed; inset: 0; background: ${t.bg}; color: ${t.text};\n z-index: 1000001; display: flex; flex-direction: column; align-items: center;\n justify-content: ${s?"flex-end":"center"}; padding: ${s?"0":"40px 20px"};\n animation: aegisFadeIn 0.3s ease-out; overflow: hidden;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,s){const t=document.createElement("div");if(t.style.cssText="position: absolute; inset: 0; z-index: 0; background: #000;",i)this._heroVideo(i,e.image_url,t,"top-left");else if(e.image_url){const n=this.sanitizeUrl(e.image_url);if(n){const e=document.createElement("img");e.src=n,e.alt="",e.style.cssText="position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;",t.appendChild(e)}}const n=document.createElement("div");n.style.cssText="position: absolute; inset: 0; z-index: 1; background: linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.35) 42%, rgba(0,0,0,0.05) 100%);",t.appendChild(n),r.appendChild(t)}else if(i){const t=document.createElement("div");t.style.cssText="position: relative; width: min(100%, 560px); aspect-ratio: 16/9; margin-bottom: 32px; border-radius: 14px; overflow: hidden; background: #000;",this._heroVideo(i,e.image_url,t,"bottom-left"),r.appendChild(t)}else if(e.image_url){const t=this.sanitizeUrl(e.image_url);if(t){const e=document.createElement("img");e.src=t,e.alt="",e.style.cssText="max-width: 100%; max-height: 40vh; object-fit: contain; margin-bottom: 32px;",r.appendChild(e)}}const c=document.createElement("div");c.style.cssText=s?`position: relative; z-index: 2; max-width: 640px; width: 100%; box-sizing: border-box; text-align: center; padding: 0 24px 52px; color: ${a}; animation: aegisFadeIn 0.45s ease-out 0.1s both;`:"max-width: 600px; text-align: center;";const d=document.createElement("h1");d.textContent=e.title,d.style.cssText=`margin: 0 0 16px 0; font-size: ${s?"30px":"32px"}; font-weight: ${t.weight}; color: ${a};`+(s?" text-shadow: 0 2px 12px rgba(0,0,0,0.4);":""),c.appendChild(d);const l=document.createElement("p");l.textContent=e.body,l.style.cssText=`margin: 0 0 28px 0; font-size: ${s?"16px":"18px"}; line-height: 1.6; opacity: 0.92; color: ${a};`,c.appendChild(l);const p=e.button_text||(e.action_url?"Continue":"");if(p){const n=document.createElement("button");n.className="aegis-cta",n.textContent=p,n.style.cssText=`\n background: ${t.btnBg}; color: ${t.btnText}; border: none;\n padding: 16px 48px; border-radius: ${t.btnRadius}px; font-weight: 700;\n font-size: 18px; cursor: pointer; display: block; margin: 0 auto 12px;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(r)}),c.appendChild(n)}const h=n.fullscreen_secondary_text;if(h){const t=n.fullscreen_secondary_url,i=document.createElement("button");i.type="button",i.textContent=h,i.style.cssText=`background: transparent; border: none; color: ${a}; opacity: 0.75; font-size: 14px; font-weight: 600; cursor: pointer; padding: 8px; display: block; margin: 0 auto; text-decoration: underline;`,i.addEventListener("click",()=>{if(t){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const n=this.sanitizeUrl(t);if(n)return this.navigateToCampaignAction(e,n),void this.removeModal(r)}this.trackEvent(e.id,"dismissed"),this.removeModal(r)}),c.appendChild(i)}r.appendChild(c);const u=document.createElement("button");u.textContent="✕",u.setAttribute("aria-label","Close"),u.style.cssText=`\n position: absolute; top: 20px; right: 20px; z-index: 3; background: ${s?"rgba(0,0,0,0.45)":"transparent"};\n border: none; color: ${s?"#fff":"inherit"}; font-size: ${s?"20px":"32px"}; cursor: pointer;\n padding: 0; width: ${s?"36px":"48px"}; height: ${s?"36px":"48px"}; border-radius: 50%;\n display: flex; align-items: center; justify-content: center; opacity: ${s?"0.9":"0.6"};\n `,u.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(r)}),r.appendChild(u),this.addAnimationStyles(),document.body.appendChild(r)}renderHalfInterstitial(e){const t=this.inAppStyle(e),n=e.interactive_config||{},i=e.video_url||n.video_url,o=document.createElement("div");o.className="aegis-in-app-half-interstitial-overlay",o.setAttribute("data-campaign-id",e.id),o.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\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 s=document.createElement("div");s.className="aegis-in-app-half-interstitial",s.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px ${t.radius}px 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 `;const a=document.createElement("div");if(a.style.cssText=`width: 40px; height: 4px; border-radius: 2px; background: ${t.text}33; margin: 10px auto 0;`,s.appendChild(a),i){const n=document.createElement("div");n.style.cssText=`position: relative; width: 100%; height: ${t.mediaHeight}px; overflow: hidden; margin-top: 10px; background: #000;`,this._heroVideo(i,e.image_url,n,"bottom-left"),s.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%; height: ${t.mediaHeight}px; object-fit: cover; margin-top: 10px;`,s.appendChild(n))}const r=document.createElement("div");r.style.cssText=`padding: ${t.padY}px ${t.padX}px;`;const c=document.createElement("h2");c.textContent=e.title,c.style.cssText=`margin: 0 0 12px 0; font-size: 24px; font-weight: ${t.weight}; color: ${t.text};`,r.appendChild(c);const d=document.createElement("p");d.textContent=e.body,d.style.cssText=`margin: 0 0 24px 0; font-size: 16px; line-height: 1.5; color: ${t.text}; opacity: 0.9;`,r.appendChild(d);const l=e.button_text||(e.action_url?"Continue":"");if(l){const n=document.createElement("button");n.className="aegis-cta",n.textContent=l,n.style.cssText=`\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n padding: 14px 32px;\n border-radius: ${t.btnRadius}px;\n font-weight: 700;\n font-size: 16px;\n cursor: pointer;\n width: 100%;\n `,n.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(o)}),r.appendChild(n)}const p=n.half_secondary_text;if(p){const i=n.half_secondary_url,s=document.createElement("button");s.type="button",s.textContent=p,s.style.cssText=`margin-top: 10px; background: transparent; border: none; color: ${t.text}; opacity: 0.75; font-weight: 600; font-size: 14px; cursor: pointer; width: 100%; text-decoration: underline;`,s.addEventListener("click",()=>{if(i){this.trackEvent(e.id,"clicked",{meta:{action:"secondary"}});const t=this.sanitizeUrl(i);if(t)return this.navigateToCampaignAction(e,t),void this.removeModal(o)}this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),r.appendChild(s)}s.appendChild(r);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: 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 ",h.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(o)}),s.style.position="relative",s.appendChild(h),o.appendChild(s),!1!==n.half_dismiss_on_overlay&&o.addEventListener("click",t=>{t.target===o&&(this.trackEvent(e.id,"dismissed"),this.removeModal(o))}),this.addAnimationStyles(),document.body.appendChild(o)}renderAlert(e){const t=this.inAppStyle(e),n=document.createElement("div");n.className="aegis-in-app-alert-overlay",n.setAttribute("data-campaign-id",e.id),n.style.cssText=`\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, ${t.overlay});\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.2s ease-out;\n `;const i=document.createElement("div");i.className="aegis-in-app-alert",i.style.cssText=`\n background: ${t.bg};\n color: ${t.text};\n border-radius: ${t.radius}px;\n max-width: 320px;\n width: 85%;\n box-shadow: 0 16px 48px rgba(0,0,0,0.22);\n animation: aegisScaleIn 0.2s ease-out;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n overflow: hidden;\n `;const o=document.createElement("div");o.style.cssText=`padding: ${t.padY}px ${t.padX}px; text-align: center;`;const s={info:{glyph:"ℹ",color:"#3b82f6"},success:{glyph:"✓",color:"#10b981"},warning:{glyph:"!",color:"#f59e0b"},error:{glyph:"✕",color:"#ef4444"}}[(e.interactive_config||{}).alert_variant||""];if(s){const e=document.createElement("div");e.style.cssText=`width: 48px; height: 48px; border-radius: 50%; margin: 0 auto 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 800; background: ${s.color}22; color: ${s.color};`,e.textContent=s.glyph,o.appendChild(e)}const a=document.createElement("h3");a.textContent=e.title,a.style.cssText=`margin: 0 0 8px 0; font-size: 18px; font-weight: ${t.weight}; color: ${t.text};`,o.appendChild(a);const r=document.createElement("p");r.textContent=e.body,r.style.cssText=`margin: 0; font-size: 14px; line-height: 1.4; color: ${t.text}; opacity: 0.85;`,o.appendChild(r),i.appendChild(o);const c=document.createElement("div");c.style.cssText=`display: flex; gap: 8px; justify-content: center; padding: 0 ${t.padX}px ${t.padY}px;`;const d=e.button_text||(e.action_url?"OK":"");if(d){const i=document.createElement("button");i.className="aegis-cta",i.textContent=d,i.style.cssText=`\n flex: 1;\n background: ${t.btnBg};\n color: ${t.btnText};\n border: none;\n border-radius: ${t.btnRadius}px;\n padding: 12px;\n font-weight: 600;\n font-size: 15px;\n cursor: pointer;\n `,i.addEventListener("click",()=>{if(this.trackEvent(e.id,"clicked"),e.action_url){const t=this.sanitizeUrl(e.action_url);t&&this.navigateToCampaignAction(e,t)}this.removeModal(n)}),c.appendChild(i)}const l=document.createElement("button");l.textContent="Cancel",l.style.cssText=`\n flex: 1;\n background: transparent;\n border: 1px solid ${t.text}55;\n color: ${t.text};\n opacity: 0.85;\n border-radius: ${t.btnRadius}px;\n padding: 12px;\n font-weight: 600;\n font-size: 15px;\n cursor: pointer;\n `,l.addEventListener("click",()=>{this.trackEvent(e.id,"dismissed"),this.removeModal(n)}),c.appendChild(l),i.appendChild(c),n.appendChild(i),this.addAnimationStyles(),document.body.appendChild(n)}_pipCornerCss(e,t){switch(e){case"bottom-left":return`bottom: ${t}px; left: ${t}px;`;case"top-right":return`top: ${t}px; right: ${t}px;`;case"top-left":return`top: ${t}px; left: ${t}px;`;default:return`bottom: ${t}px; right: ${t}px;`}}renderPIP(e){const t=e.interactive_config||{},n=t.pip_position||"bottom-right",i=t.pip_size||"standard",o=!1!==t.pip_autoplay,s=!1!==t.pip_loop,a=!1!==t.pip_muted,r=!1!==t.pip_expandable,c=!0===t.pip_draggable,d=20,l="undefined"!=typeof window&&window.innerWidth||360,p=Math.min({compact:250,standard:320,large:400}[i]??320,l-40),h=document.createElement("div");h.className="aegis-in-app-pip",h.setAttribute("data-campaign-id",e.id);const u=this._pipCornerCss(n,d),g=n.startsWith("top")?"aegisSlideDown":"aegisSlideUp";h.style.cssText=`\n position: fixed; ${u} width: ${p}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 14px; overflow: hidden;\n box-shadow: 0 10px 30px rgba(0,0,0,0.38); z-index: 999999;\n animation: ${g} 0.3s ease-out; transition: width 0.25s ease, border-radius 0.25s ease;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `;const m=document.createElement("div");m.style.cssText="position: relative; width: 100%; background: #000; line-height: 0; aspect-ratio: 16 / 9;";const f=e.video_url||t.video_url;let x=null,y=!1;if(f){const t=this.sanitizeUrl(f);if(t){if(x=document.createElement("video"),x.src=t,x.muted=a,x.loop=s,x.autoplay=o,x.playsInline=!0,x.setAttribute("playsinline",""),x.setAttribute("webkit-playsinline",""),x.controls=!1,e.image_url){const t=this.sanitizeUrl(e.image_url);t&&(x.poster=t)}x.style.cssText="width: 100%; height: 100%; display: block; object-fit: cover; background: #000;",m.appendChild(x),y=!0}}else if(e.image_url){const t=this.sanitizeUrl(e.image_url);if(t){const e=document.createElement("img");e.src=t,e.alt="",e.style.cssText="width: 100%; height: 100%; display: block; object-fit: cover;",m.appendChild(e),y=!0}}if(!y){const e=document.createElement("div");e.style.cssText="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #1f2937, #0f172a); color: rgba(255,255,255,0.35); font-size: 34px;",e.textContent="▶",m.appendChild(e)}if(h.appendChild(m),x){const e=x,t=document.createElement("button");t.type="button",t.setAttribute("aria-label","Play or pause"),t.style.cssText="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 52px; height: 52px; border-radius: 50%; border: none; background: rgba(0,0,0,0.45); color: #fff; font-size: 22px; cursor: pointer; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.25s ease; backdrop-filter: blur(2px);";const n=()=>{t.textContent=e.paused?"▶":"❚❚",t.style.opacity=e.paused?"1":"0"},i=()=>{e.paused?e.play().catch(()=>{}):e.pause()};t.addEventListener("click",e=>{e.stopPropagation(),i()}),m.addEventListener("click",i),e.addEventListener("play",()=>{n(),setTimeout(()=>{e.paused||(t.style.opacity="0")},600)}),e.addEventListener("pause",n),m.appendChild(t);const s=document.createElement("button");s.type="button";const a=()=>{s.replaceChildren();const t=document.createElement("span");if(t.style.fontSize="13px",t.textContent=e.muted?"🔇":"🔊",s.appendChild(t),e.muted){const e=document.createElement("span");e.textContent="Tap for sound",s.appendChild(e)}s.style.padding=e.muted?"6px 11px":"6px 9px"};s.style.cssText="position: absolute; left: 10px; bottom: 10px; display: inline-flex; align-items: center; gap: 6px; background: rgba(0,0,0,0.6); color: #fff; border: none; border-radius: 999px; font-size: 11.5px; font-weight: 700; cursor: pointer; z-index: 3; backdrop-filter: blur(3px);",s.setAttribute("aria-label","Toggle sound"),s.addEventListener("click",t=>{t.stopPropagation(),e.muted=!e.muted,!e.muted&&e.paused&&e.play().catch(()=>{}),a()}),e.addEventListener("volumechange",a),a(),m.appendChild(s),o&&e.play().catch(()=>{})}const b=this.inAppStyle(e),v=b.btnBg,w=b.btnText,_=document.createElement("div");if(_.style.cssText="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(to top, rgba(0,0,0,0.92), rgba(0,0,0,0.2) 70%, transparent); padding: 36px 14px 13px; color: #fff; pointer-events: none;",e.title){const t=document.createElement("div");t.textContent=e.title,t.style.cssText="font-size: 14px; font-weight: 700; margin-bottom: 3px; line-height: 1.25;",_.appendChild(t)}if(e.body){const t=document.createElement("div");t.textContent=e.body,t.style.cssText="font-size: 12px; opacity: 0.9; line-height: 1.35;",_.appendChild(t)}if(e.action_url&&e.button_text){const t=document.createElement("button");t.type="button",t.textContent=e.button_text,t.style.cssText=`pointer-events: auto; margin-top: 10px; padding: 8px 18px; border-radius: 999px; border: none; background: ${v}; color: ${w}; font-weight: 800; font-size: 12.5px; cursor: pointer;`,t.addEventListener("click",t=>{t.stopPropagation(),this.trackEvent(e.id,"clicked");const n=this.sanitizeUrl(e.action_url);n&&this.navigateToCampaignAction(e,n)}),_.appendChild(t)}h.appendChild(_);const C=document.createElement("div");C.style.cssText="position: absolute; top: 8px; right: 8px; display: flex; gap: 6px; z-index: 4;";const k="background: rgba(0,0,0,0.6); border: none; color: #fff; font-size: 14px; cursor: pointer; width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(3px);";let E=!1,S=null,T=null;const $=()=>{E=!1,S&&(S.remove(),S=null),h.style.position="fixed",h.style.cssText=`\n position: fixed; ${u} width: ${p}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 14px; overflow: hidden;\n box-shadow: 0 10px 30px rgba(0,0,0,0.38); z-index: 999999; transition: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,T&&(T.textContent="⤢",T.setAttribute("aria-label","Expand"))},I=()=>{E=!0,this.trackEvent(e.id,"impression",{meta:{action:"pip_expand"}}),S=document.createElement("div"),S.style.cssText="position: fixed; inset: 0; background: rgba(0,0,0,0.72); z-index: 999998; animation: aegisFadeIn 0.2s ease-out;",S.addEventListener("click",$),document.body.appendChild(S);const t=Math.min(760,l-40);h.style.cssText=`\n position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);\n width: ${t}px; max-width: calc(100vw - 40px);\n background: #000; border-radius: 16px; overflow: hidden;\n box-shadow: 0 24px 60px rgba(0,0,0,0.55); z-index: 999999; transition: none;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n `,T&&(T.textContent="✕",T.setAttribute("aria-label","Minimize")),x&&x.muted&&(x.muted=!1,x.dispatchEvent(new Event("volumechange")))};r&&y&&(T=document.createElement("button"),T.type="button",T.textContent="⤢",T.setAttribute("aria-label","Expand"),T.style.cssText=k,T.addEventListener("click",e=>{e.stopPropagation(),E?$():I()}),C.appendChild(T));const z=document.createElement("button");if(z.type="button",z.textContent="✕",z.setAttribute("aria-label","Close"),z.style.cssText=k,z.addEventListener("click",t=>{t.stopPropagation(),this.trackEvent(e.id,"dismissed"),S&&S.remove(),h.style.animation=("aegisSlideDown"===g?"aegisSlideUp":"aegisSlideDown")+" 0.3s ease-out",setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},300)}),C.appendChild(z),h.appendChild(C),c){let e=!1,t=0,n=0,i=0,o=0;const s=s=>{if(E)return;if(s.target.closest("button"))return;e=!0;const a=h.getBoundingClientRect();i=a.left,o=a.top,t=s.clientX,n=s.clientY,h.style.bottom="auto",h.style.right="auto",h.style.left=`${i}px`,h.style.top=`${o}px`,h.setPointerCapture(s.pointerId)},a=s=>{if(!e)return;const a=Math.max(4,Math.min(l-h.offsetWidth-4,i+(s.clientX-t))),r=Math.max(4,Math.min((window.innerHeight||800)-h.offsetHeight-4,o+(s.clientY-n)));h.style.left=`${a}px`,h.style.top=`${r}px`},r=()=>{e=!1};h.addEventListener("pointerdown",s),h.addEventListener("pointermove",a),h.addEventListener("pointerup",r),h.style.touchAction="none"}this.addAnimationStyles(),document.body.appendChild(h),this.trackEvent(e.id,"impression")}removeBanner(e){const t="bottom"===e.getAttribute("data-banner-position");e.style.animation=(t?"aegisSlideOutToBottom":"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)}_spotlightDimColor(e,t,n){const i=e.spotlight_dim_color||"dark",o="black"===i?"#000000":"brand"===i?t:"custom"===i?this.sanitizeColor(e.spotlight_dim_custom||"#0f172a"):"#0f172a",s=Math.round(255*Math.max(0,Math.min(1,n))).toString(16).padStart(2,"0");return/^#[0-9a-fA-F]{6}$/.test(o)?`${o}${s}`:`rgba(15,23,42,${n})`}renderTooltip(e){const t=e.interactive_config||{},n=t.tooltip_anchor_selector||"[data-aegis-tooltip]",i=t.tooltip_position||"auto",o=!1!==t.tooltip_highlight;let s=document.querySelector(n);if(!s)return console.warn(`[AegisInApp] Tooltip anchor "${n}" not found on this surface — tooltip not shown. On native apps this must be a key registered via registerInAppAnchor(); adding a new anchor needs an app release.`),void this.trackEvent(e.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:n,widget_type:"tooltip"}});const a=this.sanitizeColor(e.background_color||"#1a1a1a"),r=this.sanitizeColor(e.text_color||"#ffffff"),c=document.createElement("div");c.className="aegis-in-app-tooltip",c.setAttribute("data-campaign-id",e.id),c.style.cssText=`\n position: absolute; z-index: 1000001; max-width: 280px; width: max-content;\n background: ${a}; color: ${r}; border-radius: 10px; padding: 14px 16px;\n box-shadow: 0 8px 24px rgba(0,0,0,0.18); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.2s ease-out; pointer-events: auto;\n `;const d=document.createElement("div");d.className="aegis-tooltip-arrow",d.style.cssText=`\n position: absolute; width: 10px; height: 10px; background: ${a};\n transform: rotate(45deg);\n `;let l=null,p=null,h=null;const u=()=>{c.style.animation="aegisFadeOut 0.2s ease-out",l&&(l.remove(),l=null),p&&(document.removeEventListener("click",p),p=null),h&&(h(),h=null),setTimeout(()=>{var e;null==(e=c.parentNode)||e.removeChild(c)},200),this.trackEvent(e.id,"dismissed")},g=document.createElement("button");if(g.type="button",g.textContent="×",g.setAttribute("aria-label","Close"),g.style.cssText=`\n position: absolute; top: 4px; right: 4px; z-index: 1; background: none; border: none;\n color: ${r}; opacity: 0.7; font-size: 16px; line-height: 1; cursor: pointer;\n width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; padding: 0;\n `,g.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),u()}),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: 18px;",c.appendChild(t)}const m=document.createElement("div");if(m.textContent=e.body||"Here’s a quick tip.",m.style.cssText="font-size: 12px; line-height: 1.4; opacity: 0.9; padding-right: 18px;",c.appendChild(m),e.button_text&&e.action_url){const t=document.createElement("a");t.textContent=e.button_text,t.href=e.action_url,t.style.cssText=`\n display: inline-block; margin-top: 8px; font-size: 12px; font-weight: 600;\n color: ${r}; text-decoration: underline; cursor: pointer;\n `,t.addEventListener("click",()=>{this.trackEvent(e.id,"clicked")}),c.appendChild(t)}c.appendChild(g),c.appendChild(d),document.body.appendChild(c);const f="spotlight"===t.highlight_style,x="number"==typeof t.spotlight_padding?t.spotlight_padding:f?6:4,y="circle"===t.spotlight_shape?"50%":"12px",b="number"==typeof t.spotlight_dim?Math.max(0,Math.min(95,t.spotlight_dim))/100:.64,v=this._spotlightDimColor(t,a,b);if(o){l=document.createElement("div"),l.className="aegis-tooltip-highlight";const e=f?`box-shadow: 0 0 0 3px rgba(255,255,255,0.92), 0 0 0 6px ${a}66, 0 0 0 9999px ${v};`:`box-shadow: 0 0 0 3px ${a}55, 0 0 0 9999px rgba(0,0,0,0.04);`,t=f?"":"animation: aegisTooltipPulse 1.6s ease-in-out infinite;";l.style.cssText=`position: absolute; z-index: 1000000; pointer-events: none; border-radius: ${f?y:"8px"}; ${e} ${t}`,document.body.appendChild(l)}const w=10+("number"==typeof t.tooltip_offset?t.tooltip_offset:0),_={top:"bottom",bottom:"top",left:"right",right:"left"},C=()=>{if(!s)return;const e=s.getBoundingClientRect(),t=c.getBoundingClientRect(),n=window.scrollX,o=window.scrollY,a=window.innerWidth,r=window.innerHeight;l&&(l.style.top=e.top+o-x+"px",l.style.left=e.left+n-x+"px",l.style.width=`${e.width+2*x}px`,l.style.height=`${e.height+2*x}px`);const p=r-e.bottom,h=e.top,u=a-e.right,g=e.left,m=t.height+w,f=t.width+w,y=e=>"top"===e?h>=m:"bottom"===e?p>=m:"left"===e?g>=f:u>=f;let b=i;"auto"===b?b=p>=m?"bottom":h>=m?"top":u>=f?"right":g>=f?"left":p>=h?"bottom":"top":!y(b)&&y(_[b])&&(b=_[b]);let v=0,C=0,k="",E="",S="",T="";switch(b){case"top":v=e.top+o-t.height-w,C=e.left+n+(e.width-t.width)/2,S="-5px",E=t.width/2-5+"px";break;case"left":v=e.top+o+(e.height-t.height)/2,C=e.left+n-t.width-w,T="-5px",k=t.height/2-5+"px";break;case"right":v=e.top+o+(e.height-t.height)/2,C=e.right+n+w,E="-5px",k=t.height/2-5+"px";break;default:v=e.bottom+o+w,C=e.left+n+(e.width-t.width)/2,k="-5px",E=t.width/2-5+"px"}C=Math.max(8,Math.min(C,a+n-t.width-8)),v=Math.max(8+o,Math.min(v,r+o-t.height-8)),c.style.top=`${v}px`,c.style.left=`${C}px`,d.style.top=k||"",d.style.left=E||"",d.style.bottom=S||"",d.style.right=T||""},k=()=>{if(s&&s.isConnected)return!0;const t=document.querySelector(n);return t?(s=t,!0):(this.trackEvent(e.id,"anchor_unresolved",{meta:{anchor_resolved:!1,anchor_selector:n,widget_type:"tooltip",phase:"runtime"}}),u(),!1)};let E=0;const S=()=>{E||(E=window.requestAnimationFrame(()=>{E=0,k()&&C()}))};C(),window.addEventListener("scroll",S,{passive:!0,capture:!0}),window.addEventListener("resize",S,{passive:!0});let T=null,$=null;"undefined"!=typeof ResizeObserver&&(T=new ResizeObserver(S),s&&T.observe(s),T.observe(document.documentElement)),"undefined"!=typeof MutationObserver&&($=new MutationObserver(S),$.observe(document.body,{childList:!0,subtree:!0,attributes:!0})),h=()=>{E&&(window.cancelAnimationFrame(E),E=0),window.removeEventListener("scroll",S,{capture:!0}),window.removeEventListener("resize",S),T&&(T.disconnect(),T=null),$&&($.disconnect(),$=null)},p=e=>{c.contains(e.target)||s&&s.contains(e.target)||u()},setTimeout(()=>{p&&document.addEventListener("click",p)},100)}_fireConfetti(e){var t;try{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches)return;this.addAnimationStyles();const n=document.createElement("div");n.className="aegis-in-app-confetti",n.style.cssText="position: fixed; left: 0; right: 0; top: 0; height: 0; z-index: 2147483647; pointer-events: none;";const i=["#fbbf24","#10b981","#4169e1","#ef4444","#a855f7"],o=80;for(let e=0;e<o;e++){const t=document.createElement("span"),s=Math.round(e/o*100),a=Math.round(240*(Math.random()-.5))+"px",r=Math.round(1080*Math.random())+"deg",c=(.2*Math.random()).toFixed(2),d=(1.6+1.2*Math.random()).toFixed(2),l=i[e%i.length],p=6+Math.round(6*Math.random());t.style.cssText=`position: absolute; top: 0; left: ${s}%; width: ${p}px; height: ${p}px; background: ${l}; border-radius: 2px; --dx: ${a}; --r: ${r}; animation: aegisConfetti ${d}s cubic-bezier(.2,.6,.3,1) ${c}s forwards;`,n.appendChild(t)}((null==(t=null==e?void 0:e.ownerDocument)?void 0:t.body)||document.body).appendChild(n),window.setTimeout(()=>n.remove(),3200)}catch{}}_playReaction(e,t,n,i){try{if("undefined"==typeof document)return;this.addAnimationStyles();const o="undefined"!=typeof window&&window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=e||document.body,a=s.style.position;a&&"static"!==a||(s.style.position="relative");const r=document.createElement("div");r.className="aegis-in-app-reaction",r.style.cssText="position: absolute; inset: 0; z-index: 2147483646; pointer-events: none; overflow: visible;";const c={celebrate:{file:"trophy.json",svg:"gift",ring:"#fbbf24",festive:!0},affirm:{file:"affirm.json",svg:"star",ring:"#fbbf24",festive:!0},acknowledge:{file:"check.json",svg:"check",ring:"#34d399",festive:!1},empathize:{file:"empathize.json",svg:"heart",ring:"",festive:!1}}[t],d=c.festive;if(d&&!o)for(let e=0;e<3;e++){const t=document.createElement("div");t.style.cssText=`position: absolute; left: 50%; top: 50%; width: 60px; height: 60px; border-radius: 50%; border: 3px solid ${c.ring}; animation: aegisRing 1.1s ease-out ${.18*e}s forwards;`,r.appendChild(t)}const l=document.createElement("div"),p=Ue(this._reactionSvg(c.svg));p&&l.appendChild(p);const h=o?"":"empathize"!==t?"animation: aegisReactionPop 0.7s cubic-bezier(.2,.9,.3,1.2) forwards, aegisReactionFloatOut 0.7s ease-in 1.9s forwards;":"animation: aegisReactionSoft 0.9s ease-out forwards;",u=d?150:"acknowledge"===t?92:124;l.style.cssText=`position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: ${u}px; height: ${u}px; display: flex; align-items: center; justify-content: center; line-height: 0; filter: drop-shadow(0 8px 16px rgba(0,0,0,0.30)); ${h}`,r.appendChild(l),s.appendChild(r),d&&!o&&this._fireConfetti(e);const g=i&&"object"==typeof i?i.reaction_animations:void 0,m=(g&&"string"==typeof g[t]?g[t]:void 0)||n||c.file;if(!o&&m){const e=this._assetBase(),n="empathize"===t,i=/^https?:\/\//.test(m)?m:`${e}lottie/${m}`;this._loadLottie().then(e=>{e&&l.isConnected&&(l.replaceChildren(),e.loadAnimation({container:l,renderer:"svg",loop:n,autoplay:!0,path:i}))}).catch(()=>{})}window.setTimeout(()=>{r.remove(),s.style.position!==a&&(s.style.position=a)},"acknowledge"===t?1800:d?2700:2200)}catch{}}_reactionSvg(e){switch(e){case"star":return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#fbbf24"/><circle cx="37" cy="37" r="31" fill="none" stroke="#fff" stroke-width="2" opacity="0.6"/><path d="M37 19 l5.6 11.8 13 1.7 -9.5 9 2.4 12.8 -11.5 -6.2 -11.5 6.2 2.4 -12.8 -9.5 -9 13 -1.7 Z" fill="#fff"/></svg>';case"gift":return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#eef2ff"/><rect x="20" y="35" width="34" height="22" rx="3" fill="#6366f1"/><rect x="17" y="28" width="40" height="10" rx="3" fill="#4f46e5"/><rect x="34" y="28" width="6" height="29" fill="#fbbf24"/><path d="M34 28 C28 20 20 24 24 28 Z" fill="#fbbf24"/><path d="M40 28 C46 20 54 24 50 28 Z" fill="#fbbf24"/></svg>';case"heart":return'<svg width="66" height="66" viewBox="0 0 66 66" fill="none" style="animation: aegisBreathe 1.6s ease-in-out infinite; transform-origin: center;"><circle cx="33" cy="33" r="30" fill="#f1f5f9"/><path d="M33 49 C16 38 19 23 28 23 C32 23 33 27 33 27 C33 27 34 23 38 23 C47 23 50 38 33 49 Z" fill="rgba(244,114,182,0.18)" stroke="#f472b6" stroke-width="2.5" stroke-linejoin="round"/></svg>';default:return'<svg width="74" height="74" viewBox="0 0 74 74" fill="none"><circle cx="37" cy="37" r="31" fill="#10b981"/><circle cx="37" cy="37" r="31" fill="none" stroke="#fff" stroke-width="2" opacity="0.6"/><path d="M24 38 l9 9 l18 -21" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100" style="animation: aegisDraw 0.45s 0.25s ease forwards"/></svg>'}}_assetBase(){try{const e=Array.from(document.getElementsByTagName("script")).find(e=>/\/(?:aegis|lottie)\.min\.js/.test(e.src));if(e&&e.src)return e.src.replace(/[^/]*(?:\?.*)?$/,"")}catch{}return"/sdk/"}_loadLottie(){const e=window;return e.lottie?Promise.resolve(e.lottie):(e.__aegisLottieP||(e.__aegisLottieP=new Promise((e,t)=>{try{const n=document.createElement("script");n.src=`${this._assetBase()}lottie.min.js`,n.async=!0,n.onload=()=>e(window.lottie),n.onerror=()=>t(new Error("lottie player failed to load")),document.head.appendChild(n)}catch(n){t(n instanceof Error?n:new Error("lottie load error"))}})),e.__aegisLottieP)}addAnimationStyles(){if(document.getElementById("aegis-in-app-styles"))return;const e=document.createElement("style");e.id="aegis-in-app-styles",e.textContent="\n @keyframes aegisSlideDown {\n from { transform: translateY(-100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisSlideUp {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(-100%); opacity: 0; }\n }\n \n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisFadeOut {\n from { opacity: 1; }\n to { opacity: 0; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.9); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n\n /* Bottom-anchored slide IN (opposite of aegisSlideUp which slides OUT).\n Used by the preload-first renderers: sticky_bar (bottom),\n progress_bar, carousel_cards, product_recommendation. */\n @keyframes aegisSlideInFromBottom {\n from { transform: translateY(100%); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n\n /* Bottom-anchored slide OUT (mirror of aegisSlideInFromBottom). A\n bottom banner must exit DOWNWARD, not up through the viewport. */\n @keyframes aegisSlideOutToBottom {\n from { transform: translateY(0); opacity: 1; }\n to { transform: translateY(100%); opacity: 0; }\n }\n\n /* Celebration confetti (ported from the cashier-portal aegis-confetti\n keyframe) — fired on positive moments: high star rating, won spin/\n scratch prize, completed form. Empathetic (no confetti) on negatives. */\n @keyframes aegisConfetti {\n 0% { transform: translate3d(0,0,0) rotate(0); opacity: 1; }\n 100% { transform: translate3d(var(--dx), 112vh, 0) rotate(var(--r)); opacity: 0; }\n }\n\n /* Poll result bar — fills to its share once a vote lands. */\n @keyframes aegisPollFill {\n from { width: 0%; }\n to { width: var(--pct, 0%); }\n }\n\n /* Countdown urgency — pulse the digits red in the final stretch (<60s). */\n @keyframes aegisUrgencyPulse {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n\n /* Emotional reaction (success) — the hero glyph springs in with an\n overshoot, gives a happy wiggle, then gently settles + floats out. */\n @keyframes aegisReactionPop {\n 0% { transform: translate(-50%, -40%) scale(0.2) rotate(-12deg); opacity: 0; }\n 45% { transform: translate(-50%, -52%) scale(1.18) rotate(6deg); opacity: 1; }\n 62% { transform: translate(-50%, -50%) scale(0.94) rotate(-3deg); }\n 78% { transform: translate(-50%, -50%) scale(1.05) rotate(1deg); }\n 100% { transform: translate(-50%, -50%) scale(1) rotate(0); opacity: 1; }\n }\n @keyframes aegisReactionFloatOut {\n 0% { transform: translate(-50%, -50%) scale(1); opacity: 1; }\n 100% { transform: translate(-50%, -150%) scale(0.9); opacity: 0; }\n }\n /* Empathetic reaction — soft fade-in + gentle sway, NO celebration. */\n @keyframes aegisReactionSoft {\n 0% { transform: translate(-50%, -45%) scale(0.7); opacity: 0; }\n 25% { transform: translate(-50%, -50%) scale(1); opacity: 1; }\n 50% { transform: translate(-52%, -50%) scale(1) rotate(-4deg); }\n 75% { transform: translate(-48%, -50%) scale(1) rotate(4deg); }\n 100% { transform: translate(-50%, -50%) scale(1) rotate(0); opacity: 1; }\n }\n /* Radiating celebration rings behind the success glyph. */\n @keyframes aegisRing {\n 0% { transform: translate(-50%, -50%) scale(0.3); opacity: 0.55; }\n 100% { transform: translate(-50%, -50%) scale(2.4); opacity: 0; }\n }\n /* Self-drawing stroke (the check / outline draws itself in). */\n @keyframes aegisDraw {\n from { stroke-dashoffset: 100; }\n to { stroke-dashoffset: 0; }\n }\n /* Gentle breathing for the empathetic heart. */\n @keyframes aegisBreathe {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.08); }\n }\n /* Comment-box placeholder — inherit the modal's text color (not the\n browser default near-black, which is invisible on a dark/accent modal). */\n .aegis-rating-comment::placeholder, .aegis-field::placeholder { color: currentColor; opacity: 0.55; }\n /* Tooltip target highlight — a soft pulsing ring drawing the eye. */\n @keyframes aegisTooltipPulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n /* Countdown final-minute urgency — a gentle breathing pulse (NOT a harsh\n solid-red fill). */\n @keyframes aegisCountdownPulse {\n 0%, 100% { transform: scale(1); }\n 50% { transform: scale(1.04); }\n }\n /* Shared CTA micro-interaction — one consistent hover-lift + press across\n every widget's primary button, so they feel like one system. */\n .aegis-cta { transition: transform 0.12s ease, box-shadow 0.12s ease, filter 0.12s ease; }\n .aegis-cta:hover { transform: translateY(-1px); box-shadow: 0 6px 16px rgba(0,0,0,0.18); filter: brightness(1.04); }\n .aegis-cta:active { transform: translateY(0); box-shadow: 0 2px 6px rgba(0,0,0,0.15); filter: brightness(0.98); }\n @media (prefers-reduced-motion: reduce) { .aegis-cta { transition: none; } .aegis-cta:hover { transform: none; } }\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,n){var i;const o=this.campaigns.find(t=>t.id===e);"dismissed"===t&&o&&this.emit("campaign-dismiss",{campaign:o,source:"close_button"});try{const s=`${this.apiHost}/v1/in_app/events`,a=`inapp_${e}_${t}_${Date.now()}`,r={"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey};this.organizationId&&(r["X-Organization-ID"]=this.organizationId),this.userId&&(r["X-User-ID"]=this.userId),this.contactId&&(r["X-Contact-ID"]=this.contactId);const c=null==(i=this.getWorkspaceId)?void 0:i.call(this),d={campaign_id:e,event_type:t,user_id:this.userId,contact_id:this.contactId,anonymous_id:this.userId,platform:"web",workspace_id:c,current_surface:this.currentSurface??void 0,step_id:null==n?void 0:n.stepId,journey_execution_id:null==o?void 0:o.journey_execution_id,lifecycle_fork_id:null==o?void 0:o.lifecycle_fork_id,location_id:null==o?void 0:o.location_id,metadata:{property_id:this.propertyId,variant_id:this.getVariantId(e)??void 0,lifecycle_fork_id:null==o?void 0:o.lifecycle_fork_id,location_id:null==o?void 0:o.location_id,...(null==n?void 0:n.meta)??{}},idempotency_key:a};fetch(s,{method:"POST",headers:r,body:JSON.stringify(d),credentials:"include"}).catch(e=>{this.log(`Error tracking event: ${e}`,"error")}),this.log(`Tracked ${t} event for campaign ${e}`)}catch(s){this.log(`Error tracking event: ${s}`,"error")}}log(e,t="log"){this.debugMode&&console[t](`[AegisInApp] ${e}`)}destroy(e){if(this.disconnectSSE(),null==Oe||Oe.stop(),Oe=null,null==Fe||Fe.destroy(),Fe=null,this.activeWebChat=void 0,this.refreshDebounceTimer&&(clearTimeout(this.refreshDebounceTimer),this.refreshDebounceTimer=void 0),"undefined"!=typeof document){document.querySelectorAll(".aegis-in-app-banner, .aegis-in-app-modal-overlay, .aegis-in-app-fullscreen-overlay, .aegis-in-app-half-interstitial-overlay, .aegis-in-app-alert-overlay, .aegis-in-app-pip, .aegis-in-app-nps-overlay, .aegis-in-app-countdown-overlay, .aegis-in-app-rating-overlay, .aegis-in-app-poll-overlay, .aegis-in-app-quiz-overlay, .aegis-in-app-rating-card, .aegis-in-app-nps-card").forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});const e=document.getElementById("aegis-in-app-styles");e&&e.parentNode&&e.parentNode.removeChild(e)}(null==e?void 0:e.clearABState)&&"undefined"!=typeof localStorage&&localStorage.removeItem("aegis_ab_assignments"),this.isInitialized=!1,this.log("AegisInApp destroyed")}};je.CONVERSION_STORAGE_PREFIX="aegis_conv_",je.REFRESH_DEBOUNCE_MS=300,je.KNOWN_SURFACES=new Set(["bill","storefront_catalog","storefront_rewards","storefront_feedback","storefront_reviews","storefront_members","external_website","external_mobile_screen"]),je.SERVED_DEDUP_PREFIX="aegis_served_fired:";let We=je;function qe(e){if(e.id)return`#${CSS.escape(e.id)}`;for(const i of["data-testid","data-test","data-aegis-anchor","data-qa","name"]){const t=e.getAttribute(i);if(t){const n=`${e.tagName.toLowerCase()}[${i}="${CSS.escape(t)}"]`;if(1===document.querySelectorAll(n).length)return n}}const t=[];let n=e;for(;n&&n!==document.body&&t.length<6;){if(n.id){t.unshift(`#${CSS.escape(n.id)}`);break}const e=n.tagName.toLowerCase(),i=n.parentElement;if(!i){t.unshift(e);break}const o=Array.from(i.children).filter(e=>e.tagName===n.tagName),s=o.indexOf(n)+1;t.unshift(o.length>1?`${e}:nth-of-type(${s})`:e),n=i}return t.join(" > ")}async function He(e,t,n={}){const i=`${e.replace(/\/$/,"")}/v1/device-pairing`,o=()=>{};try{const e=await fetch(`${i}/${encodeURIComponent(t)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({platform:"web",device_label:n.deviceLabel||"Web browser"})});if(!e.ok)return{ok:!1,stop:o,error:`claim failed (${e.status})`};const s=async()=>{try{const e=function(e){const t=[],n=document.querySelectorAll("a,button,input,select,textarea,[role],[data-aegis-anchor],[data-testid],h1,h2,h3,img,[data-aegis-slot]");for(const i of Array.from(n)){if(t.length>=400)break;const e=i.getBoundingClientRect();if(e.width<=0||e.height<=0)continue;const n=i.getAttribute("data-aegis-slot"),o=n?`slot:${n}`:i.getAttribute("role")||i.tagName.toLowerCase(),s=(i.textContent||i.getAttribute("aria-label")||"").trim().slice(0,80);t.push({selector:qe(i),role:o,...s?{text:s}:{},bounds:{x:Math.round(e.left+window.scrollX),y:Math.round(e.top+window.scrollY),w:Math.round(e.width),h:Math.round(e.height)}})}return{screen_name:e||window.location.pathname||"/",view_tree:t,viewport:{w:window.innerWidth,h:window.innerHeight,scale:window.devicePixelRatio||1},platform:"web"}}(n.screenName);await fetch(`${i}/${encodeURIComponent(t)}/screens`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch{}};if(await s(),!1===n.live)return{ok:!0,stop:o};let a=null;const r=()=>{s()};window.addEventListener("popstate",r),window.addEventListener("hashchange",r),a=setInterval(()=>{s()},4e3);return{ok:!0,stop:()=>{window.removeEventListener("popstate",r),window.removeEventListener("hashchange",r),a&&(clearInterval(a),a=null)}}}catch(s){return{ok:!1,stop:o,error:s instanceof Error?s.message:"pairing error"}}}let Ve=!1;function Xe(e){if(!Ve&&"undefined"!=typeof window)try{const t=new URLSearchParams(window.location.search).get("aegis_pair");if(!t)return;Ve=!0,He(e||"https://api.active-reach.ai",t,{live:!0})}catch{}}class Ke{constructor(e){this.widgets=[],this.renderedWidgets=new Set,this.isInitialized=!1,this.isDestroyed=!1,this.prefetchWidgetConfigs={},this.writeKey=e.writeKey,this.apiHost=e.apiHost||"https://api.aegis.ai",this.userId=e.userId??function(){if("undefined"!=typeof document)try{return(new l).get("anon_id")??void 0}catch{return}}(),this.contactId=e.contactId,this.organizationId=e.organizationId,this.debugMode=e.debugMode||!1,this.triggerEngine=e.triggerEngine,this.ownsTriggerEngine=!0===e.ownsTriggerEngine,this.enablePrefetch=!1!==e.enablePrefetch,this.cssCustomization=e.cssCustomization||{},this.onEvent=e.onEvent,this.sourcePlatform=e.sourcePlatform,this.getWorkspaceId=e.getWorkspaceId}updateCSSCustomization(e){this.cssCustomization={...this.cssCustomization,...e},this.log("CSS customization updated")}async updateContactId(e){this.contactId!==e&&(this.contactId=e,this.log(`Contact ID updated → ${e??"(cleared)"}`),this.isInitialized&&!this.isDestroyed&&this.enablePrefetch&&e&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()))}renderInteractiveCampaign(e){if(this.isDestroyed)return;if("undefined"==typeof document)return;const t=e.sub_type;if("spin_wheel"!==t&&"scratch_card"!==t)return void this.log(`renderInteractiveCampaign: unsupported sub_type "${t}"`,!0);const n={widget_id:e.id,widget_type:t,name:e.title,config:e.interactive_config??{},priority:e.priority??0};this.renderedWidgets.has(n.widget_id)||(this.renderedWidgets.add(n.widget_id),"spin_wheel"===t?this.renderSpinWheel(n):this.renderScratchCard(n))}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.triggerEngine&&this.ownsTriggerEngine&&this.triggerEngine.stop(),"undefined"!=typeof document){const e=document.getElementById("aegis-widget-animations");null==e||e.remove(),document.querySelectorAll("[data-aegis-widget-root]").forEach(e=>{e.remove()})}this.renderedWidgets.clear(),this.widgets=[],this.isInitialized=!1,this.log("AegisWidgets destroyed"),this.emitEvent("destroyed",{})}}emitEvent(e,t){if(this.onEvent)try{this.onEvent(e,t)}catch(n){this.log(`Error in event callback: ${n}`,!0)}}async initialize(){this.isInitialized?this.log("AegisWidgets already initialized"):(this.enablePrefetch&&this.contactId&&(await this.fetchPrefetchConfigs(),this.preloadWidgetAssets()),await this.fetchWidgets(),this.renderImmediateWidgets(),this.setupTriggerListeners(),this.setupExitIntentWithPrefetch(),this.isInitialized=!0,this.log("AegisWidgets initialized successfully"))}setCartData(e){this.cartData=e,this.log(`Cart data updated: ${e.cart_items.length} items, total: ${e.cart_currency} ${e.cart_total}`)}detectPlatformCart(){const e=this.normalizeShopifyCart();if(e)return this.log("Detected Shopify cart via browser globals"),e;const t=this.normalizeWooCart();if(t)return this.log("Detected WooCommerce cart via injected data"),t;const n=this.normalizeMagentoCart();return n?(this.log("Detected Magento cart via localStorage"),n):this.cartData?(this.log("Using manually set cart data"),this.cartData):null}normalizeShopifyCart(){var e;try{if("undefined"==typeof window)return null;const t=window;if(null==(e=t.Shopify)?void 0:e.checkout){const e=t.Shopify.checkout;return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:parseFloat(e.total_price)||0,cart_currency:e.currency||"USD",cart_items:(e.line_items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.title||e.product_title,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}const n=document.getElementById("cart-json");if(null==n?void 0:n.textContent){const e=JSON.parse(n.textContent);return{cart_id:e.token||`shopify_${Date.now()}`,cart_total:(e.total_price||0)/100,cart_currency:e.currency||"USD",cart_items:(e.items||[]).map(e=>({product_id:String(e.product_id||e.id),product_name:e.product_title||e.title,quantity:e.quantity||1,price:(e.price||0)/100}))}}return null}catch(t){return this.log(`Error detecting Shopify cart: ${t}`,!0),null}}normalizeWooCart(){try{if("undefined"==typeof window)return null;const e=window;if(e.aegis_cart){const t=e.aegis_cart;return{cart_id:t.cart_id||`woo_${Date.now()}`,cart_total:parseFloat(t.cart_total)||0,cart_currency:t.cart_currency||"USD",cart_items:(t.cart_items||[]).map(e=>({product_id:String(e.product_id),product_name:e.product_name,quantity:e.quantity||1,price:parseFloat(e.price)||0}))}}return null}catch(e){return this.log(`Error detecting WooCommerce cart: ${e}`,!0),null}}normalizeMagentoCart(){try{if("undefined"==typeof window||!window.localStorage)return null;const e=localStorage.getItem("mage-cache-storage");if(!e)return null;const t=JSON.parse(e);if(!(null==t?void 0:t.cart))return null;const n=t.cart;return{cart_id:n.quote_id||n.id||`magento_${Date.now()}`,cart_total:parseFloat(n.subtotalAmount||n.subtotal||0),cart_currency:n.currencyCode||"USD",cart_items:(n.items||[]).map(e=>({product_id:String(e.item_id||e.product_id),product_name:e.product_name||e.name,quantity:e.qty||1,price:parseFloat(e.product_price_value||e.price||0)}))}}catch(e){return this.log(`Error detecting Magento cart: ${e}`,!0),null}}preloadWidgetAssets(){try{const e=this.prefetchWidgetConfigs.exit_intent;if(null==e?void 0:e.enabled){const t=e.image_url;if(t){(new Image).src=t,this.log(`Preloading exit intent image: ${t}`)}}const t=this.prefetchWidgetConfigs.spin_wheel;if(null==t?void 0:t.enabled){const e=t.image_url;if(e){(new Image).src=e,this.log(`Preloading spin wheel image: ${e}`)}}}catch(e){this.log(`Error preloading widget assets: ${e}`,!0)}}async fetchPrefetchConfigs(){try{const e=performance.now(),t=`${this.apiHost}/v1/widgets/config/prefetch`,n={"X-Aegis-Write-Key":this.writeKey};this.contactId&&(n["X-Contact-ID"]=this.contactId),this.organizationId&&(n["X-Organization-ID"]=this.organizationId);const i=await fetch(t,{headers:n,credentials:"include"});if(!i.ok)throw new Error(`Failed to fetch prefetch configs: ${i.status}`);this.prefetchWidgetConfigs=await i.json();const o=performance.now()-e;this.log(`Fetched prefetch widget configs in ${o.toFixed(2)}ms`)}catch(e){this.log(`Error fetching prefetch configs: ${e}`,!0)}}async fetchWidgets(){try{const e=`${this.apiHost}/v1/widgets/config`,t={"X-Aegis-Write-Key":this.writeKey,"X-Device-Platform":"web","X-Device-Type":this.getDeviceType()};this.userId&&(t["X-User-ID"]=this.userId),this.contactId&&(t["X-Contact-ID"]=this.contactId),this.organizationId&&(t["X-Organization-ID"]=this.organizationId),this.sourcePlatform&&(t["X-Source-Platform"]=this.sourcePlatform);const n=await fetch(e,{headers:t,credentials:"include"});if(!n.ok)throw new Error(`Failed to fetch widgets: ${n.status}`);this.widgets=await n.json(),this.log(`Fetched ${this.widgets.length} widgets`)}catch(e){this.log(`Error fetching widgets: ${e}`,!0)}}renderImmediateWidgets(){this.widgets.filter(e=>!e.trigger_rules||"immediate"===e.trigger_rules.type).forEach(e=>this.renderWidget(e))}setupTriggerListeners(){this.triggerEngine?this.widgets.forEach(e=>{if(!e.trigger_rules)return;const{type:t,config:n}=e.trigger_rules;switch(t){case"exit_intent":this.triggerEngine.registerExitIntent(),this.triggerEngine.on("exit_intent",()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"scroll_depth":const t=(null==n?void 0:n.depth_percent)||50;this.triggerEngine.registerScrollDepth(t),this.triggerEngine.on(`scroll_depth_${t}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)});break;case"time_on_page":const i=(null==n?void 0:n.seconds)||30;this.triggerEngine.registerTimeOnPage(i),this.triggerEngine.on(`time_on_page_${i}`,()=>{this.renderedWidgets.has(e.widget_id)||this.renderWidget(e)})}}):this.log("TriggerEngine not provided, skipping trigger-based widgets")}setupExitIntentWithPrefetch(){if(!this.enablePrefetch||!this.triggerEngine)return;const e=this.prefetchWidgetConfigs.spin_wheel,t=this.prefetchWidgetConfigs.exit_intent;if(e&&e.enabled){const n=this.isMobileDevice(),i=(null==t?void 0:t.mobile_triggers)||{},o=()=>{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",o),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}`,o),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",o),this.log("Registered mobile visibility change trigger for spin wheel (cart detected)"))}!0===i.back_button&&(this.triggerEngine.registerBackButton(),this.triggerEngine.on("back_button",o),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",o),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||{},o=()=>{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",o),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}`,o),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",o),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",o),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",o),this.log(`Setup desktop exit intent: type=${t.type}, priority=${t.priority}`)}sendCartAbandonmentBeacon(){if(!this.cartData)return void this.log("No cart data available for beacon",!0);const e={organization_id:this.organizationId||"default",contact_id:this.contactId,cart_id:this.cartData.cart_id,cart_total:this.cartData.cart_total,cart_currency:this.cartData.cart_currency,cart_items:this.cartData.cart_items,user_email:this.userId,abandoned_at:(new Date).toISOString(),page_url:window.location.href,referrer:document.referrer},t=`${this.apiHost}/v1/widgets/beacon/cart-abandoned`;if(navigator.sendBeacon){const n=new Blob([JSON.stringify(e)],{type:"application/json"});navigator.sendBeacon(t,n)?this.log("Cart abandonment beacon sent successfully"):this.log("Failed to send cart abandonment beacon",!0)}else fetch(t,{method:"POST",headers:{"Content-Type":"application/json","X-Aegis-Write-Key":this.writeKey},body:JSON.stringify(e),keepalive:!0,credentials:"include"}).catch(e=>{this.log(`Error sending cart abandonment via fetch: ${e}`,!0)})}renderWidget(e){if(!this.isDestroyed&&!this.renderedWidgets.has(e.widget_id)){switch(this.renderedWidgets.add(e.widget_id),e.widget_type){case"chat_bubble":this.renderChatBubble(e);break;case"spin_wheel":this.renderSpinWheel(e);break;case"scratch_card":this.renderScratchCard(e);break;case"toast":this.renderToast(e);break;case"feedback_form":this.renderFeedbackForm(e);break;case"exit_intent_popup":this.renderExitIntentPopup(e);break;default:this.log(`Unknown widget type: ${e.widget_type}`,!0)}this.trackEvent(e.widget_id,"show")}}renderChatBubble(e){const{text:t,icon_url:n,link_url:i,background_color:o,text_color:s}=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(o||"#25D366")};\n color: ${this.sanitizeColor(s||"#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(),r.setAttribute("data-aegis-widget-root",""),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 o=document.createElement("p");o.textContent=e.config.description||"Try your luck and win exclusive prizes!",o.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(o);const s=Array.isArray(e.config.segments)?e.config.segments:[{label:"Prize 1",color:"#ff6b6b"},{label:"Prize 2",color:"#feca57"},{label:"Prize 3",color:"#48dbfb"},{label:"Prize 4",color:"#ff6348"}],a="http://www.w3.org/2000/svg",r=document.createElementNS(a,"svg");r.setAttribute("viewBox","-160 -160 320 320"),r.setAttribute("width","300"),r.setAttribute("height","300"),r.style.cssText="margin: 0 auto 24px; display: block;";const c=s.length,d=2*Math.PI/c,l=140;for(let u=0;u<c;u++){const e=u*d-Math.PI/2,t=e+d,n=Math.cos(e)*l,i=Math.sin(e)*l,o=Math.cos(t)*l,c=Math.sin(t)*l,p=d>Math.PI?1:0,h=document.createElementNS(a,"path");h.setAttribute("d",`M 0 0 L ${n.toFixed(2)} ${i.toFixed(2)} A 140 140 0 ${p} 1 ${o.toFixed(2)} ${c.toFixed(2)} Z`),h.setAttribute("fill",this.sanitizeColor(s[u].color||"#cccccc")),h.setAttribute("stroke","#ffffff"),h.setAttribute("stroke-width","2"),r.appendChild(h);const g=e+d/2,m=Math.cos(g)*l*.65,f=Math.sin(g)*l*.65,x=document.createElementNS(a,"text");x.setAttribute("x",m.toFixed(2)),x.setAttribute("y",f.toFixed(2)),x.setAttribute("fill","#ffffff"),x.setAttribute("font-size","13"),x.setAttribute("font-weight","600"),x.setAttribute("text-anchor","middle"),x.setAttribute("dominant-baseline","middle"),x.textContent=s[u].label||`#${u+1}`,r.appendChild(x)}n.appendChild(r);const p=document.createElement("button");p.textContent="SPIN NOW!",p.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 ",p.addEventListener("click",async()=>{p.disabled=!0,p.textContent="SPINNING...";try{const t=await this.generatePrize(e.config.config_id);r.style.animation="aegisSpin 2s ease-out",setTimeout(()=>{this.showPrizeResult(n,t)},2e3)}catch(t){this.log(`Error generating prize: ${t}`,!0),p.disabled=!1,p.textContent="TRY AGAIN"}}),n.appendChild(p);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: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",h.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),n.style.position="relative",n.appendChild(h),t.appendChild(n),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderSpinWheelWidget(e,t){if(this.isDestroyed)return;const n=this.detectPlatformCart();if("cart_recovery"===t.type&&!n)return void this.log("Spin wheel requires cart, but none detected");n&&(this.cartData=n);const i=this.cssCustomization.spinWheel||{},o=i.accentColor||t.accent_color||"#FF6B6B",s=i.backgroundColor||t.background_color||"#FFFFFF",a=i.textColor||t.text_color||"#333333",r=i.buttonColor||t.button_color||o,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(s)};\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 p=document.createElement("button");p.innerHTML="✕",p.className="aegis-spin-wheel-close",p.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 ",p.onclick=()=>{this.trackEvent(e,"dismiss",{type:"spin_wheel"}),document.body.removeChild(d),this.renderedWidgets.delete(e)},l.appendChild(p);const h=document.createElement("h2");if(h.textContent=this.interpolateCartVariables(t.title||"Spin to Win!"),h.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(h),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 x=document.createElement("input");x.type="text",x.placeholder="Enter your name (optional)",x.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(x);const y=document.createElement("button");y.type="submit",y.textContent="Spin the Wheel!",y.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(y);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(),o=f.value.trim(),s=x.value.trim();return this.validatePhone(i)?o&&!this.validateEmail(o)?(b.textContent="Please enter a valid email address",void(b.style.display="block")):(b.style.display="none",y.disabled=!0,y.textContent="Spinning...",u.style.animation="aegisSpin 2s ease-out",void setTimeout(async()=>{try{const t=await this.submitSpinWheel({phone:i,email:o,name:s,cart:n,widgetId:e});this.showSpinWheelPrize(l,t),this.trackEvent(e,"submit",{type:"spin_wheel",prize_label:t.prize_label,has_email:!!o})}catch(t){this.log(`Error submitting spin wheel: ${t}`,!0),b.textContent="Failed to submit. Please try again.",b.style.display="block",y.disabled=!1,y.textContent="Spin the Wheel!",u.style.animation=""}},2e3)):(b.textContent="Please enter a valid phone number (e.g., +1234567890)",void(b.style.display="block"))}),l.appendChild(u),l.appendChild(g),d.appendChild(l),this.addAnimationStyles(),d.setAttribute("data-aegis-widget-root",""),document.body.appendChild(d),this.trackEvent(e,"show",{type:"spin_wheel"})}validatePhone(e){return/^\+?[1-9]\d{1,14}$/.test(e.replace(/[\s()-]/g,""))}validateEmail(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}async submitSpinWheel(e){var t,n,i,o,s;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(),p={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==(o=e.cart)?void 0:o.cart_currency)||"USD",cart_items:(null==(s=e.cart)?void 0:s.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},h=await fetch(a,{method:"POST",headers:r,body:JSON.stringify(p),credentials:"include"});if(!h.ok){const e=await h.text();throw new Error(`Failed to submit spin wheel: ${h.status} - ${e}`)}return await h.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 o=document.createElement("h2");o.textContent="Congratulations!",o.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(o);const s=document.createElement("p");if(s.textContent=t.prize_label,s.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(s),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 o=document.createElement("div");o.textContent=t.coupon_code,o.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(o),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 o=document.createElement("p");o.textContent=e.config.description||"Scratch to reveal your prize!",o.style.cssText="margin: 0 0 24px 0; font-size: 14px; color: #666;",n.appendChild(o);const s=document.createElement("canvas");s.width=300,s.height=200,s.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(s);const a=s.getContext("2d");if(a){a.fillStyle="#c0c0c0",a.fillRect(0,0,s.width,s.height),a.fillStyle="#888",a.font="20px Arial",a.textAlign="center",a.fillText("Scratch here!",s.width/2,s.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()};s.addEventListener("mousedown",()=>{e=!0}),s.addEventListener("mouseup",()=>{e=!1}),s.addEventListener("mousemove",n=>{if(e){const e=s.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(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderToast(e){const{message:t,icon:n,duration:i}=e.config,o=e.position||"bottom_left",s=document.createElement("div");s.className="aegis-toast",s.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(s.style.cssText=`\n position: fixed;\n ${a[o]||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;",s.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;",s.appendChild(r),this.addAnimationStyles(),s.setAttribute("data-aegis-widget-root",""),document.body.appendChild(s),setTimeout(()=>{s.style.animation="aegisToastOut 0.3s ease-out",setTimeout(()=>{document.body.contains(s)&&document.body.removeChild(s),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 o=document.createElement("form"),s=document.createElement("label");s.textContent="How likely are you to recommend us? (0-10)",s.style.cssText="display: block; font-size: 14px; font-weight: 600; margin-bottom: 8px; color: #333;",o.appendChild(s);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 ",o.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;",o.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 ",o.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 ",o.appendChild(d),o.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(o);const l=document.createElement("button");l.textContent="×",l.setAttribute("aria-label","Close"),l.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: transparent;\n border: none;\n font-size: 28px;\n cursor: pointer;\n color: #999;\n ",l.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(t),this.renderedWidgets.delete(e.widget_id)}),t.appendChild(l),this.addAnimationStyles(),t.setAttribute("data-aegis-widget-root",""),document.body.appendChild(t)}renderExitIntentPopup(e){const{title:t,description:n,cta_text:i,cta_url:o,image_url:s}=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 ',s){const e=document.createElement("img"),t=this.sanitizeUrl(s);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&&o){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(o);t&&(window.location.href=t)}),c.appendChild(t)}r.appendChild(c);const p=document.createElement("button");p.textContent="×",p.setAttribute("aria-label","Close"),p.style.cssText="\n position: absolute;\n top: 16px;\n right: 16px;\n background: 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 ",p.addEventListener("click",()=>{this.trackEvent(e.widget_id,"dismiss"),document.body.removeChild(a),this.renderedWidgets.delete(e.widget_id)}),r.style.position="relative",r.appendChild(p),a.appendChild(r),this.addAnimationStyles(),a.setAttribute("data-aegis-widget-root",""),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}),credentials:"include"});if(!i.ok)throw new Error(`Failed to generate prize: ${i.status}`);return await i.json()}showPrizeResult(e,t){e.innerHTML="";const n=document.createElement("div");n.style.cssText="text-align: center; padding: 40px 20px;";const i=document.createElement("div");i.textContent="🎉",i.style.cssText="font-size: 60px; margin-bottom: 20px;",n.appendChild(i);const o=document.createElement("h2");o.textContent="Congratulations!",o.style.cssText="margin: 0 0 12px 0; font-size: 28px; font-weight: 700; color: #1a73e8;",n.appendChild(o);const s=document.createElement("p");if(s.textContent=t.prize_label,s.style.cssText="margin: 0 0 20px 0; font-size: 20px; font-weight: 600; color: #333;",n.appendChild(s),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 o=document.createElement("div");o.textContent=t.coupon_code,o.style.cssText="font-size: 24px; font-weight: 700; color: #1a73e8; letter-spacing: 2px;",e.appendChild(o),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){var n;const i=`${this.apiHost}/v1/widgets/track-event`,o={"X-Aegis-Write-Key":this.writeKey,"Content-Type":"application/json"};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 s=null==(n=this.getWorkspaceId)?void 0:n.call(this),a=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({widget_id:e,event_type:"submit",event_data:t,workspace_id:s}),credentials:"include"});if(!a.ok)throw new Error(`Failed to submit feedback: ${a.status}`)}async trackEvent(e,t,n){var i;try{const o=`${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);const a=null==(i=this.getWorkspaceId)?void 0:i.call(this);await fetch(o,{method:"POST",headers:s,body:JSON.stringify({widget_id:e,event_type:t,event_data:n||{},workspace_id:a}),credentials:"include"})}catch(o){this.log(`Error tracking widget event: ${o}`,!0)}}sanitizeUrl(e){if(!e)return null;try{const t=new URL(e,window.location.href);return"javascript:"===t.protocol||"data:"===t.protocol?(this.log(`Blocked dangerous URL: ${e}`,!0),null):t.href}catch{return this.log(`Invalid URL: ${e}`,!0),null}}sanitizeColor(e){return/^#[0-9A-F]{3,8}$/i.test(e)||/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)$/i.test(e)||/^rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*[\d.]+\s*\)$/i.test(e)?e:"#1a73e8"}getDeviceType(){const e=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(e)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(e)?"mobile":"desktop"}isMobileDevice(){const e=this.getDeviceType();return"mobile"===e||"tablet"===e}addAnimationStyles(){if(document.getElementById("aegis-widget-animations"))return;const e=document.createElement("style");e.id="aegis-widget-animations",e.textContent="\n @keyframes aegisFadeIn {\n from { opacity: 0; }\n to { opacity: 1; }\n }\n \n @keyframes aegisScaleIn {\n from { transform: scale(0.8); opacity: 0; }\n to { transform: scale(1); opacity: 1; }\n }\n \n @keyframes aegisBubbleIn {\n from { transform: translateY(20px); opacity: 0; }\n to { transform: translateY(0); opacity: 1; }\n }\n \n @keyframes aegisToastIn {\n from { transform: translateX(-100%); opacity: 0; }\n to { transform: translateX(0); opacity: 1; }\n }\n \n @keyframes aegisToastOut {\n from { transform: translateX(0); opacity: 1; }\n to { transform: translateX(-100%); opacity: 0; }\n }\n \n @keyframes aegisSlideInRight {\n from { transform: translateX(100%); }\n to { transform: translateX(0); }\n }\n \n @keyframes aegisSpin {\n from { transform: rotate(0deg); }\n to { transform: rotate(1440deg); }\n }\n ",document.head.appendChild(e)}renderCartRecoveryPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-cart-recovery-modal",i.style.cssText=`\n background: ${this.sanitizeColor(t.background_color||"#FFFFFF")};\n color: ${this.sanitizeColor(t.text_color||"#333333")};\n border-radius: 16px;\n max-width: 600px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n `;const o=document.createElement("h2"),s=this.interpolateCartVariables(t.title||"Complete Your Order");o.textContent=s,o.style.cssText=`margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: ${this.sanitizeColor(t.accent_color||"#FF6B00")};`,i.appendChild(o);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(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"cart_recovery",tier:t.tier})}renderLeadGenPopup(e,t){if(this.isDestroyed)return;const n=document.createElement("div");n.className="aegis-exit-popup-overlay",n.setAttribute("data-widget-id",e),n.setAttribute("data-aegis-widget-root",""),n.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.7);\n z-index: 1000000;\n display: flex;\n align-items: center;\n justify-content: center;\n animation: aegisFadeIn 0.3s ease-out;\n ";const i=document.createElement("div");i.className="aegis-leadgen-modal",i.style.cssText='\n background: white;\n border-radius: 16px;\n max-width: 500px;\n width: 90%;\n padding: 40px;\n box-shadow: 0 10px 40px rgba(0,0,0,0.3);\n text-align: center;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n animation: aegisScaleIn 0.3s ease-out;\n position: relative;\n ';const o=document.createElement("h2");o.textContent=t.title||"Get 10% Off Your First Order!",o.style.cssText="margin: 0 0 16px 0; font-size: 28px; font-weight: 700; color: #1a1a1a;",i.appendChild(o);const s=document.createElement("p");s.textContent=t.message||"Subscribe to our newsletter and get an exclusive discount code.",s.style.cssText="margin: 0 0 24px 0; font-size: 16px; color: #666;",i.appendChild(s);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(o){this.log(`Error submitting lead gen form: ${o}`,!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(),n.setAttribute("data-aegis-widget-root",""),document.body.appendChild(n),this.trackEvent(e,"show",{type:"lead_gen"})}interpolateCartVariables(e){return this.cartData?e.replace(/\{\{cart_total\}\}/g,`${this.cartData.cart_currency} ${this.cartData.cart_total.toFixed(2)}`).replace(/\{\{cart_currency\}\}/g,this.cartData.cart_currency).replace(/\{\{cart_items_count\}\}/g,this.cartData.cart_items.length.toString()):e}log(e,t=!1){if(this.debugMode||t){console[t?"error":"log"](`[AegisWidgets] ${e}`)}}}function Ye(e,t){if(!e||!t)return;let n=e;for(const i of t.split(".")){if(null===n||"object"!=typeof n||Array.isArray(n))return;n=n[i]}return n}function Qe(e,t,n){if(function(e){return!("operands"in e)}(e))return function(e,t,n){const i=void 0!==e.path?Ye(n,e.path):void 0!==e.signal?t[e.signal]:void 0;if(null==i)return null;const o=e.value;switch(e.op){case"gte":case"lte":case"gt":case"lt":return"number"==typeof i&&"number"==typeof o&&("gte"===e.op?i>=o:"lte"===e.op?i<=o:"gt"===e.op?i>o:i<o);case"eq":return i===o;case"neq":return i!==o;case"in":case"nin":{if(!Array.isArray(o))return!1;const t=o.some(e=>e===i);return"in"===e.op?t:!t}default:return e.op,!1}}(e,t,n);switch(e.op){case"AND":for(const i of e.operands){const e=Qe(i,t,n);if(null===e)return!1;if(!e)return!1}return!0;case"OR":{let i=!0;for(const o of e.operands){const e=Qe(o,t,n);if(!0===e)return!0;null!==e&&(i=!1)}return!!i&&null}case"NOT":{const i=Qe(e.operands[0],t,n);return null===i?null:!i}default:return!1}}function Ge(e,t,n){return!0===Qe(e.when,t,n)}class Je{constructor(){this.armed=[],this.snapshot={},this.namespaces={},this.firedThisSession=new Set,this.silencedThisSession=new Set}updateSignal(e,t){this.snapshot[e]=t}updateSnapshot(e){Object.assign(this.snapshot,e)}getSnapshot(){return this.snapshot}updateContext(e,t){e&&t&&(this.namespaces[e]={...this.namespaces[e],...t})}getNamespaces(){return this.namespaces}getValueByPath(e){return Ye(this.namespaces,e)}setArmed(e){this.armed=[...e]}getArmed(){return this.armed}markFired(e){this.firedThisSession.add(e)}reset(){this.firedThisSession.clear(),this.silencedThisSession.clear()}onSignalChanged(e){const t=this.armed.filter(t=>t.rule.fire_on.includes(e)).filter(e=>!this.firedThisSession.has(e.id)).filter(e=>!this.silencedThisSession.has(e.id)).sort((e,t)=>t.rule.priority!==e.rule.priority?t.rule.priority-e.rule.priority:e.id<t.id?-1:e.id>t.id?1:0);for(let n=0;n<t.length;n++){const e=t[n];if(Ge(e.rule,this.snapshot,this.namespaces)){if(e.rule.suppress_competing){const t=this.armed.filter(t=>t.id!==e.id).map(e=>e.id);return t.forEach(e=>this.silencedThisSession.add(e)),{kind:"suppress",campaignId:e.id,suppressIds:t}}return{kind:"fire",campaignId:e.id}}}return{kind:"none"}}}class Ze{constructor(e){this.lastFetchedAt=0,this.latestSnapshot=null,this.apiHost=e.apiHost.replace(/\/$/,""),this.writeKey=e.writeKey,this.organizationId=e.organizationId,this.evaluator=e.evaluator,this.dedupWindowMs=e.dedupWindowMs??6e4,this.fetchImpl=e.fetchImpl??("undefined"!=typeof fetch?fetch.bind(globalThis):()=>Promise.reject(new Error("fetch unavailable"))),this.onError=e.onError}updateOrganizationId(e){this.organizationId=e}getSnapshot(){return this.latestSnapshot}async fetchForContact(e,t={}){var n;if(!e)return null;const i=Date.now();if(!t.force&&this.lastFetchedContactId===e&&i-this.lastFetchedAt<this.dedupWindowMs)return this.latestSnapshot;this.lastFetchedContactId=e,this.lastFetchedAt=i;const o={"X-Aegis-Write-Key":this.writeKey,"X-Contact-ID":e,"X-User-ID":e};this.organizationId&&(o["X-Organization-ID"]=this.organizationId);try{const e=await this.fetchImpl(`${this.apiHost}/v1/sdk/contact-scores`,{method:"GET",headers:o,credentials:"include"});if(204===e.status)return this.latestSnapshot=null,null;if(!e.ok)return this.latestSnapshot=null,null;const t=await e.json();if(this.latestSnapshot=t,this.evaluator&&(this.evaluator.updateSnapshot(function(e){const t={};e.rfm_segment&&(t.rfm_segment=e.rfm_segment);e.lifecycle_stage&&(t.lifecycle_stage=e.lifecycle_stage);e.churn_risk_tier&&(t.churn_risk_tier=e.churn_risk_tier);e.predicted_ltv_tier&&(t.predicted_ltv_tier=e.predicted_ltv_tier);"number"==typeof e.predicted_ltv&&(t.predicted_ltv=e.predicted_ltv);"number"==typeof e.price_sensitivity_score&&(t.price_sensitivity_score=e.price_sensitivity_score);e.scoring_tier&&(t.scoring_tier=e.scoring_tier);return t}(t)),t.context&&"object"==typeof t.context))for(const[n,i]of Object.entries(t.context))i&&"object"==typeof i&&this.evaluator.updateContext(n,i);return t}catch(s){return null==(n=this.onError)||n.call(this,s,e),null}}}class et{constructor(e){this.config=e}url(e){return`${(this.config.apiHost??"").replace(/\/$/,"")}/api/v1/commerce/store/${encodeURIComponent(this.config.slug)}${e}`}async get(e){const t=await fetch(this.url(e),{method:"GET",credentials:this.config.credentials??"include",headers:{"content-type":"application/json"}});if(!t.ok){const n=await t.text();throw new Error(`GET ${e} failed (${t.status}): ${n}`)}return t.json()}async post(e,t){const n=await fetch(this.url(e),{method:"POST",credentials:this.config.credentials??"include",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){const t=await n.text();let i=t;try{i=JSON.parse(t).detail??t}catch{}throw new Error(`POST ${e} failed (${n.status}): ${i}`)}return n.json()}}class tt{constructor(e){this.http=e}async listActive(e){return((await this.http.get(`/store-credit/list-active?phone=${encodeURIComponent(e)}`)).balances??[]).map(e=>({workspaceId:e.workspace_id,balancePaise:e.balance_paise,expiresAt:e.expires_at,lastActivityAt:e.last_activity_at}))}async startReload(e){if(!e.workspaceId)throw new Error("workspaceId is required for store credit reload (closed-loop C1)");const t=await this.http.post("/store-credit/reload",{phone:e.phone,workspace_id:e.workspaceId,amount_paise:e.amountPaise,first_name:e.firstName,email:e.email,callback_url:e.callbackUrl});return{contactId:t.contact_id,checkoutUrl:t.checkout_url,provider:t.provider,paymentLinkId:t.payment_link_id,amountPaise:t.amount_paise}}}class nt{constructor(e){this.http=e}async startPurchase(e){if(!e.workspaceId)throw new Error("workspaceId is required for gift card purchase (closed-loop C1)");if(!e.recipientPhone)throw new Error("recipientPhone is required (no bearer cards — C3)");const t=await this.http.post("/gift-cards/purchase",{sender_phone:e.senderPhone,workspace_id:e.workspaceId,recipient_phone:e.recipientPhone,recipient_name:e.recipientName,amount_paise:e.amountPaise,personal_message:e.personalMessage,callback_url:e.callbackUrl});return{senderContactId:t.sender_contact_id,giftCardId:t.gift_card_id,checkoutUrl:t.checkout_url,provider:t.provider,paymentLinkId:t.payment_link_id,amountPaise:t.amount_paise}}async claim(e){const t=await this.http.post("/gift-cards/claim",{gift_card_id:e.giftCardId,phone:e.phone});return{recipientContactId:t.recipient_contact_id,giftCardId:t.gift_card_id,amountCreditedPaise:t.amount_credited_paise,newBalancePaise:t.new_balance_paise}}async listReceived(e){return((await this.http.get(`/gift-cards/received?phone=${encodeURIComponent(e)}`)).gift_cards??[]).map(e=>({id:e.id,workspaceId:e.workspace_id,senderContactId:e.sender_contact_id,amountPaise:e.amount_paise,status:e.status,personalMessage:e.personal_message,deliveredAt:e.delivered_at,claimedAt:e.claimed_at,expiresAt:e.expires_at,createdAt:e.created_at}))}}class it{constructor(e){if(!e.slug)throw new Error("AegisLoyaltyManager requires a slug");const t=new et(e);this.storeCredit=new tt(t),this.giftCards=new nt(t)}}const ot="aegis_fpc";class st extends Error{constructor(e,t){super(t),this.status=e,this.name="BootstrapError"}}const at="aegis",rt=window[at]||[],ct=new Q;if(Array.isArray(rt)){const e=rt._loadOptions;rt.forEach(e=>{if(!Array.isArray(e))return;const[t,...n]=e;if("string"!=typeof t||0===t.length)return;const i=t.split(".");let o=null,s=ct;for(let r=0;r<i.length&&null!=s;r+=1)o=s,s=s[i[r]];if("function"==typeof s)try{s.apply(o,n)}catch(a){console.error(`[Active Reach SDK] Error executing queued method "${t}":`,a)}else console.warn(`[Active Reach SDK] Unknown method "${t}"`)}),(null==e?void 0:e.key)&&ct.init(e.key,e.options).catch(e=>{console.error("[Active Reach SDK] Initialization failed:",e)})}window[at]=ct,window.Aegis=Q,window.AegisMessageRuntime=class{constructor(e){var t;this.initialized=!1;const n=e.triggerEngine??new Ne,i=!e.triggerEngine;if(this.contactId=e.contactId,this.pairingApiHost=e.apiHost??"",this.widgets=new Ke({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,debugMode:e.debugMode,triggerEngine:n,ownsTriggerEngine:i,enablePrefetch:!1!==e.enableWidgetPrefetch,sourcePlatform:e.sourcePlatform,getWorkspaceId:e.getWorkspaceId}),this.inApp=new We({writeKey:e.writeKey,apiHost:e.apiHost,userId:e.userId,contactId:e.contactId,organizationId:e.organizationId,propertyId:e.propertyId,debugMode:e.debugMode,enableSSE:e.enableSSE,onInteractiveCampaign:e=>{this.widgets.renderInteractiveCampaign(e)},getWorkspaceId:e.getWorkspaceId,getCartState:()=>this.deriveCartState()}),this.intentRuleEvaluator=new Je,this.contactScores=new Ze({apiHost:e.apiHost??"",writeKey:e.writeKey,organizationId:e.organizationId,evaluator:this.intentRuleEvaluator}),this.loyalty=new it({slug:e.storefrontSlug??"__unconfigured__",apiHost:e.apiHost,debugMode:e.debugMode}),e.enableChat){this.chat=new Pe({writeKey:e.writeKey,apiHost:e.apiHost,organizationId:e.organizationId,contactId:e.contactId,debugMode:e.debugMode,...e.chat});const i=(null==(t=e.chat)?void 0:t.proactiveTriggers)??[];for(const e of i)n.on(e,()=>{var e;return null==(e=this.chat)?void 0:e.openPanel()})}}async initialize(){var e;this.initialized||(this.initialized=!0,Xe(this.pairingApiHost),await Promise.all([this.inApp.initialize(),this.widgets.initialize()]),null==(e=this.chat)||e.initialize(),this.contactId&&this.contactScores.fetchForContact(this.contactId))}async updateContactId(e){var t,n,i;this.contactId=e,null==(n=(t=this.inApp).updateContactId)||n.call(t,e),null==(i=this.chat)||i.updateContactId(e),await this.widgets.updateContactId(e),this.contactScores.fetchForContact(e)}onClientEvent(e,t={}){var n,i;null==(i=(n=this.inApp).onClientEvent)||i.call(n,e,t)}updateContext(e,t){e&&"string"==typeof e&&t&&(this.intentRuleEvaluator.updateContext(e,t),this.bridgeContextToSignals(e),this.inApp.refreshOnEvent("context_updated"))}getContext(){return this.intentRuleEvaluator.getNamespaces()}bridgeContextToSignals(e){if("cart"===e){const e=Number(this.intentRuleEvaluator.getValueByPath("cart.total")??this.intentRuleEvaluator.getValueByPath("cart.cart_value"));Number.isFinite(e)&&this.intentRuleEvaluator.updateSignal("cart_value",e)}}deriveCartState(){const e=Number(this.intentRuleEvaluator.getValueByPath("cart.total"));if(!Number.isFinite(e))return;const t=Number(this.intentRuleEvaluator.getValueByPath("cart.items")??this.intentRuleEvaluator.getValueByPath("cart.itemCount")),n=this.intentRuleEvaluator.getValueByPath("cart.currency");return{total:e,itemCount:Number.isFinite(t)?t:0,currency:"string"==typeof n?n:"INR"}}setCartState(e){this.updateContext("cart",{total:e.total,items:e.itemCount,currency:e.currency})}track(e){e&&this.inApp.refreshOnEvent(e)}page(e){this.inApp.refreshOnEvent(e??"page_view",!0)}screen(e){e&&this.inApp.refreshOnEvent(e,!0)}notifyConversion(e){var t,n;null==(n=(t=this.inApp).notifyConversion)||n.call(t,e)}destroy(){var e,t,n;null==(t=(e=this.inApp).destroy)||t.call(e),this.widgets.destroy(),null==(n=this.chat)||n.destroy(),this.initialized=!1}getCampaigns(){return this.inApp.campaigns??[]}},window.TriggerEngine=Ne,window.AegisChat=Pe,ct.chat={open:function(e){null==Re||Re.openPanel(e)},close:function(){null==Re||Re.closePanel()}},window.aegisBootstrap=async function(e,t){const n={writeKey:t.writeKey};t.currentOrigin&&(n.currentOrigin=t.currentOrigin),t.firstPartyCookieId&&(n.firstPartyCookieId=t.firstPartyCookieId),t.attestationToken&&(n.attestationToken=t.attestationToken),t.userAgent&&(n.userAgent=t.userAgent);const i=`${e.replace(/\/$/,"")}/v1/sdk/bootstrap`,o=async()=>fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"omit"});let s=await o();if(s.status>=500&&(await new Promise(e=>setTimeout(e,750)),s=await o()),401===s.status)throw new st(401,"writeKey not recognized or revoked");if(403===s.status)throw new st(403,"Origin validation failed — this writeKey is bound to a different property");if(!s.ok)throw new st(s.status,`Bootstrap failed: HTTP ${s.status}`);const a=await s.json();return function(e){if("undefined"==typeof document)return;const t=new Date;t.setDate(t.getDate()+730),document.cookie=`${ot}=${encodeURIComponent(e)};expires=${t.toUTCString()};path=/;SameSite=Lax`;try{window.localStorage.setItem(ot,e)}catch{}}(a.firstPartyCookieId),a},window.AegisRenderPreview=function(e,t){document.querySelectorAll('[class^="aegis-in-app-"]').forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)});try{if("undefined"!=typeof localStorage)for(let e=localStorage.length-1;e>=0;e--){const t=localStorage.key(e);t&&(t.startsWith("aegis_coachmark_progress:")||t.startsWith("aegis_sticky_dismissed:"))&&localStorage.removeItem(t)}}catch{}if(!e)return;const n=new We({writeKey:"preview-mode",apiHost:"",debugMode:!1,enableSSE:!1,...(null==t?void 0:t.cart)?{getCartState:()=>t.cart}:{}}),i=n;i.trackEvent=async()=>{},i.addAnimationStyles();const o=e,s=Array.isArray(o.delivery_modes)?o.delivery_modes:[],a="string"==typeof o.widget_category?o.widget_category:"",r=s.includes("embedded_card")&&!!a,c=(null==t?void 0:t.coGroup)??[];if("undefined"!=typeof document&&(c.length>0||r)){const t=document.querySelectorAll("[data-aegis-slot]");if(t.length>0)try{t.forEach(e=>{e.querySelectorAll(":scope > :not([data-aegis-slot-default])").forEach(e=>e.remove())});const i=n;if(i.campaigns=(r?[e,...c]:c).map(e=>({...e,surface:void 0,target_screens:void 0})).sort((e,t)=>(t.priority||0)-(e.priority||0)),i.renderIntoSlots(),r)return}catch{}}if("stories"===e.type||"stories"===e.sub_type){const t=document.createElement("div");return t.className="aegis-in-app-stories-host",t.style.cssText="position: fixed; left: 0; right: 0; top: 0; z-index: 99998; padding-top: 4px;background: rgba(255,255,255,0.94); backdrop-filter: blur(8px);box-shadow: 0 2px 12px rgba(0,0,0,0.06);",document.body.appendChild(t),void re(i.buildRenderContext(e),t)}i.displayCampaign(e)};try{const t=null==rt?void 0:rt._loadOptions;Xe(null==(e=null==t?void 0:t.options)?void 0:e.apiHost)}catch{}return ct}();
|
|
2
2
|
//# sourceMappingURL=aegis.min.js.map
|