posthog-js
Version:
Posthog-js allows you to automatically capture usage and send events to PostHog.
2 lines • 71.2 kB
JavaScript
!function(){var e,t,i,n,r,o,s,l,a,c,u,d,h,f,p={},g=[],v=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,m=Array.isArray;function y(e,t){for(var i in t)e[i]=t[i];return e}function x(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function w(e,n,r,o,s){var l={type:e,props:n,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==s?++i:s,__i:-1,__u:0};return null==s&&null!=t.vnode&&t.vnode(l),l}function b(e){return e.children}function k(e,t){this.props=e,this.context=t}function $(e,t){if(null==t)return e.__?$(e.__,e.__i+1):null;for(var i;e.__k.length>t;t++)if(null!=(i=e.__k[t])&&null!=i.__e)return i.__e;return"function"==typeof e.type?$(e):null}function _(e){if(e.__P&&e.__d){var i=e.__v,n=i.__e,r=[],o=[],s=y({},i);s.__v=i.__v+1,t.vnode&&t.vnode(s),z(e.__P,s,i,e.__n,e.__P.namespaceURI,32&i.__u?[n]:null,r,null==n?$(i):n,!!(32&i.__u),o),s.__v=i.__v,s.__.__k[s.__i]=s,D(r,s,o),i.__e=i.__=null,s.__e!=n&&S(s)}}function S(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),S(e)}function C(e){(!e.__d&&(e.__d=!0)&&n.push(e)&&!T.__r++||r!=t.debounceRendering)&&((r=t.debounceRendering)||o)(T)}function T(){try{for(var e,t=1;n.length;)n.length>t&&n.sort(s),e=n.shift(),t=n.length,_(e)}finally{n.length=T.__r=0}}function E(e,t,i,n,r,o,s,l,a,c,u){var d,h,f,v,m,y,x,w=n&&n.__k||g,b=t.length;for(a=I(i,t,w,a,b),d=0;b>d;d++)null!=(f=i.__k[d])&&(h=-1!=f.__i&&w[f.__i]||p,f.__i=d,y=z(e,f,h,r,o,s,l,a,c,u),v=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&P(h.ref,null,f),u.push(f.ref,f.__c||v,f)),null==m&&null!=v&&(m=v),(x=!!(4&f.__u))||h.__k===f.__k?(a=R(f,a,e,x),x&&h.__e&&(h.__e=null)):"function"==typeof f.type&&void 0!==y?a=y:v&&(a=v.nextSibling),f.__u&=-7);return i.__e=m,a}function I(e,t,i,n,r){var o,s,l,a,c,u=i.length,d=u,h=0;for(e.__k=new Array(r),o=0;r>o;o++)null!=(s=t[o])&&"boolean"!=typeof s&&"function"!=typeof s?("string"==typeof s||"number"==typeof s||"bigint"==typeof s||s.constructor==String?s=e.__k[o]=w(null,s,null,null,null):m(s)?s=e.__k[o]=w(b,{children:s},null,null,null):void 0===s.constructor&&s.__b>0?s=e.__k[o]=w(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[o]=s,a=o+h,s.__=e,s.__b=e.__b+1,l=null,-1!=(c=s.__i=M(s,i,a,d))&&(d--,(l=i[c])&&(l.__u|=2)),null==l||null==l.__v?(-1==c&&(r>u?h--:u>r&&h++),"function"!=typeof s.type&&(s.__u|=4)):c!=a&&(c==a-1?h--:c==a+1?h++:(c>a?h--:h++,s.__u|=4))):e.__k[o]=null;if(d)for(o=0;u>o;o++)null!=(l=i[o])&&!(2&l.__u)&&(l.__e==n&&(n=$(l)),N(l,l));return n}function R(e,t,i,n){var r,o;if("function"==typeof e.type){for(r=e.__k,o=0;r&&r.length>o;o++)r[o]&&(r[o].__=e,t=R(r[o],t,i,n));return t}e.__e!=t&&(n&&(t&&e.type&&!t.parentNode&&(t=$(e)),i.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function M(e,t,i,n){var r,o,s,l=e.key,a=e.type,c=t[i],u=null!=c&&!(2&c.__u);if(null===c&&null==l||u&&l==c.key&&a==c.type)return i;if(n>(u?1:0))for(r=i-1,o=i+1;r>=0||t.length>o;)if(null!=(c=t[s=0>r?o++:r--])&&!(2&c.__u)&&l==c.key&&a==c.type)return s;return-1}function L(e,t,i){"-"==t[0]?e.setProperty(t,null==i?"":i):e[t]=null==i?"":"number"!=typeof i||v.test(t)?i:i+"px"}function F(e,t,i,n,r){var o,s;e:if("style"==t)if("string"==typeof i)e.style.cssText=i;else{if("string"==typeof n&&(e.style.cssText=n=""),n)for(t in n)i&&t in i||L(e.style,t,"");if(i)for(t in i)n&&i[t]==n[t]||L(e.style,t,i[t])}else if("o"==t[0]&&"n"==t[1])o=t!=(t=t.replace(u,"$1")),s=t.toLowerCase(),t=s in e||"onFocusOut"==t||"onFocusIn"==t?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=i,i?n?i[c]=n[c]:(i[c]=d,e.addEventListener(t,o?f:h,o)):e.removeEventListener(t,o?f:h,o);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==i?"":i;break e}catch(e){}"function"==typeof i||(null==i||!1===i&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==i?"":i))}}function q(e){return function(i){if(this.l){var n=this.l[i.type+e];if(null==i[a])i[a]=d++;else if(n[c]>i[a])return;return n(t.event?t.event(i):i)}}}function z(e,i,n,r,o,s,l,a,c,u){var d,h,f,p,v,w,_,S,C,T,$,I,R,M,L,F,q=i.type;if(void 0!==i.constructor)return null;128&n.__u&&(c=!!(32&n.__u),s=[a=i.__e=n.__e]),(d=t.__b)&&d(i);e:if("function"==typeof q){h=l.length;try{if(C=i.props,T=q.prototype&&q.prototype.render,$=(d=q.contextType)&&r[d.__c],I=d?$?$.props.value:d.__:r,n.__c?S=(f=i.__c=n.__c).__=f.__E:(T?i.__c=f=new q(C,I):(i.__c=f=new k(C,I),f.constructor=q,f.render=j),$&&$.sub(f),f.state||(f.state={}),f.__n=r,p=f.__d=!0,f.__h=[],f._sb=[]),T&&null==f.__s&&(f.__s=f.state),T&&null!=q.getDerivedStateFromProps&&(f.__s==f.state&&(f.__s=y({},f.__s)),y(f.__s,q.getDerivedStateFromProps(C,f.__s))),v=f.props,w=f.state,f.__v=i,p)T&&null==q.getDerivedStateFromProps&&null!=f.componentWillMount&&f.componentWillMount(),T&&null!=f.componentDidMount&&f.__h.push(f.componentDidMount);else{if(T&&null==q.getDerivedStateFromProps&&C!==v&&null!=f.componentWillReceiveProps&&f.componentWillReceiveProps(C,I),i.__v==n.__v||!f.__e&&null!=f.shouldComponentUpdate&&!1===f.shouldComponentUpdate(C,f.__s,I)){i.__v!=n.__v&&(f.props=C,f.state=f.__s,f.__d=!1),i.__e=n.__e,i.__k=n.__k,i.__k.some(function(e){e&&(e.__=i)}),g.push.apply(f.__h,f._sb),f._sb=[],f.__h.length&&l.push(f);break e}null!=f.componentWillUpdate&&f.componentWillUpdate(C,f.__s,I),T&&null!=f.componentDidUpdate&&f.__h.push(function(){f.componentDidUpdate(v,w,_)})}if(f.context=I,f.props=C,f.__P=e,f.__e=!1,R=t.__r,M=0,T)f.state=f.__s,f.__d=!1,R&&R(i),d=f.render(f.props,f.state,f.context),g.push.apply(f.__h,f._sb),f._sb=[];else do{f.__d=!1,R&&R(i),d=f.render(f.props,f.state,f.context),f.state=f.__s}while(f.__d&&25>++M);f.state=f.__s,null!=f.getChildContext&&(r=y(y({},r),f.getChildContext())),T&&!p&&null!=f.getSnapshotBeforeUpdate&&(_=f.getSnapshotBeforeUpdate(v,w)),L=null!=d&&d.type===b&&null==d.key?B(d.props.children):d,a=E(e,m(L)?L:[L],i,n,r,o,s,l,a,c,u),f.base=i.__e,i.__u&=-161,f.__h.length&&l.push(f),S&&(f.__E=f.__=null)}catch(e){if(l.length=h,i.__v=null,c||null!=s)if(e.then){for(i.__u|=c?160:128;a&&8==a.nodeType&&a.nextSibling;)a=a.nextSibling;null!=s&&(s[s.indexOf(a)]=null),i.__e=a}else{if(null!=s)for(F=s.length;F--;)x(s[F]);W(i)}else i.__e=n.__e,!i.__k&&n.__k&&(i.__k=n.__k),e.then||W(i);t.__e(e,i,n)}}else null==s&&i.__v==n.__v?(i.__k=n.__k,i.__e=n.__e):a=i.__e=O(n.__e,i,n,r,o,s,l,c,u);return(d=t.diffed)&&d(i),128&i.__u?void 0:a}function W(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(W))}function D(e,i,n){for(var r=0;n.length>r;r++)P(n[r],n[++r],n[++r]);t.__c&&t.__c(i,e),e.some(function(i){try{e=i.__h,i.__h=[],e.some(function(e){e.call(i)})}catch(e){t.__e(e,i.__v)}})}function B(e){return"object"!=typeof e||null==e||e.__b>0?e:m(e)?e.map(B):void 0!==e.constructor?null:y({},e)}function O(i,n,r,o,s,l,a,c,u){var d,h,f,g,v,y,w,b=r.props||p,k=n.props,_=n.type;if("svg"==_?s="http://www.w3.org/2000/svg":"math"==_?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),null!=l)for(d=0;l.length>d;d++)if((v=l[d])&&"setAttribute"in v==!!_&&(_?v.localName==_:3==v.nodeType)){i=v,l[d]=null;break}if(null==i){if(null==_)return document.createTextNode(k);i=document.createElementNS(s,_,k.is&&k),c&&(t.__m&&t.__m(n,l),c=!1),l=null}if(null==_)b===k||c&&i.data==k||(i.data=k);else{if(l="textarea"==_&&null!=k.defaultValue?null:l&&e.call(i.childNodes),!c&&null!=l)for(b={},d=0;i.attributes.length>d;d++)b[(v=i.attributes[d]).name]=v.value;for(d in b)v=b[d],"dangerouslySetInnerHTML"==d?f=v:"children"==d||d in k||"value"==d&&"defaultValue"in k||"checked"==d&&"defaultChecked"in k||F(i,d,null,v,s);for(d in k)v=k[d],"children"==d?g=v:"dangerouslySetInnerHTML"==d?h=v:"value"==d?y=v:"checked"==d?w=v:c&&"function"!=typeof v||b[d]===v||F(i,d,v,b[d],s);if(h)c||f&&(h.__html==f.__html||h.__html==i.innerHTML)||(i.innerHTML=h.__html),n.__k=[];else if(f&&(i.innerHTML=""),E("template"==n.type?i.content:i,m(g)?g:[g],n,r,o,"foreignObject"==_?"http://www.w3.org/1999/xhtml":s,l,a,l?l[0]:r.__k&&$(r,0),c,u),null!=l)for(d=l.length;d--;)x(l[d]);c&&"textarea"!=_||(d="value","progress"==_&&null==y?i.removeAttribute("value"):null!=y&&(y!==i[d]||"progress"==_&&!y||"option"==_&&y!=b[d])&&F(i,d,y,b[d],s),d="checked",null!=w&&w!=i[d]&&F(i,d,w,b[d],s))}return i}function P(e,i,n){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==i||(e.__u=e(i))}else e.current=i}catch(e){t.__e(e,n)}}function N(e,i,n){var r,o;if(t.unmount&&t.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||P(r,null,i)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){t.__e(e,i)}r.base=r.__P=r.__n=null}if(r=e.__k)for(o=0;r.length>o;o++)r[o]&&N(r[o],i,n||"function"!=typeof e.type);n||x(e.__e),e.__c=e.__=e.__e=void 0}function j(e,t,i){return this.constructor(e,i)}function U(i,n,r){var o,s,l,a;n==document&&(n=document.documentElement),t.__&&t.__(i,n),s=(o="function"==typeof r)?null:r&&r.__k||n.__k,l=[],a=[],z(n,i=(!o&&r||n).__k=function(t,i,n){var r,o,s,l={};for(s in i)"key"==s?r=i[s]:"ref"==s?o=i[s]:l[s]=i[s];if(arguments.length>2&&(l.children=arguments.length>3?e.call(arguments,2):n),"function"==typeof t&&null!=t.defaultProps)for(s in t.defaultProps)void 0===l[s]&&(l[s]=t.defaultProps[s]);return w(t,l,r,o,null)}(b,null,[i]),s||p,p,n.namespaceURI,!o&&r?[r]:s?null:n.firstChild?e.call(n.childNodes):null,l,!o&&r?r:s?s.__e:n.firstChild,o,a),D(l,i,a),i.props.children=null}e=g.slice,t={__e(e,t,i,n){for(var r,o,s;t=t.__;)if((r=t.__c)&&!r.__)try{if((o=r.constructor)&&null!=o.getDerivedStateFromError&&(r.setState(o.getDerivedStateFromError(e)),s=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,n||{}),s=r.__d),s)return r.__E=r}catch(t){e=t}throw e}},i=0,k.prototype.setState=function(e,t){var i=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=y({},this.state);"function"==typeof e&&(e=e(y({},i),this.props)),e&&y(i,e),null!=e&&this.__v&&(t&&this._sb.push(t),C(this))},k.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),C(this))},k.prototype.render=b,n=[],o="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,s=function(e,t){return e.__v.__b-t.__v.__b},T.__r=0,l=Math.random().toString(8),a="__d"+l,c="__a"+l,u=/(PointerCapture)$|Capture$/i,d=0,h=q(!1),f=q(!0);const A=Object.prototype,H=A.hasOwnProperty,V=A.toString,Y=Array.isArray||function(e){return"[object Array]"===V.call(e)},G=e=>void 0===e,X=e=>null===e,K=e=>"[object Number]"==V.call(e)&&e==e;function J(e,t,i,n,r,o,s){try{var l=e[o](s),a=l.value}catch(e){return void i(e)}l.done?t(a):Promise.resolve(a).then(n,r)}function Z(e){return function(){var t=this,i=arguments;return new Promise(function(n,r){var o=e.apply(t,i);function s(e){J(o,n,r,s,l,"next",e)}function l(e){J(o,n,r,s,l,"throw",e)}s(void 0)})}}function Q(e){return Q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Q(e)}function ee(e,t,i){return(t=function(e){var t=function(e){if("object"!=Q(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!=Q(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==Q(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function te(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,n)}return i}function ie(e){for(var t=1;arguments.length>t;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?te(Object(i),!0).forEach(function(t){ee(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):te(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}const ne="$conversations_widget_session_id",re="$conversations_ticket_id",oe="$conversations_widget_state",se="$conversations_user_traits",le=(e,{debugEnabled:t}={})=>{const i={N(i,...n){let r;try{r=typeof window>"u"?void 0:window}catch(e){return}r&&(r.POSTHOG_DEBUG||t)&&!G(r.console)&&r.console&&("__rrweb_original__"in r.console[i]?r.console[i].__rrweb_original__:r.console[i])(e,...n)},debug(...e){i.N("debug",...e)},info(...e){i.N("log",...e)},warn(...e){i.N("warn",...e)},error(...e){i.N("error",...e)},critical(...t){console.error(e,...t)},uninitializedWarning(e){i.error(`You must initialize PostHog before calling ${e}`)},createLogger:(t,i)=>le(`${e} ${t}`,i)};return i},ae=le("[PostHog.js]").createLogger,ce="u">typeof window?window:void 0,ue="u">typeof globalThis?globalThis:ce,de=null==ue?void 0:ue.document;null!=ue&&ue.XMLHttpRequest&&new ue.XMLHttpRequest;var he=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,n,r){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(n)||!Number.isInteger(r)||0>t||0>i||0>n||0>r||t>0xffffffffffff||i>4095||n>1073741823||r>4294967295)throw new RangeError("invalid field value");const o=new Uint8Array(16);return o[0]=t/Math.pow(2,40),o[1]=t/Math.pow(2,32),o[2]=t/Math.pow(2,24),o[3]=t/Math.pow(2,16),o[4]=t/256,o[5]=t,o[6]=112|i>>>8,o[7]=i,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=r>>>24,o[13]=r>>>16,o[14]=r>>>8,o[15]=r,new e(o)}toString(){let e="";for(let t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new e(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;16>t;t++){const i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}},fe=class{generate(){const e=this.generateOrAbort();if(!G(e))return e;{this.Ct=0;const e=this.generateOrAbort();if(G(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const e=(()=>{const e=Date.now();return K(e)&&isFinite(e)?Math.min(Math.max(Math.floor(e),0),0xffffffffffff):0})();if(e>this.Ct)this.Ct=e,this.It();else{if(this.Ct>=e+1e4)return;this.Mt++,this.Mt>4398046511103&&(this.Ct++,this.It())}return he.fromFieldsV7(this.Ct,Math.trunc(this.Mt/Math.pow(2,30)),this.Mt&Math.pow(2,30)-1,this.Tt.nextUint32())}It(){this.Mt=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.Mt=0,this.Tt=new ve}};const pe=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};let ge;var ve=class{nextUint32(){var e;return this.Rt.length>this.Et||((null!==(e=ge)&&void 0!==e?e:ge="u">typeof window&&!G(window.crypto)&&crypto.getRandomValues?e=>crypto.getRandomValues(e):pe)(this.Rt),this.Et=0),this.Rt[this.Et++]}constructor(){this.Rt=new Uint32Array(8),this.Et=1/0}};let me;const ye=ae("[ConversationsPersistence]");var xe=class{constructor(e){this._posthog=e,this.t=null,this.Cl=function(e){var t;const i=null===(t=e.config)||void 0===t?void 0:t.token;return i?"ph_conv_"+i:null}(e),this.i()}getOrCreateWidgetSessionId(){var e;if(this.t)return this.t;let t=null===(e=this.o())||void 0===e?void 0:e.widgetSessionId;return t||(t=(me||(me=new fe)).generate().toString(),this.h({widgetSessionId:t})),this.t=t,t}setWidgetSessionId(e){this.t=e;const t=this.o()||{};this.h(ie(ie({},t),{},{widgetSessionId:e}))}clearWidgetSessionId(){this.t=null;const e=this.o();e&&(delete e.widgetSessionId,this.h(e))}saveTicketId(e){const t=this.o()||{};this.h(ie(ie({},t),{},{ticketId:e}))}loadTicketId(){var e;return(null===(e=this.o())||void 0===e?void 0:e.ticketId)||null}clearTicketId(){const e=this.o();e&&(delete e.ticketId,this.h(e))}saveWidgetState(e){const t=this.o()||{};this.h(ie(ie({},t),{},{widgetState:e}))}loadWidgetState(){var e;const t=null===(e=this.o())||void 0===e?void 0:e.widgetState;return"open"===t||"closed"===t?t:null}saveUserTraits(e){const t=this.o()||{};this.h(ie(ie({},t),{},{userTraits:e}))}loadUserTraits(){var e;const t=null===(e=this.o())||void 0===e?void 0:e.userTraits;return t&&(t.name||t.email)?t:null}clearUserTraits(){const e=this.o();e&&(delete e.userTraits,this.h(e))}clearAll(){if(this.t=null,this.Cl)try{var e;null==ce||null===(e=ce.localStorage)||void 0===e||e.removeItem(this.Cl)}catch(e){ye.error("Failed to remove localStorage item")}}o(){if(!this.Cl)return null;try{var e;const t=null==ce||null===(e=ce.localStorage)||void 0===e?void 0:e.getItem(this.Cl);return t?JSON.parse(t):null}catch(e){return null}}h(e){if(this.Cl)try{var t;null==ce||null===(t=ce.localStorage)||void 0===t||t.setItem(this.Cl,JSON.stringify(e))}catch(e){ye.error("Failed to write to localStorage",e)}}i(){var e;if(this.Cl&&!(null===(e=this.o())||void 0===e?void 0:e.widgetSessionId))try{var t;const e=this._posthog.persistence;if(!e||(null===(t=e.isDisabled)||void 0===t?void 0:t.call(e)))return;const i=e.get_property(ne);if(!i){const e=this.p();return void(e&&(this.h(e),ye.info("Migrated conversations data from raw localStorage")))}const n={widgetSessionId:i},r=e.get_property(re);r&&(n.ticketId=r);const o=e.get_property(oe);"open"!==o&&"closed"!==o||(n.widgetState=o);const s=e.get_property(se);s&&(n.userTraits=s),this.h(n),e.unregister(ne),e.unregister(re),e.unregister(oe),e.unregister(se),ye.info("Migrated conversations data to dedicated storage")}catch(e){ye.error("Migration from legacy persistence failed",e)}}p(){try{var e,t;const i=null===(e=this._posthog.config)||void 0===e?void 0:e.token;if(!i)return null;const n=null==ce||null===(t=ce.localStorage)||void 0===t?void 0:t.getItem(this._posthog.config.persistence_name?"ph_"+this._posthog.config.persistence_name:"ph_"+i+"_posthog");if(!n)return null;const r=JSON.parse(n),o=null==r?void 0:r[ne];if("string"!=typeof o||!o)return null;const s={widgetSessionId:o},l=null==r?void 0:r[re];l&&(s.ticketId=l);const a=null==r?void 0:r[oe];"open"!==a&&"closed"!==a||(s.widgetState=a);const c=null==r?void 0:r[se];return c&&(s.userTraits=c),s}catch(e){return null}}};function we(e){const t=e.replace(/^#/,""),i=3===t.length?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,n=parseInt(i.slice(0,2),16),r=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return Math.sqrt(n*n*.299+r*r*.587+o*o*.114)>127.5?"#020617":"white"}const be=(e,t="bottom_right")=>{const i=t.includes("left"),n=t.includes("top");return{widget:ie(ie(ie({position:"fixed"},n?{top:"20px"}:{bottom:"20px"}),i?{left:"20px"}:{right:"20px"}),{},{zIndex:2147483644,fontFamily:'-apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif'}),buttonContainer:{position:"relative"},button:{width:"50px",height:"50px",borderRadius:"50%",background:e,color:we(e),border:"none",cursor:"pointer",filter:"drop-shadow(rgba(9, 14, 21, 0.54) 0px 1px 6px) drop-shadow(rgba(9, 14, 21, 0.9) 0px 2px 32px)",display:"flex",alignItems:"center",justifyContent:"center",transition:"transform 0.2s ease-out"},unreadBadge:ie(ie(ie({position:"absolute"},n?{bottom:"-4px"}:{top:"-4px"}),i?{left:"-4px"}:{right:"-4px"}),{},{minWidth:"20px",height:"20px",borderRadius:"10px",background:"#ef4444",color:"white",fontSize:"11px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center",padding:"0 5px",boxShadow:"0 2px 4px rgba(0, 0, 0, 0.2)",border:"2px solid white",boxSizing:"border-box"}),window:ie(ie(ie({position:"absolute"},n?{top:0}:{bottom:0}),i?{left:0}:{right:0}),{},{background:"white",borderRadius:"10px",boxShadow:"0 10px 25px -3px rgba(0,0,0,0.12), 0 4px 12px -2px rgba(0,0,0,0.10)",display:"flex",flexDirection:"column",overflow:"hidden",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",border:"none"}),windowOpen:{width:"400px",maxWidth:"calc(100vw - 40px)",height:"600px",maxHeight:"calc(100vh - 100px)"},header:{background:e,color:we(e),padding:"8px 12px",display:"flex",justifyContent:"space-between",alignItems:"center",flexShrink:0},headerTitle:{fontWeight:500,fontSize:"14px"},headerActions:{display:"flex",gap:"4px",alignItems:"center"},headerLinkButton:{background:"transparent",border:"none",color:we(e),cursor:"pointer",padding:"6px 8px",fontSize:"12px",borderRadius:"4px",opacity:.9},headerButton:{background:"transparent",border:"none",color:we(e),cursor:"pointer",padding:"6px 8px",fontSize:"16px",lineHeight:1,borderRadius:"4px",transition:"background 0.2s ease-out",opacity:.9},messages:{flex:1,overflowY:"auto",padding:"14px",display:"flex",flexDirection:"column",gap:"8px",background:"white"},message:{display:"flex",flexDirection:"column",maxWidth:"85%",animation:"fadeIn 0.2s ease-out"},messageCustomer:{alignSelf:"flex-end",alignItems:"flex-end"},messageAgent:{alignSelf:"flex-start",alignItems:"flex-start"},messageAuthor:{fontSize:"10px",color:"#939393",marginBottom:"4px",fontWeight:500},messageContent:{padding:"8px 12px",borderRadius:"8px",fontSize:"12px",lineHeight:1.5,wordWrap:"break-word",whiteSpace:"pre-wrap"},messageContentCustomer:{background:e,color:we(e),borderBottomRightRadius:"2px"},messageContentAgent:{background:"white",color:"#020617",border:"1.5px solid #dcdcdc",borderBottomLeftRadius:"2px"},messageTime:{fontSize:"10px",color:"#939393",marginTop:"4px",opacity:.8},error:{padding:"10px 16px",background:"#fee2e2",color:"#991b1b",fontSize:"13px",borderTop:"1px solid #fecaca",borderBottom:"1px solid #fecaca",textAlign:"center",fontWeight:500},inputContainer:{padding:"8px 12px",background:"white",borderTop:"1px solid #dcdcdc",display:"flex",gap:"8px",alignItems:"center",flexShrink:0},resolvedBanner:{paddingTop:"12px",background:"white",borderTop:"1px solid #dcdcdc",display:"flex",flexDirection:"column",flexShrink:0},resolvedBannerText:{padding:"0 20px",fontSize:"13px",color:"#64748b",textAlign:"center",lineHeight:1.5},input:{flex:1,maxHeight:"120px",fontSize:"14px",resize:"vertical",fontFamily:"inherit",lineHeight:1.5,color:"#020617",background:"white",border:"none",outline:"none",transition:"border-color 0.2s ease-out, box-shadow 0.2s ease-out",display:"flex",alignItems:"center",fieldSizing:"content"},sendButton:{width:"33px",height:"33px",borderRadius:"10px",background:e,color:we(e),border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.2s ease-out",boxShadow:"0 2px 0 rgba(0, 0, 0, 0.045)",fontWeight:700,flexShrink:0},identificationForm:{flex:1,display:"flex",flexDirection:"column",padding:"24px",background:"#eeeded",overflowY:"auto"},formTitle:{fontSize:"18px",fontWeight:600,color:"#020617",marginBottom:"8px"},formDescription:{fontSize:"14px",color:"#64748b",marginBottom:"24px",lineHeight:1.5},recoverFooter:{padding:"10px 14px",borderTop:"1px solid #e5e7eb",fontSize:"12px",color:"#64748b",lineHeight:1.5,flexShrink:0,textAlign:"center"},recoverFooterLink:{background:"none",border:"none",padding:0,color:"#64748b",cursor:"pointer",fontSize:"12px",fontFamily:"inherit",textDecoration:"underline"},formField:{marginBottom:"16px"},formLabel:{display:"block",fontSize:"13px",fontWeight:500,color:"#020617",marginBottom:"6px"},formInput:{width:"100%",padding:"10px 12px",border:"1px solid #dcdcdc",borderRadius:"6px",fontSize:"14px",fontFamily:"inherit",color:"#020617",background:"white",transition:"border-color 0.2s ease-out, box-shadow 0.2s ease-out",boxSizing:"border-box"},formInputError:{borderColor:"#ef4444"},formError:{fontSize:"12px",color:"#ef4444",marginTop:"4px"},formSubmitButton:{width:"100%",padding:"12px 16px",borderRadius:"6px",background:e,color:we(e),border:"none",cursor:"pointer",fontSize:"14px",fontWeight:600,transition:"all 0.2s ease-out",marginTop:"8px"},formOptional:{fontSize:"12px",color:"#939393",fontWeight:400},restoreRequestSuccess:{marginTop:"12px",fontSize:"12px",color:"#166534",background:"#dcfce7",border:"1px solid #86efac",borderRadius:"6px",padding:"10px 12px",lineHeight:1.4},ticketListContainer:{flex:1,display:"flex",flexDirection:"column",background:"white",overflowY:"auto"},ticketList:{flex:1,overflowY:"auto"},ticketItem:{padding:"14px 16px",borderBottom:"1px solid #f1f1f1",cursor:"pointer",transition:"background 0.15s ease-out",background:"white",display:"flex",alignItems:"center",gap:"12px"},ticketItemUnread:{background:"#fafafa"},ticketItemContent:{display:"flex",flexDirection:"column",gap:"6px",flex:1,minWidth:0},ticketItemArrow:{color:"#939393",flexShrink:0,display:"flex",alignItems:"center"},ticketItemHeader:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:"8px"},ticketPreview:{fontSize:"13px",color:"#020617",lineHeight:1.4,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},ticketPreviewUnread:{fontSize:"13px",color:"#020617",lineHeight:1.4,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:600},ticketUnreadBadge:{minWidth:"18px",height:"18px",borderRadius:"9px",background:"#ef4444",color:"white",fontSize:"10px",fontWeight:600,display:"flex",alignItems:"center",justifyContent:"center",padding:"0 5px",flexShrink:0},ticketMeta:{display:"flex",alignItems:"center",gap:"8px"},ticketTime:{fontSize:"11px",color:"#939393"},ticketStatus:{fontSize:"10px",color:"#64748b",background:"#f1f5f9",padding:"2px 6px",borderRadius:"4px",textTransform:"uppercase",letterSpacing:"0.3px"},newConversationButton:{display:"flex",alignItems:"center",justifyContent:"center",margin:"12px 16px",padding:"10px 16px",borderRadius:"8px",background:e,color:we(e),border:"none",cursor:"pointer",fontSize:"13px",fontWeight:500,transition:"all 0.2s ease-out"},ticketListLoading:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"12px",color:"#64748b",fontSize:"13px"},loadingSpinner:{width:"24px",height:"24px",border:"2px solid #e2e8f0",borderTop:`2px solid ${e}`,borderRadius:"50%",animation:"spin 0.8s linear infinite"},ticketListEmpty:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"32px 24px",textAlign:"center"},emptyStateIcon:{color:"#cbd5e1",marginBottom:"16px"},emptyStateTitle:{fontSize:"16px",fontWeight:600,color:"#020617",marginBottom:"8px"},emptyStateDescription:{fontSize:"13px",color:"#64748b",lineHeight:1.5,marginBottom:"20px"},newConversationButtonLarge:{padding:"12px 24px",borderRadius:"8px",background:e,color:we(e),border:"none",cursor:"pointer",fontSize:"14px",fontWeight:600,transition:"all 0.2s ease-out"},fetchPreviousButton:{marginTop:"10px",background:"transparent",border:"none",color:e,cursor:"pointer",fontSize:"13px",textDecoration:"underline",opacity:1},backButton:{background:"transparent",border:"none",color:we(e),cursor:"pointer",padding:"6px 0px",marginRight:"4px",fontSize:"16px",lineHeight:1,borderRadius:"4px",transition:"background 0.2s ease-out",opacity:.9,display:"flex",alignItems:"center",justifyContent:"center"},headerWithBack:{display:"flex",alignItems:"center"}}};var ke=0;function _e(e,i,n,r,o,s){i||(i={});var l,a,c=i;if("ref"in c)for(a in c={},i)"ref"==a?l=i[a]:c[a]=i[a];var u={type:e,props:c,key:n,ref:l,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ke,__i:-1,__u:0,__source:o,__self:s};if("function"==typeof e&&(l=e.defaultProps))for(a in l)void 0===c[a]&&(c[a]=l[a]);return t.vnode&&t.vnode(u),u}const Se=({primaryColor:e,position:t="bottom_right",handleToggleOpen:i,unreadCount:n=0})=>{const r=be(e,t),o=n>99?"99+":n.toString();return _e("div",{style:r.widget,children:_e("div",{style:r.buttonContainer,children:[_e("button",{style:r.button,onClick:i,"aria-label":n>0?`Open chat (${n} unread)`:"Open chat",onMouseEnter(e){e.currentTarget.style.transform="scale(1.05)"},onMouseLeave(e){e.currentTarget.style.transform="scale(1)"},children:_e("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:_e("path",{d:"M12 2C6.48 2 2 6.48 2 12C2 13.93 2.6 15.71 3.64 17.18L2.5 21.5L7.04 20.42C8.46 21.28 10.17 21.75 12 21.75C17.52 21.75 22 17.27 22 11.75C22 6.23 17.52 2 12 2Z",fill:"currentColor"})})}),n>0&&_e("div",{style:r.unreadBadge,children:o})]})})},Ce=({primaryColor:e,handleClose:t})=>_e("button",{style:be(e).headerButton,onClick:t,"aria-label":"Close",onMouseEnter(e){e.currentTarget.style.background="rgba(255, 255, 255, 0.15)",e.currentTarget.style.opacity="1"},onMouseLeave(e){e.currentTarget.style.background="transparent",e.currentTarget.style.opacity="0.9"},children:"✕"});function Te(e){if(!e)return"";const t=new Date(e),i=(new Date).getTime()-t.getTime(),n=Math.floor(i/6e4),r=Math.floor(n/60),o=Math.floor(r/24);return 1>n?"Just now":60>n?`${n}m ago`:24>r?`${r}h ago`:1===o?"Yesterday":7>o?`${o}d ago`:t.toLocaleDateString()}function Ee(e,t){return e?e.length>t?e.substring(0,t-3)+"...":e:"No messages yet"}const Ie=({ticket:e,styles:t,onClick:i})=>{const n=(e.unread_count||0)>0,r="on_hold"===(o=e.status)?"On hold":o.charAt(0).toUpperCase()+o.slice(1);var o;const s=()=>{i(e.id)};return _e("div",{style:ie(ie({},t.ticketItem),n?t.ticketItemUnread:{}),onClick:s,onKeyDown(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),s())},role:"button",tabIndex:0,children:[_e("div",{style:t.ticketItemContent,children:[_e("div",{style:t.ticketItemHeader,children:[_e("span",{style:n?t.ticketPreviewUnread:t.ticketPreview,children:Ee((l=e.last_message,l?l.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/^>\s*/gm,"").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/~~([^~]+)~~/g,"$1").replace(/<[^>]*>/g,"").replace(/[<>]/g,"").replace(/\n{2,}/g,"\n").trim():""),60)}),n&&_e("span",{style:t.ticketUnreadBadge,children:e.unread_count})]}),_e("div",{style:t.ticketMeta,children:[_e("span",{style:t.ticketTime,children:Te(e.last_message_at||e.created_at)}),_e("span",{style:t.ticketStatus,children:r})]})]}),_e("div",{style:t.ticketItemArrow,children:_e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:_e("polyline",{points:"9 18 15 12 9 6"})})})]});var l},Re=({styles:e,onClick:t})=>_e("button",{type:"button",style:e.newConversationButton,onClick:t,onMouseEnter(e){e.currentTarget.style.opacity="0.9"},onMouseLeave(e){e.currentTarget.style.opacity="1"},children:[_e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginRight:"8px"},children:[_e("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),_e("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),"New conversation"]}),Me=({styles:e})=>_e("div",{style:e.ticketListLoading,children:[_e("div",{style:e.loadingSpinner}),_e("span",{children:"Loading conversations..."})]}),Le=({styles:e,onNewConversation:t,onOpenRestoreRequest:i})=>_e("div",{style:e.ticketListEmpty,children:[_e("div",{style:e.emptyStateIcon,children:_e("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:_e("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),_e("div",{style:e.emptyStateTitle,children:"No conversations yet"}),_e("div",{style:e.emptyStateDescription,children:"Start a new conversation to get help from our team."}),_e("button",{style:e.newConversationButtonLarge,onClick:t,onMouseEnter(e){e.currentTarget.style.opacity="0.9"},onMouseLeave(e){e.currentTarget.style.opacity="1"},children:"Start a conversation"}),_e("button",{style:e.fetchPreviousButton,onClick:i,onMouseEnter(e){e.currentTarget.style.opacity="0.8"},onMouseLeave(e){e.currentTarget.style.opacity="1"},children:"Fetch previous conversations"})]}),Fe=({tickets:e,isLoading:t,styles:i,onSelectTicket:n,onNewConversation:r,onOpenRestoreRequest:o})=>t&&0===e.length?_e(Me,{styles:i}):0===e.length?_e(Le,{styles:i,onNewConversation:r,onOpenRestoreRequest:o}):_e("div",{style:i.ticketListContainer,children:[_e("div",{style:i.ticketList,children:[...e].sort((e,t)=>{const i=new Date(e.last_message_at||e.created_at).getTime();return new Date(t.last_message_at||t.created_at).getTime()-i}).map(e=>_e(Ie,{ticket:e,styles:i,onClick:n},`${e.id}-${e.last_message_at||e.created_at}-${e.unread_count}`))}),_e(Re,{styles:i,onClick:r})]});function $e({config:e,styles:t,formName:i,formEmail:n,formEmailError:r,onNameChange:o,onEmailChange:s,onSubmit:l}){const a=e.identificationFormDescription||"Please provide your details so we can help you better.",c=!1!==e.collectName;return _e("div",{style:t.identificationForm,children:[_e("div",{style:t.formTitle,children:e.identificationFormTitle||"Before we start..."}),_e("div",{style:t.formDescription,children:a}),_e("form",{onSubmit:l,children:[c&&_e("div",{style:t.formField,children:[_e("label",{style:t.formLabel,children:["Name ",_e("span",{style:t.formOptional,children:"(optional)"})]}),_e("input",{type:"text",style:t.formInput,value:i,onInput:o,placeholder:"Your name",autoComplete:"name"})]}),_e("div",{style:t.formField,children:[_e("label",{style:t.formLabel,children:["Email ",!e.requireEmail&&_e("span",{style:t.formOptional,children:"(optional)"})]}),_e("input",{type:"email",style:ie(ie({},t.formInput),r?t.formInputError:{}),value:n,onInput:s,placeholder:"you@example.com",autoComplete:"email"}),r&&_e("div",{style:t.formError,children:r})]}),_e("button",{type:"submit",style:t.formSubmitButton,onMouseEnter(e){e.currentTarget.style.opacity="0.9"},onMouseLeave(e){e.currentTarget.style.opacity="1"},children:"Start Chat"})]})]})}function qe({styles:e,restoreEmail:t,restoreEmailError:i,restoreRequestLoading:n,restoreRequestSuccess:r,onEmailChange:o,onSubmit:s}){return _e("div",{style:e.identificationForm,children:[_e("div",{style:e.formTitle,children:"Restore conversations"}),_e("div",{style:e.formDescription,children:"Don't see your previous conversations? Maybe you use another browser or computer. Enter your email and we will send a secure restore link if matching conversations exist."}),_e("form",{onSubmit:s,children:[_e("div",{style:e.formField,children:[_e("label",{style:e.formLabel,children:"Email"}),_e("input",{type:"email",style:ie(ie({},e.formInput),i?e.formInputError:{}),value:t,onInput:o,placeholder:"you@example.com",autoComplete:"email",disabled:n}),i&&_e("div",{style:e.formError,children:i})]}),_e("button",{type:"submit",style:e.formSubmitButton,disabled:n,children:n?"Sending...":"Send restore link"})]}),r&&_e("div",{style:e.restoreRequestSuccess,children:"Check your email for a secure restore link. If an account is found, we sent it."})]})}const ze=({primaryColor:e,inputValue:t,isLoading:i,handleSendMessage:n})=>_e("button",{style:ie(ie({},be(e).sendButton),{},{opacity:!t.trim()||i?.6:1,cursor:!t.trim()||i?"not-allowed":"pointer"}),onClick:n,disabled:!t.trim()||i,"aria-label":"Send message",onMouseEnter(e){e.currentTarget.disabled||(e.currentTarget.style.transform="scale(1.02)",e.currentTarget.style.boxShadow="0 4px 8px rgba(0, 0, 0, 0.1)")},onMouseLeave(e){e.currentTarget.style.transform="scale(1)",e.currentTarget.style.boxShadow="0 2px 0 rgba(0, 0, 0, 0.045)"},children:_e("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:_e("path",{d:"M2 10L18 2L10 18L8 11L2 10Z",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round"})})});var We,De,Be,Oe,Pe=0,Ne=[],je=t,Ue=je.__b,Ae=je.__r,He=je.diffed,Ve=je.__c,Ye=je.unmount,Ge=je.__;function Xe(e,t){je.__h&&je.__h(De,e,Pe||t),Pe=0;var i=De.__H||(De.__H={__:[],__h:[]});return e>=i.__.length&&i.__.push({}),i.__[e]}function Ke(){for(var e;e=Ne.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Qe),t.__h.some(et),t.__h=[]}catch(i){t.__h=[],je.__e(i,e.__v)}}}je.__b=function(e){De=null,Ue&&Ue(e)},je.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ge&&Ge(e,t)},je.__r=function(e){Ae&&Ae(e),We=0;var t=(De=e.__c).__H;t&&(Be===De?(t.__h=[],De.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.length&&Ke(),We=0)),Be=De},je.diffed=function(e){He&&He(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Ne.push(t)&&Oe===je.requestAnimationFrame||((Oe=je.requestAnimationFrame)||Ze)(Ke)),t.__H.__.some(function(e){e.u&&(e.__H=e.u,e.u=void 0)})),Be=De=null},je.__c=function(e,t){t.some(function(e){try{e.__h.some(Qe),e.__h=e.__h.filter(function(e){return!e.__||et(e)})}catch(i){t.some(function(e){e.__h&&(e.__h=[])}),t=[],je.__e(i,e.__v)}}),Ve&&Ve(e,t)},je.unmount=function(e){Ye&&Ye(e);var t,i=e.__c;i&&i.__H&&(i.__H.__.some(function(e){try{Qe(e)}catch(e){t=e}}),i.__H=void 0,t&&je.__e(t,i.__v))};var Je="function"==typeof requestAnimationFrame;function Ze(e){var t,i=function(){clearTimeout(n),Je&&cancelAnimationFrame(t),setTimeout(e)},n=setTimeout(i,35);Je&&(t=requestAnimationFrame(i))}function Qe(e){var t=De,i=e.__c;"function"==typeof i&&(e.__c=void 0,i()),De=t}function et(e){var t=De;e.__c=e.__(),De=t}function tt(e){if(!e||"string"!=typeof e)return;const t=e.replace(/[\x00-\x1f\x7f\u200b-\u200d\ufeff]/g,"").trim();if(!t)return;const i=t.replace(/\s+/g,"").toLowerCase();if(i.startsWith("javascript:")||i.startsWith("vbscript:")||i.startsWith("data:")||i.startsWith("file:"))return;if(t.startsWith("//"))return;if(t.startsWith("/")||t.startsWith("./")||t.startsWith("../")||t.startsWith("#"))return t;const n=t.toLowerCase();return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("mailto:")||n.startsWith("tel:")?t:void 0}function it(e,t,i,n){if(!t||0===t.length)return _e("span",{children:e},n);let r=_e(b,{children:e});for(const e of t)switch(e.type){case"bold":r=_e("strong",{style:{fontWeight:700},children:r});break;case"italic":r=_e("em",{style:{fontStyle:"italic"},children:r});break;case"underline":r=_e("u",{style:{textDecoration:"underline"},children:r});break;case"strike":r=_e("s",{style:{textDecoration:"line-through"},children:r});break;case"code":r=_e("code",{style:i.code,children:r});break;case"link":{var o;const t=null===(o=e.attrs)||void 0===o?void 0:o.href,n="string"==typeof t?tt(t):void 0;n&&(r=_e("a",{href:n,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",style:i.link,children:r}));break}}return _e("span",{children:r},n)}function nt(e,t,i,n){var r;if(i>20)return null;if("text"===e.type&&!G(e.text))return it(e.text,e.marks,t,n);const o=(null===(r=e.content)||void 0===r?void 0:r.map((e,r)=>nt(e,t,i+1,`${n}-${r}`)))||[];switch(e.type){case"doc":return _e(b,{children:o});case"paragraph":return _e("p",{style:{margin:"0 0 8px 0"},children:o.length>0?o:_e("br",{})},n);case"hardBreak":return _e("br",{},n);case"codeBlock":{var s;const i=(null===(s=e.content)||void 0===s||null===(s=s[0])||void 0===s?void 0:s.text)||"";return _e("pre",{style:t.codeBlock,children:_e("code",{children:i})},n)}case"image":{var l,a;const i=null===(l=e.attrs)||void 0===l?void 0:l.src,r=null===(a=e.attrs)||void 0===a?void 0:a.alt,o="string"==typeof i?tt(i):void 0;return o?_e("img",{src:o,alt:"string"==typeof r?r:"",style:t.image,onError(e){e.target.style.display="none"}},n):null}case"bulletList":return _e("ul",{style:{margin:"8px 0",paddingLeft:"24px",listStyleType:"disc",listStylePosition:"outside"},children:o},n);case"orderedList":return _e("ol",{style:{margin:"8px 0",paddingLeft:"24px",listStyleType:"decimal",listStylePosition:"outside"},children:o},n);case"listItem":return _e("li",{style:{margin:"4px 0",listStyleType:"inherit"},children:o},n);case"blockquote":return _e("blockquote",{style:{margin:"8px 0",paddingLeft:"12px",borderLeft:"3px solid #e4e4e7",color:"#71717a"},children:o},n);case"heading":{var c;const t=null===(c=e.attrs)||void 0===c?void 0:c.level,i=K(t)?t:1;return _e(`h${Math.min(Math.max(i,1),6)}`,{style:{margin:"12px 0 8px 0"},children:o},n)}case"horizontalRule":return _e("hr",{style:{margin:"12px 0",border:"none",borderTop:"1px solid #e4e4e7"}},n);default:return o.length>0?_e("span",{children:o},n):null}}function rt(e,t){const i=/(!|\\)?\[([^\]\n]+)\]\(([^()\s]+)\)/g,n=[];let r,o=0;for(;r=i.exec(e);){n.push(e.slice(o,r.index));const[,s,l,a]=r,c=!s&&-1===l.indexOf("[")&&tt(a),u="\\"===s?r[0].slice(1):r[0];n.push(c?it(l,[{type:"link",attrs:{href:c}}],t,`${r.index}`):u),o=i.lastIndex}return n.push(e.slice(o)),_e(b,{children:n})}function ot({richContent:e,content:t,isCustomer:i,primaryColor:n,isGreeting:r}){const o=function(e,t){var i=Xe(We++,7);return function(e,t){return!e||e.length!==t.length||t.some(function(t,i){return t!==e[i]})}(i.__H,t)&&(i.__=e(),i.__H=t,i.__h=e),i.__}(()=>function(e,t){return{code:{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',fontSize:"0.9em",padding:"2px 4px",borderRadius:"3px",background:e?"rgba(255, 255, 255, 0.2)":"rgba(0, 0, 0, 0.06)"},codeBlock:{fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',fontSize:"0.85em",padding:"8px 10px",borderRadius:"6px",background:e?"rgba(255, 255, 255, 0.15)":"#f4f4f5",overflowX:"auto",whiteSpace:"pre-wrap",wordWrap:"break-word",wordBreak:"break-word",margin:"8px 0",display:"block",lineHeight:1.5,border:e?"none":"1px solid #e4e4e7"},link:{color:e?"white":t,textDecoration:"underline"},image:{maxWidth:"100%",borderRadius:"4px",marginTop:"4px",marginBottom:"4px",display:"block"}}}(i,n),[i,n]);if(e)try{if(function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"doc"===t.type&&(G(t.content)||Y(t.content))}(e)){const t=nt(e,o,0,"root");if(t)return t}}catch(e){}return function(e,t,i){if(!e)return _e(b,{});const n=e.split("\n");return _e(b,{children:n.map((e,r)=>_e(b,{children:[i?rt(e,t):e,n.length-1>r&&_e("br",{})]},r))})}(t,o,r)}function st({message:e,styles:t,primaryColor:i}){const n="customer"===e.author_type,r=ie(ie({},t.message),n?t.messageCustomer:t.messageAgent),o=ie(ie({},t.messageContent),n?t.messageContentCustomer:t.messageContentAgent);return _e("div",{style:r,children:[!n&&e.author_name&&_e("div",{style:t.messageAuthor,children:e.author_name}),_e("div",{style:o,children:_e(ot,{richContent:e.rich_content,content:e.content,isGreeting:"greeting"===e.id,isCustomer:n,primaryColor:i})}),_e("div",{style:t.messageTime,children:Te(e.created_at)})]},e.id)}function lt({styles:e,primaryColor:t,placeholderText:i,messages:n,inputValue:r,isLoading:o,error:s,isResolved:l,onInputChange:a,onKeyDown:c,onSendMessage:u,onStartNewConversation:d,messagesEndRef:h}){return _e(b,{children:[_e("div",{style:e.messages,children:[n.map(i=>_e(st,{message:i,styles:e,primaryColor:t},i.id)),_e("div",{ref:h})]}),s&&_e("div",{style:e.error,children:s}),_e("div",l?{style:e.resolvedBanner,children:[_e("div",{style:e.resolvedBannerText,children:"This conversation was resolved."}),_e(Re,{styles:e,onClick:d})]}:{style:e.inputContainer,children:[_e("textarea",{style:e.input,placeholder:i,value:r,onInput:a,onKeyDown:c,rows:1,disabled:o,autoFocus:!0}),_e(ze,{primaryColor:t,inputValue:r,isLoading:o,handleSendMessage:u})]})]})}const at="__posthogHandledConversationsError",ct=(e,t)=>{const i=new Error(t);return i[at]=!0,i.kind=e,i},ut=e=>!!e&&"object"==typeof e&&!0===e[at],dt=ae("[ConversationsWidget]");var ht=class extends k{constructor(e){var t,i;super(e),t=this,this.v=null,this.m=()=>{this.setState(e=>({state:"open"===e.state?"closed":"open"}))},this.k=()=>{this.setState({state:"closed"})},this.S=e=>{this.props.onSelectTicket&&this.props.onSelectTicket(e)},this.T=()=>{this.props.onNewConversation&&this.props.onNewConversation()},this.M=()=>{this.props.onBackToTickets&&this.props.onBackToTickets()},this.L=()=>{this.setState(e=>{var t;return{view:"restore_request",restoreEmail:e.restoreEmail||(null===(t=e.userTraits)||void 0===t?void 0:t.email)||"",restoreEmailError:null,restoreRequestSuccess:!1}}),this.props.onViewChange&&this.props.onViewChange("restore_request")},this.D=()=>{const e=this.state.showTicketList?"tickets":"messages";this.setState({view:e,restoreEmailError:null,restoreRequestSuccess:!1}),this.props.onViewChange&&this.props.onViewChange(e)},this.P=e=>{this.setState({inputValue:e.target.value})},this.lt=e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),this.gt())},this.ip=e=>{this.setState({formName:e.target.value})},this.gg=e=>{this.setState({formEmail:e.target.value,formEmailError:null})},this.mg=e=>{this.setState({restoreEmail:e.target.value,restoreEmailError:null,restoreRequestSuccess:!1})},this.yg=e=>{e.preventDefault();const{formEmail:t,formName:i}=this.state,{config:n,onIdentify:r}=this.props;if(n.requireEmail&&!t.trim())return void this.setState({formEmailError:"Email is required"});if(t.trim()&&!this.xg(t.trim()))return void this.setState({formEmailError:"Please enter a valid email address"});const o={};i.trim()&&(o.name=i.trim()),t.trim()&&(o.email=t.trim());const s=this.state.showTicketList?"tickets":"messages";this.setState({userTraits:o,view:s}),r&&r(o),this.props.onViewChange&&this.props.onViewChange(s)},this.wg=(i=Z(function*(e){if(e.preventDefault(),!t.props.onRequestRestoreLink)return;const i=t.state.restoreEmail.trim();if(i)if(t.xg(i)){t.setState({restoreRequestLoading:!0,restoreEmailError:null});try{yield t.props.onRequestRestoreLink(i),t.setState({restoreRequestLoading:!1,restoreRequestSuccess:!0})}catch(e){ut(e)||dt.error("Failed to request restore link",e),t.setState({restoreRequestLoading:!1,restoreEmailError:e instanceof Error?e.message:"Failed to request restore link"})}}else t.setState({restoreEmailError:"Please enter a valid email address"});else t.setState({restoreEmailError:"Email is required"})}),function(e){return i.apply(this,arguments)}),this.gt=Z(function*(){const{inputValue:e}=t.state,i=e.trim();if(!i)return;const n={id:`temp-${Date.now()}`,content:i,author_type:"customer",author_name:"You",created_at:(new Date).toISOString(),is_private:!1};t.setState({messages:[...t.state.messages,n],inputValue:"",isLoading:!0,error:null});try{yield t.props.onSendMessage(i),t.setState({isLoading:!1})}catch(e){ut(e)||dt.error("Failed to send message",e),t.setState(t=>({isLoading:!1,error:e instanceof Error?e.message:"Failed to send message",messages:t.messages.filter(e=>e.id!==n.id)}))}});const n=e.isIdentityMode||!1,r=e.initialUserTraits||null,o=this.bg(e.config,r,e.isUserIdentified,n)?"identification":e.initialView||"messages";this.state={state:e.initialState||"closed",view:o,messages:[],tickets:e.initialTickets||[],ticketsLoading:!1,inputValue:"",isLoading:!1,error:null,formName:(null==r?void 0:r.name)||"",formEmail:(null==r?void 0:r.email)||"",formEmailError:null,userTraits:r,unreadCount:0,showTicketList:e.showTicketList||!1,isCurrentTicketResolved:!1,isIdentityMode:n,restoreEmail:(null==r?void 0:r.email)||"",restoreEmailError:null,restoreRequestLoading:!1,restoreRequestSuccess:!1}}bg(e,t,i,n){return!(n||i||!e.requireEmail||(null==t?void 0:t.email))}componentDidMount(){"messages"===this.state.view&&0===this.state.messages.length&&this.props.config.greetingText&&this.kg()}componentDidUpdate(e,t){this.state.messages.length!==t.messages.length&&this._g(),this.state.state!==t.state&&this.props.onStateChange&&this.props.onStateChange(this.state.state),"open"===this.state.state&&"open"!==t.state&&this._g()}kg(){const e={id:"greeting",content:this.props.config.greetingText||"Hi! How can we help?",author_type:"AI",author_name:"Support",created_at:(new Date).toISOString(),is_private:!1};this.setState({messages:[e]})}_g(){this.v&&this.v.scrollIntoView({behavior:"smooth"})}xg(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}addMessages(e){this.setState(t=>{const i=new Set(t.messages.map(e=>e.id)),n=e.filter(e=>!i.has(e.id));return n.length>0?{messages:[...t.messages,...n]}:null})}show(){this.setState({state:"open"})}hide(){this.setState({state:"closed"})}getUserTraits(){return this.state.userTraits}setUserIdentified(){if("identification"===this.state.view){const e=this.state.showTicketList?"tickets":"messages";this.setState({view:e}),this.props.onViewChange&&this.props.onViewChange(e)}}setUnreadCount(e){this.setState({unreadCount:e})}updateTickets(e,t){this.setState({tickets:e,ticketsLoading:!1,showTicketList:t})}setCurrentTicketResolved(e){this.setState({isCurrentTicketResolved:e})}setView(e){this.setState({view:e}),this.props.onViewChange&&this.props.onViewChange(e)}getView(){return this.state.view}setTicketsLoading(e){this.setState({ticketsLoading:e})}setIdentityMode(e){let t;this.setState(i=>{const n={isIdentityMode:e};return"identification"!==i.view&&"restore_request"!==i.view&&"messages"!==i.view||(t=i.showTicketList?"tickets":"messages",n.view=t),n},()=>{t&&this.props.onViewChange&&this.props.onViewChange(t)})}clearMessages(e=!1){this.setState({messages:[]},()=>{e&&this.props.config.greetingText&&this.kg()})}Sg(e){return _e($e,{config:this.props.config,styles:e,formName:this.state.formName,formEmail:this.state.formEmail,formEmailError:this.state.formEmailError,onNameChange:this.ip,onEmailChange:this.gg,onSubmit:this.yg})}Cg(e){return _e("button",{style:e.backButton,onClick:"restore_request"===this.state.view?this.D:this.M,"aria-label":"Back to conversations",children:_e("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:_e("polyline",{points:"15 18 9 12 15 6"})})})}Tg(e){const{tickets:t,ticketsLoading:i}=this.state;return _e(Fe,{tickets:t,isLoading:i,styles:e,onSelectTicket:this.S,onNewConversation:this.T,onOpenRestoreRequest:this.L})}Eg(e,t,i){return _e(lt,{styles:e,primaryColor:t,placeholderText:i,messages:this.state.messages,inputValue:this.state.inputValue,isLoading:this.state.isLoading,error:this.state.error,isResolved:this.state.isCurrentTicketResolved,onInputChange:this.P,onKeyDown:this.lt,onSendMessage:this.gt,onStartNewConversation:this.T,messagesEndRef:e=>{this.v=e}})}Ig(e){return _e(qe,{styles:e,restoreEmail:this.state.restoreEmail,restoreEmailError:this.state.restoreEmailError,restoreRequestLoading:this.state.restoreRequestLoading,restoreRequestSuccess:this.state.restoreRequestSuccess,onEmailChange:this.mg,onSubmit:this.wg})}Rg(e){switch(e){case"tickets":return"Conversations";case"restore_request":return"Restore conversations";case"identification":case"messages":return"Support chat"}}Mg(e,t,i){switch(this.state.view){case"identification":return this.Sg(e);case"restore_request":return this.Ig(e);case"tickets":return this.Tg(e);case"messages":return this.Eg(e,t,i)}}render(){const{config:e}=this.props,{state:t,view:i}=this.state,n=e.color||"#5375ff",r=e.widgetPosition||"bottom_right",o=e.placeholderText||"Type your message...",s=be(n,r);if("closed"===t)return _e(Se,{primaryColor:n,position:r,handleToggleOpen:this.m,unreadCount:this.state.unreadCount});const l=ie(ie({},s.window),s.windowOpen),a="messages"===i&&this.state.showTicketList||"restore_request"===i,c=!this.state.isIdentityMode&&("tickets"===i||"messages"===i);return _e("div",{style:s.widget,children:_e("div",{style:l,children:[_e("div",{style:s.header,children:[_e("div",{style:a?s.headerWithBack:s.headerTitle,children:[a&&this.Cg(s),_e("span",{style:s.headerTitle,children:this.Rg(i)})]}),_e("div",{style:s.headerActions,children:_e(Ce,{primaryColor:n,handleClose:this.k})})]}),this.Mg(s,n,o),c&&_e("div",{style:s.recoverFooter,children:["Don't see your previous tickets?"," ",_e("button",{type:"button",style:s.recoverFooterLink,onClick:this.L,children:"Recover them here"})]})]})})}};const ft=()=>{try{return"u">typeof window&&!1!==window.navigator.onLine}catch(e){return!1}},pt=(e,t)=>e>=t&&ft(),gt=function(e,t="&"){let i,n;const r=[];return function(e,t){if(!(e=>G(e)||X(e))(e))if(Y(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(const i in e)H.call(e,i)&&t(e[i],i)}(e,function(e,t){G(e)||G(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),n=encodeURIComponent(t),r[r.length]=n+"="+i)}),r.join(t)},vt=ae("[ConversationsManager]"),mt="ph_conv_restore";function yt(){var e;if(!(null==ce||null===(e=ce.location)||void 0===e?void 0:e.search))return null;try{const e=new URLSearchParams(ce.location.search).get(mt);return(null==e?void 0:e.trim())||null}catch(e){return vt.warn("Failed to parse restore token from URL",e),null}}function xt(){var e;if((null==ce?void 0:ce.location)&&(null==ce||null===(e=ce.history)||void 0===e?void 0:e.replaceState))try{const e=new URL(ce.location.href);e.searchParams.delete(mt),ce.history.replaceState(ce.history.state,"",`${e.pathname}${e.search}${e.hash}`)}catch(e){vt.warn("Failed to clear restore token from URL",e)}}const wt=ae("[ConversationsManager]"),bt=(e,t,i,n=!1,r=!0)=>{var o,s,l;if(0===e.statusCode){const i=ct("network","Unable to reach the server. Please check your connection and try again.");return e.error?i.cause=e.error:r&&wt.warn(`Network error ${t}`),i}if(429===e.statusCode)return r&&(n?wt.warn(`Rate limited ${t}`):wt.error(i,{status:e.statusCode})),ct("rate_limit","Too many requests. Please wait before trying again.");const a=(null===(o=e.json)||void 0===o?void 0:o.error)||(null===(s=e.json)||void 0===s?void 0:s.detail)||(null===(l=e.json)||void 0===l?void 0:l.message)||i;return r&&wt.error(i,{status:e.statusCode}),ct("http",a)},kt=(e,t=!0)=>{const i="Invalid response from server";return t&&wt.error(i,{operation:e}),ct("invalid_response",i)},_t="ph-conversations-widget-container";let St=null;var Ct=class{constructor(e,t){var i,n,r,o,s=this;this._posthog=t,this.Lg=null,this.Fg=null,this.$g=null,this.qg=null,this.zg=!1,this.Wg=0,this.Dg=0,this.Bg=null,this.Og=null,this.Pg=!1,this.Ng=!1,this.jg=null,this.Ug=0,this.Ag="closed",this.Hg=!1,this.Vg=!1,this.Yg=null,this.Gg=0,this.Xg="messages",this.Kg=[],this.Jg=!1,this.Zg=0,this.rn=()=>{this.Zg=0,this.Dg=0,this.zg&&(this.Qg(),this.cv())},this.kv=e=>{this._c.saveUserTraits(e),this._posthog.capture("$conversations_user_identified",{hasName:!!e.name,hasEmail:!!e.email})},this.tm=(i=Z(function*(e){const t=yield s.requestRestoreLink(e);return s._posthog.capture("$conversations_restore_link_requested",{hasEmail:!!e}),t}),function(e){return i.apply(this,arguments)}),this.gt=(n=Z(function*(e){var t;const i=(null===(t=s.Lg)||void 0===t?void 0:t.getUserTraits())||void 0;yield s.sendMessage(e,i),setTimeout(()=>s.im(),1e3)}),function(e){return n.apply(this,arguments)}),this.nm=e=>{this.Ag=e,wt.info("Widget state changed",{state:e,view:this.Xg}),this._posthog.capture("$conversations_widget_state_changed",{state:e,view:this.Xg,ticketId:this.$g}),this._c.saveWidgetState(e),this.Hg&&(this.Qg(),this.cv()),"open"===e&&"messages"===this.Xg&&this.Ug>0&&this.$g&&this.rm()},this.im=Z(function*(){if(!s.Pg&&s.$g&&!pt(s.Zg,3)){s.Pg=!0;try{yield s.om()}finally{s.Pg=!1}}}),this.sm=Z(function*(){if(!s.Ng&&!pt(s.Zg,3)){s.Ng=!0;try{yield s.lm()}finally{s.Ng=!1}}}),this.hc=Z(function*(){"restore_request"!==s.Xg&&("messages"===s.Xg?yield s.im():yield s.sm())}),this.am=e=>{wt.info("View changed",{from:this.Xg,to:e}),this.Xg=e},this.S=(r=Z(function*(e){var t,i,n;s.um(e),s.Og=null,null===(t=s.Lg)||void 0===t||t.clearMessages(),s.Xg="messages",null===(i=s.Lg)||void 0===i||i.setView("messages"),null===(n=s.Lg)||void 0===n||n.setCurrentTicketResolved(s.dm()),s.cv(),yield s.om(),s.hm()&&s.Ug>0&&s.rm()}),function(e){return r.apply(this,arguments)}),this.T=()=>{var e,t,i;wt.info("New conversation requested"),this.$g=null,this._c.clearTicketId(),this.Og=null,this.Xg="messages",null===(e=this.Lg)||void 0===e||e.setView("messages"),null===(t=this.Lg)||void 0===t||t.setCurrentTicketResolved(!1),null===(i=this.Lg)||void 0===i||i.clearMessages(!0)},this.M=Z(function*(){var e,t;wt.info("Back to tickets requested"),s.Xg="tickets",null===(e=s.Lg)||void 0===e||e.setView("tickets"),null===(t=s.Lg)||void 0===t||t.setTicketsLoading(!0),yield s.lm(),s.cv(),s._posthog.capture("$conversations_back_to_tickets")}),this.fm=(o=Z(function*(e){try{yield s.hc()}catch(e){wt.error("Polling iteration failed",e)}e===s.Wg&&s.pm(e)}),function(e){return o.apply(this,arguments)}),this.Ar=e,this._c=new xe(t),this.gm=this._c.getOrCreateWidgetSessionId(),this.vm=!0===e.widgetEnabled,this.ym=function(e){var t;if(!e||0===e.length)return!0;const i=null==ce||null===(t=ce.location)||void 0===t?void 0:t.hostname;return!i||e.some(e=>{const t=function(e){let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0].split("?")[0].split(":")[0],t||null}(e);if(!t)return!1;if(t.startsWith("*.")){const e=t.slice(2);return i.endsWith(`.${e}`)||i===e}return i===t})}(e.domains),ce&&function(e,t,i){const{capture:n=!1,passive:r=!0}={};null==e||e.addEventListener("online",i,{capture:n,passive:r})}(ce,0,this.rn),this.xm()}wm(){var e;const t=null==ce||null===(e=ce.location)||void 0===e?void 0:e.href;return this._posthog.config.disable_capture_url_hashes?(i=t)?i.split("#")[0]:i:t;var i}sendMessage(e,t,i){var n=this;return Z(function*(){const r=i?null:n.$g,o=!r,s=n.Ar.token;return new Promise((l,a)=>{const c=n.bm(),u=(null==t?void 0:t.name)||c.name||null,d=(null==t?void 0:t.email)||c.email||null,h=n.km(),f={message:e.trim(),traits:{name:u,email:d},ticket_id:r};h?(Object.assign(f,h),f.distinct_id=h.identity_distinct_id):(f.widget_session_id=n.gm,f.distinct_id=n._posthog.get_distinct_id());try{const e=n._posthog.get_session_id();e&&(f.session_id=e);const t=n._posthog.get_session_replay_url({withTimestamp:!0,timestampLookBack:30}),i=o?n.wm():void 0;(t||i)&&(f.session_context={session_replay_url:t||void 0,current_url:i||void 0})}catch(e){wt.warn("Failed to capture session context",e)}n._posthog._send_request({url:n._posthog.requestRouter.endpointFor("api","/api/conversations/v1/widget/message"),method:"POST",data:f,headers:{"X-Conversations-Token":s},callback(t){if(200!==t.statusCode&&201!==t.statusCode)return void a(bt(t,"sending message","Failed to send message",!0));if(!t.json)return void a(kt("sending message"));const r=t.json;o&&r.ticket_id&&(n.$g=r.ticket_id,n._c.saveTicketId(r.ticket_id),wt.info("New ticket created",{ticketId:r.ticket_id,forced:!0===i})),n._posthog.capture("$conversations_message_sent",{ticketId:r.ticket_id,isNewTicket:o,messageLength:e.length}),n.Og=r.created_at,n.Hg&&n.cv(),l(r)}})})})()}um(e){e&&e!==this.$g&&(this.$g=e,this._c.saveTicketId(e),this.Og=null)}getMessages(e,t){var i=this;return Z(function*(){const n=e||i.$g;if(!n)throw new Error("No ticket ID provided and no active conversation");i.um(e);const r=i.Ar.token;return new Promise((e,o)=>{const s=i.km(),l={limit:"50"};s?Object.assign(l,s):l.widget_session_id=i.gm,t&&(l.after=t),i._posthog._send_request({url:i._posthog.requestRouter.endpointFor("api",`/api/conversations/v1/widget/messages/${n}?${gt(l)}`),method:"GET",timestampMode:"query",headers:{"X-Conversations-Token":r},callback(t){i._m(t.statusCode),i.Sm(t.statusCode),200===t.statusCode?t.json?e(t.json):o(kt("fetching messages")):o(bt(t,"fetching messages","Failed to fetch messages"))}})})})()}markAsRead(e){var t=this;return Z(function*(){const i=e||t.$g;if(!i)throw new Error("No ticket ID provided and no active conversation");t.um(e);const n=t.Ar.token;return wt.info("Marking messages as read",{ticketId:i}),new Promise((e,r)=>{const o=t.km()||{widget_session_id:t.gm};t._posthog._send_request({url:t._posthog.requestRouter.endpointFor("api",`/api/conversations/v1/widget/messages/${i}/read`),method:"POST",data:o,headers:{"X-Conversations-Token":n},callback(t){200===t.statusCode?t.json?e(t.json):r(kt("marking messages as read")):r(bt(t,"marking messages as read","Failed to mark messages as read"))}})})})()}xm(){if(!de||!ce)return void wt.info("Conversations not available: Document or window not available");if(this.km())return this._c.clearTicketId(),void this.ug();const e=yt();if(e&&!this.Vg){this.Vg=!0,xt(),setTimeout(xt,0);const t=this.Gg;return void this.Cm(e).catch(e=>{ut(e)||wt.warn("Failed to restore conversations from URL token",e)}).finally(()=>{xt(),t===this.Gg&&this.ug()})}this.ug()}ug(){this.Vg=!0,this.$g=this._c.loadTicketId(),wt.info("Loaded ticket ID from storage",{ticketId:this.$g}),this._posthog.capture("$conversations_loaded",{hasExistingTicket:!!this.$g,widgetEnabled:this.vm,domainAllowed:this.ym}),this.vm&&this.ym?this.Tm():wt.info("Widget not rendered",{widgetEnabled:this.vm,domainAllowed:this.ym}),this.Em()}Cm(e){var t=this;return Z(function*(){try{return yield t.Im(e)}catch(i){return ut(i)&&"network"===i.kind&&"cause"in i||wt.warn("Restore token exchange failed, retrying once",i),yield t.Im(e)}})()}Im(e){var t=this;return Z(function*(){var i;const n=t.Ar.token,r=t.Gg,o={restore_token:e,widget_session_id:t.gm,distinct_id:t._posthog.get_distinct_id(),current_url:t.wm()},s=yield new Promise((e,i)=>{t._posthog._send_request({url:t._posthog.requestRouter.endpointFor("api","/api/conversations/v1/widget/restore"),method:"POST",data:o,headers:{"X-Conversations-Token":n},callback(t){200===t.statusCode?t.json?e(t.json):i(kt("restoring conversations",!1)):i(bt(t,"restoring conversations","Failed to restore conversations",!0,!1))}})});return"success"!==s.status?(wt.info("Restore token was not accepted",{status:s.status,code:s.code}),s):r!==t.Gg?(wt.info("Conversations destroyed during restore, discarding the result"),s):(t.Og=null,t.Ug=0,s.widget_session_id&&(t.gm=s.widget_session_id,t._c.setWidgetSessionId(s.widget_session_id)),(null===(i=s.migrated_ticket_ids)||void 0===i?void 0:i.length)?(t.$g=s.migrated_ticket_ids[0],t._c.saveTicketId(t.$g),t.Hg&&t.cv(),t.im(),t.sm()):(t.$g=null,t._c.clearTicketId()),s)})()}Tm(){return this.Hg?Promise.resolve():(this.Yg||(this.Yg=this.Rm()),this.Yg)}Rm(){var e=this;return Z(function*(){const t="open"===e._c.loadWidgetState()?"open":"closed";e.Ag=t;const i=e.Mm(),n=e.Gg,{view:r,tickets:o}=yield e.Lm();n===e.Gg?(e.Xg=r,e.Fm(t,i,r,o),e.Hg=!0,e._posthog.capture("$conversations_widget_loaded",{hasExistingTicket:!!e.$g,initialState:t,initialView:r,ticketCount:o.length,hasUserTraits:!!i}),e.cv(),e.$m()):wt.info("Conversations destroyed during widget initialization, not rendering")})()}bm(){var e;const t=(null===(e=this._posthog.persistence)||void 0===e?void 0:e.props)||{},i=this._posthog.get_property("$stored_person_properties")||{};return{name:i.$name||i.name||t.$name||t.name||void 0,email:i.$email||i.email||t.$email||t.email||void 0}}Mm(){const{name:e,email:t}=this.bm();if(e||t)return{name:e||void 0,email:t||void 0};const i=this._c.loadUserTraits();return i&&(i.name||i.email)?i:null}rm(){var e=this;return Z(function*(){if(e.$g)try{var t;const i=yield e.markAsRead(e.$g);e.Ug=i.unread_count,null===(t=e.Lg)||void 0===t||t.setUnreadCount(0),wt.info("Messages marked as read",{unreadCount:i.unread_count})}catch(e){ut(e)||wt.error("Failed to mark messages as read",e)}})()}om(){var e=this;return Z(function*(){if(e.$g)try{const n=e._posthog.config.identity_distinct_id,r=e.$g,o=yield e.getMessages(e.$g,e.Og||void 0);if(e._posthog.config.identity_distinct_id!==n||e.$g!==r)return;var t,i;K(o.unread_count)&&(e.Ug=o.unread_count,null===(t=e.Lg)||void 0===t||t.setUnreadCount(o.unread_count),o.unread_count>0&&e.hm()&&e.rm()),o.ticket_status&&e.qm(r,o.ticket_status),o.messages.length>0&&(null===(i=e.Lg)||void 0===i||i.addMessages(o.messages),e.Og=o.messages[o.messages.length-1].created_at)}catch(e){ut(e)||wt.error("Failed to load messages",e)}})()}hm(){return"open"===this.Ag}lm(){var e=this;return Z(function*(){try{var t,i,n;const r=yield e.getTickets();e.Kg=r.results,e.Jg=e.zm(r.results),null===(t=e.Lg)||void 0===t||t.updateTickets(r.results,e.Jg);const o=r.results.reduce((e,t)=>e+(t.unread_count||0),0);e.Ug=o,null===(i=e.Lg)||void 0===i||i.setUnreadCount(o),null===(n=e.Lg)||void 0===n||n.setCurrentTicketResolved(e.dm()),wt.info("Tickets loaded",{count:r.results.length,totalUnread:o})}catch(e){ut(e)||wt.error("Failed to load tickets",e)}})()}zm(e){return e.length>=1}dm(){if(!this.$g)return!1;const e=this.Kg.find(e=>e.id===this.$g);return"resolved"===(null==e?void 0:e.status)}qm(e,t){var i,n;const r=this.Kg.findIndex(t=>t.id===e);-1!==r&&this.Kg[r].status!==t&&(this.Kg=[...this.Kg.slice(0,r),ie(ie({},this.Kg[r]),{},{status:t}),...this.Kg.slice(r+1)],this.Jg=this.zm(this.Kg),null===(i=this.Lg)||void 0===i||i.updateTickets(this.Kg,this.Jg),null===(n=this.Lg)||void 0===n||n.setCurrentTicketResolved(this.dm()))}_m(e){this.Zg=((e,t)=>{if(0===e){if(ft()){const e=t+1;return 3===e&&wt.warn("Conversations polling requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped polling conversations; will try again when connectivity changes."),e}return t}return 0})(e,this.Zg)}Sm(e){429===e?this.Dg+=1:e>=200&&300>e&&(this.Dg=0)}Lm(){var e=this;return Z(function*(){try{const t=e._posthog.config.identity_distinct_id,i=e.Gg,n=yield e.getTickets();return e._posthog.config.identity_distinct_id!==t||i!==e.Gg?{view:"messages",tickets:[]}:{view:e.Wm(n.results),tickets:n.results}}catch(e){return ut(e)||wt.error("Failed to determine initial view",e),{view:"messages",tickets:[]}}})()}Wm(e){this.Kg=e,this.Jg=this.zm(e);const t=e.reduce((e,t)=>e+(t.unread_count||0),0);return this.Ug=t,2>e.length?1===e.length&&"resolved"===e[0].status?(this.$g=null,this._c.clearTicketId(),"tickets"):(1===e.length&&(this.$g=e[0].id,this._c.saveTicketId(e[0].id)),"messages"):(this.$g=null,"tickets")}cv(){if(this.zg)return;this.zg=!0;const e=++this.Wg;wt.info("Started polling",{view:this.Xg}),this.fm(e)}pm(e){if(this.zg&&e===this.Wg)return this.Dm()?void(this.qg=null==ce?void 0:ce.setTimeout(()=>{this.fm(e)},this.Bm())):(this.qg=null,this.zg=!1,void wt.info("Nothing to poll, pausing until next user action"))}Bm(){return this.Dg>0?Math.min(5e3*Math.pow(2,this.Dg-1),6e4):this.hm()?5e3:15e3}Dm(){return"restore_request"!==this.Xg&&("messages"===this.Xg?!!this.$g:this.Kg.length>0)}Qg(){null!=this.qg&&(null==ce||ce.clearTimeout(this.qg),this.qg=null,wt.info("Stopped polling for messages")),this.zg=!1,this.Wg++}Om(){this.Hg&&this.Fg&&(this.Fg.isConnected||(null==de?void 0:de.body)&&(de.body.appendChild(this.Fg),wt.info("Re-attached widget after it was detached from the DOM")))}$m(){this.Bg||(this.Bg=null==ce?void 0:ce.setInterval(()=>{this.Om()},1e3))}Pm(){this.Bg&&(null==ce||ce.clearInterval(this.Bg),this.Bg=null)}Em(){this.jg=this._posthog.on("eventCaptured",e=>{var t;"$identify"===e.event&&(null===(t=this.Lg)||void 0===t||t.setUserIdentified())})}show(){this.ym?this.Hg||this.Tm():wt.warn("Cannot show widget: current domain is not allowed")}hide(){this.Qg(),this.Pm(),this.Fg&&(U(null,this.Fg),this.Fg.remove(),this.Fg=null),this.Lg=null,this.Hg=!1,this.Yg=null,this.Og=null}isVisible(){return this.Hg}getTickets(e){var t=this;return Z(function*(){var i,n;const r=t.Ar.token,o=t.km(),s={limit:String(null!==(i=null==e?void 0:e.limit)&&void 0!==i?i:20),offset:String(null!==(n=null==e?void 0:e.offset)&&void 0!==n?n:0)};return o?Object.assign(s,o):s.widget_session_id=t.gm,(null==e?void 0:e.status)&&(s.status=e.status),new Promise((e,i)=>{t._posthog._send_request({url:t._posthog.requestRouter.endpointFor("api",`/api/conversations/v1/widget/tickets?${gt(s)}`),method:"GET",timestampMode:"query",headers:{"X-Conversations-Token":r},callback(n){t._m(n.statusCode),t.Sm(n.statusCode),200===n.statusCode?n.json?e(n.json):i(kt("fetching tickets")):i(bt(n,"fetching tickets","Failed to fetch tickets"))}})})})()}requestRestoreLink(e){var t=this;return Z(function*(){if(t.km())return{ok:!0};const i=e.trim().toLowerCase();if(!i)throw new Error("Email is required");const n=t.Ar.token,r={email:i,request_url:t.wm()||""};return new Promise((e,i)=>{t._posthog._send_request({url:t._posthog.requestRouter.endpointFor("api","/api/conversations/v1/widget/restore/request"),method:"POST",data:r,headers:{"X-Conversations-Token":n},callback(t){200===t.statusCode?e({ok:!0}):i(bt(t,"requesting restore link","Failed to request restore link"))}})})})()}restoreFromToken(e){var t=this;return Z(function*(){if(t.km())return{status:"success"};const i=e.trim();if(!i)throw new Error("Restore token is required");try{return yield t.Cm(i)}finally{xt()}})()}restoreFromUrlToken(){var e=this;return Z(function*(){if(e.km())return null;const t=yt();if(!t)return null;try{return yield e.restoreFromToken(t)}finally{xt()}})()}getCurrentTicketId(){return this.$g}getWidgetSessionId(){return this.gm}km(){const e=this._posthog.config.identity_distinct_id,t=this._posthog.config.identity_hash;if(!e||!t)return null;const i={identity_distinct_id:e,identity_hash:t},n=this._posthog.config.identity_claims;return n&&Object.entries(n).forEach(([e,t])=>{const n="distinct_id"===e||"hash"===e||e.startsWith("hash_");e&&!n&&t&&"string"==typeof t.value&&t.value.length>0&&"string"==typeof t.hash&&t.hash.length>0&&(i[`identity_${e}`]=t.value,i[`identity_hash_${e}`]=t.hash)}),i}setIdentity(){var e;this.Nm(),null===(e=this.Lg)||void 0===e||e.setIdentityMode(!0),this.jm()}clearIdentity(){var e;this.Nm(),null===(e=this.Lg)||void 0===e||e.setIdentityMode(!1),this.jm()}Nm(){var e;this.$g=null,this._c.clearTicketId(),this.Og=null,null===(e=this.Lg)||void 0===e||e.clearMessages(!0)}jm(){var e=this;return Z(function*(){try{var t,i,n,r;const o=e._posthog.config.identity_distinct_id,s=yield e.getTickets();if(e._posthog.config.identity_distinct_id!==o)return;const l=e.Wm(s.results);null===(t=e.Lg)||void 0===t||t.updateTickets(s.results,e.Jg),null===(i=e.Lg)||void 0===i||i.setUnreadCount(e.Ug),null===(n=e.Lg)||void 0===n||n.setCurrentTicketResolved(e.dm()),e.Xg=l,null===(r=e.Lg)||void 0===r||r.setView(l),e.Hg&&e.cv(),"messages"===l&&e.$g&&e.om()}catch(e){ut(e)||wt.error("Failed to load tickets after identity change",e)}})()}destroy(){this.Gg++,this.Qg(),this.Pm(),ce&&ce.removeEventListener("online",this.rn),this.jg&&(this.jg(),this.jg=null),this.Fg&&(U(null,this.Fg),this.Fg.remove(),this.Fg=null),this.Lg=null,St===this&&(St=null),wt.info("Widget destroyed")}reset(){this._c.clearAll(),this.$g=null,this.Og=null,this.Ug=0,this.Zg=0,this.destroy(),wt.info("Conversations reset")}Fm(e,t,i="messages",n=[]){if(!de)return void wt.info("Conversations widget not rendered: Document not available");let r=de.getElementById(_t);if(!r){if(!de.body)return void wt.info("Conversations widget not rendered: Document body not available yet");r=de.createElement("div"),r.id=_t,de.body.appendChild(r)}this.Fg=r,U(_e(ht,{ref:e=>{this.Lg=e},config:this.Ar,initialState:e,initialUserTraits:t,isUserIdentified:this._posthog._isIdentified(),isIdentityMode:!X(this.km()),initialView:i,initialTickets:n,showTicketList:this.Jg,onSendMessage:this.gt,onStateChange:this.nm,onIdentify:this.kv,onRequestRestoreLink:this.tm,onSelectTicket:this.S,onNewConversation:this.T,onBackToTickets:this.M,onViewChange:this.am}),r)}};const Tt="undefined"!=typeof globalThis?globalThis:ce;Tt&&"undefined"==typeof self&&(Tt.self=Tt),Tt&&"undefined"==typeof File&&(Tt.File=function(){});const Et=null!=ce?ce:{};Et.__PosthogExtensions__=Et.__PosthogExtensions__||{},Et.__PosthogExtensions__.initConversations=function(e,t){return St||(St=new Ct(e,t),St)}}();
//# sourceMappingURL=conversations.js.map