!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Analitas=t():e.Analitas=t()}(this,()=>(()=>{"use strict";function e(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const t=new class{constructor(){e(this,"save",(e,t)=>{try{return localStorage.setItem(e,t),!0}catch(e){return console.error("Analitas Cache: Error saving to localStorage:",e),!1}}),e(this,"get",e=>{try{return localStorage.getItem(e)}catch(e){return console.error("Analitas Cache: Error reading from localStorage:",e),null}}),e(this,"saveObject",(e,t)=>{try{return localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){return console.error("Analitas Cache: Error saving object to localStorage:",e),!1}}),e(this,"getObject",e=>{try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return console.error("Analitas Cache: Error parsing object from localStorage:",e),null}}),e(this,"deleteObject",e=>{try{return localStorage.removeItem(e),!0}catch(e){return console.error("Analitas Cache: Error removing from localStorage:",e),!1}}),e(this,"clear",()=>{try{return localStorage.clear(),!0}catch(e){return console.error("Analitas Cache: Error clearing localStorage:",e),!1}})}};function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function o(e){for(var t=1;t{let o="";if(n){const e=new Date;e.setTime(e.getTime()+60*n*1e3),o="; expires="+e.toUTCString()}document.cookie=e+"="+(t||"")+o+"; path=/"},d=e=>{const t=e+"=",n=document.cookie.split(";");for(let e=0;e{const e=document.getElementsByTagName("script");for(let t=0;t{let e=d(s);return e||(e="sxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),l(s,e,c)),e&&l(s,e,c),e},h=()=>{const e=sessionStorage.getItem("analitasa_session_id"),t=localStorage.getItem("analitasa_session_id_temp"),n=d(r),o=e||t||n;return o||console.warn("Analitas: No session ID found in any source. SessionStorage:",e,"LocalStorage:",t,"Cookie:",n),o},w=e=>new URLSearchParams(window.location.search).get(e),f=async e=>{if(200!=e.status)throw new Error("API error: ".concat(e.status));return{success:!0,message:(await e.json()).message}},v=e=>(console.error("Analitas: API request failed:",e.message),{success:!1,message:e.message}),x=async e=>{if(!u)return{success:!1,message:"Missing brandId"};if(!e.sessionId)return{success:!1,message:"Missing sessionId"};try{const t=g?"".concat(a,"/sessions/update/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/update/app/").concat(u);e.ping=void 0===e.ping||e.ping,e.isRefresh=!0===e.isRefresh,e.timestamp=Date.now();const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),keepalive:!0});return await f(n)}catch(e){return console.error("Analitas: Failed to update session:",e.message),v(e)}},b=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];try{const i=h();if(!i)return console.error("Analitas: No session ID found for updating page"),!1;const a={path:window.location.pathname,title:document.title,fullUrl:window.location.href,timestamp:Date.now()},s=!0===e.isRefresh;let r=t.getObject("pageHistory")||[];const c=r.length>0?r[r.length-1]:null;if(s&&c&&c.path===a.path){c.refreshCount=(c.refreshCount||0)+1,c.lastRefreshAt=a.timestamp,r[r.length-1]=c,t.saveObject("pageHistory",r);const s=o({sessionId:i,currentPage:a.path,pageTitle:a.title,fullUrl:a.fullUrl,isRefresh:!0,pageHistory:r,ping:!n,timestamp:Date.now()},e);return(await x(s)).success}if(!s&&c&&c.path===a.path){if(!n){const e={sessionId:i,ping:!0,currentPage:a.path,timestamp:Date.now()};return(await x(e)).success}return!0}if(c&&!c.timeSpent){const e=a.timestamp-c.timestamp;if(e<1e3){if(r.pop(),e<300)return t.saveObject("pageHistory",r),!1}else c.timeSpent=e,r[r.length-1]=c}(!s||c&&c.path!==a.path)&&r.push(a),t.saveObject("pageHistory",r);const l=o({sessionId:i,currentPage:a.path,pageTitle:a.title,fullUrl:a.fullUrl,pageHistory:r,ping:!n,timestamp:Date.now()},e);return c&&(l.prevPage={path:c.path,timeSpent:c.timeSpent,title:c.title}),(await x(l)).success}catch(e){return console.error("Analitas: Failed to update session page:",e),!1}},y=async()=>{try{const e=sessionStorage.getItem("analitasa_session_id"),n=localStorage.getItem("analitasa_session_id_temp"),o=d(r),i=e||n||o;if(!i)return!0;if(!d(s)){const e=i.substring(0,8);l(s,e,c)}if(!o&&i&&l(r,i,c),i){if(!e||e!==i)try{sessionStorage.setItem("analitasa_session_id",i)}catch(e){console.error("Analitas: Error setting sessionStorage:",e)}if(!n||n!==i)try{localStorage.setItem("analitasa_session_id_temp",i)}catch(e){console.error("Analitas: Error setting localStorage:",e)}}const a=t.getObject("sessionUTMData");if(a&&a.timestamp){const e=(new Date).getTime(),n=(e-a.timestamp)/6e4;if(parseFloat(c-n)<=0)return!0;a.timestamp=e,t.saveObject("sessionUTMData",a)}else a||t.saveObject("sessionUTMData",{timestamp:Date.now(),brandId:u,domainId:g});return!1}catch(e){return console.error("Analitas: Failed to check/restart session:",e),!0}},S=async()=>{if("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||window.location.hostname.includes(".local"))return void console.debug("Analitas: Skipping tracking on localhost environment");if(!u)return void console.error("Analitas: Cannot initialize without brandId");try{localStorage.setItem("debug","true")}catch(e){console.warn("Analitas: Could not set debug mode",e)}E(),document.addEventListener("visibilitychange",()=>{if("hidden"===document.visibilityState)sessionStorage.setItem("analitas_hidden_time",Date.now());else if("visible"===document.visibilityState){const e=sessionStorage.getItem("analitas_hidden_time");e&&Date.now()-parseInt(e)<1e3&&b(window.location.href,!0)}});const e=(()=>{let e=!1;return window.performance&&window.performance.navigation?1===window.performance.navigation.type&&(e=!0):window.performance&&window.performance.getEntriesByType&&window.performance.getEntriesByType("navigation").length&&"reload"===window.performance.getEntriesByType("navigation")[0].type&&(e=!0),e||sessionStorage.getItem("analitasa_last_page")===window.location.href&&(e=!0),sessionStorage.setItem("analitasa_last_page",window.location.href),e?(t.save("isPageRefresh","true"),sessionStorage.setItem("analitasa_page_refresh","true")):(t.save("isPageRefresh","false"),sessionStorage.removeItem("analitasa_page_refresh")),e})();t.save("analitasInitialized","true");let n,o=window.location.href;if(await y()?n=await T():(n=h(),n||(n=await T())),!n)return void console.error("Analitas: Failed to initialize session tracking");e?b({isRefresh:!0}):b();const i=(()=>{const e={},t=(t,n,o,i)=>{t.addEventListener(n,o,i),e[n]||(e[n]=[]),e[n].push({element:t,handler:o,options:i})};(()=>{try{const e={width:window.innerWidth,height:window.innerHeight,scrollX:window.scrollX,scrollY:window.scrollY,zoom:window.devicePixelRatio||1},t={width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight};A("session_start",{url:window.location.href,title:document.title,referrer:document.referrer,viewport:e,documentSize:t,userAgent:navigator.userAgent,timestamp:Date.now()})}catch(e){console.error("Analitas: Error capturing initial state:",e)}})();let n=0,o={x:0,y:0};t(document,"mousemove",e=>{try{const t=Date.now();t-n>100&&Math.sqrt(Math.pow(e.clientX-o.x,2)+Math.pow(e.clientY-o.y,2))>5&&(n=t,o={x:e.clientX,y:e.clientY},A("mouse_move",{x:e.clientX,y:e.clientY,relativeX:Math.round(e.clientX/window.innerWidth*100)/100,relativeY:Math.round(e.clientY/window.innerHeight*100)/100,timestamp:t}))}catch(e){console.error("Analitas: Error tracking mouse movement:",e)}},{passive:!0}),t(document,"click",e=>{try{const t=e.target;if(t===document.body||t===document)return;const n="A"===t.tagName?t:t.closest("a");if(n){const e=n.getAttribute("href"),t=n.getAttribute("target");e&&_(e)&&e&&O(e,{targetUrl:e,openInNewTab:"_blank"===t})}let o="";try{if(t.id)o="#".concat(t.id);else if(t.className){const e=t.className.split(" ").filter(e=>e);e.length>0&&(o=".".concat(e.join(".")))}if(!o){const e=t.tagName.toLowerCase(),n=t.parentNode,i=Array.from(n.children).filter(e=>e.tagName===t.tagName),a=i.indexOf(t);if(o=i.length>1?"".concat(e,":nth-child(").concat(a+1,")"):e,n!==document.body){let e="";if(n.id)e="#".concat(n.id);else if(n.className){const t=n.className.split(" ").filter(e=>e);t.length>0&&(e=".".concat(t.join(".")))}e&&(o="".concat(e," > ").concat(o))}}}catch(e){console.error("Analitas: Error generating CSS selector:",e)}const i={tag:t.tagName.toLowerCase(),id:t.id||null,class:t.className||null,text:t.innerText?t.innerText.substring(0,50):null,href:t.href||null,selector:o,x:e.clientX,y:e.clientY,scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()};try{const e=t.getBoundingClientRect();i.dimensions={width:e.width,height:e.height,top:e.top,left:e.left,bottom:e.bottom,right:e.right}}catch(e){console.error("Analitas: Error capturing element dimensions:",e)}if(t.hasAttribute("data-track")&&(i.trackId=t.getAttribute("data-track"),t.hasAttribute("data-track-data")))try{const e=JSON.parse(t.getAttribute("data-track-data"));Object.assign(i,e)}catch(e){console.error("Analitas: Error parsing tracking data:",e)}A("click",i)}catch(e){console.error("Analitas: Error tracking click:",e)}},{passive:!0}),t(document,"submit",e=>{try{const t=e.target;let n="";if(t.id)n="#".concat(t.id);else if(t.className){const e=t.className.split(" ").filter(e=>e);e.length>0&&(n=".".concat(e.join(".")))}else n="form";const o={formId:t.id||null,formName:t.name||null,formAction:t.action||null,formMethod:t.method||null,formClass:t.className||null,selector:n,fieldsCount:t.elements.length,scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()},i=[];for(let e=0;ee);t.length>0&&(e=".".concat(t.join(".")))}i.push({name:n.name,type:n.type,selector:e,filled:n.value.length>0,isValid:n.validity?n.validity.valid:null})}}o.fields=i,A("form_submit",o)}catch(e){console.error("Analitas: Error tracking form submission:",e)}},{passive:!0});let i={};t(document,"input",e=>{try{const t=e.target;if("password"===t.type)return;const n=t.id||t.name||"input_".concat(t.type,"_").concat(Math.random());i[n]&&clearTimeout(i[n]),i[n]=setTimeout(()=>{let e="";if(t.id)e="#".concat(t.id);else if(t.name)e='[name="'.concat(t.name,'"]');else if(t.className){const n=t.className.split(" ").filter(e=>e);n.length>0&&(e=".".concat(n.join(".")))}A("input_change",{type:t.type,id:t.id||null,name:t.name||null,selector:e,valueLength:t.value?t.value.length:0,isValid:t.validity?t.validity.valid:null,timestamp:Date.now()}),delete i[n]},500)}catch(e){console.error("Analitas: Error tracking input change:",e)}},{passive:!0});let a,s={x:0,y:0},r=0;t(window,"scroll",()=>{try{const e=Date.now();if(e-r>150){r=e,clearTimeout(a);const t=window.scrollX,n=window.scrollY,o=document.documentElement.scrollWidth,i=document.documentElement.scrollHeight,c=window.innerWidth,l=window.innerHeight,d=Math.round(t/(o-c)*100),m=Math.round(n/(i-l)*100),u=e-r,g=Math.abs(t-s.x),p=Math.abs(n-s.y);(p>.05*l||g>.05*c)&&(A("scroll",{x:t,y:n,percentageX:d,percentageY:m,speedX:u>0?g/u:0,speedY:u>0?p/u:0,windowWidth:c,windowHeight:l,documentWidth:o,documentHeight:i,timestamp:e}),s={x:t,y:n})}}catch(e){console.error("Analitas: Error tracking scroll:",e)}},{passive:!0});let c=0;t(window,"resize",()=>{try{const e=Date.now();e-c>250&&(c=e,A("window_resize",{width:window.innerWidth,height:window.innerHeight,documentWidth:document.documentElement.scrollWidth,documentHeight:document.documentElement.scrollHeight,scrollX:window.scrollX,scrollY:window.scrollY,devicePixelRatio:window.devicePixelRatio||1,timestamp:e}))}catch(e){console.error("Analitas: Error tracking window resize:",e)}},{passive:!0}),t(document,"visibilitychange",()=>{try{A("visibility_change",{visible:"visible"===document.visibilityState,timestamp:Date.now()})}catch(e){console.error("Analitas: Error tracking visibility change:",e)}},{passive:!0}),t(document,"copy",()=>{try{const t=window.getSelection().toString();if(t&&t.length>0){var e;const n=null===(e=window.getSelection().anchorNode)||void 0===e?void 0:e.parentElement;let o="";if(n)if(n.id)o="#".concat(n.id);else if(n.className){const e=n.className.split(" ").filter(e=>e);e.length>0&&(o=".".concat(e.join(".")))}A("copy",{length:t.length,text:t.length>50?t.substring(0,50)+"...":t,selector:o,scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()})}}catch(e){console.error("Analitas: Error tracking copy:",e)}},{passive:!0}),t(document,"play",e=>{try{if("VIDEO"===e.target.tagName){const t=e.target;let n="";if(t.id)n="#".concat(t.id);else if(t.className){const e=t.className.split(" ").filter(e=>e);e.length>0&&(n=".".concat(e.join(".")))}const o=t.getBoundingClientRect();A("video_play",{src:t.currentSrc,duration:t.duration,position:t.currentTime,selector:n,dimensions:{width:o.width,height:o.height,top:o.top,left:o.left},scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()})}}catch(e){console.error("Analitas: Error tracking video play:",e)}},!0),t(document,"pause",e=>{try{if("VIDEO"===e.target.tagName){const t=e.target;let n="";if(t.id)n="#".concat(t.id);else if(t.className){const e=t.className.split(" ").filter(e=>e);e.length>0&&(n=".".concat(e.join(".")))}A("video_pause",{src:t.currentSrc,duration:t.duration,position:t.currentTime,percent:Math.round(t.currentTime/t.duration*100),selector:n,scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()})}}catch(e){console.error("Analitas: Error tracking video pause:",e)}},!0),t(window,"popstate",()=>{try{A("navigation",{type:"popstate",url:window.location.href,title:document.title,scrollX:window.scrollX,scrollY:window.scrollY,timestamp:Date.now()})}catch(e){console.error("Analitas: Error tracking popstate:",e)}}),t(window,"error",e=>{try{A("error",{message:e.message,source:e.filename,line:e.lineno,column:e.colno,timestamp:Date.now()})}catch(e){console.error("Analitas: Error tracking error event:",e)}});const l=()=>{};["mousedown","mousemove","keypress","scroll","touchstart","click"].forEach(e=>{t(document,e,l,{passive:!0})});const d=setInterval(I,1e4);return()=>{Object.keys(i).forEach(e=>{clearTimeout(i[e])}),clearTimeout(a),clearInterval(d),Object.keys(e).forEach(t=>{e[t].forEach(e=>{let{element:n,handler:o,options:i}=e;n.removeEventListener(t,o,i)})})}})();t.save("cleanupActionTracking",i),(()=>{let e=15e3,n=!0,o=Date.now();const i=["mousedown","mousemove","keypress","scroll","touchstart","click"],a=()=>{n=!0,o=Date.now(),e>15e3&&(clearInterval(r),e=15e3,r=setInterval(s,e))};i.forEach(e=>{document.addEventListener(e,a,{passive:!0})});const s=async()=>{h()?(Date.now()-o>3e4&&(n=!1,3e4!==e&&(clearInterval(r),e=3e4,r=setInterval(s,e))),b(window.location.pathname).then(e=>{e||console.error("Analitas: Ping failed")}).catch(e=>{console.error("Analitas: Ping error",e)})):await y()&&await T()};let r=setInterval(s,e);t.save("pingIntervalId",r),t.save("removeActivityListeners",()=>{i.forEach(e=>{document.removeEventListener(e,a)})})})(),window.addEventListener("beforeunload",D,{once:!0}),window.addEventListener("unload",()=>{"true"!==t.get("finishTrackingInProgress")&&D()},{once:!0}),window.addEventListener("pagehide",()=>{"true"!==t.get("finishTrackingInProgress")&&D()},{once:!0}),document.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState||"visible"===document.visibilityState&&y().then(e=>{e&&T()})}),window.addEventListener("blur",()=>{});const a=()=>{const e=window.location.href;if(o===e)return;console.debug("Analitas: Route change detected",{from:o,to:e});const t=o;o=e;const n=h();n&&(A("navigation",{from:t,to:e,type:"spa_navigation",timestamp:Date.now()}),b({prevUrl:t,navigationType:"spa_navigation"}).then(e=>{e||console.error("Analitas: Failed to update page for session:",n)}).catch(e=>{console.error("Analitas: Error updating page for session:",e)}))};window.addEventListener("popstate",()=>{console.debug("Analitas: Popstate event detected"),a()});const s=window.history.pushState,r=window.history.replaceState;window.history.pushState=function(){s.apply(this,arguments),console.debug("Analitas: pushState detected"),a()},window.history.replaceState=function(){r.apply(this,arguments),console.debug("Analitas: replaceState detected"),a()},document.addEventListener("click",e=>{let n=e.target.closest("a");if(n&&n.href){const e=n.href,o=n.getAttribute("target");o&&"_self"!==o||_(e)&&(console.debug("Analitas: External navigation detected",e),O(e,{targetUrl:e,openInNewTab:!1}),"true"!==t.get("finishTrackingInProgress")&&setTimeout(()=>{D()},0))}}),setInterval(a,500),setInterval(()=>{y().then(e=>{e&&T()})},3e4)};function A(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{if(!e)return console.error("Analitas: Missing action type in trackUserAction"),null;if(!h())return console.error("Analitas: No session ID found for tracking action"),null;const o={type:e,timestamp:(new Date).toISOString(),page:window.location.pathname,details:n||{}};let i=t.getObject("actionBuffer")||[];return i.push(o),t.saveObject("actionBuffer",i),i.length>=5&&I(),o}catch(e){return console.error("Analitas: Error tracking user action:",e),null}}const I=async()=>{try{const e=h();if(!e)return;const n=t.getObject("actionBuffer")||[];if(0===n.length)return;const o=[...n];t.saveObject("actionBuffer",[]);try{const t=await k(e,window.location.pathname,o);if(!t.success)throw new Error("Failed to send actions: ".concat(t.message))}catch(e){console.error("Analitas: Error sending actions, restoring buffer:",e);const n=t.getObject("actionBuffer")||[];t.saveObject("actionBuffer",[...n,...o]),setTimeout(I,3e4)}}catch(e){console.error("Analitas: Error flushing action buffer:",e)}},k=async(e,t,n)=>{if(!u)return{success:!1,message:"Missing brandId"};if(!e)return{success:!1,message:"Missing sessionId"};if(!n||!Array.isArray(n)||0===n.length)return{success:!1,message:"No actions to send"};try{const o=g?"".concat(a,"/sessions/actions/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/actions/app/").concat(u),i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e,currentPage:t,actions:n,timestamp:Date.now()}),keepalive:!0});return await f(i)}catch(e){return console.error("Analitas: Failed to update session with actions:",e),v(e)}},O=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{const n=h();if(!n||!e)return console.error("Analitas: Cannot track exit link - missing sessionId or exitLinks"),!1;const o="".concat(a,"/sessions/exit-links/app/").concat(u).concat(g?"?domain=".concat(encodeURIComponent(g)):"");if(!o)return console.error("Analitas: Cannot track exit link - missing API URL"),!1;const i=Array.isArray(e)?e:[e];return fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:n,exitLinks:i,targetUrl:t.targetUrl||null,openInNewTab:!!t.openInNewTab,isRefresh:!!t.isRefresh}),keepalive:!0}).catch(e=>{console.error("Analitas: Error recording exit links:",e)}),!0}catch(e){return console.error("Analitas: Error tracking exit links:",e),!1}},_=e=>{if(!e)return!1;if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))try{return new URL(e.startsWith("//")?"https:".concat(e):e).hostname!==window.location.hostname}catch(e){return!0}return!!e.includes(":")},E=()=>{document.addEventListener("click",e=>{let t=e.target.closest("a");if(!t||!t.href)return;const n=t.href,o="_blank"===t.getAttribute("target");_(n)&&O(n,{targetUrl:n,openInNewTab:o})},{passive:!0})},T=async()=>{try{var e;t.saveObject("pageHistory",[]),t.saveObject("actionBuffer",[]);const n=w("gclid"),o=w("fbclid");let i=w("utm_source"),d=w("ref")||document.referrer;const m=w("q")||w("query");n?(i="google",m&&(d="google.com/search?q=".concat(m))):o?i="facebook":!i&&null!==(e=d)&&void 0!==e&&e.includes("google")?(i="google_organic",m&&(d="google.com/search?q=".concat(m))):i||(i="direct");const h=t.getObject("sessionUTMSource");(!h||0===Object.keys(h||{}).length)&&t.saveObject("sessionUTMSource",{utm_source:i,referrer:d,gclid:n,fbclid:o,fbc:o?"fb.1.".concat(Date.now(),".").concat(o):void 0,brandId:u,domainId:g,timestamp:Date.now()});const x=navigator.userAgent,b=(e=>{const t=e.toLowerCase();return t.includes("iphone")?"iPhone":t.includes("ipad")?"iPad":t.includes("ipod")?"iPod":t.includes("android")&&t.includes("mobile")?"Android Phone":t.includes("android")&&!t.includes("mobile")?"Android Tablet":t.includes("windows phone")?"Windows Phone":/(tablet|playbook|silk)|(android(?!.*mobile))/i.test(t)?t.includes("kindle")||t.includes("silk")?"Kindle":t.includes("playbook")?"PlayBook":t.includes("surface")?"Surface":"Tablet":/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(t)?t.includes("blackberry")?"BlackBerry":t.includes("windows")&&t.includes("phone")?"Windows Phone":t.includes("iemobile")?"IE Mobile":"Mobile":t.includes("windows")?"Windows Desktop":t.includes("macintosh")||t.includes("mac os x")?"Mac Desktop":t.includes("linux")||t.includes("x11")?"Linux Desktop":t.includes("cros")?"ChromeOS":"Desktop"})(x),y=(e=>{const t=e.toLowerCase(),n=[{name:"Edge",regex:/edg(?:e|ios|a)?\/([\d.]+)/,version:1},{name:"Opera",regex:/(opr|opera)(?:.*version|)[ \/]([\d.]+)/,version:2},{name:"Samsung Browser",regex:/samsungbrowser\/([\d.]+)/,version:1},{name:"Vivaldi",regex:/vivaldi\/([\d.]+)/,version:1},{name:"Brave",regex:/brave\/([\d.]+)/,version:1},{name:"Chrome",regex:/chrome\/([\d.]+)/,version:1,exclusion:/chromium|edg|opr|opera|crios|vivaldi/},{name:"Chromium",regex:/chromium\/([\d.]+)/,version:1},{name:"Firefox",regex:/(?:firefox|fxios)\/([\d.]+)/,version:1},{name:"Safari",regex:/version\/([\d.]+)(?:.+safari|)/,version:1,exclusion:/chrome|chromium|android/},{name:"Chrome iOS",regex:/crios\/([\d.]+)/,version:1},{name:"Firefox iOS",regex:/fxios\/([\d.]+)/,version:1},{name:"UC Browser",regex:/ucbrowser\/([\d.]+)/,version:1},{name:"Yandex Browser",regex:/yabrowser\/([\d.]+)/,version:1},{name:"DuckDuckGo",regex:/duckduckgo\/([\d.]+)/,version:1},{name:"QQ Browser",regex:/m?qqbrowser\/([\d.]+)/,version:1},{name:"Maxthon",regex:/maxthon\/([\d.]+)/,version:1},{name:"Sogou Explorer",regex:/metasr\s(\d+\.\d+)/,version:1},{name:"MIUI Browser",regex:/miuibrowser\/([\d.]+)/,version:1},{name:"Baidu Browser",regex:/baidubrowser[\s\/]([\d.]+)/,version:1},{name:"Internet Explorer",regex:/msie\s(\d+\.\d+)/,version:1},{name:"Internet Explorer",regex:/trident.+rv:(\d+\.\d+)/,version:1},{name:"WebView",regex:/web(?:kit)?view(?:browser)?\/?([\d.]+)?/,version:1}];if("undefined"!=typeof navigator&&navigator.brave&&t.includes("chrome/")){const e=/chrome\/([\d.]+)/.exec(t),n=e?e[1]:"";return"Brave ".concat(n)}for(const e of n){if(e.exclusion&&e.exclusion.test(t))continue;const n=e.regex.exec(t);if(n&&n[e.version])return"".concat(e.name," ").concat(n[e.version])}const o=t.match(/\s([a-zA-Z]+(?:browser|explorer)?)[\/\s](\d+(?:\.\d+)+)/i);if(o){const e=o[1].charAt(0).toUpperCase()+o[1].slice(1);return"".concat(e," ").concat(o[2])}if(t.includes("fbav/")||t.includes("fb_iab/")){const e=/(?:fbav|fb_iab)\/(\d+(?:\.\d+)+)/i.exec(t),n=e?e[1]:"";return"Facebook ".concat(n)}if(t.includes("instagram")){const e=/instagram\s(\d+(?:\.\d+)+)/i.exec(t),n=e?e[1]:"";return"Instagram ".concat(n)}if(t.includes("twitter")){const e=/twitter\/(\d+(?:\.\d+)+)/i.exec(t),n=e?e[1]:"";return"Twitter ".concat(n)}return t.includes("webkit")?"WebKit-based Browser":t.includes("gecko")&&t.includes("firefox")?"Gecko-based Browser":t.includes("presto")?"Presto-based Browser":t.includes("trident")||t.includes("msie")?"Trident-based Browser":"Unknown Browser (".concat(e.substring(0,60)).concat(e.length>60?"...":"",")")})(x),S=(e=>{const t=e.toLowerCase(),n=[{name:"Windows 11",regex:/windows nt 10.0.*osversion\/|windows nt 11/i},{name:"Windows 10",regex:/windows nt 10.0/i},{name:"Windows 8.1",regex:/windows nt 6\.3/i},{name:"Windows 8",regex:/windows nt 6\.2/i},{name:"Windows 7",regex:/windows nt 6\.1/i},{name:"Windows Vista",regex:/windows nt 6\.0/i},{name:"Windows XP",regex:/windows nt 5\.1|windows xp/i},{name:"Windows 2000",regex:/windows nt 5\.0|windows 2000/i},{name:"Windows ME",regex:/win 9x 4\.90|windows me/i},{name:"Windows 98",regex:/win98|windows 98/i},{name:"Windows 95",regex:/win95|windows 95/i},{name:"Windows NT",regex:/windows nt|winnt/i},{name:"Windows 3.1",regex:/win16|windows 3\.1/i},{name:"Windows",regex:/win(?!dow)|windows(?!.*(phone|ce|mobile))/i,excludeIf:/windows nt|windows \d/i},{name:"macOS Sequoia",regex:/mac os x 15[._]/i},{name:"macOS Sonoma",regex:/mac os x 14[._]/i},{name:"macOS Ventura",regex:/mac os x 13[._]/i},{name:"macOS Monterey",regex:/mac os x 12[._]/i},{name:"macOS Big Sur",regex:/mac os x 11[._]/i},{name:"macOS Catalina",regex:/mac os x 10[._]15/i},{name:"macOS Mojave",regex:/mac os x 10[._]14/i},{name:"macOS High Sierra",regex:/mac os x 10[._]13/i},{name:"macOS Sierra",regex:/mac os x 10[._]12/i},{name:"OS X El Capitan",regex:/mac os x 10[._]11/i},{name:"OS X Yosemite",regex:/mac os x 10[._]10/i},{name:"OS X Mavericks",regex:/mac os x 10[._]9/i},{name:"OS X Mountain Lion",regex:/mac os x 10[._]8/i},{name:"OS X Lion",regex:/mac os x 10[._]7/i},{name:"OS X Snow Leopard",regex:/mac os x 10[._]6/i},{name:"OS X Leopard",regex:/mac os x 10[._]5/i},{name:"OS X Tiger",regex:/mac os x 10[._]4/i},{name:"OS X Panther",regex:/mac os x 10[._]3/i},{name:"OS X Jaguar",regex:/mac os x 10[._]2/i},{name:"OS X Puma",regex:/mac os x 10[._]1/i},{name:"OS X Cheetah",regex:/mac os x 10[._]0/i},{name:"macOS",regex:/mac os x/i,version:/mac os x (\d+[._]\d+)/i},{name:"Mac OS",regex:/macintosh|mac os/i,excludeIf:/mac os x/i},{name:"iOS",regex:/iphone|ipad|ipod/i,version:/os (\d+)[._](\d+)[._]?(\d+)?/i,versionFormatter:e=>e&&"".concat(e[1],".").concat(e[2]).concat(e[3]?".".concat(e[3]):"")},{name:"Android",regex:/android/i,version:/android (\d+(?:\.\d+)?)/i},{name:"Chrome OS",regex:/cros|chromium os/i},{name:"Ubuntu",regex:/ubuntu/i,version:/ubuntu[\/\s](\d+\.\d+)/i},{name:"Debian",regex:/debian/i,version:/debian[\/\s](\d+)/i},{name:"Fedora",regex:/fedora/i,version:/fedora[\/\s](\d+)/i},{name:"Linux Mint",regex:/mint/i,version:/mint[\/\s](\d+)/i},{name:"CentOS",regex:/centos/i,version:/centos[\/\s](\d+)/i},{name:"Red Hat",regex:/redhat|red hat/i,version:/(?:redhat|red hat)[\/\s](\d+)/i},{name:"Gentoo",regex:/gentoo/i},{name:"Arch Linux",regex:/arch/i},{name:"Linux",regex:/linux/i,excludeIf:/ubuntu|debian|fedora|mint|centos|redhat|red hat|gentoo|arch|android/i},{name:"FreeBSD",regex:/freebsd/i},{name:"OpenBSD",regex:/openbsd/i},{name:"NetBSD",regex:/netbsd/i},{name:"BSD",regex:/bsd/i,excludeIf:/freebsd|openbsd|netbsd/i},{name:"Unix",regex:/x11|unix/i,excludeIf:/linux|bsd|ubuntu|debian|fedora|mint|centos|redhat|red hat|gentoo|arch/i},{name:"Solaris",regex:/sunos|solaris/i},{name:"webOS",regex:/webos|hpwos/i},{name:"BlackBerry OS",regex:/blackberry|playbook|bb10/i},{name:"Sailfish OS",regex:/sailfish/i},{name:"Symbian OS",regex:/symbian|series60/i},{name:"Tizen",regex:/tizen/i},{name:"KaiOS",regex:/kaios/i},{name:"Fire OS",regex:/fire os|silk/i,version:/(?:fire os)[\/\s](\d+\.\d+)/i},{name:"Firefox OS",regex:/firefox os/i},{name:"Windows Phone",regex:/windows phone/i,version:/windows phone (?:os )?([\d.]+)/i},{name:"Windows Mobile",regex:/windows mobile/i},{name:"Windows CE",regex:/windows ce/i},{name:"Nintendo Switch",regex:/nintendo switch/i},{name:"Nintendo WiiU",regex:/nintendo wiiu/i},{name:"Nintendo Wii",regex:/nintendo wii/i},{name:"Nintendo 3DS",regex:/nintendo 3ds/i},{name:"Nintendo DS",regex:/nintendo ds/i},{name:"Nintendo",regex:/nintendo/i,excludeIf:/nintendo switch|nintendo wiiu|nintendo wii|nintendo 3ds|nintendo ds/i},{name:"PlayStation 5",regex:/playstation 5|ps5/i},{name:"PlayStation 4",regex:/playstation 4|ps4/i},{name:"PlayStation 3",regex:/playstation 3|ps3/i},{name:"PlayStation Vita",regex:/playstation vita|psvita/i},{name:"PlayStation Portable",regex:/playstation portable|psp/i},{name:"PlayStation",regex:/playstation|ps\d/i,excludeIf:/playstation 5|ps5|playstation 4|ps4|playstation 3|ps3|playstation vita|psvita|playstation portable|psp/i},{name:"Xbox Series X/S",regex:/xbox series/i},{name:"Xbox One",regex:/xbox one/i},{name:"Xbox 360",regex:/xbox 360/i},{name:"Xbox",regex:/xbox/i,excludeIf:/xbox series|xbox one|xbox 360/i},{name:"Roku OS",regex:/roku/i},{name:"tvOS",regex:/apple tv|tvos/i},{name:"watchOS",regex:/watch os/i},{name:"Samsung Smart TV",regex:/smart-tv|smarttv|samsung.*smart.*tv/i},{name:"MIUI",regex:/miui/i,version:/miui[\/ ]([0-9.]+)/i},{name:"Amazon Echo",regex:/alexa|echo/i},{name:"Google Home",regex:/google home/i}];for(const e of n)if(e.regex.test(t)){if(e.excludeIf&&e.excludeIf.test(t))continue;if(e.version){const n=t.match(e.version);if(n&&e.versionFormatter){const t=e.versionFormatter(n);if(t)return"".concat(e.name," ").concat(t)}if(n&&n[1])return"".concat(e.name," ").concat(n[1].replace("_","."))}return e.name}if(t.includes("mac os x")){const e=/mac os x (\d+)[._](\d+)[._]?(\d+)?/,n=t.match(e);if(n){const e=parseInt(n[1],10),t=parseInt(n[2],10);return"macOS ".concat(e,".").concat(t)}}const o=t.match(/\(([^;)]+)[;)]/i);if(o&&o[1]){const e=o[1].trim();if(e&&!e.includes("compatible")&&e.length<40)return e.charAt(0).toUpperCase()+e.slice(1)}return"Unknown OS (".concat(e.substring(0,50)).concat(e.length>50?"...":"",")")})(x),A=p(),I={userAgent:x,device:b,browser:y,os:S,utm_source:(null==h?void 0:h.utm_source)||i,referrer:(null==h?void 0:h.referrer)||d,link_page:window.location.pathname,domain:g,others:{gclid:(null==h?void 0:h.gclid)||n,fbclid:(null==h?void 0:h.fbclid)||o,fbc:(null==h?void 0:h.fbc)||(o?"fb.1.".concat(Date.now(),".").concat(o):void 0),search_query:m,clientSessionId:A,viewport:{width:window.innerWidth,height:window.innerHeight},timestamp:Date.now()}},k=await(async e=>{if(!u)return{success:!1,message:"Missing brandId"};try{const t=g?"".concat(a,"/sessions/start/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/start/app/").concat(u),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await f(n)}catch(e){return console.error("Analitas: Failed to start session:",e),v(e)}})(I);if(k.success&&k.message&&k.message.sessionId){const{sessionId:e}=k.message;return sessionStorage.setItem("analitasa_session_id",e),localStorage.setItem("analitasa_session_id_temp",e),l(s,A,c),l(r,e,c),(n||o||i)&&(e=>{const n={gclid:e.gclid,fbclid:e.fbclid,utmSource:e.utmSource,searchQuery:e.searchQuery,referrer:e.referrer,brandId:u,domainId:g,timestamp:(new Date).getTime()};t.saveObject("sessionUTMData",n);try{sessionStorage.setItem("sessionUTMData",JSON.stringify(n))}catch(e){console.error("Analitas: Failed to store session data:",e)}})({gclid:n,fbclid:o,utmSource:i,searchQuery:m,referrer:d,timestamp:Date.now()}),e}return console.error("Analitas: Failed to create session:",k),null}catch(e){return console.error("Analitas: Failed to start session:",e),null}},D=()=>{try{if("true"===t.get("finishTrackingInProgress"))return void console.debug("Analitas: finishTracking already in progress, skipping duplicate call");t.save("finishTrackingInProgress","true");const e=sessionStorage.getItem("analitasa_session_id"),n=localStorage.getItem("analitasa_session_id_temp"),o=d(r),i=e||n||o;if(!i)return console.error("Analitas: Cannot finish tracking without session ID. Checked sessionStorage, localStorage, and cookies but found nothing."),void setTimeout(()=>{t.save("finishTrackingInProgress","false")},500);try{e||sessionStorage.setItem("analitasa_session_id",i),n||localStorage.setItem("analitasa_session_id_temp",i),o||l(r,i,c)}catch(e){console.warn("Analitas: Error ensuring session ID redundancy",e)}const s="true"===t.get("isPageRefresh")||"true"===sessionStorage.getItem("analitasa_page_refresh");console.debug("Analitas: Finishing tracking for session:",i,"isRefresh:",s,"path:",window.location.pathname);const m=window.location.pathname,p=g?"".concat(a,"/sessions/end/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/end/app/").concat(u);if(!p)return console.error("Analitas: No endpoint URL available for session end"),void t.save("finishTrackingInProgress","false");const h=t.getObject("actionBuffer")||[],w=t.get("pingIntervalId");w&&(clearInterval(w),t.deleteObject("pingIntervalId"));const f=t.get("removeActivityListeners");"function"==typeof f&&(f(),t.deleteObject("removeActivityListeners"));const v=t.get("cleanupActionTracking");"function"==typeof v&&(v(),t.deleteObject("cleanupActionTracking"));let x="unknown";if(s?x="refresh":"hidden"===document.visibilityState?x="tab_close":window.event&&"beforeunload"===window.event.type?x="page_close":window.event&&"popstate"===window.event.type&&(x="history_navigation"),h.length>0){const e=g?"".concat(a,"/sessions/actions/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/actions/app/").concat(u);if(h.push({type:"session_end",timestamp:(new Date).toISOString(),page:window.location.pathname,details:{navigationType:x,timestamp:Date.now()}}),navigator.sendBeacon){const t=new Blob([JSON.stringify({sessionId:i,currentPage:m,actions:h,isRefresh:s,navigationType:x})],{type:"application/json"});try{const n=navigator.sendBeacon(e,t);console.debug("Analitas: Action buffer beacon send result:",n)}catch(e){console.error("Analitas: Error sending action buffer beacon:",e)}}else try{const t=new XMLHttpRequest;t.open("POST",e,!1),t.setRequestHeader("Content-Type","application/json"),t.send(JSON.stringify({sessionId:i,currentPage:m,actions:h,isRefresh:s,navigationType:x}))}catch(e){console.error("Analitas: Error sending actions by XHR:",e)}t.saveObject("actionBuffer",[])}let b=!1;if(navigator.sendBeacon)try{const e=new FormData;e.append("sessionId",i),e.append("exitLink",m),e.append("navigationType",x),e.append("timestamp",Date.now().toString()),s&&e.append("isRefresh","true");const t=navigator.sendBeacon(p,e);console.debug("Analitas: Session end beacon send result:",t),t&&(b=!0)}catch(e){console.error("Analitas: Error sending session end beacon:",e)}if(!b)try{!function(e,t,n){let o=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"unknown";try{if(!t)return void console.error("Analitas: Cannot send XHR without sessionId");if(!e)return void console.error("Analitas: Cannot send XHR without URL");console.debug("Analitas: Sending sync XHR for session end",{sessionId:t,exitLink:n,isRefresh:o,navigationType:i});const a=new XMLHttpRequest;a.open("POST",e,!1),a.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),a.timeout=2e3,a.onerror=function(){console.error("Analitas: XHR request failed during session end",a.status,a.statusText)},a.ontimeout=function(){console.error("Analitas: XHR request timed out during session end")};let s="sessionId=".concat(encodeURIComponent(t),"&exitLink=").concat(encodeURIComponent(n||window.location.pathname),"&navigationType=").concat(encodeURIComponent(i));o&&(s+="&isRefresh=true"),s+="×tamp=".concat(Date.now()),a.send(s),a.status>=200&&a.status<300?console.debug("Analitas: Successfully sent sync XHR to end session"):console.error("Analitas: XHR request failed with status",a.status)}catch(e){console.error("Analitas: Error sending sync XHR for session end:",e)}}(p,i,m,s,x),b=!0}catch(e){console.error("Analitas: Error with sync XHR fallback:",e)}try{let e="sessionId=".concat(encodeURIComponent(i),"&exitLink=").concat(encodeURIComponent(m),"&navigationType=").concat(encodeURIComponent(x),"×tamp=").concat(Date.now());s&&(e+="&isRefresh=true"),fetch(p,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e,keepalive:!0}).catch(e=>console.error("Analitas: Fetch fallback failed:",e))}catch(e){console.error("Analitas: Error with fetch fallback:",e)}const y=t.getObject("sessionUTMData")||{};return y.lastEnd=Date.now(),y.navigationTypeLast=x,t.saveObject("sessionUTMData",y),t.save("isPageRefresh","false"),sessionStorage.removeItem("analitasa_page_refresh"),setTimeout(()=>{t.save("finishTrackingInProgress","false")},500),b}catch(e){return console.error("Analitas: Failed to end session:",e),t.save("finishTrackingInProgress","false"),!1}};return"undefined"!=typeof window&&(window.Analitas={getSessionId:h,getEndSessionUrl:()=>u?g?"".concat(a,"/sessions/end/app/").concat(u,"?domain=").concat(encodeURIComponent(g)):"".concat(a,"/sessions/end/app/").concat(u):null,trackUserAction:A,updateSessionPage:b,trackExitLink:O,isExternalUrl:_,addTracking:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"custom",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(e){if(e instanceof HTMLElement)return e.hasAttribute("data-track")||e.setAttribute("data-track",t),Object.keys(n).length>0&&e.setAttribute("data-track-data",JSON.stringify(n)),e.addEventListener("click",n=>{try{let i={};if(e.hasAttribute("data-track-data"))try{i=JSON.parse(e.getAttribute("data-track-data"))}catch(e){console.error("Analitas: Error parsing tracking data:",e)}const a=o(o({tag:e.tagName.toLowerCase(),id:e.id||null,class:e.className||null,text:e.innerText?e.innerText.substring(0,50):null,href:e.href||null},i),{},{x:n.clientX,y:n.clientY});A(t,a)}catch(e){console.error("Analitas: Error in custom tracking:",e)}},{passive:!0}),e;console.error("Analitas: addTracking requires an HTML element")}}},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",S):S()),{}})());