(function(){"use strict";var ie=Object.defineProperty;var ae=(n,e,t)=>e in n?ie(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var g=(n,e,t)=>(ae(n,typeof e!="symbol"?e+"":e,t),t);const N=(n,e,t)=>{const i=new Date;i.setTime(i.getTime()+t*24*60*60*1e3);let a="expires="+i.toUTCString();document.cookie=n+"="+e+";"+a+";path=/;SameSite=None;Secure"},b=n=>{let e=n+"=",t=document.cookie.split(";");for(let i=0;i{document.cookie=n+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;SameSite=None;Secure",document.cookie=n+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;domain=.chatway.app;Secure;SameSite=None"},x=()=>window.matchMedia("(max-width: 767px)").matches,U=(n,e)=>{const t=document.querySelector(`#${n}`);if(t){const i=t.src;return new URL(i).searchParams.get(e)||null}else return se("chatway.app",e)},se=(n,e)=>{const t=document.getElementsByTagName("script");for(let i=0;i{let i,a,o,r=!1;if(n){const c=n.split(/\s+/);for(o=0;o{e&&(n.className+=` ${e}`)},j=(n,e)=>{ne(e,"remove",n)},h=n=>document.querySelector(n),z=n=>document.querySelectorAll(n),oe=()=>{const n=document.createElement("link");n.rel="stylesheet",n.href="https://cdn.chatway.app/sdk.css",n.id="chatway-widget-css",document.head.appendChild(n)},J=(n,e)=>{switch(n){case"s":return 44;case"m":return 60;case"l":return 70;case"xl":return 84;case"xxl":return 94;case"custom":return e?Number(e):60;default:return 60}},X=n=>{var e;return((e=[{color:"#0446DE",hex:"#0446DE"},{color:"linear-gradient(100.96deg, #43cea2 0%, #185a9d 100%), #414141",hex:"#185A9D"},{color:"#282D3E",hex:"#282D3E"},{color:"linear-gradient(101.04deg, #56CCF2 0.59%, #2F80ED 100%), #7E8E9C",hex:"#2F80ED"},{color:"linear-gradient(101.04deg, #00317A 0.59%, #001F4F 100%)",hex:"#001F4F"},{color:"linear-gradient(100.96deg, #5E3D86 0%, #2F164D 100%), #537EE1",hex:"#2F164D"},{color:"linear-gradient(180deg, #F69D01 0%, #F65901 100%)",hex:"#F65901"},{color:"linear-gradient(100.96deg, #6A3093 0%, #A044FF 100%), #3B9488",hex:"#A044FF"},{color:"linear-gradient(100.96deg, #E96443 0%, #904E95 100%), #5BB055",hex:"#904E95"}].find(t=>t.color.includes(n)))==null?void 0:e.hex)||n},re=(n=100)=>new Promise(e=>setTimeout(e,n)),ce=()=>{const n=document.activeElement;n&&n.blur()},le=()=>{const n=document.querySelector("body"),e=window.getComputedStyle(n);sessionStorage.setItem("_bdyF",e.getPropertyValue("overflow")),document.body.style.overflow="hidden"},de=()=>{const n=sessionStorage.getItem("_bdyF")||"auto";document.body.style.overflow=n,sessionStorage.removeItem("_bdyF")},ge=n=>{const e=window.location.search;return new URLSearchParams(e).get(n)},he=function(n){const e="\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC";try{return new RegExp("^[^"+e+"]*?["+e+"]").test(n)}catch{return!1}},H=n=>n?n.replace(/[^\p{L}0-9\s]/gu,"").match(/(^\S\S?|\s\S)?/g).map(e=>e.trim()).join("").match(/(^\S|\S$)?/g).join("").toLocaleUpperCase():"",ue=n=>n.trim().split(` `).reduce(function(e,t){return t=t.split("="),e[t[0]]=t[1],e},{}),Y=()=>{var n,e;return window.Shopify?"shopify":window.wpChatwaySettings?"wordpress":(e=(n=document.querySelector("meta[name='generator']"))==null?void 0:n.getAttribute("content"))!=null&&e.toLowerCase().includes("wix")?"wix":""},q=()=>Y()==="shopify",$=()=>window.location.origin;class s{}g(s,"widgetID"),g(s,"userID"),g(s,"triggerData"),g(s,"appContainer"),g(s,"frameContainer"),g(s,"triggerContainer"),g(s,"iconToggler"),g(s,"agents",null),g(s,"allAgents",null),g(s,"previewText",null),g(s,"status","online"),g(s,"unReadCount",0),g(s,"pageTitle",""),g(s,"fallbackAvatar","https://prod-chaty-uploads.s3.us-west-2.amazonaws.com/npgRZqDneIU48ejuo2VR9TK13Lu40mnVdoOGA59Jj3P5VgT140758.svg"),g(s,"agentMessage",null),g(s,"hasAlreadyLoaded",!1),g(s,"token",""),g(s,"isChatInitialized",""),g(s,"visibilityHourTimezone",""),g(s,"visibilityHours",[]),g(s,"isWidgetVisible",!1),g(s,"widgetTriggers",{is_trigger_enabled:!1,has_display_after_time:!1,display_after_time:0,has_display_page_scroll:!1,display_page_scroll:0}),g(s,"pageRules"),g(s,"isHideChatwayIcon"),g(s,"previewTextBubbleDelay",0),g(s,"chatContactId",""),g(s,"browserData"),g(s,"shopifyCustomerId",""),g(s,"isVerifiedVisitor",!1);class p{constructor(){}getSessionToken(){return b(`ch_cw_token_${s.widgetID}`)||s.token||""}setSessionToken(e){N(`ch_cw_token_${s.widgetID}`,e,365)}getChatInitStatus(){return b(`ch_cw_status_${s.widgetID}`)||s.isChatInitialized||"false"}setChatInitStatus(e){N(`ch_cw_status_${s.widgetID}`,e,365)}setWidgetStatus(e){const t=this.getUserConfig();t.widgetStatus=e?"open":"close",this.setUserConfig(t)}setTextBubbleStatus(e){const t=this.getUserConfig();t.hasOpenedTextBubble=e,this.setUserConfig(t)}setShowAttentionEffect(e){N(`ch_cw_shw_atn_efct_${s.widgetID}`,e?"true":"false",1)}getShowAttentionEffect(){return b(`ch_cw_shw_atn_efct_${s.widgetID}`)!=="false"}getUserConfig(){return JSON.parse(sessionStorage.getItem(`ch_session_info_${s.widgetID}`)||"{}")}setUserConfig(e){sessionStorage.setItem(`ch_session_info_${s.widgetID}`,JSON.stringify(e))}deleteUserConfig(){const e=s.widgetID;sessionStorage.removeItem(`ch_session_info_${e}`),sessionStorage.removeItem(`ch_cw_status_${e}`),sessionStorage.removeItem(`ch_cw_token_${e}`),L(`ch_cw_status_${e}`),L(`ch_cw_token_${e}`)}setBubbleExpiration(){let e={data:"false",expireTime:Date.now()+36e5};localStorage.setItem("showTextBubble",JSON.stringify(e))}get wasWidgetOpen(){return this.getUserConfig().widgetStatus==="open"}get hasShownTextBubble(){const e=this.getUserConfig();return Boolean(e.hasOpenedTextBubble)}get showTextBubble(){const e=localStorage.getItem("showTextBubble");if(e){let t=JSON.parse(e);return t.expireTime<=Date.now()?(localStorage.removeItem("showTextBubble"),null):t.data?t.data:"true"}return null}}class C{constructor(){g(this,"triggerData");this.triggerData=s.triggerData}getCalculatedWidgetHeight(e){const t=window.innerHeight,i=704,a=400,o=t-e-104,r=Math.max(a,o);return Math.min(r,i)}async makeAppContainer(){let e;if(e=document.getElementsByTagName("body")[0],e||(await new Promise(o=>setTimeout(o,1e3)),e=document.body),!e)return;const t=document.createElement("div");t.classList.add("chatway--container"),t.classList.add("disable--widget");const i=document.createElement("div");i.classList.add("chatway--frame-container");const a=document.createElement("div");if(a.classList.add("chatway--trigger-container"),t.appendChild(i),t.appendChild(a),this.triggerData.default_state=="opened"&&!localStorage.getItem("showTextBubble")&&!x()&&(t.classList.add("widget--open"),e&&e.classList.add("chatway-is-open")),this.triggerData.position=="left"&&t.classList.add("widget--left"),this.triggerData.position=="custom"){this.triggerData.custom_position_side=="left"&&t.classList.add("widget--left");const o=this.getCalculatedWidgetHeight(this.triggerData.bottom_spacing),r=document.createElement("style");r.innerHTML="@media screen and (min-width: 601px) { .custom-position-widget-height .chatway--frame-container{ height: min("+o+"px,100% - 104px); }}",document.head.appendChild(r),t.classList.add("custom-position-widget-height")}return e.appendChild(t),t}makeTriggerContainer(){const e=h(".chatway--trigger-container"),t=document.createElement("div");t.id="chatway_widget_trigger",t.classList.add("chatway--trigger-icon-container");const i=J(this.triggerData.widget_size,this.triggerData.custom_widget_size);return t.style.width=`${i}px`,t.style.height=`${i}px`,this.setPosition(e),e.appendChild(t),t}makeFrameContainer(){const e=s.widgetID,i=`https://widget.chatway.app/?userId=${s.userID}&widgetId=${e}&bg-color=${this.triggerData.widget_color}`;if(h(".chatway--widget-frame"))return null;const a=h(".chatway--frame-container"),o=document.createElement("iframe");return o.classList.add("chatway--widget-frame"),o.src=i,o.id="chatway_widget_app",o.title="Live chat widget",this.setPosition(a),a.appendChild(o),a}setPosition(e){const t=J(this.triggerData.widget_size,this.triggerData.custom_widget_size),i=10,a=20,o=10;let r=this.triggerData.bottom_spacing;if(e.classList.contains("chatway--frame-container"))if(this.triggerData.position=="custom"){r=t+i+Number(this.triggerData.bottom_spacing);const l=this.getCalculatedWidgetHeight(r),d=r+l;if(d>window.innerHeight){const w=d-window.innerHeight+o;r=r-w}}else r=t+i+a;if(e.classList.contains("chatway--trigger-container"))if(this.triggerData.position=="custom"){r=Number(this.triggerData.bottom_spacing);const l=this.getCalculatedWidgetHeight(r),d=r+l;if(d>window.innerHeight){const w=d-window.innerHeight;r=r-w-t-a}}else r=a;const c=window.innerWidth;if(this.triggerData.position=="custom"){e.style.left="unset",e.style.right="unset";let l=this.triggerData.side_spacing;if(c>=480){const d=c-420;l>d&&(l=d)}else{const d=c-70;l>d&&(l=d)}l<0&&(l=0),this.triggerData.custom_position_side=="left"?e.style.left=`${l}px`:e.style.right=`${l}px`}e.classList.contains("chatway--frame-container")&&c<=600&&(e.style.left="unset",e.style.right="unset"),e.style.bottom=`${r}px`}destroyAppContainer(){const e=h(".chatway--container"),t=h("#chatway-widget-css");e==null||e.remove(),t==null||t.remove()}get isWidgetVisible(){var e;return(e=s.appContainer)==null?void 0:e.classList.contains("widget--open")}}class I{makeMultipePreviewContainer(){let e=h(".chatway--preview-container");e||(e=document.createElement("div"),e.classList.add("chatway--preview-container"));const t=h(".chatway--trigger-container"),i=this.makeCloseIcon(),a=this.makeMultipleTextBubbleContainer(),o=this.makeMessagePreviewContainer();return e.innerHTML=` ${i.outerHTML} ${a.outerHTML} ${o.outerHTML} `,t.appendChild(e),e.addEventListener("click",r=>{this.executePreviewContainerClick(r)}),e}makeSinglePreviewContainer(){let e=h(".chatway--preview-container");e||(e=document.createElement("div"),e.classList.add("chatway--preview-container"));const t=h(".chatway--trigger-container"),i=this.makeCloseIcon(),a=this.makeSingleTextBubbleContainer(),o=this.makeMessagePreviewContainer();return e.innerHTML=` ${i.outerHTML} ${a.outerHTML} ${o.outerHTML} `,t.appendChild(e),e.addEventListener("click",r=>{this.executePreviewContainerClick(r)}),e}executePreviewContainerClick(e){var i;const t=(i=e.target)==null?void 0:i.classList;t&&t.contains("chatway--preview-link-container")?(new I().hidePreview(),new p().setBubbleExpiration()):new f().openWidget()}makeMultipleTextBubbleContainer(){const e=s.triggerData.is_preview_text_enabled,t=document.createElement("div");t.classList.add("chatway--text-bubble-container");const i=document.createElement("div");i.classList.add("chatway--preview-agents-container");const a=document.createElement("div");a.classList.add("chatway--preview-status-container");const o=document.createElement("div");return o.classList.add("chatway--preview-text-container"),t.appendChild(i),e&&t.appendChild(o),t.appendChild(a),t}makeSingleTextBubbleContainer(){const e=s.triggerData.is_preview_text_enabled,t=document.createElement("div");t.classList.add("bubble-container");const i=document.createElement("div");i.classList.add("imageOnlineStatus");const a=document.createElement("div");a.classList.add("agentDetailsText");const o=document.createElement("div");o.classList.add("agentDetailsName");const r=document.createElement("div");return r.classList.add("agentDetailsContent"),t.appendChild(i),t.appendChild(a),a.appendChild(o),e&&a.appendChild(r),t}makeMessagePreviewContainer(){const e=document.createElement("div");e.classList.add("chatway--message-preview-container");const t=document.createElement("div");t.classList.add("img-container");const i=document.createElement("div");i.classList.add("text-container");const a=document.createElement("div");a.classList.add("agent-name");const o=document.createElement("div");return o.classList.add("agent-message"),i.appendChild(a),i.appendChild(o),e.appendChild(t),e.appendChild(i),e}displayMultipleAgents(){var c;const e=h(".chatway--preview-agents-container");if(!e||!((c=s.agents)!=null&&c.length))return null;const t=s.triggerData.avatar_border_color,i=s.triggerData.header_text_color,a=s.triggerData.chat_font_type,o=[...s.agents].map(l=>`
${l.attributes.profile_photo_url?`agent image`:`
${H(l.attributes.name)}
`}
`);o.push('');const r=o.join("");return e.innerHTML=r,e}displaySingleAgent(){var c;const e=h(".imageOnlineStatus");if(!e||!((c=s.agents)!=null&&c.length))return this.hidePreview(),null;const t=s.agents[0].attributes,i=s.triggerData.avatar_border_color,a=s.triggerData.header_text_color,o=s.triggerData.chat_font_type,r=` ${t.profile_photo_url?`agent image`:`
${H(t.name)}
`} `;return e.innerHTML=r,e}makePreviewText(){var a;const e=s.agents&&((a=s.agents)==null?void 0:a.length)>1?h(".chatway--preview-text-container"):h(".agentDetailsContent"),t=s.triggerData.is_preview_text_enabled,i=s.previewText;return!e||!t||!i?null:(he(i)&&h(".chatway--preview-container").classList.add("rtl"),e.textContent=i,e)}makeNameText(){var t;const e=h(".agentDetailsName");return!e||((t=s.agents)==null?void 0:t.length)!=1?null:(e.textContent=s.agents[0].attributes.name,e)}toggleOnlineStatus(){const e=h(".chatway--preview-agents-container");if(!e)return null;const t=s.status;return e.classList.remove("online","offline"),e.classList.add(t),e}makeCloseIcon(){const e=` `,t=document.createElement("div");return t.classList.add("chatway--preview-link-container"),t.innerHTML=e,t.addEventListener("click",i=>{i.preventDefault(),this.hidePreview(),new p().setBubbleExpiration()}),t}showPreview(){var i;const e=h(".chatway--preview-container"),t=new C().isWidgetVisible;!e||t||((i=s.agents)==null?void 0:i.length)&&s.triggerData.is_preview_text_enabled&&s.previewText&&e.classList.add("opened","show--text-bubble")}hidePreview(){const e=h(".chatway--preview-container");!e||e.classList.remove("opened","show--text-bubble","show--message-preview")}togglePreview(){const e=h(".chatway--preview-container");!e||e.classList.toggle("opened")}showUnreadMessage(){var m,v,R,V,O;if(!s.agentMessage)return;let e=h(".chatway--preview-container");const t=new C().isWidgetVisible;if(!e||t)return;e.classList.remove("show--text-bubble");const i=(m=s.agentMessage)==null?void 0:m.agent.attributes,a=h(".chatway--message-preview-container .img-container");i!=null&&i.profile_photo_url?(a.classList.remove("initials-container"),a.classList.add("image-container")):(a.classList.remove("image-container"),a.classList.add("initials-container"));const o=h(".chatway--message-preview-container .agent-name"),r=h(".chatway--message-preview-container .agent-message"),c=s.triggerData.avatar_border_color,l=s.triggerData.header_text_color,d=s.triggerData.chat_font_type;a.innerHTML=` ${i!=null&&i.profile_photo_url?`agent image`:`
${H(i==null?void 0:i.name)}
`} `,o.innerText=i==null?void 0:i.name;const w=(v=s.agentMessage)!=null&&v.message_html?(R=s.agentMessage)==null?void 0:R.message_html:(V=s.agentMessage)==null?void 0:V.message;r.innerHTML=((O=s.agentMessage)==null?void 0:O.type)=="text"?w:"Image received!",e.classList.add("opened","show--message-preview")}get isPreviewVisible(){const e=h(".chatway--preview-container");return e?e.classList.contains("opened"):!1}}class we{removePendingStatus(){const e=h("#chatway_widget_trigger");e&&e.classList.add("has-unread-message");const t=z(".Chatway-channel-link, .csaas-widget-trigger.has-chatway-channel");t&&t.forEach(i=>{i.classList.add("has-unread-message")})}updatePendingStatus(){const e=h("#chatway_widget_trigger");if(!e)return;const t=s.pageTitle,i=s.unReadCount,a=s.isWidgetVisible;!a||i==0?(document.title=t,e.classList.remove("has-unread-message")):(document.title=`(${i}) ${t}`,e.classList.add("has-unread-message")),e.setAttribute("data-unread-message",String(i));const o=z(".Chatway-channel-link, .csaas-widget-trigger.has-chatway-channel");o&&o.forEach(r=>{!a||i==0?(document.title=t,r.classList.remove("has-unread-message")):(document.title=`(${i}) ${t}`,r.classList.add("has-unread-message")),r.setAttribute("data-unread-message",String(i))})}}var u=(n=>(n.widgetToggle="widget.toggle",n.widgetLoaded="widget.loaded",n.widgetMetaData="widget.metadata",n.agentStatusChange="agent.status.change",n.unreadMessage="messages.unread",n.locationChange="location.change",n.agentMessaged="agent.messages.received",n.visitorConversationStarted="visitor.conversation.started",n.loadImage="load.image",n.removeImage="remove.image",n.profileData="profile.data",n.chatHistory="chat.history",n.focusEvent="focus.event",n.widgetReload="widget.reload",n.widgetDestroy="widget.destroy",n.customData="custom.data",n.removeToken="remove.token",n.chatContactLoaded="chat.contact.loaded",n.customerDataLoaded="customer.data.loaded",n.setVisitorEmail="set.visitor.email",n.setChatwaySettings="set.chatway.settings",n.openContactChannel="open.contact.channel",n.copyToClipboard="copy.to.clipboard",n.widgetDisable="widget.disable",n))(u||{});class A extends Event{constructor(e={}){super("urlchangeevent",{cancelable:!0,...e}),this.newURL=e.newURL,this.oldURL=e.oldURL,this.action=e.action}get[Symbol.toStringTag](){return"UrlChangeEvent"}}const pe=window.history.pushState.bind(window.history);window.history.pushState=function(n,e,t){const i=new URL(t||"",window.location.href);window.dispatchEvent(new A({newURL:i,oldURL:T,action:"pushState"}))&&(pe({_index:E+1,...n},e,t),M())};const Q=window.history.replaceState.bind(window.history);window.history.replaceState=function(n,e,t){const i=new URL(t||"",window.location.href);window.dispatchEvent(new A({newURL:i,oldURL:T,action:"replaceState"}))&&(Q({_index:E,...n},e,t),M())};let T,E;function ee(){const n=window.history.state;(!n||typeof n._index!="number")&&Q({_index:window.history.length,...n},null,null)}function M(){T=new URL(window.location.href),E=window.history.state._index}ee();M();window.addEventListener("popstate",function(n){ee();const e=window.history.state._index,t=new URL(window.location);if(e===E){n.stopImmediatePropagation();return}if(!window.dispatchEvent(new A({oldURL:T,newURL:t,action:"popstate"}))){n.stopImmediatePropagation(),window.history.go(E-e);return}M()});window.addEventListener("beforeunload",function(n){if(!window.dispatchEvent(new A({oldURL:T,newURL:null,action:"beforeunload"}))){n.preventDefault();const t="o/";return n.returnValue=t,t}});class G{constructor(e){g(this,"src","");this.src=e}openImageViewer(){const e=this.makeViewerContainer();document.body.appendChild(e),this.animateContainer()}closeImageViewer(){var e;(e=h(".chatway--image-viewer-container"))==null||e.remove()}makeViewerContainer(){const e=document.createElement("div"),t=document.createElement("div");t.classList.add("chatway--image--container");const i=this.makeImage();i.addEventListener("load",()=>{e.classList.add("chatway--image--loaded")});const a=this.makeCloseButton();return t.appendChild(i),t.appendChild(a),e.classList.add("chatway--image-viewer-container"),e.appendChild(t),e.addEventListener("click",o=>{o.target!==i&&this.closeImageViewer()}),e}makeImage(){const e=new Image;return e.src=this.src,e.classList.add("chatway--image-viewer-image"),e}convertStringToElement(e){return new DOMParser().parseFromString(e,"image/svg+xml").documentElement}makeCloseButton(){const e=document.createElement("a");e.href="#",e.classList.add("dismiss--button");const t=` `;return e.appendChild(this.convertStringToElement(t)),e.addEventListener("click",i=>{i.preventDefault(),this.closeImageViewer()}),e}animateContainer(){setTimeout(()=>{var e;(e=h(".chatway--image-viewer-container"))==null||e.classList.add("enter-active")},150)}}var Z;(function(n){n.fatal="fatal",n.error="error",n.warning="warning",n.log="log",n.info="info",n.debug="debug",n.critical="critical"})(Z||(Z={}));const me=/^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,fe=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js))(?::(\d+))?(?::(\d+))?\s*$/i,ye=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,W="?",Ce="X-Sentry-Auth",be=/^(?:(\w+):)\/\/(?:([\w-]+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/;function ve(n){if(!n.stack)return null;const e=[],t=n.stack.split(` `);let i,a;for(let o=0;o!!t)[0]}function _e(n){try{const e=ve(n);if(e)return e}catch{}return{value:te(n),type:n&&n.name,stacktrace:{frames:[]}}}function Se(){return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class De{constructor(e){if(e&&e.dsn){const t=be.exec(e.dsn),i=t?t.slice(1):[],a=i[5].split("/"),o=a.slice(0,-1).join("/");this.apiUrl=i[0]+"://"+i[3]+(i[4]?":"+i[4]:"")+(o?"/"+o:"")+"/api/"+a.pop()+"/store/",this.authHeader="Sentry sentry_version=7,sentry_key="+i[1]+(i[2]?",sentry_secret="+i[2]:"")}this.environment=e&&e.environment}prepare(e){return{...this.getRequestBlank(),exception:{values:[_e(e)]}}}report(e){this.send(this.prepare(e))}send(e){!this.apiUrl||!e||this.createRequest(e)}createRequest(e){const t=new XMLHttpRequest;t.open("POST",this.apiUrl,!0),t.setRequestHeader("Content-type","application/json"),t.setRequestHeader(Ce,this.authHeader||""),t.send(JSON.stringify(e))}getRequestBlank(){return{platform:"javascript",event_id:Se(),sdk:{name:"micro-sentry.javascript.core",version:"0.0.0"},timestamp:Date.now()/1e3,environment:this.environment}}}function K(n,e){return Object.prototype.toString.call(e)==="[object RegExp]"?e.test(n):typeof e=="string"?n.indexOf(e)!==-1:!1}function xe(){return window}class P extends De{constructor(e,t=xe()){super(e),this.options=e,this.window=t,this.destroyed=!1,this._state={};const{plugins:i=[],beforeSend:a=d=>d,beforeBreadcrumb:o=d=>d,blacklistUrls:r=[],ignoreErrors:c=[],release:l=void 0}=this.options||{};this.plugins=i.map(d=>new d(this)),this.beforeSend=a,this.beforeBreadcrumb=o,this.blacklistUrls=r,this.ignoreErrors=c,this.release=l}get state(){return this._state}clearState(){this._state={}}setTags(e){return this.setKeyState("tags",{...e}),this}setTag(e,t){return this.extendState({tags:{[e]:t}}),this}setExtra(e,t){return this.extendState({extra:{[e]:t}}),this}setExtras(e){return this.setKeyState("extra",{...e}),this}setUser(e){return this.setKeyState("user",{...e}),this}clone(){const e=new P({...this.options,plugins:[]});return e.extendState(this.state),e}withScope(e){const t=this.clone();e(t),t.destroy(),this.setBreadcrumbs(void 0)}addBreadcrumb(e){this.extendState({breadcrumbs:[{timestamp:Date.now()/1e3,...this.beforeBreadcrumb(e)}]})}setBreadcrumbs(e){this.setKeyState("breadcrumbs",e)}captureMessage(e,t){this.send({...this.getRequestBlank(),message:e,level:t})}destroy(){this.destroyed=!0,this.plugins.forEach(e=>{e.destroy&&e.destroy()})}isIgnoredError(e){return this.ignoreErrors.length?this.getPossibleEventMessages(e).some(t=>this.ignoreErrors.some(i=>K(t,i))):!1}getRequestBlank(){return{request:{url:this.window.location.toString(),headers:{"User-Agent":this.window.navigator.userAgent}},...super.getRequestBlank(),sdk:{name:"micro-sentry.javascript.browser",version:"0.0.0"},...this.state}}send(e){this.destroyed||this.isDeniedUrl(e)||this.isIgnoredError(e)||(super.send(this.beforeSend({release:this.release,...e})),this.setBreadcrumbs(void 0))}getPossibleEventMessages(e){if(e.message)return[e.message];if(e.exception)try{const{type:t="",value:i=""}=e.exception.values&&e.exception.values[0]||{};return[`${i}`,`${t}: ${i}`]}catch{return[]}return[]}isDeniedUrl(e){if(!this.blacklistUrls.length)return!1;const t=this.getEventFilterUrl(e);return t?this.blacklistUrls.some(i=>K(t,i)):!1}getEventFilterUrl(e){try{if(e.exception){const t=e.exception.values&&e.exception.values[0].stacktrace&&e.exception.values[0].stacktrace.frames;return t&&t[t.length-1].filename||null}return null}catch{return null}}extendState(e){this._state=Object.keys(e).reduce((t,i)=>{const a=this._state[i],o=Array.isArray(a)?a:null,r=e[i],c=Array.isArray(r)?r:null;return{...t,[i]:o||c?[...o||[],...c||[]]:{...typeof a!="string"?a:{},...typeof r!="string"?r:{}}}},this._state)}setKeyState(e,t){this._state[e]=t}}class y{init(){new P({dsn:"https://830cd780e8fd7e83482ca5710da08c54@o4505458601361408.ingest.sentry.io/4506268568518656",ignoreErrors:["Failed to fetch","NetworkError when attempting to fetch resource.","Property description must be an object.","No error message","App container not found","JSON.parse: unexpected","Unexpected token","The string did not match the expected pattern."]})}logError(e){}}const S=()=>{const n="https://prod-api.chatway.app/api/widget/",e={headers:{"Content-Type":"application/json",Accept:"application/json"}};function t(c,l){return fetch(n+c,{...e,...l,method:"get"})}function i(c,l,d){return fetch(n+c,{...e,...d,body:JSON.stringify(l),method:"post"})}function a(c,l,d){return fetch(n+c,{...e,...d,body:JSON.stringify(l),method:"put"})}function o(c,l,d){return fetch(n+c,{...e,...d,body:JSON.stringify(l),method:"PATCH"})}function r(c,l,d){return fetch(n+c,{...e,...d,body:JSON.stringify(l),method:"DELETE"})}return{post:i,get:t,put:a,patch:o,delete:r}};class _{addCustomData({token:e,name:t,value:i}){return S().post("chat-contacts/custom-fields",{name:t,value:i},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}deleteCustomData({token:e,name:t}){return S().delete("chat-contacts/custom-fields",{name:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}updateEmailName({token:e,name:t,value:i}){return S().patch("chat-contacts/profile",{[t]:i},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}deleteEmailName({token:e,name:t}){return S().patch("chat-contacts/profile",{remove:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}addTag({token:e,tags:t}){return S().post("chat-contacts/tags",{tags:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}deleteTag({token:e,tags:t}){return S().delete("chat-contacts/tags",{tags:t},{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}assignShopifyCustomer(e){return fetch(`${e.marketplace_origin}/apps/chatway-app-proxy/chat-contacts/${e.chat_contact_id}/assign-customer-id`,{method:"GET",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"}})}getShopifyCustomerData(e){return fetch(`${e.marketplace_origin}/apps/chatway-app-proxy/logged-in-customer-id`,{method:"GET",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"}})}saveShopifyCartData({token:e,chat_contact_id:t,cart_data:i}){return fetch(`https://prod-api.chatway.app/api/pixel/chat-contacts/${t}/cart-info`,{method:"POST",body:JSON.stringify({cart_data:i}),headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}})}}class k{async updateChatwayCustomData(e,t){try{if(!e||!t)return;const i=new p().getSessionToken();if(!i)return new f().dispatchEvent(u.customData,JSON.stringify({name:e,value:t,method:"updateChatwayCustomData"}));const a=new _;if(e.toLowerCase()==="email"||e.toLowerCase()==="name"||e.toLowerCase()==="phone"){const r=await a.updateEmailName({token:i,name:e,value:t}),{data:c}=await r.json();let l;return l={email:c.attributes.email,phone:c.attributes.phone},e==="name"&&(l={...l,name:c.attributes.name}),new f().actionDispatcher(u.profileData,l),{message:"Success"}}return(await a.addCustomData({token:i,name:e,value:t})).json()}catch(i){new y().logError(i)}}getContactId(){return s.chatContactId}getContactToken(){return new p().getSessionToken()}async removeChatwayCustomData(e){try{if(!e)return;const t=new p().getSessionToken();if(!t)return new f().dispatchEvent(u.customData,JSON.stringify({name:e,method:"removeChatwayCustomData"}));const i=new _;if(e.toLowerCase()==="email"||e.toLowerCase()==="name"||e.toLowerCase()==="phone"){const o=await i.deleteEmailName({token:t,name:e}),{data:r}=await o.json();let c;return c={email:r.attributes.email,phone:r.attributes.phone},e==="name"&&(c={...c,name:"remove"}),new f().actionDispatcher(u.profileData,c),r}return(await i.deleteCustomData({token:t,name:e})).json()}catch(t){console.log(t),new y().logError(t)}}hideChatwayIcon(){s.isHideChatwayIcon=!0;const e=document.getElementsByClassName("chatway--trigger-icon-container")[0];if(!e)return;e.classList&&e.classList.add("hide--chatway");let t=h(".chatway--preview-container");(t==null?void 0:t.classList)&&!s.agentMessage&&t.classList.add("hide--chatway");const i=s.widgetID,a=JSON.parse(sessionStorage.getItem(`ch_session_info_${i}`)||"{}");(a==null?void 0:a.widgetStatus)!=="open"&&new f().closeWidget()}showChatwayIcon(){s.isHideChatwayIcon=!1;const e=document.getElementsByClassName("chatway--trigger-icon-container")[0];if(!e)return;e.classList&&e.classList.remove("hide--chatway");let t=h(".chatway--preview-container");t!=null&&t.classList&&t.classList.remove("hide--chatway");const i=s.widgetID,a=JSON.parse(sessionStorage.getItem(`ch_session_info_${i}`)||"{}");(a==null?void 0:a.widgetStatus)!=="open"&&new f().closeWidget()}openChatwayWidget(){new f().openWidget()}closeChatwayWidget(){new f().closeWidget()}async addChatwayTags(e){try{if(!e)return;const t=new p().getSessionToken();if(!t)return new f().dispatchEvent(u.customData,JSON.stringify({tag:e,method:"addChatwayTags"}));const i=new _,a=Array.isArray(e)?e.map(r=>({name:r})):[{name:e}];return(await i.addTag({token:t,tags:a})).json()}catch(t){new y().logError(t)}}async removeChatwayTags(e){try{if(!e)return;const t=new p().getSessionToken();if(!t)return new f().dispatchEvent(u.customData,JSON.stringify({tag:e,method:"removeChatwayTags"}));const i=new _,a=Array.isArray(e)?e.map(r=>({name:r})):[{name:e}];return(await i.deleteTag({token:t,tags:a})).json()}catch(t){console.log(t),new y().logError(t)}}setChatwaySettings(e){if(window.chatwaySettings=e,!(e!=null&&e.visitor))return;const{data:t,hmac:i}=e.visitor;!(t!=null&&t.id)&&!(t!=null&&t.email)||!i||new f().dispatchEvent(u.setChatwaySettings,JSON.stringify(e))}}const D=new class{async assignCustomer(){if(!$()||!s.chatContactId)return;const e={chat_contact_id:s.chatContactId,marketplace_origin:$()};try{const i=await(await new _().assignShopifyCustomer(e)).json();new f().dispatchEvent(u.setVisitorEmail,JSON.stringify(i))}catch(t){console.log(t)}}isShopifyCartURL(e){if(!e)return!1;const t=["/cart/add","/cart/change","/cart/clear","/cart/add.js","/cart/change.js","/cart/clear.js"],i=e.split("/").pop();return t.includes(`/cart/${i}`)}watchCartChange(){if(!window.fetch||typeof window.fetch!="function")return;const e=window.fetch,t=this;window.fetch=function(){const i=e.apply(this,arguments);return t.isShopifyCartURL(arguments[0])&&i.then(a=>{a.clone().json().then(o=>t.saveCartData(o))}),i}}async getCartData(){try{return await(await fetch(window.location.origin+window.Shopify.routes.root+"cart.js")).json()}catch(e){console.log(e)}}async saveCartData(e){const t=new p().getSessionToken(),i=e!=null&&e.token?e:await this.getCartData();if(!t||!s.chatContactId||!i)return;const a={token:t,cart_data:i,chat_contact_id:s.chatContactId};try{await new _().saveShopifyCartData(a)}catch(o){console.error(o)}}async getCustomerData(){if(!$())return;const e={marketplace_origin:$()};try{const i=await(await new _().getShopifyCustomerData(e)).json();new f().dispatchEvent(u.customerDataLoaded,JSON.stringify(i)),s.chatContactId=i==null?void 0:i.contact_id,s.shopifyCustomerId=i==null?void 0:i.logged_in_customer_id}catch(t){console.log(t),new f().dispatchEvent(u.customerDataLoaded,JSON.stringify({}))}}};class f{constructor(){g(this,"origin","https://widget.chatway.app/");g(this,"actionType","CHATWAY");g(this,"appContainer");g(this,"frameContainer");g(this,"bodyContainer");g(this,"triggerContainer");g(this,"iconToggler");g(this,"widgetStatus",!0);this.appContainer=s.appContainer,this.bodyContainer=document.getElementsByTagName("body")[0]?document.getElementsByTagName("body")[0]:null,this.frameContainer=s.frameContainer,this.triggerContainer=s.triggerContainer,this.iconToggler=s.iconToggler}setupEvents(){window.addEventListener("message",this.messageCallback.bind(this),!1),window.addEventListener("urlchangeevent",this.urlChangeCallback.bind(this),!1)}cleanupEvents(){var e;(e=this.iconToggler)==null||e.removeEventListener("click",()=>{this.actionDispatcher(u.widgetToggle)}),window.removeEventListener("message",this.messageCallback.bind(this),!1),window.removeEventListener("urlchangeevent",this.urlChangeCallback.bind(this),!1)}async actionDispatcher(e,t=null){switch(e){case u.widgetToggle:this.toggleWidget();break;case u.widgetDestroy:new B().destroyApp();break;case u.widgetReload:new p().deleteUserConfig(),new B().destroyApp(),s.isChatInitialized="false",s.token="",await re(300),new B().initialize();break;case u.agentStatusChange:const i=s.previewTextBubbleDelay*1e3;setTimeout(()=>{this.toggleTextBubble({agentDetails:t,isNewMessage:!1,isStatusChange:!0})},i);break;case u.unreadMessage:this.handleUnread(t);break;case u.agentMessaged:this.handleIncomingMessage(t);break;case u.visitorConversationStarted:this.setVisitorID(t);break;case u.loadImage:this.loadImage(t);break;case u.removeImage:this.removeImage();break;case u.widgetDisable:this.toggleWidgetStatus(t);break;case u.widgetLoaded:await this.updateSessionKeys(),this.sendChatHistoryData(),this.sendWidgetData(),this.runConfigChecks(),this.emitIconState(),q()&&!new p().getSessionToken()&&D.getCustomerData();break;case u.profileData:this.setProfileData(t);break;case u.focusEvent:this.handleFocusEvent();break;case u.customData:this.saveCustomData(t);break;case u.removeToken:new p().deleteUserConfig();break;case u.chatContactLoaded:this.setContactData(t),this.syncWordPressData(),q()&&(D.assignCustomer(),D.saveCartData(),D.watchCartChange(),s.isVerifiedVisitor||await D.assignCustomer(),D.getCustomerData());break;case u.openContactChannel:this.openContactChannel(t);break;case u.copyToClipboard:this.copyToClipboard(t);break}}saveCustomData(e){if(!new p().getSessionToken()||!e)return;const a=JSON.parse(e);switch(a.method){case"updateChatwayCustomData":new k().updateChatwayCustomData(a.name,a.value);break;case"removeChatwayCustomData":new k().removeChatwayCustomData(a.name);break;case"addChatwayTags":new k().addChatwayTags(a.tag);break;case"removeChatwayTags":new k().removeChatwayTags(a.tag);break}}addIconEvent(){this.iconToggler.addEventListener("click",()=>{this.actionDispatcher(u.widgetToggle)})}messageCallback(e){e.data.type&&e.data.type==this.actionType&&this.actionDispatcher(e.data.action,e.data.meta)}urlChangeCallback(e){var t,i,a;try{if(e.action=="popstate"&&x()){const o=((t=e.oldURL)==null?void 0:t.pathname)||"",r=((i=e.newURL)==null?void 0:i.pathname)||"",c=new C().isWidgetVisible;if(o===r&&!c||!c)return;if(o===r&&c){this.closeWidget();return}e.preventDefault(),this.closeWidget(),(a=window.history)==null||a.pushState(null,"",window.location.href)}if(e.action=="pushState"&&e.oldURL.href!=e.newURL.href){const o=u.locationChange,r={origin:e.newURL.origin,path:e.newURL.pathname};this.dispatchEvent(o,JSON.stringify(r))}}catch(o){new y().logError(o)}}toggleWidget(){new C().isWidgetVisible?this.closeWidget():this.openWidget()}closeWidget(){if(new C().isWidgetVisible){j(this.appContainer,"widget--open"),j(this.bodyContainer,"chatway-is-open"),this.emitIconState(),document.body.style.position="",document.body.style.top="",document.body.style.width="",(window.innerWidth<601||sessionStorage.getItem("_bdyF"))&&de(),new p().setWidgetStatus(!1);let t={data:"false",expireTime:Date.now()+1*60*60*1e3};localStorage.setItem("showTextBubble",JSON.stringify(t)),window.removeEventListener("popstate",this.urlChangeCallback.bind(this),!1)}}findAttentionEffectClass(e){const t=/\S*effect\S*/,i=e==null?void 0:e.className.match(t);return i?i[0]:""}openWidget(){var i;const e=new C().isWidgetVisible,t=document.getElementsByClassName("chatway-launcher")?document.getElementsByClassName("chatway-launcher")[0]:null;if(t&&this.findAttentionEffectClass(t)&&(t.classList&&t.classList.remove(this.findAttentionEffectClass(t)),new p().setShowAttentionEffect(!1)),(i=window.history)==null||i.pushState({page:"widget"},"",window.location.href),window.addEventListener("popstate",this.urlChangeCallback.bind(this),!1),!e){F(this.appContainer,"widget--open"),F(this.bodyContainer,"chatway-is-open");const a=new I;a.isPreviewVisible&&a.hidePreview(),ce(),x()&&(document.body.style.position="fixed",document.body.style.top=`-${scrollY}px`,document.body.style.width="100%"),window.innerWidth<=601&&le(),this.emitIconState(),new p().setWidgetStatus(!0),new p().setBubbleExpiration()}}emitIconState(){if(this.appContainer){const e=u.widgetToggle,t=new C().isWidgetVisible;let i={isOpen:!1};t&&(i.isOpen=!0),this.dispatchEvent(e,JSON.stringify(i))}}syncWordPressData(){window!=null&&window.syncChatwayData&&window.syncChatwayData()}sendChatHistoryData(){const e=ge("res_chtwy_cht");if(e){const t=u.chatHistory,i={res_chtwy_cht:e};this.dispatchEvent(t,JSON.stringify(i))}}sendWidgetData(){const e=s.triggerData,t=new p,i={"bg-color":e.widget_color,"icon-color":X(e.widget_color),isMobileDevice:x(),userId:s.userID,widgetId:s.widgetID,origin:location.origin,marketplace:Y(),path:location.pathname,agents:s.allAgents,previewText:s.previewText,token:t.getSessionToken(),isChatInitialized:t.getChatInitStatus(),chatwaySettings:window.chatwaySettings,wpUserInfo:window==null?void 0:window.wpChatwaySettings,...e};this.dispatchEvent(u.widgetLoaded,JSON.stringify(i))}runConfigChecks(){new p().wasWidgetOpen&&this.toggleWidget()}dispatchEvent(e,t=null){var i;try{const a=h("#chatway_widget_app"),o={type:"CHATWAY",action:e,meta:t};if(!a||a.contentWindow===null)return;(i=a.contentWindow)==null||i.postMessage(o,"*")}catch(a){new y().logError(a)}}toggleTextBubble(e){const t=new p,i=JSON.parse(e.agentDetails);if(s.agents=i,!s.triggerData.is_preview_text_enabled||t.showTextBubble==="false"&&!e.isNewMessage||s.isHideChatwayIcon&&e.isStatusChange)return;s.status=i.some(o=>o.attributes.online_status.toLowerCase()=="online")?"online":"offline";const a=new I;s.agents&&s.agents.length>1?a.makeMultipePreviewContainer():a.makeSinglePreviewContainer(),s.agents&&s.agents.length>1?a.displayMultipleAgents():a.displaySingleAgent(),a.makePreviewText(),a.makeNameText(),a.toggleOnlineStatus(),a.showPreview(),t.setTextBubbleStatus(!0)}handleUnread(e){const t=JSON.parse(e);s.unReadCount=parseInt(t.count),new we().updatePendingStatus()}handleIncomingMessage(e){s.agentMessage=JSON.parse(e);const t=JSON.stringify(s.agents),i=s.widgetID,a=JSON.parse(sessionStorage.getItem(`ch_session_info_${i}`)||"{}");(a==null?void 0:a.widgetStatus)!=="open"&&this.toggleTextBubble({agentDetails:t,isNewMessage:!0,isStatusChange:!1});const o=new I;let r=h(".chatway--preview-container");r!=null&&r.classList&&r.classList.remove("hide--chatway"),o.showUnreadMessage()}setVisitorID(e){const t=JSON.parse(e),i=new p;s.token=t.token,s.isChatInitialized=t.isChatInitialized,i.setSessionToken(t.token),i.setChatInitStatus(t.isChatInitialized),this.addConversationStartedEvent(t.isChatInitialized),window!=null&&window.syncChatwayData&&window.syncChatwayData()}addConversationStartedEvent(e){typeof window.$chatwayConversationStarted=="function"&&window.$chatwayConversationStarted({isChatInitialized:e})}setContactData(e){if(!e)return;const t=JSON.parse(e);s.chatContactId=t.contactId,s.isVerifiedVisitor=t.isVerified}setProfileData(e){const t=u.profileData;this.dispatchEvent(t,JSON.stringify(e))}async updateSessionKeys(){return new Promise((e,t)=>{try{const i=s.userID,a=new p;b(`ch_cw_token_${i}`)&&(a.setSessionToken(b(`ch_cw_token_${i}`)),sessionStorage.removeItem(`ch_cw_token_${i}`),L(`ch_cw_token_${i}`)),b(`ch_cw_status_${i}`)&&(a.setChatInitStatus(b(`ch_cw_status_${i}`)),sessionStorage.removeItem(`ch_cw_status_${i}`),L(`ch_cw_status_${i}`)),b(`ch_cw_shw_atn_efct_${i}`)&&(a.setShowAttentionEffect(!0),L(`ch_cw_shw_atn_efct_${i}`)),sessionStorage.getItem(`ch_session_info_${i}`)&&(a.setUserConfig(JSON.parse(sessionStorage.getItem(`ch_session_info_${i}`)||"{}")),sessionStorage.removeItem(`ch_session_info_${i}`)),e("Tokens updated")}catch{t("Couldn't update tokens")}})}handleFocusEvent(){this.closeWidget()}loadImage(e){const{src:t}=JSON.parse(e);new G(t).openImageViewer()}removeImage(){new G("").closeImageViewer()}toggleWidgetStatus(e){this.widgetStatus=e;const t=h(".chatway--container");!t||(e?t.classList.remove("disable--widget"):t.classList.add("disable--widget"))}checkPageRules(){const e=s.pageRules;if(!(e!=null&&e.is_enable)||!(e!=null&&e.rules)||!e.rules.length){this.toggleWidgetVisibility(!0);return}const t=this.removeSlashFromUrl(window.location.href.replace(window.location.origin,"")),i=this.cleanDomain(window.location.host),a=this.checkForPageRules(i,t,e.rules,"show",!0),o=this.checkForPageRules(i,t,e.rules,"hide",!1);this.toggleWidgetVisibility(a&&o)}checkForPageRules(e,t,i,a,o){let r=!1,c=!o;for(const l of i){const d=this.cleanDomain(this.removeSlashFromUrl(l.domain)),w=this.removeSlashFromUrl(l.page);e===d&&l.visibility==a&&(r=!0,(l.condition==="any-page"||l.condition==="contains"&&t.includes(w)||l.condition==="equals"&&t===w||l.condition==="start-with"&&t.startsWith(w)||l.condition==="end-with"&&t.endsWith(w)||l.condition==="homepage"&&t==="")&&(c=o))}return r?c:!0}cleanDomain(e){return e.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/:\d+$/,"")}removeSlashFromUrl(e){return e?(e.endsWith("/")&&(e=e.slice(0,-1)),e.startsWith("/")&&(e=e.replace("/","")),e):""}toggleWidgetVisibility(e){const t=h(".chatway--container"),i=h("body");!t||!i||(e&&this.widgetStatus?(t.classList.remove("hide--widget"),i.classList.add("chatway--active")):(t.classList.add("hide--widget"),i.classList.remove("chatway--active")))}checkVisibilityRules(){var d,w;const e=h(".chatway--container");if(!e)return;const t=s.visibilityHours;if(s.visibilityHourTimezone==null||!t.length){s.isWidgetVisible=!0,this.checkForTriggers();return}const i=new Date,a=new Date(i.toLocaleString("en-US",{timeZone:s.visibilityHourTimezone})),o=i.getDay(),c=(d=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][o])==null?void 0:d.toLowerCase();let l=!1;for(const m of t){const v=m.is_full_day||this.timeWithinRange(a,m.start_time,m.end_time);if(m.is_custom&&m.custom_date===a.toISOString().slice(0,10)&&(l=m.is_published?v:!v,v))break;m.is_published&&((w=m.day)==null?void 0:w.toLowerCase())===c&&v&&(l=!0)}s.isWidgetVisible=l,l?(this.checkForTriggers(),this.checkPageRules()):(e.style.display="none",this.toggleWidgetVisibility(!1))}displayWidget(){const e=h(".chatway--container");e!==null&&e.classList.add("has-loaded"),localStorage.setItem("isWidgetVisible","true")}checkForTriggers(){const{is_trigger_enabled:e,has_display_after_time:t,has_display_page_scroll:i,display_after_time:a,display_page_scroll:o}=s.widgetTriggers;if(this.toggleWidgetVisibility(!0),localStorage.getItem("isWidgetVisible")==="true"||!e){this.displayWidget();return}if(!t&&!i){this.displayWidget();return}t&&setTimeout(()=>this.displayWidget(),1e3*a),i&&(document.body.scrollHeight>window.innerHeight?window.onscroll=()=>{Math.ceil(window.scrollY/(document.documentElement.scrollHeight-window.innerHeight)*100)>=o&&this.displayWidget()}:this.displayWidget())}timeWithinRange(e,t,i){const a=new Date(`${e.toDateString()} ${t}`),o=new Date(`${e.toDateString()} ${i}`);return e>=a&&e<=o}openContactChannel(e){if(!!e)try{const{channelUrl:t,target:i}=JSON.parse(e);window.open(t,i)}catch(t){new y().logError(t)}}copyToClipboard(e){if(!!e)try{const{text:t}=JSON.parse(e);navigator.clipboard.writeText(t)}catch(t){new y().logError(t)}}}class ke{constructor(e,t,i){this.widgetIcon=e,this.widgetColor=t,this.widgetImage=i}getChatIcon(){let e=null;switch(!0){case this.widgetIcon=="chat-base":e=this.chatBase;break;case this.widgetIcon=="chat-smile":e=this.chatSmile;break;case this.widgetIcon=="chat-bubble":e=this.chatBubble;break;case this.widgetIcon=="chat-db":e=this.chatDb;break;case this.widgetIcon=="chat-image":e=this.chatImage;break;default:e="";break}return this.widgetIcon=="chat-image"?this.parseImage(e):this.convertStringToElement(e)}hasCustomImage(){return this.widgetIcon=="chat-image"}getCloseIcon(){return this.convertStringToElement(this.closeIcon)}convertStringToElement(e){const i=new DOMParser().parseFromString(e,"image/svg+xml"),a=i.querySelectorAll(".fill--element");return a.length>0&&a.forEach(o=>o.setAttribute("fill",this.widgetColor)),i.documentElement}parseImage(e){return new DOMParser().parseFromString(e,"text/html").querySelector("img")}get chatBase(){return` `}get chatBubble(){return` `}get chatDb(){return` `}get chatSmile(){return` `}get chatImage(){return``}get closeIcon(){return` `}}class Le{constructor(){g(this,"_svgBuilder");g(this,"triggerData");this.triggerData=s.triggerData,this._svgBuilder=new ke(this.triggerData.widget_icon,X(this.triggerData.widget_color),this.triggerData.widget_icon_url)}makeIconContainer(){const e=document.createElement("div");return e.classList.add("chatway-launcher"),e.setAttribute("role","button"),e.setAttribute("aria-label","Open Chatway Messenger"),e.setAttribute("tabindex","0"),e.style.background=this.triggerData.widget_color,new p().getShowAttentionEffect()&&this.triggerData.default_state==="click"&&e.classList.add(this.triggerData.attention_effect+"-effect"),e}makeLauncherContainer(){const e=document.createElement("div");e.classList.add("launcher-icon"),e.classList.add("launcher-default-open-icon"),e.classList.add("launcher-default-open-animated");const t=this._svgBuilder.getChatIcon();return this._svgBuilder.hasCustomImage()&&e.classList.add("has-custom-image"),e.appendChild(t),e}makeAnimatedContainer(){const e=document.createElement("div");e.classList.add("launcher-icon"),e.classList.add("animatedIcon");const t=document.createElement("dotlottie-player");return t.setAttribute("src","https://lottie.host/6468be3e-a133-4b36-aba2-01a8014e8406/LoRT0NHpMO.json"),t.setAttribute("background","transparent"),t.setAttribute("speed","1"),t.setAttribute("style","width: inherit; height: inherit;"),t.setAttribute("loop","true"),t.setAttribute("autoplay","true"),e.appendChild(t),e}makeCloseContainer(){const e=document.createElement("div");e.classList.add("launcher-icon"),e.classList.add("launcher-minimize-icon");const t=this._svgBuilder.getCloseIcon();return e.appendChild(t),e}makeIcon(){const e=this.makeIconContainer(),t=this.makeLauncherContainer(),i=this.makeCloseContainer();return e.appendChild(t),e.appendChild(i),e}}const Ie=n=>new Promise(function(e,t){var i=new XMLHttpRequest;i.open("GET",n,!0),typeof i.setRequestHeader=="function"&&(i.setRequestHeader("Content-Type","application/json"),i.setRequestHeader("Accept","application/json")),i.onload=function(){i.status==200?e(JSON.parse(i.responseText)):t("Error "+i.status+": "+i.statusText)},i.onerror=function(){t("Network error")},i.send()});class B{constructor(){g(this,"triggerData",null);g(this,"scriptId")}start(){this.isChatwayInstalled||(this.setupGlobalFunctions(),this.addWindowLoadEvent())}getEcwidShopID(){let e=0;return typeof window.Ecwid=="object"&&(e=window.Ecwid.getOwnerId()),e}async initialize(){if(!s.hasAlreadyLoaded)try{if(s.hasAlreadyLoaded=!0,this.removeWindowLoadEvent(),this.setCurrentUserId(),!this.scriptId)return;oe(),await this.fetchWidgetData()&&(this.checkForChatyScript(),this.buildApp())}catch(e){new y().logError(e)}}addWindowLoadEvent(){document.readyState=="complete"?this.initialize():window.addEventListener&&window.addEventListener("load",()=>{this.initialize()},!0)}addChatwayLoadedEvent(){typeof window.$chatwayOnLoad=="function"&&window.$chatwayOnLoad({widgetId:s.widgetID,timestamp:Date.now()})}removeWindowLoadEvent(){window.removeEventListener("load",this.initialize)}setCurrentUserId(){var e,t;this.scriptId=U("chatway","id"),!this.scriptId&&((e=window.wpChatwaySettings)==null?void 0:e.widgetId)&&(this.scriptId=window.wpChatwaySettings.widgetId),!this.scriptId&&!((t=window.wpChatwaySettings)!=null&&t.widgetId)&&this.getEcwidShopID()&&(this.scriptId=this.getEcwidShopID().toString()),s.userID=this.scriptId}async fetchLocationData(){try{return await(await fetch("https://www.cloudflare.com/cdn-cgi/trace",{method:"GET"})).text()}catch(e){console.log(e)}return""}async fetchWidgetData(){try{const e=await this.fetchLocationData(),t=ue(e),i=(t==null?void 0:t.ip)||"",a=(t==null?void 0:t.loc)||"",o=x()?1:0,r=U("chatway","id");let c="";!r&&this.getEcwidShopID()&&(c="ecwid");const l=`https://prod-api.chatway.app/api/v2/pixel/widgets?${!r&&this.getEcwidShopID()?"site_identifier":"user_identifier"}=${this.scriptId}&include[]=agents&include[]=faqs&ip=${i}&is_mobile=${o}&loc=${a}&channel=${c}`,{data:d,included:w}=await Ie(l);if(!d)throw new Error(`No data returned from API for ${this.scriptId}`);const m=d.attributes;return m.hasOwnProperty("is_ch_ob")&&!m.is_ch_ob||m.is_blocked?!1:(this.triggerData=d.attributes,s.widgetID=d.id,s.triggerData={...m,browserData:t},s.allAgents=w,s.pageTitle=document.title,s.visibilityHourTimezone=m.timezone,s.visibilityHours=this.setWidgetVisibilityHour(w),s.widgetTriggers=this.setWidgetTriggers(w),s.pageRules=this.setPageRules(m),this.setDevicePreferences(w),!0)}catch(e){throw console.log(e),new y().logError(e),e}}setDevicePreferences(e){if(!e)return;const t=e.filter(d=>d.type==="device_preferences"),i=s.triggerData,a=t.find(d=>d.attributes.is_mobile),o=t.find(d=>!d.attributes.is_mobile);if(a&&o)i.device_preferences={desktop:o.attributes,mobile:a.attributes};else{const d={position:i==null?void 0:i.position,custom_position_side:i==null?void 0:i.custom_position_side,bottom_spacing:i==null?void 0:i.bottom_spacing,side_spacing:i==null?void 0:i.side_spacing,custom_widget_size:i==null?void 0:i.custom_widget_size,is_preview_text_enabled:!!(i!=null&&i.is_preview_text_enabled),preview_text_bubble_delay:i==null?void 0:i.preview_text_bubble_delay,preview_text:i==null?void 0:i.preview_text,is_welcome_text_enabled:i==null?void 0:i.is_welcome_text_enabled,widget_size:i==null?void 0:i.widget_size};i.device_preferences={desktop:d,mobile:d}}if(!s.triggerData)return;let r=!i.is_separate_device_preference&&i.device_appearance==="both"?"desktop":x()?"mobile":"desktop";const c=i.device_preferences[r];Object.keys(c).forEach(d=>{s.triggerData[d]=c[d]}),s.previewText=this.getPreviewText(i.device_preferences[r].preview_text,e,r),s.previewTextBubbleDelay=i.device_preferences[r].preview_text_bubble_delay}setPageRules(e){var t,i;return(e==null?void 0:e.has_paid_access)&&((t=e==null?void 0:e.page_targeting)==null?void 0:t.is_enable)&&((i=e==null?void 0:e.page_targeting)==null?void 0:i.rules.length)>0?e==null?void 0:e.page_targeting:{is_enable:!1,rules:[]}}setWidgetTriggers(e){let t={is_trigger_enabled:!1,has_display_after_time:!1,display_after_time:0,has_display_page_scroll:!1,display_page_scroll:0};return e.forEach(i=>{i.type==="widget_trigger"&&(t=i.attributes)}),t}setWidgetVisibilityHour(e){const t=[];return e.forEach(i=>{i.type==="widget_visibility_hour"&&t.push(i.attributes)}),t}checkForChatyScript(){if(document.getElementById("pixel-chaty")){let e=document.getElementsByTagName("body")[0]?document.getElementsByTagName("body")[0]:null;e&&e.classList.add("has--chaty")}}async buildApp(){var e;try{const t=new C,i=await t.makeAppContainer();if(!i)throw new Error("App container not found");const a=t.makeFrameContainer();if(!a)throw new Error("Frame container not found");const o=t.makeTriggerContainer();if(!o)throw new Error("Trigger container not found");const c=new Le().makeIcon();o.appendChild(c),s.appContainer=i,s.frameContainer=a,s.triggerContainer=o,s.iconToggler=c;const l=new f;if(l.setupEvents(),l.addIconEvent(),l.emitIconState(),l.checkVisibilityRules(),setInterval(()=>{l.checkVisibilityRules()},6e4),(e=s.pageRules)!=null&&e.is_enable){let d=history.pushState;history.pushState=function(){d.apply(history,arguments),l.checkVisibilityRules()}}this.addChatwayLoadedEvent()}catch(t){new y().logError(t)}}setupGlobalFunctions(){window.$chatway=window.$chatway||new k}get isChatwayInstalled(){return window.$chatway!==void 0}async destroyApp(){const e=new f,t=new C;e.cleanupEvents(),e.closeWidget(),t.destroyAppContainer(),s.hasAlreadyLoaded=!1}getPreviewText(e,t,i){if(!t)return e;const a=t.filter(d=>d.type==="widget_langs");let o=navigator.language;o!=="zh-TW"&&(o=o.split("-")[0]);const r=t.filter(d=>d.type==="device_preferences"),c=a.find(d=>d.id===o);if(c)return c.attributes[r.length?`widget_text_bubble_${i}`:"widget_text_bubble"];const l=a.find(d=>{var w;return(w=d.attributes)==null?void 0:w.is_default});if(l){const d=t.filter(m=>m.type==="device_preferences"),w=l.attributes[d.length?`widget_text_bubble_${i}`:"widget_text_bubble"];return w!==e?e:w}return e}}new y().init();new B().start(); })()