tybotflow-widget 0.9.4 → 0.9.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.es.js
CHANGED
|
@@ -64170,7 +64170,7 @@ Object.assign(Ll, {
|
|
|
64170
64170
|
io: Ll,
|
|
64171
64171
|
connect: Ll
|
|
64172
64172
|
});
|
|
64173
|
-
const nQ = "https://api.tybotflow.com/api/v1", kuA = "https://api.tybotflow.com/api/v1/chatbots-config", Pv = "https://migration-meta.tybotflow.com/", TV = Pv + "
|
|
64173
|
+
const nQ = "https://api.tybotflow.com/api/v1", kuA = "https://api.tybotflow.com/api/v1/chatbots-config", Pv = "https://migration-meta.tybotflow.com/", TV = Pv + "ucc/v", aQ = Ll(Pv, {
|
|
64174
64174
|
transports: ["websocket", "polling"],
|
|
64175
64175
|
reconnection: !0,
|
|
64176
64176
|
reconnectionAttempts: 3,
|
package/dist/index.umd.js
CHANGED
|
@@ -632,7 +632,7 @@ end`};A.events.push(["putFont",function(o){(function(B){var I=B.font,r=B.out,a=B
|
|
|
632
632
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
633
633
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
634
634
|
PERFORMANCE OF THIS SOFTWARE.
|
|
635
|
-
***************************************************************************** */function f1(e,A){const[i,t]=vA.useState(null),g=vA.useMemo(()=>Object.entries(A).flat(),[A]);return vA.useEffect(()=>{if(!e?.current)return;const o=dp.create(Object.assign(Object.assign({},A),{container:e.current}));return t(o),()=>{o.destroy()}},[e,...g]),i}const j1=/^on([A-Z])/,ccA=e=>j1.test(e);function hcA(e,A){const i=vA.useMemo(()=>Object.entries(A).flat(),[A]);vA.useEffect(()=>{if(!e)return;const t=Object.entries(A);if(!t.length)return;const g=t.map(([o,B])=>{const I=o.replace(j1,(r,a)=>a.toLowerCase());return e.on(I,(...r)=>B(e,...r))});return()=>{g.forEach(o=>o())}},[e,...i])}vA.memo(e=>{const A=vA.useRef(null),[i,t]=function(g){return vA.useMemo(()=>{const o=Object.assign({},g),B=Object.assign({},g);for(const I in o)ccA(I)?delete o[I]:delete B[I];return[o,B]},[g])}(e);return hcA(f1(A,i),t),U.jsx("div",{ref:A})});function lcA(e){var{container:A}=e;const i=f1(A,function(g,o){var B={};for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&o.indexOf(I)<0&&(B[I]=g[I]);if(g!=null&&typeof Object.getOwnPropertySymbols=="function"){var r=0;for(I=Object.getOwnPropertySymbols(g);r<I.length;r++)o.indexOf(I[r])<0&&Object.prototype.propertyIsEnumerable.call(g,I[r])&&(B[I[r]]=g[I[r]])}return B}(e,["container"])),t=function(g){const[o,B]=vA.useState(!1),[I,r]=vA.useState(!1),[a,C]=vA.useState(!1),[s,c]=vA.useState(0);return vA.useEffect(()=>{if(!g)return;const w=[g.on("load",()=>{B(!1),r(!1),c(0)}),g.on("ready",()=>{B(!0),r(!1),C(!1),c(0)}),g.on("finish",()=>{C(!0)}),g.on("play",()=>{r(!0)}),g.on("pause",()=>{r(!1)}),g.on("timeupdate",()=>{c(g.getCurrentTime())}),g.on("destroy",()=>{B(!1),r(!1)})];return()=>{w.forEach(l=>l())}},[g]),vA.useMemo(()=>({isReady:o,isPlaying:I,hasFinished:a,currentTime:s}),[I,a,s,o])}(i);return vA.useMemo(()=>Object.assign(Object.assign({},t),{wavesurfer:i}),[t,i])}const L1=({src:e,mainColor:A,secondaryColor:i,controlsColor:t})=>{const g=vA.useRef(null),[o,B]=vA.useState(1),{wavesurfer:I,isPlaying:r}=lcA({container:g,waveColor:A,progressColor:i,barWidth:2,height:50,url:e}),a=()=>{I&&I.playPause()},C=()=>{const w=o===0?1:0;B(w),I?.setVolume(w)},s=()=>{I?.skip(-.096)},c=()=>{I?.skip(.096)};return U.jsxs("div",{className:"flex w-full flex-col items-center rounded-xl pt-1",children:[U.jsx("div",{ref:g,className:"w-full px-2"}),U.jsxs("div",{className:"flex w-full items-center justify-between",children:[U.jsx("div",{className:"relative flex items-center",children:U.jsx("button",{className:"transition-colors",style:{color:t},onClick:C,"aria-label":"Toggle volume",children:o===0?U.jsx(qiA,{size:20}):U.jsx(ziA,{size:20})})}),U.jsxs("div",{className:"-ml-9 flex flex-1 cursor-auto justify-center gap-2 rounded-full py-2 text-white",children:[U.jsx("button",{onClick:s,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":"Step back",children:U.jsx(TiA,{})}),U.jsx("button",{onClick:a,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":r?"Pause":"Play",children:r?U.jsx(OiA,{}):U.jsx(JiA,{})}),U.jsx("button",{onClick:c,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":"Step forward",children:U.jsx(biA,{})})]})]})]})},McA=({attachment:e,formatFileSize:A,mainColor:i,secondaryColor:t,controlsColor:g})=>{const{type:o,url:B,name:I,size:r}=e;switch(o){case"image":return U.jsxs("div",{className:"relative group",children:[U.jsx("img",{src:B,alt:I,className:"max-w-xs max-h-48 size-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(B,"_blank")}),U.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-60 text-white text-xs px-2 py-1 rounded",children:A(r)})]});case"video":return U.jsxs("div",{className:"max-w-xs",children:[U.jsx("video",{src:B,controls:!0,className:"w-full max-h-48 rounded-lg",preload:"metadata",onError:()=>{console.error("Video failed to load:",B)},children:"Your browser does not support the video tag."}),U.jsxs("div",{className:"flex text-xs text-white mt-1 w-full overflow-hidden whitespace-nowrap text-ellipsis",children:[U.jsx("span",{className:"block w-full overflow-hidden whitespace-nowrap text-ellipsis",title:I,children:I}),U.jsxs("span",{className:"ml-2",children:["• ",A(r)]})]})]});case"audio":return U.jsxs("div",{className:"bg-gray-800 bg-opacity-70 p-3 rounded-lg flex-1 w-full",children:[U.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[U.jsx(zu,{className:"w-4 h-4",style:{color:i}}),U.jsx("span",{className:"text-sm font-medium truncate text-white",title:I,children:I})]}),U.jsx(L1,{src:B,mainColor:i,secondaryColor:t,controlsColor:g}),U.jsx("p",{className:"text-xs text-gray-400 mt-1",children:A(r)})]});case"document":return U.jsx("div",{className:"bg-gray-800 bg-opacity-50 p-3 rounded-lg max-w-xs cursor-pointer hover:bg-opacity-70 transition-colors",onClick:()=>window.open(B,"_blank"),children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 bg-purple-600 rounded-lg flex items-center justify-center",children:U.jsx(Bn,{className:"w-5 h-5 text-white"})}),U.jsxs("div",{className:"flex-1 min-w-0",children:[U.jsx("p",{className:"text-sm font-medium truncate text-white",children:I}),U.jsx("p",{className:"text-xs text-gray-400",children:A(r)})]})]})});default:return null}},DcA=vA.memo(({attachment:e,onRemove:A})=>U.jsxs("div",{className:"relative group w-24 h-24 rounded-xl overflow-hidden bg-gray-900 shadow-md border border-gray-700",children:[e.type==="image"&&e.url?U.jsx("img",{src:e.url,alt:e.name,className:"w-full h-full object-cover"}):U.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center text-gray-300 px-1 text-center text-xs",children:[e.type==="video"&&U.jsx(Rx,{className:"w-5 h-5 mb-1 text-red-400"}),e.type==="audio"&&U.jsx(zu,{className:"w-5 h-5 mb-1 text-green-400"}),e.type==="document"&&U.jsx(hx,{className:"w-5 h-5 mb-1 text-yellow-400"}),U.jsx("span",{className:"w-full truncate",title:e.name,children:e.name})]}),U.jsx("button",{onClick:A,className:"absolute top-1 right-1 w-5 h-5 bg-black bg-opacity-50 rounded-full text-white flex items-center justify-center hover:bg-opacity-80",title:"Remove",children:U.jsx(nr,{className:"w-3 h-3"})})]})),HI=Object.create(null);HI.open="0",HI.close="1",HI.ping="2",HI.pong="3",HI.message="4",HI.upgrade="5",HI.noop="6";const rl=Object.create(null);Object.keys(HI).forEach(e=>{rl[HI[e]]=e});const Gp={type:"error",data:"parser error"},T1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",b1=typeof ArrayBuffer=="function",V1=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Fp=({type:e,data:A},i,t)=>T1&&A instanceof Blob?i?t(A):z1(A,t):b1&&(A instanceof ArrayBuffer||V1(A))?i?t(A):z1(new Blob([A]),t):t(HI[e]+(A||"")),z1=(e,A)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];A("b"+(t||""))},i.readAsDataURL(e)};function q1(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Up;function ucA(e,A){if(T1&&e.data instanceof Blob)return e.data.arrayBuffer().then(q1).then(A);if(b1&&(e.data instanceof ArrayBuffer||V1(e.data)))return A(q1(e.data));Fp(e,!1,i=>{Up||(Up=new TextEncoder),A(Up.encode(i))})}const Z1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Aw=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Z1.length;e++)Aw[Z1.charCodeAt(e)]=e;const RcA=e=>{let A=e.length*.75,i=e.length,t,g=0,o,B,I,r;e[e.length-1]==="="&&(A--,e[e.length-2]==="="&&A--);const a=new ArrayBuffer(A),C=new Uint8Array(a);for(t=0;t<i;t+=4)o=Aw[e.charCodeAt(t)],B=Aw[e.charCodeAt(t+1)],I=Aw[e.charCodeAt(t+2)],r=Aw[e.charCodeAt(t+3)],C[g++]=o<<2|B>>4,C[g++]=(B&15)<<4|I>>2,C[g++]=(I&3)<<6|r&63;return a},YcA=typeof ArrayBuffer=="function",mp=(e,A)=>{if(typeof e!="string")return{type:"message",data:W1(e,A)};const i=e.charAt(0);return i==="b"?{type:"message",data:dcA(e.substring(1),A)}:rl[i]?e.length>1?{type:rl[i],data:e.substring(1)}:{type:rl[i]}:Gp},dcA=(e,A)=>{if(YcA){const i=RcA(e);return W1(i,A)}else return{base64:!0,data:e}},W1=(e,A)=>{switch(A){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},P1="",GcA=(e,A)=>{const i=e.length,t=new Array(i);let g=0;e.forEach((o,B)=>{Fp(o,!1,I=>{t[B]=I,++g===i&&A(t.join(P1))})})},FcA=(e,A)=>{const i=e.split(P1),t=[];for(let g=0;g<i.length;g++){const o=mp(i[g],A);if(t.push(o),o.type==="error")break}return t};function UcA(){return new TransformStream({transform(e,A){ucA(e,i=>{const t=i.length;let g;if(t<126)g=new Uint8Array(1),new DataView(g.buffer).setUint8(0,t);else if(t<65536){g=new Uint8Array(3);const o=new DataView(g.buffer);o.setUint8(0,126),o.setUint16(1,t)}else{g=new Uint8Array(9);const o=new DataView(g.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(t))}e.data&&typeof e.data!="string"&&(g[0]|=128),A.enqueue(g),A.enqueue(i)})}})}let pp;function nl(e){return e.reduce((A,i)=>A+i.length,0)}function al(e,A){if(e[0].length===A)return e.shift();const i=new Uint8Array(A);let t=0;for(let g=0;g<A;g++)i[g]=e[0][t++],t===e[0].length&&(e.shift(),t=0);return e.length&&t<e[0].length&&(e[0]=e[0].slice(t)),i}function mcA(e,A){pp||(pp=new TextDecoder);const i=[];let t=0,g=-1,o=!1;return new TransformStream({transform(B,I){for(i.push(B);;){if(t===0){if(nl(i)<1)break;const r=al(i,1);o=(r[0]&128)===128,g=r[0]&127,g<126?t=3:g===126?t=1:t=2}else if(t===1){if(nl(i)<2)break;const r=al(i,2);g=new DataView(r.buffer,r.byteOffset,r.length).getUint16(0),t=3}else if(t===2){if(nl(i)<8)break;const r=al(i,8),a=new DataView(r.buffer,r.byteOffset,r.length),C=a.getUint32(0);if(C>Math.pow(2,21)-1){I.enqueue(Gp);break}g=C*Math.pow(2,32)+a.getUint32(4),t=3}else{if(nl(i)<g)break;const r=al(i,g);I.enqueue(mp(o?r:pp.decode(r),A)),t=0}if(g===0||g>e){I.enqueue(Gp);break}}}})}const v1=4;function Sg(e){if(e)return pcA(e)}function pcA(e){for(var A in Sg.prototype)e[A]=Sg.prototype[A];return e}Sg.prototype.on=Sg.prototype.addEventListener=function(e,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(A),this},Sg.prototype.once=function(e,A){function i(){this.off(e,i),A.apply(this,arguments)}return i.fn=A,this.on(e,i),this},Sg.prototype.off=Sg.prototype.removeListener=Sg.prototype.removeAllListeners=Sg.prototype.removeEventListener=function(e,A){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var i=this._callbacks["$"+e];if(!i)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var t,g=0;g<i.length;g++)if(t=i[g],t===A||t.fn===A){i.splice(g,1);break}return i.length===0&&delete this._callbacks["$"+e],this},Sg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var A=new Array(arguments.length-1),i=this._callbacks["$"+e],t=1;t<arguments.length;t++)A[t-1]=arguments[t];if(i){i=i.slice(0);for(var t=0,g=i.length;t<g;++t)i[t].apply(this,A)}return this},Sg.prototype.emitReserved=Sg.prototype.emit,Sg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Sg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Cl=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,i)=>i(A,0),gE=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ScA="arraybuffer";function eSA(){}function X1(e,...A){return A.reduce((i,t)=>(e.hasOwnProperty(t)&&(i[t]=e[t]),i),{})}const KcA=gE.setTimeout,kcA=gE.clearTimeout;function Ql(e,A){A.useNativeTimers?(e.setTimeoutFn=KcA.bind(gE),e.clearTimeoutFn=kcA.bind(gE)):(e.setTimeoutFn=gE.setTimeout.bind(gE),e.clearTimeoutFn=gE.clearTimeout.bind(gE))}const ycA=1.33;function HcA(e){return typeof e=="string"?NcA(e):Math.ceil((e.byteLength||e.size)*ycA)}function NcA(e){let A=0,i=0;for(let t=0,g=e.length;t<g;t++)A=e.charCodeAt(t),A<128?i+=1:A<2048?i+=2:A<55296||A>=57344?i+=3:(t++,i+=4);return i}function _1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xcA(e){let A="";for(let i in e)e.hasOwnProperty(i)&&(A.length&&(A+="&"),A+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return A}function OcA(e){let A={},i=e.split("&");for(let t=0,g=i.length;t<g;t++){let o=i[t].split("=");A[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return A}class JcA extends Error{constructor(A,i,t){super(A),this.description=i,this.context=t,this.type="TransportError"}}class Sp extends Sg{constructor(A){super(),this.writable=!1,Ql(this,A),this.opts=A,this.query=A.query,this.socket=A.socket,this.supportsBinary=!A.forceBase64}onError(A,i,t){return super.emitReserved("error",new JcA(A,i,t)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(A){this.readyState==="open"&&this.write(A)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(A){const i=mp(A,this.socket.binaryType);this.onPacket(i)}onPacket(A){super.emitReserved("packet",A)}onClose(A){this.readyState="closed",super.emitReserved("close",A)}pause(A){}createUri(A,i={}){return A+"://"+this._hostname()+this._port()+this.opts.path+this._query(i)}_hostname(){const A=this.opts.hostname;return A.indexOf(":")===-1?A:"["+A+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(A){const i=xcA(A);return i.length?"?"+i:""}}class fcA extends Sp{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(A){this.readyState="pausing";const i=()=>{this.readyState="paused",A()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||i()})),this.writable||(t++,this.once("drain",function(){--t||i()}))}else i()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(A){const i=t=>{if(this.readyState==="opening"&&t.type==="open"&&this.onOpen(),t.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)};FcA(A,this.socket.binaryType).forEach(i),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const A=()=>{this.write([{type:"close"}])};this.readyState==="open"?A():this.once("open",A)}write(A){this.writable=!1,GcA(A,i=>{this.doWrite(i,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const A=this.opts.secure?"https":"http",i=this.query||{};return this.opts.timestampRequests!==!1&&(i[this.opts.timestampParam]=_1()),!this.supportsBinary&&!i.sid&&(i.b64=1),this.createUri(A,i)}}let $1=!1;try{$1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const jcA=$1;function LcA(){}class TcA extends fcA{constructor(A){if(super(A),typeof location<"u"){const i=location.protocol==="https:";let t=location.port;t||(t=i?"443":"80"),this.xd=typeof location<"u"&&A.hostname!==location.hostname||t!==A.port}}doWrite(A,i){const t=this.request({method:"POST",data:A});t.on("success",i),t.on("error",(g,o)=>{this.onError("xhr post error",g,o)})}doPoll(){const A=this.request();A.on("data",this.onData.bind(this)),A.on("error",(i,t)=>{this.onError("xhr poll error",i,t)}),this.pollXhr=A}}let gQ=class HD extends Sg{constructor(A,i,t){super(),this.createRequest=A,Ql(this,t),this._opts=t,this._method=t.method||"GET",this._uri=i,this._data=t.data!==void 0?t.data:null,this._create()}_create(){var A;const i=X1(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");i.xdomain=!!this._opts.xd;const t=this._xhr=this.createRequest(i);try{t.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let g in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(g)&&t.setRequestHeader(g,this._opts.extraHeaders[g])}}catch{}if(this._method==="POST")try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}(A=this._opts.cookieJar)===null||A===void 0||A.addCookies(t),"withCredentials"in t&&(t.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(t.timeout=this._opts.requestTimeout),t.onreadystatechange=()=>{var g;t.readyState===3&&((g=this._opts.cookieJar)===null||g===void 0||g.parseCookies(t.getResponseHeader("set-cookie"))),t.readyState===4&&(t.status===200||t.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof t.status=="number"?t.status:0)},0))},t.send(this._data)}catch(g){this.setTimeoutFn(()=>{this._onError(g)},0);return}typeof document<"u"&&(this._index=HD.requestsCount++,HD.requests[this._index]=this)}_onError(A){this.emitReserved("error",A,this._xhr),this._cleanup(!0)}_cleanup(A){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=LcA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete HD.requests[this._index],this._xhr=null}}_onLoad(){const A=this._xhr.responseText;A!==null&&(this.emitReserved("data",A),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(gQ.requestsCount=0,gQ.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Aq);else if(typeof addEventListener=="function"){const e="onpagehide"in gE?"pagehide":"unload";addEventListener(e,Aq,!1)}}function Aq(){for(let e in gQ.requests)gQ.requests.hasOwnProperty(e)&&gQ.requests[e].abort()}const bcA=function(){const e=eq({xdomain:!1});return e&&e.responseType!==null}();class VcA extends TcA{constructor(A){super(A);const i=A&&A.forceBase64;this.supportsBinary=bcA&&!i}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new gQ(eq,this.uri(),A)}}function eq(e){const A=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||jcA))return new XMLHttpRequest}catch{}if(!A)try{return new gE[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const iq=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class zcA extends Sp{get name(){return"websocket"}doOpen(){const A=this.uri(),i=this.opts.protocols,t=iq?{}:X1(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(t.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(A,i,t)}catch(g){return this.emitReserved("error",g)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=A=>this.onClose({description:"websocket connection closed",context:A}),this.ws.onmessage=A=>this.onData(A.data),this.ws.onerror=A=>this.onError("websocket error",A)}write(A){this.writable=!1;for(let i=0;i<A.length;i++){const t=A[i],g=i===A.length-1;Fp(t,this.supportsBinary,o=>{try{this.doWrite(t,o)}catch{}g&&Cl(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const A=this.opts.secure?"wss":"ws",i=this.query||{};return this.opts.timestampRequests&&(i[this.opts.timestampParam]=_1()),this.supportsBinary||(i.b64=1),this.createUri(A,i)}}const Kp=gE.WebSocket||gE.MozWebSocket;class qcA extends zcA{createSocket(A,i,t){return iq?new Kp(A,i,t):i?new Kp(A,i):new Kp(A)}doWrite(A,i){this.ws.send(i)}}class ZcA extends Sp{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(A){return this.emitReserved("error",A)}this._transport.closed.then(()=>{this.onClose()}).catch(A=>{this.onError("webtransport error",A)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(A=>{const i=mcA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),t=A.readable.pipeThrough(i).getReader(),g=UcA();g.readable.pipeTo(A.writable),this._writer=g.writable.getWriter();const o=()=>{t.read().then(({done:I,value:r})=>{I||(this.onPacket(r),o())}).catch(I=>{})};o();const B={type:"open"};this.query.sid&&(B.data=`{"sid":"${this.query.sid}"}`),this._writer.write(B).then(()=>this.onOpen())})})}write(A){this.writable=!1;for(let i=0;i<A.length;i++){const t=A[i],g=i===A.length-1;this._writer.write(t).then(()=>{g&&Cl(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const WcA={websocket:qcA,webtransport:ZcA,polling:VcA},PcA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vcA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function kp(e){if(e.length>8e3)throw"URI too long";const A=e,i=e.indexOf("["),t=e.indexOf("]");i!=-1&&t!=-1&&(e=e.substring(0,i)+e.substring(i,t).replace(/:/g,";")+e.substring(t,e.length));let g=PcA.exec(e||""),o={},B=14;for(;B--;)o[vcA[B]]=g[B]||"";return i!=-1&&t!=-1&&(o.source=A,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=XcA(o,o.path),o.queryKey=_cA(o,o.query),o}function XcA(e,A){const i=/\/{2,9}/g,t=A.replace(i,"/").split("/");return(A.slice(0,1)=="/"||A.length===0)&&t.splice(0,1),A.slice(-1)=="/"&&t.splice(t.length-1,1),t}function _cA(e,A){const i={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,g,o){g&&(i[g]=o)}),i}const yp=typeof addEventListener=="function"&&typeof removeEventListener=="function",sl=[];yp&&addEventListener("offline",()=>{sl.forEach(e=>e())},!1);class Rn extends Sg{constructor(A,i){if(super(),this.binaryType=ScA,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,A&&typeof A=="object"&&(i=A,A=null),A){const t=kp(A);i.hostname=t.host,i.secure=t.protocol==="https"||t.protocol==="wss",i.port=t.port,t.query&&(i.query=t.query)}else i.host&&(i.hostname=kp(i.host).host);Ql(this,i),this.secure=i.secure!=null?i.secure:typeof location<"u"&&location.protocol==="https:",i.hostname&&!i.port&&(i.port=this.secure?"443":"80"),this.hostname=i.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=i.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},i.transports.forEach(t=>{const g=t.prototype.name;this.transports.push(g),this._transportsByName[g]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},i),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=OcA(this.opts.query)),yp&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},sl.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const i=Object.assign({},this.opts.query);i.EIO=v1,i.transport=A,this.id&&(i.sid=this.id);const t=Object.assign({},this.opts,{query:i,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[A]);return new this._transportsByName[A](t)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const A=this.opts.rememberUpgrade&&Rn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const i=this.createTransport(A);i.open(),this.setTransport(i)}setTransport(A){this.transport&&this.transport.removeAllListeners(),this.transport=A,A.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",i=>this._onClose("transport close",i))}onOpen(){this.readyState="open",Rn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(A){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",A),this.emitReserved("heartbeat"),A.type){case"open":this.onHandshake(JSON.parse(A.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const i=new Error("server error");i.code=A.data,this._onError(i);break;case"message":this.emitReserved("data",A.data),this.emitReserved("message",A.data);break}}onHandshake(A){this.emitReserved("handshake",A),this.id=A.sid,this.transport.query.sid=A.sid,this._pingInterval=A.pingInterval,this._pingTimeout=A.pingTimeout,this._maxPayload=A.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const A=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+A,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},A),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const A=this._getWritablePackets();this.transport.send(A),this._prevBufferLen=A.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let i=1;for(let t=0;t<this.writeBuffer.length;t++){const g=this.writeBuffer[t].data;if(g&&(i+=HcA(g)),t>0&&i>this._maxPayload)return this.writeBuffer.slice(0,t);i+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const A=Date.now()>this._pingTimeoutTime;return A&&(this._pingTimeoutTime=0,Cl(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),A}write(A,i,t){return this._sendPacket("message",A,i,t),this}send(A,i,t){return this._sendPacket("message",A,i,t),this}_sendPacket(A,i,t,g){if(typeof i=="function"&&(g=i,i=void 0),typeof t=="function"&&(g=t,t=null),this.readyState==="closing"||this.readyState==="closed")return;t=t||{},t.compress=t.compress!==!1;const o={type:A,data:i,options:t};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),g&&this.once("flush",g),this.flush()}close(){const A=()=>{this._onClose("forced close"),this.transport.close()},i=()=>{this.off("upgrade",i),this.off("upgradeError",i),A()},t=()=>{this.once("upgrade",i),this.once("upgradeError",i)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?t():A()}):this.upgrading?t():A()),this}_onError(A){if(Rn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",A),this._onClose("transport error",A)}_onClose(A,i){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),yp&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=sl.indexOf(this._offlineEventListener);t!==-1&&sl.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,i),this.writeBuffer=[],this._prevBufferLen=0}}}Rn.protocol=v1;class $cA extends Rn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let A=0;A<this._upgrades.length;A++)this._probe(this._upgrades[A])}_probe(A){let i=this.createTransport(A),t=!1;Rn.priorWebsocketSuccess=!1;const g=()=>{t||(i.send([{type:"ping",data:"probe"}]),i.once("packet",s=>{if(!t)if(s.type==="pong"&&s.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",i),!i)return;Rn.priorWebsocketSuccess=i.name==="websocket",this.transport.pause(()=>{t||this.readyState!=="closed"&&(C(),this.setTransport(i),i.send([{type:"upgrade"}]),this.emitReserved("upgrade",i),i=null,this.upgrading=!1,this.flush())})}else{const c=new Error("probe error");c.transport=i.name,this.emitReserved("upgradeError",c)}}))};function o(){t||(t=!0,C(),i.close(),i=null)}const B=s=>{const c=new Error("probe error: "+s);c.transport=i.name,o(),this.emitReserved("upgradeError",c)};function I(){B("transport closed")}function r(){B("socket closed")}function a(s){i&&s.name!==i.name&&o()}const C=()=>{i.removeListener("open",g),i.removeListener("error",B),i.removeListener("close",I),this.off("close",r),this.off("upgrading",a)};i.once("open",g),i.once("error",B),i.once("close",I),this.once("close",r),this.once("upgrading",a),this._upgrades.indexOf("webtransport")!==-1&&A!=="webtransport"?this.setTimeoutFn(()=>{t||i.open()},200):i.open()}onHandshake(A){this._upgrades=this._filterUpgrades(A.upgrades),super.onHandshake(A)}_filterUpgrades(A){const i=[];for(let t=0;t<A.length;t++)~this.transports.indexOf(A[t])&&i.push(A[t]);return i}}let AhA=class extends $cA{constructor(A,i={}){const t=typeof A=="object"?A:i;(!t.transports||t.transports&&typeof t.transports[0]=="string")&&(t.transports=(t.transports||["polling","websocket","webtransport"]).map(g=>WcA[g]).filter(g=>!!g)),super(A,t)}};function ehA(e,A="",i){let t=e;i=i||typeof location<"u"&&location,e==null&&(e=i.protocol+"//"+i.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=i.protocol+e:e=i.host+e),/^(https?|wss?):\/\//.test(e)||(typeof i<"u"?e=i.protocol+"//"+e:e="https://"+e),t=kp(e)),t.port||(/^(http|ws)$/.test(t.protocol)?t.port="80":/^(http|ws)s$/.test(t.protocol)&&(t.port="443")),t.path=t.path||"/";const o=t.host.indexOf(":")!==-1?"["+t.host+"]":t.host;return t.id=t.protocol+"://"+o+":"+t.port+A,t.href=t.protocol+"://"+o+(i&&i.port===t.port?"":":"+t.port),t}const ihA=typeof ArrayBuffer=="function",thA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,tq=Object.prototype.toString,ghA=typeof Blob=="function"||typeof Blob<"u"&&tq.call(Blob)==="[object BlobConstructor]",ohA=typeof File=="function"||typeof File<"u"&&tq.call(File)==="[object FileConstructor]";function Hp(e){return ihA&&(e instanceof ArrayBuffer||thA(e))||ghA&&e instanceof Blob||ohA&&e instanceof File}function wl(e,A){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let i=0,t=e.length;i<t;i++)if(wl(e[i]))return!0;return!1}if(Hp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return wl(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&wl(e[i]))return!0;return!1}function BhA(e){const A=[],i=e.data,t=e;return t.data=Np(i,A),t.attachments=A.length,{packet:t,buffers:A}}function Np(e,A){if(!e)return e;if(Hp(e)){const i={_placeholder:!0,num:A.length};return A.push(e),i}else if(Array.isArray(e)){const i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=Np(e[t],A);return i}else if(typeof e=="object"&&!(e instanceof Date)){const i={};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(i[t]=Np(e[t],A));return i}return e}function EhA(e,A){return e.data=xp(e.data,A),delete e.attachments,e}function xp(e,A){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<A.length)return A[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=xp(e[i],A);else if(typeof e=="object")for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=xp(e[i],A));return e}const IhA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],rhA=5;var ji;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ji||(ji={}));class nhA{constructor(A){this.replacer=A}encode(A){return(A.type===ji.EVENT||A.type===ji.ACK)&&wl(A)?this.encodeAsBinary({type:A.type===ji.EVENT?ji.BINARY_EVENT:ji.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let i=""+A.type;return(A.type===ji.BINARY_EVENT||A.type===ji.BINARY_ACK)&&(i+=A.attachments+"-"),A.nsp&&A.nsp!=="/"&&(i+=A.nsp+","),A.id!=null&&(i+=A.id),A.data!=null&&(i+=JSON.stringify(A.data,this.replacer)),i}encodeAsBinary(A){const i=BhA(A),t=this.encodeAsString(i.packet),g=i.buffers;return g.unshift(t),g}}function gq(e){return Object.prototype.toString.call(e)==="[object Object]"}class Op extends Sg{constructor(A){super(),this.reviver=A}add(A){let i;if(typeof A=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");i=this.decodeString(A);const t=i.type===ji.BINARY_EVENT;t||i.type===ji.BINARY_ACK?(i.type=t?ji.EVENT:ji.ACK,this.reconstructor=new ahA(i),i.attachments===0&&super.emitReserved("decoded",i)):super.emitReserved("decoded",i)}else if(Hp(A)||A.base64)if(this.reconstructor)i=this.reconstructor.takeBinaryData(A),i&&(this.reconstructor=null,super.emitReserved("decoded",i));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+A)}decodeString(A){let i=0;const t={type:Number(A.charAt(0))};if(ji[t.type]===void 0)throw new Error("unknown packet type "+t.type);if(t.type===ji.BINARY_EVENT||t.type===ji.BINARY_ACK){const o=i+1;for(;A.charAt(++i)!=="-"&&i!=A.length;);const B=A.substring(o,i);if(B!=Number(B)||A.charAt(i)!=="-")throw new Error("Illegal attachments");t.attachments=Number(B)}if(A.charAt(i+1)==="/"){const o=i+1;for(;++i&&!(A.charAt(i)===","||i===A.length););t.nsp=A.substring(o,i)}else t.nsp="/";const g=A.charAt(i+1);if(g!==""&&Number(g)==g){const o=i+1;for(;++i;){const B=A.charAt(i);if(B==null||Number(B)!=B){--i;break}if(i===A.length)break}t.id=Number(A.substring(o,i+1))}if(A.charAt(++i)){const o=this.tryParse(A.substr(i));if(Op.isPayloadValid(t.type,o))t.data=o;else throw new Error("invalid payload")}return t}tryParse(A){try{return JSON.parse(A,this.reviver)}catch{return!1}}static isPayloadValid(A,i){switch(A){case ji.CONNECT:return gq(i);case ji.DISCONNECT:return i===void 0;case ji.CONNECT_ERROR:return typeof i=="string"||gq(i);case ji.EVENT:case ji.BINARY_EVENT:return Array.isArray(i)&&(typeof i[0]=="number"||typeof i[0]=="string"&&IhA.indexOf(i[0])===-1);case ji.ACK:case ji.BINARY_ACK:return Array.isArray(i)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ahA{constructor(A){this.packet=A,this.buffers=[],this.reconPack=A}takeBinaryData(A){if(this.buffers.push(A),this.buffers.length===this.reconPack.attachments){const i=EhA(this.reconPack,this.buffers);return this.finishedReconstruction(),i}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ChA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Op,Encoder:nhA,get PacketType(){return ji},protocol:rhA},Symbol.toStringTag,{value:"Module"}));function LE(e,A,i){return e.on(A,i),function(){e.off(A,i)}}const QhA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class oq extends Sg{constructor(A,i,t){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=A,this.nsp=i,t&&t.auth&&(this.auth=t.auth),this._opts=Object.assign({},t),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const A=this.io;this.subs=[LE(A,"open",this.onopen.bind(this)),LE(A,"packet",this.onpacket.bind(this)),LE(A,"error",this.onerror.bind(this)),LE(A,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...A){return A.unshift("message"),this.emit.apply(this,A),this}emit(A,...i){var t,g,o;if(QhA.hasOwnProperty(A))throw new Error('"'+A.toString()+'" is a reserved event name');if(i.unshift(A),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(i),this;const B={type:ji.EVENT,data:i};if(B.options={},B.options.compress=this.flags.compress!==!1,typeof i[i.length-1]=="function"){const C=this.ids++,s=i.pop();this._registerAckCallback(C,s),B.id=C}const I=(g=(t=this.io.engine)===null||t===void 0?void 0:t.transport)===null||g===void 0?void 0:g.writable,r=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!I||(r?(this.notifyOutgoingListeners(B),this.packet(B)):this.sendBuffer.push(B)),this.flags={},this}_registerAckCallback(A,i){var t;const g=(t=this.flags.timeout)!==null&&t!==void 0?t:this._opts.ackTimeout;if(g===void 0){this.acks[A]=i;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[A];for(let I=0;I<this.sendBuffer.length;I++)this.sendBuffer[I].id===A&&this.sendBuffer.splice(I,1);i.call(this,new Error("operation has timed out"))},g),B=(...I)=>{this.io.clearTimeoutFn(o),i.apply(this,I)};B.withError=!0,this.acks[A]=B}emitWithAck(A,...i){return new Promise((t,g)=>{const o=(B,I)=>B?g(B):t(I);o.withError=!0,i.push(o),this.emit(A,...i)})}_addToQueue(A){let i;typeof A[A.length-1]=="function"&&(i=A.pop());const t={id:this._queueSeq++,tryCount:0,pending:!1,args:A,flags:Object.assign({fromQueue:!0},this.flags)};A.push((g,...o)=>t!==this._queue[0]?void 0:(g!==null?t.tryCount>this._opts.retries&&(this._queue.shift(),i&&i(g)):(this._queue.shift(),i&&i(null,...o)),t.pending=!1,this._drainQueue())),this._queue.push(t),this._drainQueue()}_drainQueue(A=!1){if(!this.connected||this._queue.length===0)return;const i=this._queue[0];i.pending&&!A||(i.pending=!0,i.tryCount++,this.flags=i.flags,this.emit.apply(this,i.args))}packet(A){A.nsp=this.nsp,this.io._packet(A)}onopen(){typeof this.auth=="function"?this.auth(A=>{this._sendConnectPacket(A)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(A){this.packet({type:ji.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},A):A})}onerror(A){this.connected||this.emitReserved("connect_error",A)}onclose(A,i){this.connected=!1,delete this.id,this.emitReserved("disconnect",A,i),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(A=>{if(!this.sendBuffer.some(t=>String(t.id)===A)){const t=this.acks[A];delete this.acks[A],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(A){if(A.nsp===this.nsp)switch(A.type){case ji.CONNECT:A.data&&A.data.sid?this.onconnect(A.data.sid,A.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ji.EVENT:case ji.BINARY_EVENT:this.onevent(A);break;case ji.ACK:case ji.BINARY_ACK:this.onack(A);break;case ji.DISCONNECT:this.ondisconnect();break;case ji.CONNECT_ERROR:this.destroy();const t=new Error(A.data.message);t.data=A.data.data,this.emitReserved("connect_error",t);break}}onevent(A){const i=A.data||[];A.id!=null&&i.push(this.ack(A.id)),this.connected?this.emitEvent(i):this.receiveBuffer.push(Object.freeze(i))}emitEvent(A){if(this._anyListeners&&this._anyListeners.length){const i=this._anyListeners.slice();for(const t of i)t.apply(this,A)}super.emit.apply(this,A),this._pid&&A.length&&typeof A[A.length-1]=="string"&&(this._lastOffset=A[A.length-1])}ack(A){const i=this;let t=!1;return function(...g){t||(t=!0,i.packet({type:ji.ACK,id:A,data:g}))}}onack(A){const i=this.acks[A.id];typeof i=="function"&&(delete this.acks[A.id],i.withError&&A.data.unshift(null),i.apply(this,A.data))}onconnect(A,i){this.id=A,this.recovered=i&&this._pid===i,this._pid=i,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(A=>this.emitEvent(A)),this.receiveBuffer=[],this.sendBuffer.forEach(A=>{this.notifyOutgoingListeners(A),this.packet(A)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(A=>A()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ji.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(A){return this.flags.compress=A,this}get volatile(){return this.flags.volatile=!0,this}timeout(A){return this.flags.timeout=A,this}onAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(A),this}prependAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(A),this}offAny(A){if(!this._anyListeners)return this;if(A){const i=this._anyListeners;for(let t=0;t<i.length;t++)if(A===i[t])return i.splice(t,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(A),this}prependAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(A),this}offAnyOutgoing(A){if(!this._anyOutgoingListeners)return this;if(A){const i=this._anyOutgoingListeners;for(let t=0;t<i.length;t++)if(A===i[t])return i.splice(t,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(A){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const i=this._anyOutgoingListeners.slice();for(const t of i)t.apply(this,A.data)}}}function oQ(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}oQ.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var A=Math.random(),i=Math.floor(A*this.jitter*e);e=(Math.floor(A*10)&1)==0?e-i:e+i}return Math.min(e,this.max)|0},oQ.prototype.reset=function(){this.attempts=0},oQ.prototype.setMin=function(e){this.ms=e},oQ.prototype.setMax=function(e){this.max=e},oQ.prototype.setJitter=function(e){this.jitter=e};class Jp extends Sg{constructor(A,i){var t;super(),this.nsps={},this.subs=[],A&&typeof A=="object"&&(i=A,A=void 0),i=i||{},i.path=i.path||"/socket.io",this.opts=i,Ql(this,i),this.reconnection(i.reconnection!==!1),this.reconnectionAttempts(i.reconnectionAttempts||1/0),this.reconnectionDelay(i.reconnectionDelay||1e3),this.reconnectionDelayMax(i.reconnectionDelayMax||5e3),this.randomizationFactor((t=i.randomizationFactor)!==null&&t!==void 0?t:.5),this.backoff=new oQ({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(i.timeout==null?2e4:i.timeout),this._readyState="closed",this.uri=A;const g=i.parser||ChA;this.encoder=new g.Encoder,this.decoder=new g.Decoder,this._autoConnect=i.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(A){return arguments.length?(this._reconnection=!!A,A||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(A){return A===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=A,this)}reconnectionDelay(A){var i;return A===void 0?this._reconnectionDelay:(this._reconnectionDelay=A,(i=this.backoff)===null||i===void 0||i.setMin(A),this)}randomizationFactor(A){var i;return A===void 0?this._randomizationFactor:(this._randomizationFactor=A,(i=this.backoff)===null||i===void 0||i.setJitter(A),this)}reconnectionDelayMax(A){var i;return A===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=A,(i=this.backoff)===null||i===void 0||i.setMax(A),this)}timeout(A){return arguments.length?(this._timeout=A,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(A){if(~this._readyState.indexOf("open"))return this;this.engine=new AhA(this.uri,this.opts);const i=this.engine,t=this;this._readyState="opening",this.skipReconnect=!1;const g=LE(i,"open",function(){t.onopen(),A&&A()}),o=I=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",I),A?A(I):this.maybeReconnectOnOpen()},B=LE(i,"error",o);if(this._timeout!==!1){const I=this._timeout,r=this.setTimeoutFn(()=>{g(),o(new Error("timeout")),i.close()},I);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(g),this.subs.push(B),this}connect(A){return this.open(A)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const A=this.engine;this.subs.push(LE(A,"ping",this.onping.bind(this)),LE(A,"data",this.ondata.bind(this)),LE(A,"error",this.onerror.bind(this)),LE(A,"close",this.onclose.bind(this)),LE(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(A){try{this.decoder.add(A)}catch(i){this.onclose("parse error",i)}}ondecoded(A){Cl(()=>{this.emitReserved("packet",A)},this.setTimeoutFn)}onerror(A){this.emitReserved("error",A)}socket(A,i){let t=this.nsps[A];return t?this._autoConnect&&!t.active&&t.connect():(t=new oq(this,A,i),this.nsps[A]=t),t}_destroy(A){const i=Object.keys(this.nsps);for(const t of i)if(this.nsps[t].active)return;this._close()}_packet(A){const i=this.encoder.encode(A);for(let t=0;t<i.length;t++)this.engine.write(i[t],A.options)}cleanup(){this.subs.forEach(A=>A()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(A,i){var t;this.cleanup(),(t=this.engine)===null||t===void 0||t.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",A,i),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const A=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const i=this.backoff.duration();this._reconnecting=!0;const t=this.setTimeoutFn(()=>{A.skipReconnect||(this.emitReserved("reconnect_attempt",A.backoff.attempts),!A.skipReconnect&&A.open(g=>{g?(A._reconnecting=!1,A.reconnect(),this.emitReserved("reconnect_error",g)):A.onreconnect()}))},i);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}}onreconnect(){const A=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",A)}}const ew={};function cl(e,A){typeof e=="object"&&(A=e,e=void 0),A=A||{};const i=ehA(e,A.path||"/socket.io"),t=i.source,g=i.id,o=i.path,B=ew[g]&&o in ew[g].nsps,I=A.forceNew||A["force new connection"]||A.multiplex===!1||B;let r;return I?r=new Jp(t,A):(ew[g]||(ew[g]=new Jp(t,A)),r=ew[g]),i.query&&!A.query&&(A.query=i.queryKey),r.socket(i.path,A)}Object.assign(cl,{Manager:Jp,Socket:oq,io:cl,connect:cl});const BQ="https://api.tybotflow.com/api/v1",shA="https://api.tybotflow.com/api/v1/chatbots-config",Bq="https://migration-meta.tybotflow.com/",Eq=Bq+"webhook/v",EQ=cl(Bq,{transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:3,autoConnect:!0,reconnectionDelay:2e3}),Iq=new Rr,fp=e=>{if(!e||!e.message)return"👋 Hey there! how can I help you?";const A=e.message;if(typeof A=="string")return A;if(Array.isArray(A)){const i=window.location.href,t=window.location.origin,g=window.location.pathname,o=t+g;for(const I of A){if(!I.urls||I.urls.length===0)continue;if(I.urls.some(a=>{if(!a||a.trim()==="")return!1;try{let C=a.trim();!C.startsWith("http://")&&!C.startsWith("https://")&&(C="https://"+C);const s=new URL(C),c=s.origin,w=s.pathname,l=c+w;return o===l||i===C?!0:w==="/"||w===""?t===c:!!i.startsWith(C)}catch{return console.warn("Invalid URL in message:",a),!1}}))return I.text||"👋 Hey there! how can I help you?"}const B=A.find(I=>!I.urls||I.urls.length===0||I.urls.every(r=>!r||r.trim()===""));if(B)return B.text||"👋 Hey there! how can I help you?";if(A.length>0)return A[0].text||"👋 Hey there! how can I help you?"}return"👋 Hey there! how can I help you?"},rq=(e,A)=>{const i={className:"w-5 h-5",style:{color:A}};switch(e?.toLowerCase()){case"pdf":return U.jsx(Bn,{...i});case"doc":case"docx":return U.jsx(Bn,{...i});case"xls":case"xlsx":case"csv":return U.jsx(KiA,{...i});case"ppt":case"pptx":return U.jsx(fiA,{...i});case"zip":case"rar":case"7z":case"tar":case"gz":return U.jsx(FiA,{...i});case"txt":case"md":case"rtf":return U.jsx(hx,{...i});default:return U.jsx(Bn,{...i})}},whA=({config:e})=>{const A=vA.useRef(null),i=vA.useRef(null),t=vA.useRef(null),g=vA.useRef(null),o=vA.useRef(null),[B,I]=vA.useState(null),[r,a]=vA.useState(!0),[C,s]=vA.useState(!1);vA.useEffect(()=>{(async()=>{a(!0),await Ft.get(`${shA}/bot/${e.bot?.botId}`,{}).then(jA=>{I(jA.data)}).catch(jA=>{console.error("Error fetching bot config:",jA)}).finally(()=>{a(!1)})})()},[e.bot?.botId,e?.token]);const c=B?.mainColor||"#59168b",w=B?.secondaryColor||"#6366f1",l=B?.thirdColor||"#0f172b",D=B?.headerFirstColor||"#6e11b0",d=B?.headerSecondColor||"#372aac",u=B?.inputBackgroundColor||"#1f2937",G=B?.inputTextColor||"#fff",F=B?.roundness||24,K=B?.chatRoundness||16,k=(B?.minPanelWidth||434)>window.innerWidth?window.innerWidth:B?.minPanelWidth||434,S=(B?.maxPanelWidth||window.innerWidth)>window.innerWidth?window.innerWidth:B?.maxPanelWidth||window.innerWidth,f=B?.chatMaxWidth||88,j=B?.toggleBtnBorderTopLeftRadius||12,O=B?.toggleBtnBorderTopRightRadius||0,b=B?.toggleBtnBorderBottomLeftRadius||12,x=B?.toggleBtnBorderBottomRightRadius||0,V=B?.menuBackgroundColor||"#1f2937",q=B?.menuTextColor||"#e5e7eb",z=B?.menuHoverBackgroundColor||"#374151",v=B?.agentChatResponseColor||"#e5e7eb",P=B?.agentChatResponseBgColor||"#1f2937",gA=B?.agentIconBgColor||"#59168b",$=B?.agentIconColor||"#fff",IA=B?.userChatMessagesColor||"#fff",H=B?.userChatMessagesBgColor||"#7a1ebe",AA=B?.userIconBgColor||"#7a1ebe",T=B?.userIconColor||"#fff",y=B?.ButtonColor||"#fff",X=B?.ButtonsBgColor||"#59168b",EA=qg(P,10),rA=B?.fontSize||13,wA=B?.toggleBtnPosition||"bottom-right",DA=B?.autoOpenPanel??!0,UA=B?.tempToken||"",PA=(()=>{const J=B?.firstMessageKeyword;if(Array.isArray(J)){const jA=window.location.href,RA=J.find(ce=>ce.url&&ce.url===jA);if(RA)return RA.message;const FA=J.find(ce=>!ce.url||ce.url==="");return FA?FA.message:J[0]?.message||"hi"}return J||"hi"})(),le=J=>({ip:J.ip||"",flag:{img:J.flag||"",emoji:J.emoji_flag||"",emoji_unicode:J.emoji_unicode||""},is_eu:J.is_eu??!1,postal:J.postal||"",borders:"",latitude:J.latitude||0,platform:J?.platform||"",timezone:{id:J.time_zone?.name||"",utc:J.time_zone?.offset||"",abbr:J.time_zone?.abbr||"",is_dst:J.time_zone?.is_dst??!1,offset:J.time_zone?.offset||0,current_time:J.time_zone?.current_time||""},continent:J.continent_name||"",longitude:J.longitude||0,connection:{asn:J.asn?.asn||0,isp:J.asn?.name||"",org:J.asn?.name||"",domain:J.asn?.domain||""}}),[ZA,kA]=vA.useState(k),tA=vA.useRef(!1),ge=vA.useRef(0),De=vA.useRef(k),ae=J=>{tA.current=!0,ge.current=J.clientX,De.current=ZA,document.body.style.cursor="ew-resize"};vA.useEffect(()=>{const J=RA=>{if(!tA.current)return;const FA=ge.current-RA.clientX;let ce=De.current+FA;ce=Math.max(k,Math.min(S,ce)),kA(ce)},jA=()=>{tA.current&&(tA.current=!1,document.body.style.cursor="")};return window.addEventListener("mousemove",J),window.addEventListener("mouseup",jA),()=>{window.removeEventListener("mousemove",J),window.removeEventListener("mouseup",jA)}},[ZA,k,S]);const[KA,Ee]=vA.useState(!1),[ie,Fe]=vA.useState(!1),[Qe,NA]=vA.useState(!1),[bA,hA]=vA.useState(()=>wA==="bottom-left"?{x:48,y:window.innerHeight-120}:wA==="middle-right"?{x:window.innerWidth-80,y:window.innerHeight/2-35}:{x:window.innerWidth-123,y:window.innerHeight-100}),[uA,yA]=vA.useState(!1),[VA,ue]=vA.useState({x:0,y:0}),Ge=vA.useRef(null),[Ve,je]=vA.useState(""),[Re,Ye]=vA.useState(!1),[ze,me]=vA.useState(!1),[Ne,ye]=vA.useState([]),[Ai,Di]=vA.useState(!1),Xe=vA.useRef(0),[We,ui]=vA.useState(!1),[vg,ri]=vA.useState(!1),Ot=vA.useRef(!1),[ao,Pe]=vA.useState("00:00"),zi=vA.useRef(null),yi=vA.useRef(0),[qi,Jt]=vA.useState(null),[ni,At]=vA.useState(!1),[_i,Xg]=vA.useState(new Set),[Et,Zi]=vA.useState([]),[et,vt]=vA.useState(null),[Xt,ft]=vA.useState("up"),{startRecording:it,stopRecording:_g,pauseRecording:xe,resumeRecording:lA,status:$A,error:Se}=sEA.useReactMediaRecorder({video:!1,blobPropertyBag:{type:"audio/mp3"},onStop(J,jA){if(Ot.current){Ot.current=!1,Pe("00:00"),yi.current=0;return}ye(RA=>[...RA,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:jA,type:"audio",url:J,name:`recording-${new Date().toISOString()}.webm`,size:jA.size}]),Pe("00:00"),yi.current=0}}),Fi=B?.icon||e?.icon||e?.bot.avatar_url||AQA,wt=B?.headerIcon||e?.headerIcon||Fi,rt=B?.headerImageStyle||e?.headerImageStyle||"compact",Rt=B?.launcherImageHeight??e?.launcherImageHeight??130,It=B?.launcherImageDesktopHeight??e?.launcherImageDesktopHeight??150,kt=B?.imageType||e?.imageType||"icon",Co={"--launcher-image-height":`${Rt}px`,"--launcher-image-desktop-height":`${It}px`,"--launcher-welcome-top":`${Math.round(Rt*.28)}px`,"--launcher-welcome-desktop-top":`${Math.round(It*.4)}px`},Li=B?.title||e?.bot.name||"Tybot webchat",[Ti,_o]=vA.useState(null),[$o,vE]=vA.useState(()=>{const J=localStorage.getItem("phone_client");if(e.bot?.botId==="rockskin"&&J)return J;if(!B?.botNeedsAuth){let jA=localStorage.getItem("externalUser");if(!jA){const RA=new Uint8Array(16);window.crypto.getRandomValues(RA),jA=Array.from(RA).map(FA=>FA.toString(16).padStart(2,"0")).join("")}return localStorage.setItem("externalUser",jA),jA}});vA.useEffect(()=>{if(!Ti)return;const J=jA=>{if(jA.bot.conversationId!==parseInt(Ti)||jA.bot.botId!==e?.bot?.botId){Ye(!1);return}const RA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:jA.bot.item,timestamp:new Date,seen:xo.current,nMessage:Array.isArray(jA.bot.item)?jA.bot.item.length:1};Zi(FA=>FA.some(pA=>pA.id===RA.id)?FA:[...FA,RA]),Ye(!1)};return EQ.on("bot-message",J),()=>{EQ.off("bot-message",J)}},[Ti,e?.bot?.botId]),vA.useEffect(()=>{if(!Ti)return;const J=jA=>{const RA=jA.conversationId!==void 0?jA.conversationId:jA.bot?.conversationId,FA=jA.botId!==void 0?jA.botId:jA.bot?.botId;RA!==parseInt(Ti)||FA!==e?.bot?.botId&&FA!==e.bot?.botId||Zi(ce=>{const pA=[...ce].reverse().findIndex(aA=>aA.sender==="agent");if(pA===-1)return ce;const p=ce.length-1-pA,Z=[...ce];return Z[p]={...Z[p],timingMetrics:jA.latencies},Z})};return EQ.on("timing_metrics",J),()=>{EQ.off("timing_metrics",J)}},[Ti,e?.bot?.botId,e.bot?.botId]),vA.useEffect(()=>{(async()=>{if(!(Ti||!e.bot?.botId||!$o))try{const RA=(await Ft.post(`${BQ}/conversations/start-conversation`,{bot_id:e.bot?.botId,externalUser:$o})).data.conversationId;_o(RA),localStorage.setItem("conversationId",RA),EQ.emit("join_room",parseInt(RA))}catch(jA){console.error("Error initializing conversation:",jA)}})()},[Ti,e.bot?.botId,$o]);const[AB,bi]=vA.useState(()=>B?.botNeedsAuth?!!localStorage.getItem("conversationId"):!0),[eB,xn]=vA.useState(""),[fg,aE]=vA.useState(""),[Mg,XE]=vA.useState(""),[Ri,_E]=vA.useState(null),xo=vA.useRef(!1),Qo=Et.reduce((J,jA)=>jA.seen?J:J+(jA.sender==="agent"?jA.nMessage||1:0),0),YB=()=>{Zi(J=>J.map(jA=>({...jA,seen:!0})))};vA.useEffect(()=>{let J;return!localStorage.getItem("webChatOpen")&&B&&DA&&(J=setTimeout(()=>{Ee(!0),xo.current=!0,YB(),localStorage.setItem("webChatOpen","true")},3200)),()=>clearTimeout(J)},[B]),vA.useEffect(()=>{const J=B?.widgetLoadBehavior;if(!J||!(()=>{const FA=J.message;if(typeof FA=="string"){if(!J.urls||J.urls.length===0)return!0;const ce=window.location.origin,pA=window.location.href;return J.urls.some(p=>{if(!p||p.trim()==="")return!0;try{return ce.includes(p)||pA.includes(p)||p.includes(ce)}catch{return console.warn("Invalid URL in widgetLoadBehavior:",p),!1}})}if(Array.isArray(FA)){const ce=window.location.href,pA=window.location.origin,p=window.location.pathname,Z=pA+p;for(const aA of FA)if(!aA.urls||aA.urls.length===0||aA.urls.every(dA=>!dA||dA.trim()==="")||aA.urls.some(dA=>{if(!dA||dA.trim()==="")return!1;try{let zA=dA.trim();!zA.startsWith("http://")&&!zA.startsWith("https://")&&(zA="https://"+zA);const Be=new URL(zA),te=Be.origin,Oe=Be.pathname,pe=te+Oe;return Z===pe||ce===zA?!0:Oe==="/"||Oe===""?pA===te:!!ce.startsWith(zA)}catch{return console.warn("Invalid URL in message:",dA),!1}}))return!0;return!1}return!0})())return;let RA;if(J.behavior==="after seconds")RA=setTimeout(()=>{NA(!0)},J.value*1e3);else if(J.behavior==="after scroll"){const FA=()=>{const ce=window.pageYOffset||document.documentElement.scrollTop,pA=document.documentElement.scrollHeight-document.documentElement.clientHeight;ce/pA*100>=J.value&&(NA(!0),window.removeEventListener("scroll",FA))};return window.addEventListener("scroll",FA),()=>{window.removeEventListener("scroll",FA)}}return()=>{RA&&clearTimeout(RA)}},[B?.widgetLoadBehavior]),vA.useEffect(()=>{KA&&NA(!1)},[KA]),vA.useEffect(()=>{fetch("https://api.ipdata.co/?api-key=7930ffd0621dafcb6cd830a503d726bf514b74c1cae21ffff8131890").then(function(J){J.json().then(jA=>{_E({...jA,platform:Iq.getOS().name+" "+Iq.getOS().version})})}).catch(function(J){console.log(J)})},[]);const so=vA.useCallback(async(J,jA=[],RA)=>{if(!e.bot.botId||!Ti){Ye(!1),Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:[{type:"text",text:"⚠️ Unable to send message: No bot selected or conversation not initialized."}],timestamp:new Date}]);return}if(jA.length>0||RA&&typeof RA=="object"&&RA.attachment!==void 0){const ce=RA&&typeof RA!="string"?RA.attachment.file:jA[0]?.file,pA=RA&&typeof RA!="string"?RA.attachment.type:jA[0]?.type||"file";let p=RA;if(RA&&typeof RA=="object"&&RA.attachment!==void 0){const{attachment:aA,...sA}=RA;p=sA}const Z=new FormData;Z.append("type",pA),Z.append("file",ce),Z.append("botId",e.bot.botId),Z.append("external_id",$o||""),Z.append("isintern",e.token?"true":"false"),Z.append("host",window.location.origin),Z.append("channel","web"),Z.append("payload",p?JSON.stringify(p):""),await Ft.post(Eq,Z,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"multipart/form-data"}})}else{const ce={type:"text",messageText:J,botId:e.bot.botId,external_id:$o||"",isintern:!!e.token,host:window.location.origin,channel:"web"};RA&&(ce.payload=RA),await Ft.post(Eq,ce,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"}})}},[e.bot.botId,Ti,e.token,e.user?.id]),jI=vA.useCallback(async()=>{if(e.bot.botId&&Ti){Ye(!0);try{await so(PA)}catch(J){console.error("Error sending first message:",J),Ye(!1)}}},[e.bot.botId,PA,Ti,so]);vA.useEffect(()=>{Ti&&AB&&e?.bot&&Et.length===0&&B&&DA&&(jI(),localStorage.getItem("webChatAuth")&&JSON.parse(localStorage.getItem("webChatAuth"))&&B?.botNeedsAuth&&Ti&&(eB||Mg||fg)&&(setTimeout(()=>{VB(Ti)},2e3),localStorage.setItem("webChatAuth","true")))},[AB,e?.bot,Ti,B]),vA.useEffect(()=>($A==="recording"?zi.current||(zi.current=setInterval(()=>{yi.current+=1;const J=Math.floor(yi.current/60).toString().padStart(2,"0"),jA=(yi.current%60).toString().padStart(2,"0");Pe(`${J}:${jA}`)},1e3)):zi.current&&(clearInterval(zi.current),zi.current=null),()=>{zi.current&&(clearInterval(zi.current),zi.current=null)}),[$A]),vA.useEffect(()=>{Se&&Se.toLowerCase().includes("permission_denied")&&(ri(!1),Pe("00:00"),yi.current=0,zi.current&&(clearInterval(zi.current),zi.current=null),alert("Microphone permission denied. Please allow access to record audio."))},[Se]),vA.useEffect(()=>{$A!=="recording"&&$A!=="paused"&&(Pe("00:00"),yi.current=0)},[$A]);const Oo=vA.useRef(null);vA.useEffect(()=>{if(Oo&&Oo.current){const J=Oo.current;J.style.height="auto";const jA=120;J.scrollHeight>jA?(J.style.height=jA+"px",J.style.overflowY="auto"):(J.style.height=J.scrollHeight+"px",J.style.overflowY="hidden")}},[Ve]),vA.useEffect(()=>{(KA||Re)&&A.current&&(A.current.scrollTop=A.current.scrollHeight)},[Et,Re,KA]);const CE=J=>{const jA=J.type.toLowerCase();return jA.startsWith("image/")?"image":jA.startsWith("video/")?"video":jA.startsWith("audio/")?"audio":"document"},iB=vA.useCallback((J,jA)=>{const RA=[];Array.from(J).forEach(FA=>{if(FA.size>10*1024*1024){alert(`File ${FA.name} is too large. Maximum size is 10MB.`);return}const ce={id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:FA,type:CE(FA),url:URL.createObjectURL(FA),name:FA.name,size:FA.size};RA.push(ce)}),ye(FA=>[...FA,...RA]),jA&&jA.current&&(jA.current.value="")},[]),On=vA.useCallback(J=>{J.preventDefault(),Xe.current=0,Di(!1);const jA=J.dataTransfer.files;jA.length>0&&iB(jA)},[iB]),yr=vA.useCallback(J=>{J.preventDefault(),Xe.current+=1,Di(!0)},[]),AC=vA.useCallback(J=>{J.preventDefault()},[]),Hr=vA.useCallback(J=>{J.preventDefault(),Xe.current-=1,Xe.current<=0&&Di(!1)},[]),dB=vA.useCallback(J=>{ye(jA=>{const RA=jA.find(FA=>FA.id===J);return RA&&URL.revokeObjectURL(RA.url),jA.filter(FA=>FA.id!==J)})},[]),GB=J=>{if(J===0)return"0 Bytes";const jA=1024,RA=["Bytes","KB","MB","GB"],FA=Math.floor(Math.log(J)/Math.log(jA));return Number.parseFloat((J/Math.pow(jA,FA)).toFixed(2))+" "+RA[FA]},Ui=async(J=Ve,jA)=>{if(J.trim()||Ne.length!==0){const FA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"user",content:J,attachments:[...Ne],timestamp:new Date};if(Zi(ce=>[...ce,FA]),je(""),ye([]),Ye(!0),e?.bot)try{if(!Ti){Ye(!1),Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"⚠️ Conversation not initialized. Please try again later.",timestamp:new Date,seen:xo.current,nMessage:1}]);return}await so(J,Ne,jA)}catch{Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Erreur du serveur",timestamp:new Date,seen:xo.current,nMessage:1}]),Ye(!1)}else Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Aucun bot sélectionné",timestamp:new Date,seen:xo.current,nMessage:1}]),Ye(!1)}else return},jg=J=>{switch(ui(!1),J){case"image":i.current?.click();break;case"video":t.current?.click();break;case"audio":g.current?.click();break;case"document":o.current?.click();break}};vA.useEffect(()=>{const J=Et.slice().reverse().find(jA=>jA.sender==="agent");if(J){let jA=!1;Array.isArray(J.content)&&(jA=J.content.some(RA=>RA.type==="text"&&typeof RA.text=="object"&&RA.text.type==="EVFORM")),me(jA)}else me(!1)},[Et]);const[FB,ei]=vA.useState(!1),UB=vA.useRef({x:0,y:0}),Jn=J=>{J.preventDefault(),J.stopPropagation(),yA(!0),ei(!1),UB.current={x:J.clientX,y:J.clientY},ue({x:J.clientX-bA.x,y:J.clientY-bA.y}),document.body.style.cursor="grabbing",document.body.style.userSelect="none"},$E=J=>{J.preventDefault(),J.stopPropagation();const jA=J.touches[0];yA(!0),ei(!1),UB.current={x:jA.clientX,y:jA.clientY},ue({x:jA.clientX-bA.x,y:jA.clientY-bA.y})},Hg=J=>{if(J.preventDefault(),J.stopPropagation(),FB){ei(!1);return}Ee(jA=>!jA),xo.current=!KA,KA||YB(),!DA&&Et.length===0&&jI()};vA.useEffect(()=>{const J=ce=>{if(!uA)return;const pA=Math.abs(ce.clientX-UB.current.x),p=Math.abs(ce.clientY-UB.current.y);(pA>5||p>5)&&ei(!0);const Z=ce.clientX-VA.x,aA=ce.clientY-VA.y,sA=67,dA=window.innerWidth-document.body.clientWidth,zA=Math.max(0,Math.min(window.innerWidth-sA-dA,Z)),Be=Math.max(0,Math.min(window.innerHeight-sA,aA));hA({x:zA,y:Be})},jA=ce=>{if(!uA)return;ce.preventDefault();const pA=ce.touches[0],p=Math.abs(pA.clientX-UB.current.x),Z=Math.abs(pA.clientY-UB.current.y);(p>5||Z>5)&&ei(!0);const aA=pA.clientX-VA.x,sA=pA.clientY-VA.y,dA=67,zA=window.innerWidth-document.body.clientWidth,Be=Math.max(0,Math.min(window.innerWidth-dA-zA,aA)),te=Math.max(0,Math.min(window.innerHeight-dA,sA));hA({x:Be,y:te})},RA=()=>{uA&&(yA(!1),document.body.style.cursor="",document.body.style.userSelect="")},FA=()=>{uA&&yA(!1)};return uA&&(document.addEventListener("mousemove",J),document.addEventListener("touchmove",jA,{passive:!1}),document.addEventListener("mouseup",RA),document.addEventListener("touchend",FA)),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("touchmove",jA),document.removeEventListener("mouseup",RA),document.removeEventListener("touchend",FA)}},[uA,VA,bA]),vA.useEffect(()=>{const J=()=>{const RA=window.innerWidth-67,FA=window.innerHeight-67;hA(ce=>({x:Math.max(0,Math.min(RA,ce.x)),y:Math.max(0,Math.min(FA,ce.y))}))};return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),vA.useEffect(()=>{const J=async()=>{try{await Ft.patch(`${BQ}/widget/endusers/${$o}`,{fiche_contact:{city:Ri.city,platform:Ri.platform,region:Ri.region,country:Ri.country_name,age:0,full_name:eB,gender:"",address:"",company:"","phone 2":"",facebook:"",whatsapp:"",job_title:"",avatar_url:""},user_info:le(Ri)},{headers:{Authorization:`Bearer ${UA}`}}),localStorage.setItem("enduserUpdated","true")}catch(RA){console.error("Error updating end user info:",RA)}};let jA;return Ri&&Ti&&UA&&Et.length>0&&!localStorage.getItem("enduserUpdated")&&(jA=setTimeout(()=>{J()},5e3)),()=>clearTimeout(jA)},[Ri,B,Et,Ti]);const _t=vA.useMemo(()=>({h1:({children:J})=>U.jsx("h1",{className:"sm:text-2xl text-xl font-bold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h2:({children:J})=>U.jsx("h2",{className:"sm:text-xl text-lg font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h3:({children:J})=>U.jsx("h3",{className:"sm:text-lg text-base font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h4:({children:J})=>U.jsx("h4",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h5:({children:J})=>U.jsx("h5",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h6:({children:J})=>U.jsx("h6",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),p:({children:J})=>{const jA=(FA,ce)=>{const pA=wr(FA);return U.jsx("span",{dir:pA?"rtl":"ltr",style:{display:"block",textAlign:pA?"right":"left"},children:U.jsx(ag,{sequence:[FA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70})},ce)};if(typeof J=="string")return U.jsx("div",{className:"leading-relaxed my-0.5",children:jA(J,0)});if(Array.isArray(J)){const FA=[[]];for(const ce of J)ce?.type==="br"?FA.push([]):FA[FA.length-1].push(ce);return U.jsx("div",{className:"leading-relaxed my-0.5",children:FA.map((ce,pA)=>{const p=ce.map(sA=>typeof sA=="string"?sA:"").join(""),Z=wr(p),aA=ce.every(sA=>typeof sA=="string");return U.jsx("span",{dir:Z?"rtl":"ltr",style:{display:"block",textAlign:Z?"right":"left"},children:aA&&p?U.jsx(ag,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70}):ce},pA)})})}const RA=!!(J?.props?.children&&wr(String(J?.props?.children??"")));return U.jsx("div",{className:"leading-relaxed my-0.5",dir:RA?"rtl":"ltr",children:J})},ul:({children:J})=>U.jsx("ul",{className:"list-disc list-inside ml-2 my-2",style:{color:v},dir:wr(J)?"rtl":"ltr",children:J}),ol:({children:J})=>{let jA=!1;return J.filter(RA=>typeof RA!="string").every(RA=>wr(RA?.props?.children))?jA=!0:jA=!1,U.jsx("ol",{className:"list-decimal list-inside ml-2 my-2",style:{color:v},dir:jA?"rtl":"ltr",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J})},li:({children:J})=>U.jsx("li",{className:"my-1",dir:sr(J)?"rtl":"ltr",style:{color:v},children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),a:({href:J,children:jA})=>U.jsx("a",{href:J,className:"text-blue-400 underline hover:text-blue-300",target:"_blank",rel:"noopener noreferrer",children:typeof jA=="string"?U.jsx(ag,{sequence:[jA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):jA}),blockquote:({children:J})=>U.jsx("blockquote",{className:"border-l-4 pl-4 italic my-2",style:{borderColor:X,color:v},children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),code({node:J,className:jA,children:RA,...FA}){const ce=/language-(\w+)/.exec(jA||"");return ce?U.jsx(oV,{...FA,PreTag:"div",children:String(RA).replace(/\n$/,""),language:ce[1],style:_CA,customStyle:{scrollbarWidth:"thin"}}):U.jsx("code",{className:"px-1 rounded font-mono inline",style:{backgroundColor:u,color:v},...FA,children:typeof RA=="string"?U.jsx(ag,{sequence:[RA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):RA})},table:({children:J})=>U.jsx("table",{className:"min-w-full my-2",style:{border:`1px solid ${v}`,color:P,backgroundColor:v},children:J}),thead:({children:J})=>U.jsx("thead",{children:J}),tbody:({children:J})=>U.jsx("tbody",{children:J}),tr:({children:J})=>U.jsx("tr",{style:{border:`1px solid ${P}`},children:J}),th:({children:J})=>U.jsx("th",{className:"px-3 py-2 font-bold text-left",children:J}),td:({children:J})=>U.jsx("td",{className:"px-3 py-2",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),strong:({children:J})=>U.jsx("strong",{className:"font-bold",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),em:({children:J})=>U.jsx("em",{className:"italic ",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),hr:()=>U.jsx("hr",{className:"my-4",style:{borderColor:`1px solid ${v}`}})}),[G,v,X,u,K]);vA.useEffect(()=>{const J=jA=>{We&&jA.target instanceof Element&&!jA.composedPath().some(RA=>RA?.id==="upload-button-toggle"||RA?.id==="document-button"||RA?.id==="image-button"||RA?.id==="video-button"||RA?.id==="audio-button")&&ui(!1)};return document.addEventListener("mousedown",J),()=>{document.removeEventListener("mousedown",J)}},[We]);const $g=(J,jA="formulaire soumis")=>{if(!J||typeof J!="object")return null;const RA=J;return Array.isArray(RA.fields)?U.jsx(rcA,{definition:RA,onValidate:FA=>{const ce=RA.submitType?{...FA,type:RA.submitType}:FA;Ui(RA.submitMessage||jA,ce)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u}):null},Jo=J=>{switch(J.type){case"text":if(Array.isArray(J.text))switch(J.text[0].type){case"form":const RA=$g(J.text[0].definition||J.text[0].items||J.text[0],"formulaire soumis");if(RA)return RA;break;case"products":return U.jsx(El,{products:J.text[0].items||[],onValidate:FA=>{Ui("cart",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA});case"easyspaceform":return U.jsx(IV,{onValidate:FA=>{Ui("easyspace-form-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"xcmgform":return U.jsx(y1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,formVars:JSON.parse(J.text[0])});case"auditec-form":return U.jsx(K1,{onValidate:FA=>{Ui("auditec-form-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"auditec-form-ar":return U.jsx(k1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"nousserform":return U.jsx(x1,{onValidate:FA=>{Ui("nousserform-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadaraform":case"Jadaraform":case"JadaraForm":return U.jsx(H1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadara-form-ar":return U.jsx(N1,{onValidate:FA=>{Ui("✅ تم استلام الطلب بنجاح",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}else try{const RA=typeof J.text=="string"?JSON.parse(J.text):J.text;switch(RA.type.toLowerCase()){case"form":{const FA=$g(RA.definition||RA.items||RA,"formulaire soumis");return FA||U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}case"products":return U.jsx(El,{products:RA[0].items||[],onValidate:FA=>{Ui("cart",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA});case"easyspaceform":return U.jsx(IV,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"evform":return U.jsx(tcA,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,mainColor:H});case"evform-visiteur":return U.jsx(gcA,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,mainColor:H});case"xcmgform":return U.jsx(y1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,formVars:RA?.items||{}});case"auditec-form":return U.jsx(K1,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"auditec-form-ar":return U.jsx(k1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"nousserform":return U.jsx(x1,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadaraform":case"Jadaraform":case"JadaraForm":return U.jsx(H1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadara-form-ar":return U.jsx(N1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}}catch{return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}case"single-choice":return U.jsxs(U.Fragment,{children:[U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)||""}),U.jsx("div",{className:"mt-2 flex flex-col gap-1",dir:sr(J.text||"")?"rtl":"ltr",children:J.choices?.map((RA,FA)=>U.jsxs("button",{onClick:()=>Ui(RA.title),className:"w-full flex items-center justify-between px-4 py-2.5 hover:opacity-95 transition-all duration-100",style:{background:EA,borderRadius:"18px",color:v,border:`2px solid ${qg(EA,20)}`},onMouseEnter:ce=>{ce.currentTarget.style.borderColor=`${X}`},onMouseLeave:ce=>{ce.currentTarget.style.border=`2px solid ${qg(EA,15)}`},dir:wr(RA.title)?"rtl":"ltr",children:[U.jsx("div",{className:"w-full flex items-start gap-2",children:U.jsx(ag,{sequence:[RA.title,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92})}),U.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center"},children:wr(RA.title)?U.jsx(wx,{className:"w-4 h-4",color:X}):U.jsx(cx,{className:"w-4 h-4",color:X})})]},FA))})]});case"image":return U.jsx(U.Fragment,{children:U.jsx("div",{className:"relative group",children:U.jsx("img",{src:J.image,className:"max-w-full max-h-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(J.image,"_blank")})})});case"dropdown":return U.jsxs(U.Fragment,{children:[U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.message)}),U.jsx(ncA,{options:J.options||[],message:J.message,allowMultiple:J.allowMultiple||!1,chatRoundness:K,buttonsBgColor:X,buttonColor:y,agentChatResponseColor:v,agentChatResponseBgColor:P,isRtl:sr(J.message||""),onSend:Ui,onScroll:()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}})]});case"carousel":return U.jsx(up,{items:J.items||[],chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"card":return U.jsx("div",{className:"mt-2 w-full",children:U.jsx("div",{className:"grid grid-cols-1 gap-3",children:U.jsxs("div",{className:"flex-shrink-0 border rounded-lg p-3 shadow-md",style:{background:P},children:[U.jsx("img",{src:J.image,alt:J.title,className:"max-h-48 w-full object-contain rounded-md mb-2"}),U.jsx("h3",{className:"font-bold",children:J.title}),J.actions?.map((RA,FA)=>U.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{RA.action==="Open URL"?window.open(RA.url,"_blank"):RA.title==="scan"?J.image&&fetch(J.image).then(ce=>ce.blob()).then(ce=>{const pA=URL.createObjectURL(ce),p=document.createElement("a");p.href=pA,p.download="qrcode.png",document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(pA)}).catch(()=>{alert("Failed to download image.")}):Ui(J.title,RA.payload||void 0)},style:{background:X,borderRadius:`${K}px`,color:y},children:RA.title},FA))]})})});case"video":return U.jsx("div",{className:"relative group w-[250px]",children:U.jsx("video",{src:J.video,className:"w-full rounded-lg cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"file":const jA=J.file?.split(".").pop?.()?.toLowerCase()||"";return U.jsx("div",{className:"p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(J.file,"_blank"),onMouseEnter:RA=>RA.currentTarget.style.backgroundColor=X,onMouseLeave:RA=>RA.currentTarget.style.backgroundColor="transparent",title:J.title,children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{background:X},children:rq(jA,v)}),U.jsx("div",{className:"flex-1 min-w-0",children:U.jsx("p",{className:"text-sm font-medium truncate",style:{color:v},children:J.title})})]})});case"products":return U.jsx(El,{products:J.products||[],onValidate:RA=>{Ui("cart ",RA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"json":switch(J.json?.type){case"text":return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.json.content)});case"image":return U.jsx("div",{className:"relative group",children:U.jsx("img",{src:J.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(J.json?.content,"_blank")})});case"video":return U.jsx("div",{className:"relative group",children:U.jsx("video",{src:J.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"document":const RA=J.json.content.split(".").pop?.()?.toLowerCase();return U.jsx("div",{className:"w-[300px] p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(J.json?.content,"_blank"),onMouseEnter:pA=>pA.currentTarget.style.backgroundColor=X,onMouseLeave:pA=>pA.currentTarget.style.backgroundColor="transparent",title:J.json?.title,children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{background:X},children:rq(RA||"",v)}),U.jsx("div",{className:"flex-1 min-w-0",children:U.jsx("p",{className:"text-sm font-medium truncate",style:{color:v},children:J.json.title})})]})});case"audio":return U.jsx("div",{className:"w-[300px]",children:U.jsx(L1,{src:J.json.content,mainColor:c,secondaryColor:w,controlsColor:v})});case"cards":return J.json.content.map((pA,p)=>U.jsx("div",{className:"mt-2 w-full",children:U.jsx("div",{className:"grid grid-cols-1 gap-3",children:U.jsxs("div",{className:"flex-shrink-0 border rounded-lg p-3 shadow-md",style:{background:P},children:[U.jsx("img",{src:pA.image,alt:pA.title,className:"max-h-48 w-full rounded-md mb-2"}),U.jsx("h3",{className:"font-bold",children:pA.title}),pA.button?.map((Z,aA)=>U.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{if(Z.type==="link"&&typeof Z.action=="string")window.open(Z.action,"_blank");else if(Z.type==="postback"){const sA=(typeof Z.action=="string",Z.action);Ui(Z.label,sA)}else Z.type==="say-something"&&typeof Z.action=="string"&&Zi(sA=>[...sA,{sender:"agent",content:Z.action,id:`msg-${Date.now()}`,timestamp:new Date,seen:!0}])},style:{background:X,borderRadius:`${K}px`,color:y},children:Z.label},aA))]})})},p));case"slider":const FA=J.json.content.map(pA=>({image:pA.image,title:pA.caption,subtitle:"",actions:[]}));return U.jsx(up,{items:FA,chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"carousel":const ce=J.json.content.map(pA=>({image:pA.image,title:pA.title,subtitle:pA.description||"",actions:pA.button?.map(p=>({title:p.label,payload:p.action,action:p.type,url:typeof p.action=="string"?p.action:""}))||[]}));return U.jsx(up,{items:ce,chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"products":return U.jsx(El,{products:J.json.content,onValidate:pA=>{Ui("cart ",pA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return null}}},Nr=async J=>{if(!AB)return;const jA=await fetch(`${BQ}/endusers/get-by-username`,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({username:`web_user_${J}`})});if(!jA.ok)throw new Error(`HTTP error! status: ${jA.status}`);return(await jA.json()).id},VB=async J=>{if(!AB)return;const jA=await Nr(J);let RA;eB&&(RA={last_name:eB.split(" ")[1]||eB.split(" ")[0]||`web_user_${J}`,first_name:eB.split(" ")[0]||`web_user_${J}`}),fg&&(RA={...RA,phone:fg}),Mg&&(RA={...RA,email:Mg});const FA=await fetch(`${BQ}/endusers/${jA}`,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"},method:"PUT",body:JSON.stringify(RA)});if(!FA.ok)throw new Error(`HTTP error! status: ${FA.status}`);return await FA.json()},LI=async J=>{J.preventDefault();try{const RA=(await Ft.post(`${BQ}/conversations/start-conversation`,{bot_id:e.bot?.botId,externalUser:e.user.id})).data.conversationId;_o(RA),localStorage.setItem("conversationId",RA),localStorage.setItem("webChatAuth","true"),bi(!0),EQ.emit("join_room",parseInt(RA))}catch(jA){console.error("Error during login:",jA)}},[mB,wo]=vA.useState(!1),AI=async()=>{Zi([]),localStorage.removeItem("enduserUpdated");const J=localStorage.getItem("phone_client");if(e.bot?.botId==="rockskin"&&J)return vE(J),localStorage.setItem("externalUser",J),J;const jA=new Uint8Array(16);window.crypto.getRandomValues(jA);const RA=Array.from(jA).map(FA=>FA.toString(16).padStart(2,"0")).join("");vE(RA),localStorage.setItem("externalUser",RA),localStorage.removeItem("conversationId"),_o(null)},Ng=`linear-gradient(to bottom right, ${l}, ${c}, ${l})`,fo=`linear-gradient(to right, ${c}, ${w})`,QE=`linear-gradient(to right, ${D}, ${d})`,tB=async(J,jA)=>{try{let RA="";if(typeof J=="string")RA=J;else for(const FA of J)FA.type==="text"&&FA.text?RA+=`
|
|
635
|
+
***************************************************************************** */function f1(e,A){const[i,t]=vA.useState(null),g=vA.useMemo(()=>Object.entries(A).flat(),[A]);return vA.useEffect(()=>{if(!e?.current)return;const o=dp.create(Object.assign(Object.assign({},A),{container:e.current}));return t(o),()=>{o.destroy()}},[e,...g]),i}const j1=/^on([A-Z])/,ccA=e=>j1.test(e);function hcA(e,A){const i=vA.useMemo(()=>Object.entries(A).flat(),[A]);vA.useEffect(()=>{if(!e)return;const t=Object.entries(A);if(!t.length)return;const g=t.map(([o,B])=>{const I=o.replace(j1,(r,a)=>a.toLowerCase());return e.on(I,(...r)=>B(e,...r))});return()=>{g.forEach(o=>o())}},[e,...i])}vA.memo(e=>{const A=vA.useRef(null),[i,t]=function(g){return vA.useMemo(()=>{const o=Object.assign({},g),B=Object.assign({},g);for(const I in o)ccA(I)?delete o[I]:delete B[I];return[o,B]},[g])}(e);return hcA(f1(A,i),t),U.jsx("div",{ref:A})});function lcA(e){var{container:A}=e;const i=f1(A,function(g,o){var B={};for(var I in g)Object.prototype.hasOwnProperty.call(g,I)&&o.indexOf(I)<0&&(B[I]=g[I]);if(g!=null&&typeof Object.getOwnPropertySymbols=="function"){var r=0;for(I=Object.getOwnPropertySymbols(g);r<I.length;r++)o.indexOf(I[r])<0&&Object.prototype.propertyIsEnumerable.call(g,I[r])&&(B[I[r]]=g[I[r]])}return B}(e,["container"])),t=function(g){const[o,B]=vA.useState(!1),[I,r]=vA.useState(!1),[a,C]=vA.useState(!1),[s,c]=vA.useState(0);return vA.useEffect(()=>{if(!g)return;const w=[g.on("load",()=>{B(!1),r(!1),c(0)}),g.on("ready",()=>{B(!0),r(!1),C(!1),c(0)}),g.on("finish",()=>{C(!0)}),g.on("play",()=>{r(!0)}),g.on("pause",()=>{r(!1)}),g.on("timeupdate",()=>{c(g.getCurrentTime())}),g.on("destroy",()=>{B(!1),r(!1)})];return()=>{w.forEach(l=>l())}},[g]),vA.useMemo(()=>({isReady:o,isPlaying:I,hasFinished:a,currentTime:s}),[I,a,s,o])}(i);return vA.useMemo(()=>Object.assign(Object.assign({},t),{wavesurfer:i}),[t,i])}const L1=({src:e,mainColor:A,secondaryColor:i,controlsColor:t})=>{const g=vA.useRef(null),[o,B]=vA.useState(1),{wavesurfer:I,isPlaying:r}=lcA({container:g,waveColor:A,progressColor:i,barWidth:2,height:50,url:e}),a=()=>{I&&I.playPause()},C=()=>{const w=o===0?1:0;B(w),I?.setVolume(w)},s=()=>{I?.skip(-.096)},c=()=>{I?.skip(.096)};return U.jsxs("div",{className:"flex w-full flex-col items-center rounded-xl pt-1",children:[U.jsx("div",{ref:g,className:"w-full px-2"}),U.jsxs("div",{className:"flex w-full items-center justify-between",children:[U.jsx("div",{className:"relative flex items-center",children:U.jsx("button",{className:"transition-colors",style:{color:t},onClick:C,"aria-label":"Toggle volume",children:o===0?U.jsx(qiA,{size:20}):U.jsx(ziA,{size:20})})}),U.jsxs("div",{className:"-ml-9 flex flex-1 cursor-auto justify-center gap-2 rounded-full py-2 text-white",children:[U.jsx("button",{onClick:s,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":"Step back",children:U.jsx(TiA,{})}),U.jsx("button",{onClick:a,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":r?"Pause":"Play",children:r?U.jsx(OiA,{}):U.jsx(JiA,{})}),U.jsx("button",{onClick:c,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:t},"aria-label":"Step forward",children:U.jsx(biA,{})})]})]})]})},McA=({attachment:e,formatFileSize:A,mainColor:i,secondaryColor:t,controlsColor:g})=>{const{type:o,url:B,name:I,size:r}=e;switch(o){case"image":return U.jsxs("div",{className:"relative group",children:[U.jsx("img",{src:B,alt:I,className:"max-w-xs max-h-48 size-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(B,"_blank")}),U.jsx("div",{className:"absolute bottom-2 left-2 bg-black bg-opacity-60 text-white text-xs px-2 py-1 rounded",children:A(r)})]});case"video":return U.jsxs("div",{className:"max-w-xs",children:[U.jsx("video",{src:B,controls:!0,className:"w-full max-h-48 rounded-lg",preload:"metadata",onError:()=>{console.error("Video failed to load:",B)},children:"Your browser does not support the video tag."}),U.jsxs("div",{className:"flex text-xs text-white mt-1 w-full overflow-hidden whitespace-nowrap text-ellipsis",children:[U.jsx("span",{className:"block w-full overflow-hidden whitespace-nowrap text-ellipsis",title:I,children:I}),U.jsxs("span",{className:"ml-2",children:["• ",A(r)]})]})]});case"audio":return U.jsxs("div",{className:"bg-gray-800 bg-opacity-70 p-3 rounded-lg flex-1 w-full",children:[U.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[U.jsx(zu,{className:"w-4 h-4",style:{color:i}}),U.jsx("span",{className:"text-sm font-medium truncate text-white",title:I,children:I})]}),U.jsx(L1,{src:B,mainColor:i,secondaryColor:t,controlsColor:g}),U.jsx("p",{className:"text-xs text-gray-400 mt-1",children:A(r)})]});case"document":return U.jsx("div",{className:"bg-gray-800 bg-opacity-50 p-3 rounded-lg max-w-xs cursor-pointer hover:bg-opacity-70 transition-colors",onClick:()=>window.open(B,"_blank"),children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 bg-purple-600 rounded-lg flex items-center justify-center",children:U.jsx(Bn,{className:"w-5 h-5 text-white"})}),U.jsxs("div",{className:"flex-1 min-w-0",children:[U.jsx("p",{className:"text-sm font-medium truncate text-white",children:I}),U.jsx("p",{className:"text-xs text-gray-400",children:A(r)})]})]})});default:return null}},DcA=vA.memo(({attachment:e,onRemove:A})=>U.jsxs("div",{className:"relative group w-24 h-24 rounded-xl overflow-hidden bg-gray-900 shadow-md border border-gray-700",children:[e.type==="image"&&e.url?U.jsx("img",{src:e.url,alt:e.name,className:"w-full h-full object-cover"}):U.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center text-gray-300 px-1 text-center text-xs",children:[e.type==="video"&&U.jsx(Rx,{className:"w-5 h-5 mb-1 text-red-400"}),e.type==="audio"&&U.jsx(zu,{className:"w-5 h-5 mb-1 text-green-400"}),e.type==="document"&&U.jsx(hx,{className:"w-5 h-5 mb-1 text-yellow-400"}),U.jsx("span",{className:"w-full truncate",title:e.name,children:e.name})]}),U.jsx("button",{onClick:A,className:"absolute top-1 right-1 w-5 h-5 bg-black bg-opacity-50 rounded-full text-white flex items-center justify-center hover:bg-opacity-80",title:"Remove",children:U.jsx(nr,{className:"w-3 h-3"})})]})),HI=Object.create(null);HI.open="0",HI.close="1",HI.ping="2",HI.pong="3",HI.message="4",HI.upgrade="5",HI.noop="6";const rl=Object.create(null);Object.keys(HI).forEach(e=>{rl[HI[e]]=e});const Gp={type:"error",data:"parser error"},T1=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",b1=typeof ArrayBuffer=="function",V1=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Fp=({type:e,data:A},i,t)=>T1&&A instanceof Blob?i?t(A):z1(A,t):b1&&(A instanceof ArrayBuffer||V1(A))?i?t(A):z1(new Blob([A]),t):t(HI[e]+(A||"")),z1=(e,A)=>{const i=new FileReader;return i.onload=function(){const t=i.result.split(",")[1];A("b"+(t||""))},i.readAsDataURL(e)};function q1(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Up;function ucA(e,A){if(T1&&e.data instanceof Blob)return e.data.arrayBuffer().then(q1).then(A);if(b1&&(e.data instanceof ArrayBuffer||V1(e.data)))return A(q1(e.data));Fp(e,!1,i=>{Up||(Up=new TextEncoder),A(Up.encode(i))})}const Z1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Aw=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<Z1.length;e++)Aw[Z1.charCodeAt(e)]=e;const RcA=e=>{let A=e.length*.75,i=e.length,t,g=0,o,B,I,r;e[e.length-1]==="="&&(A--,e[e.length-2]==="="&&A--);const a=new ArrayBuffer(A),C=new Uint8Array(a);for(t=0;t<i;t+=4)o=Aw[e.charCodeAt(t)],B=Aw[e.charCodeAt(t+1)],I=Aw[e.charCodeAt(t+2)],r=Aw[e.charCodeAt(t+3)],C[g++]=o<<2|B>>4,C[g++]=(B&15)<<4|I>>2,C[g++]=(I&3)<<6|r&63;return a},YcA=typeof ArrayBuffer=="function",mp=(e,A)=>{if(typeof e!="string")return{type:"message",data:W1(e,A)};const i=e.charAt(0);return i==="b"?{type:"message",data:dcA(e.substring(1),A)}:rl[i]?e.length>1?{type:rl[i],data:e.substring(1)}:{type:rl[i]}:Gp},dcA=(e,A)=>{if(YcA){const i=RcA(e);return W1(i,A)}else return{base64:!0,data:e}},W1=(e,A)=>{switch(A){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},P1="",GcA=(e,A)=>{const i=e.length,t=new Array(i);let g=0;e.forEach((o,B)=>{Fp(o,!1,I=>{t[B]=I,++g===i&&A(t.join(P1))})})},FcA=(e,A)=>{const i=e.split(P1),t=[];for(let g=0;g<i.length;g++){const o=mp(i[g],A);if(t.push(o),o.type==="error")break}return t};function UcA(){return new TransformStream({transform(e,A){ucA(e,i=>{const t=i.length;let g;if(t<126)g=new Uint8Array(1),new DataView(g.buffer).setUint8(0,t);else if(t<65536){g=new Uint8Array(3);const o=new DataView(g.buffer);o.setUint8(0,126),o.setUint16(1,t)}else{g=new Uint8Array(9);const o=new DataView(g.buffer);o.setUint8(0,127),o.setBigUint64(1,BigInt(t))}e.data&&typeof e.data!="string"&&(g[0]|=128),A.enqueue(g),A.enqueue(i)})}})}let pp;function nl(e){return e.reduce((A,i)=>A+i.length,0)}function al(e,A){if(e[0].length===A)return e.shift();const i=new Uint8Array(A);let t=0;for(let g=0;g<A;g++)i[g]=e[0][t++],t===e[0].length&&(e.shift(),t=0);return e.length&&t<e[0].length&&(e[0]=e[0].slice(t)),i}function mcA(e,A){pp||(pp=new TextDecoder);const i=[];let t=0,g=-1,o=!1;return new TransformStream({transform(B,I){for(i.push(B);;){if(t===0){if(nl(i)<1)break;const r=al(i,1);o=(r[0]&128)===128,g=r[0]&127,g<126?t=3:g===126?t=1:t=2}else if(t===1){if(nl(i)<2)break;const r=al(i,2);g=new DataView(r.buffer,r.byteOffset,r.length).getUint16(0),t=3}else if(t===2){if(nl(i)<8)break;const r=al(i,8),a=new DataView(r.buffer,r.byteOffset,r.length),C=a.getUint32(0);if(C>Math.pow(2,21)-1){I.enqueue(Gp);break}g=C*Math.pow(2,32)+a.getUint32(4),t=3}else{if(nl(i)<g)break;const r=al(i,g);I.enqueue(mp(o?r:pp.decode(r),A)),t=0}if(g===0||g>e){I.enqueue(Gp);break}}}})}const v1=4;function Sg(e){if(e)return pcA(e)}function pcA(e){for(var A in Sg.prototype)e[A]=Sg.prototype[A];return e}Sg.prototype.on=Sg.prototype.addEventListener=function(e,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(A),this},Sg.prototype.once=function(e,A){function i(){this.off(e,i),A.apply(this,arguments)}return i.fn=A,this.on(e,i),this},Sg.prototype.off=Sg.prototype.removeListener=Sg.prototype.removeAllListeners=Sg.prototype.removeEventListener=function(e,A){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var i=this._callbacks["$"+e];if(!i)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var t,g=0;g<i.length;g++)if(t=i[g],t===A||t.fn===A){i.splice(g,1);break}return i.length===0&&delete this._callbacks["$"+e],this},Sg.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var A=new Array(arguments.length-1),i=this._callbacks["$"+e],t=1;t<arguments.length;t++)A[t-1]=arguments[t];if(i){i=i.slice(0);for(var t=0,g=i.length;t<g;++t)i[t].apply(this,A)}return this},Sg.prototype.emitReserved=Sg.prototype.emit,Sg.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Sg.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Cl=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,i)=>i(A,0),gE=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),ScA="arraybuffer";function eSA(){}function X1(e,...A){return A.reduce((i,t)=>(e.hasOwnProperty(t)&&(i[t]=e[t]),i),{})}const KcA=gE.setTimeout,kcA=gE.clearTimeout;function Ql(e,A){A.useNativeTimers?(e.setTimeoutFn=KcA.bind(gE),e.clearTimeoutFn=kcA.bind(gE)):(e.setTimeoutFn=gE.setTimeout.bind(gE),e.clearTimeoutFn=gE.clearTimeout.bind(gE))}const ycA=1.33;function HcA(e){return typeof e=="string"?NcA(e):Math.ceil((e.byteLength||e.size)*ycA)}function NcA(e){let A=0,i=0;for(let t=0,g=e.length;t<g;t++)A=e.charCodeAt(t),A<128?i+=1:A<2048?i+=2:A<55296||A>=57344?i+=3:(t++,i+=4);return i}function _1(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function xcA(e){let A="";for(let i in e)e.hasOwnProperty(i)&&(A.length&&(A+="&"),A+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return A}function OcA(e){let A={},i=e.split("&");for(let t=0,g=i.length;t<g;t++){let o=i[t].split("=");A[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return A}class JcA extends Error{constructor(A,i,t){super(A),this.description=i,this.context=t,this.type="TransportError"}}class Sp extends Sg{constructor(A){super(),this.writable=!1,Ql(this,A),this.opts=A,this.query=A.query,this.socket=A.socket,this.supportsBinary=!A.forceBase64}onError(A,i,t){return super.emitReserved("error",new JcA(A,i,t)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(A){this.readyState==="open"&&this.write(A)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(A){const i=mp(A,this.socket.binaryType);this.onPacket(i)}onPacket(A){super.emitReserved("packet",A)}onClose(A){this.readyState="closed",super.emitReserved("close",A)}pause(A){}createUri(A,i={}){return A+"://"+this._hostname()+this._port()+this.opts.path+this._query(i)}_hostname(){const A=this.opts.hostname;return A.indexOf(":")===-1?A:"["+A+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(A){const i=xcA(A);return i.length?"?"+i:""}}class fcA extends Sp{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(A){this.readyState="pausing";const i=()=>{this.readyState="paused",A()};if(this._polling||!this.writable){let t=0;this._polling&&(t++,this.once("pollComplete",function(){--t||i()})),this.writable||(t++,this.once("drain",function(){--t||i()}))}else i()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(A){const i=t=>{if(this.readyState==="opening"&&t.type==="open"&&this.onOpen(),t.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)};FcA(A,this.socket.binaryType).forEach(i),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const A=()=>{this.write([{type:"close"}])};this.readyState==="open"?A():this.once("open",A)}write(A){this.writable=!1,GcA(A,i=>{this.doWrite(i,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const A=this.opts.secure?"https":"http",i=this.query||{};return this.opts.timestampRequests!==!1&&(i[this.opts.timestampParam]=_1()),!this.supportsBinary&&!i.sid&&(i.b64=1),this.createUri(A,i)}}let $1=!1;try{$1=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const jcA=$1;function LcA(){}class TcA extends fcA{constructor(A){if(super(A),typeof location<"u"){const i=location.protocol==="https:";let t=location.port;t||(t=i?"443":"80"),this.xd=typeof location<"u"&&A.hostname!==location.hostname||t!==A.port}}doWrite(A,i){const t=this.request({method:"POST",data:A});t.on("success",i),t.on("error",(g,o)=>{this.onError("xhr post error",g,o)})}doPoll(){const A=this.request();A.on("data",this.onData.bind(this)),A.on("error",(i,t)=>{this.onError("xhr poll error",i,t)}),this.pollXhr=A}}let gQ=class HD extends Sg{constructor(A,i,t){super(),this.createRequest=A,Ql(this,t),this._opts=t,this._method=t.method||"GET",this._uri=i,this._data=t.data!==void 0?t.data:null,this._create()}_create(){var A;const i=X1(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");i.xdomain=!!this._opts.xd;const t=this._xhr=this.createRequest(i);try{t.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let g in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(g)&&t.setRequestHeader(g,this._opts.extraHeaders[g])}}catch{}if(this._method==="POST")try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{t.setRequestHeader("Accept","*/*")}catch{}(A=this._opts.cookieJar)===null||A===void 0||A.addCookies(t),"withCredentials"in t&&(t.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(t.timeout=this._opts.requestTimeout),t.onreadystatechange=()=>{var g;t.readyState===3&&((g=this._opts.cookieJar)===null||g===void 0||g.parseCookies(t.getResponseHeader("set-cookie"))),t.readyState===4&&(t.status===200||t.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof t.status=="number"?t.status:0)},0))},t.send(this._data)}catch(g){this.setTimeoutFn(()=>{this._onError(g)},0);return}typeof document<"u"&&(this._index=HD.requestsCount++,HD.requests[this._index]=this)}_onError(A){this.emitReserved("error",A,this._xhr),this._cleanup(!0)}_cleanup(A){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=LcA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete HD.requests[this._index],this._xhr=null}}_onLoad(){const A=this._xhr.responseText;A!==null&&(this.emitReserved("data",A),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(gQ.requestsCount=0,gQ.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Aq);else if(typeof addEventListener=="function"){const e="onpagehide"in gE?"pagehide":"unload";addEventListener(e,Aq,!1)}}function Aq(){for(let e in gQ.requests)gQ.requests.hasOwnProperty(e)&&gQ.requests[e].abort()}const bcA=function(){const e=eq({xdomain:!1});return e&&e.responseType!==null}();class VcA extends TcA{constructor(A){super(A);const i=A&&A.forceBase64;this.supportsBinary=bcA&&!i}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new gQ(eq,this.uri(),A)}}function eq(e){const A=e.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||jcA))return new XMLHttpRequest}catch{}if(!A)try{return new gE[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const iq=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class zcA extends Sp{get name(){return"websocket"}doOpen(){const A=this.uri(),i=this.opts.protocols,t=iq?{}:X1(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(t.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(A,i,t)}catch(g){return this.emitReserved("error",g)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=A=>this.onClose({description:"websocket connection closed",context:A}),this.ws.onmessage=A=>this.onData(A.data),this.ws.onerror=A=>this.onError("websocket error",A)}write(A){this.writable=!1;for(let i=0;i<A.length;i++){const t=A[i],g=i===A.length-1;Fp(t,this.supportsBinary,o=>{try{this.doWrite(t,o)}catch{}g&&Cl(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const A=this.opts.secure?"wss":"ws",i=this.query||{};return this.opts.timestampRequests&&(i[this.opts.timestampParam]=_1()),this.supportsBinary||(i.b64=1),this.createUri(A,i)}}const Kp=gE.WebSocket||gE.MozWebSocket;class qcA extends zcA{createSocket(A,i,t){return iq?new Kp(A,i,t):i?new Kp(A,i):new Kp(A)}doWrite(A,i){this.ws.send(i)}}class ZcA extends Sp{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(A){return this.emitReserved("error",A)}this._transport.closed.then(()=>{this.onClose()}).catch(A=>{this.onError("webtransport error",A)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(A=>{const i=mcA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),t=A.readable.pipeThrough(i).getReader(),g=UcA();g.readable.pipeTo(A.writable),this._writer=g.writable.getWriter();const o=()=>{t.read().then(({done:I,value:r})=>{I||(this.onPacket(r),o())}).catch(I=>{})};o();const B={type:"open"};this.query.sid&&(B.data=`{"sid":"${this.query.sid}"}`),this._writer.write(B).then(()=>this.onOpen())})})}write(A){this.writable=!1;for(let i=0;i<A.length;i++){const t=A[i],g=i===A.length-1;this._writer.write(t).then(()=>{g&&Cl(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const WcA={websocket:qcA,webtransport:ZcA,polling:VcA},PcA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vcA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function kp(e){if(e.length>8e3)throw"URI too long";const A=e,i=e.indexOf("["),t=e.indexOf("]");i!=-1&&t!=-1&&(e=e.substring(0,i)+e.substring(i,t).replace(/:/g,";")+e.substring(t,e.length));let g=PcA.exec(e||""),o={},B=14;for(;B--;)o[vcA[B]]=g[B]||"";return i!=-1&&t!=-1&&(o.source=A,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=XcA(o,o.path),o.queryKey=_cA(o,o.query),o}function XcA(e,A){const i=/\/{2,9}/g,t=A.replace(i,"/").split("/");return(A.slice(0,1)=="/"||A.length===0)&&t.splice(0,1),A.slice(-1)=="/"&&t.splice(t.length-1,1),t}function _cA(e,A){const i={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,g,o){g&&(i[g]=o)}),i}const yp=typeof addEventListener=="function"&&typeof removeEventListener=="function",sl=[];yp&&addEventListener("offline",()=>{sl.forEach(e=>e())},!1);class Rn extends Sg{constructor(A,i){if(super(),this.binaryType=ScA,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,A&&typeof A=="object"&&(i=A,A=null),A){const t=kp(A);i.hostname=t.host,i.secure=t.protocol==="https"||t.protocol==="wss",i.port=t.port,t.query&&(i.query=t.query)}else i.host&&(i.hostname=kp(i.host).host);Ql(this,i),this.secure=i.secure!=null?i.secure:typeof location<"u"&&location.protocol==="https:",i.hostname&&!i.port&&(i.port=this.secure?"443":"80"),this.hostname=i.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=i.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},i.transports.forEach(t=>{const g=t.prototype.name;this.transports.push(g),this._transportsByName[g]=t}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},i),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=OcA(this.opts.query)),yp&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},sl.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const i=Object.assign({},this.opts.query);i.EIO=v1,i.transport=A,this.id&&(i.sid=this.id);const t=Object.assign({},this.opts,{query:i,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[A]);return new this._transportsByName[A](t)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const A=this.opts.rememberUpgrade&&Rn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const i=this.createTransport(A);i.open(),this.setTransport(i)}setTransport(A){this.transport&&this.transport.removeAllListeners(),this.transport=A,A.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",i=>this._onClose("transport close",i))}onOpen(){this.readyState="open",Rn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(A){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",A),this.emitReserved("heartbeat"),A.type){case"open":this.onHandshake(JSON.parse(A.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const i=new Error("server error");i.code=A.data,this._onError(i);break;case"message":this.emitReserved("data",A.data),this.emitReserved("message",A.data);break}}onHandshake(A){this.emitReserved("handshake",A),this.id=A.sid,this.transport.query.sid=A.sid,this._pingInterval=A.pingInterval,this._pingTimeout=A.pingTimeout,this._maxPayload=A.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const A=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+A,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},A),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const A=this._getWritablePackets();this.transport.send(A),this._prevBufferLen=A.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let i=1;for(let t=0;t<this.writeBuffer.length;t++){const g=this.writeBuffer[t].data;if(g&&(i+=HcA(g)),t>0&&i>this._maxPayload)return this.writeBuffer.slice(0,t);i+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const A=Date.now()>this._pingTimeoutTime;return A&&(this._pingTimeoutTime=0,Cl(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),A}write(A,i,t){return this._sendPacket("message",A,i,t),this}send(A,i,t){return this._sendPacket("message",A,i,t),this}_sendPacket(A,i,t,g){if(typeof i=="function"&&(g=i,i=void 0),typeof t=="function"&&(g=t,t=null),this.readyState==="closing"||this.readyState==="closed")return;t=t||{},t.compress=t.compress!==!1;const o={type:A,data:i,options:t};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),g&&this.once("flush",g),this.flush()}close(){const A=()=>{this._onClose("forced close"),this.transport.close()},i=()=>{this.off("upgrade",i),this.off("upgradeError",i),A()},t=()=>{this.once("upgrade",i),this.once("upgradeError",i)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?t():A()}):this.upgrading?t():A()),this}_onError(A){if(Rn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",A),this._onClose("transport error",A)}_onClose(A,i){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),yp&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const t=sl.indexOf(this._offlineEventListener);t!==-1&&sl.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,i),this.writeBuffer=[],this._prevBufferLen=0}}}Rn.protocol=v1;class $cA extends Rn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let A=0;A<this._upgrades.length;A++)this._probe(this._upgrades[A])}_probe(A){let i=this.createTransport(A),t=!1;Rn.priorWebsocketSuccess=!1;const g=()=>{t||(i.send([{type:"ping",data:"probe"}]),i.once("packet",s=>{if(!t)if(s.type==="pong"&&s.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",i),!i)return;Rn.priorWebsocketSuccess=i.name==="websocket",this.transport.pause(()=>{t||this.readyState!=="closed"&&(C(),this.setTransport(i),i.send([{type:"upgrade"}]),this.emitReserved("upgrade",i),i=null,this.upgrading=!1,this.flush())})}else{const c=new Error("probe error");c.transport=i.name,this.emitReserved("upgradeError",c)}}))};function o(){t||(t=!0,C(),i.close(),i=null)}const B=s=>{const c=new Error("probe error: "+s);c.transport=i.name,o(),this.emitReserved("upgradeError",c)};function I(){B("transport closed")}function r(){B("socket closed")}function a(s){i&&s.name!==i.name&&o()}const C=()=>{i.removeListener("open",g),i.removeListener("error",B),i.removeListener("close",I),this.off("close",r),this.off("upgrading",a)};i.once("open",g),i.once("error",B),i.once("close",I),this.once("close",r),this.once("upgrading",a),this._upgrades.indexOf("webtransport")!==-1&&A!=="webtransport"?this.setTimeoutFn(()=>{t||i.open()},200):i.open()}onHandshake(A){this._upgrades=this._filterUpgrades(A.upgrades),super.onHandshake(A)}_filterUpgrades(A){const i=[];for(let t=0;t<A.length;t++)~this.transports.indexOf(A[t])&&i.push(A[t]);return i}}let AhA=class extends $cA{constructor(A,i={}){const t=typeof A=="object"?A:i;(!t.transports||t.transports&&typeof t.transports[0]=="string")&&(t.transports=(t.transports||["polling","websocket","webtransport"]).map(g=>WcA[g]).filter(g=>!!g)),super(A,t)}};function ehA(e,A="",i){let t=e;i=i||typeof location<"u"&&location,e==null&&(e=i.protocol+"//"+i.host),typeof e=="string"&&(e.charAt(0)==="/"&&(e.charAt(1)==="/"?e=i.protocol+e:e=i.host+e),/^(https?|wss?):\/\//.test(e)||(typeof i<"u"?e=i.protocol+"//"+e:e="https://"+e),t=kp(e)),t.port||(/^(http|ws)$/.test(t.protocol)?t.port="80":/^(http|ws)s$/.test(t.protocol)&&(t.port="443")),t.path=t.path||"/";const o=t.host.indexOf(":")!==-1?"["+t.host+"]":t.host;return t.id=t.protocol+"://"+o+":"+t.port+A,t.href=t.protocol+"://"+o+(i&&i.port===t.port?"":":"+t.port),t}const ihA=typeof ArrayBuffer=="function",thA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,tq=Object.prototype.toString,ghA=typeof Blob=="function"||typeof Blob<"u"&&tq.call(Blob)==="[object BlobConstructor]",ohA=typeof File=="function"||typeof File<"u"&&tq.call(File)==="[object FileConstructor]";function Hp(e){return ihA&&(e instanceof ArrayBuffer||thA(e))||ghA&&e instanceof Blob||ohA&&e instanceof File}function wl(e,A){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let i=0,t=e.length;i<t;i++)if(wl(e[i]))return!0;return!1}if(Hp(e))return!0;if(e.toJSON&&typeof e.toJSON=="function"&&arguments.length===1)return wl(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&wl(e[i]))return!0;return!1}function BhA(e){const A=[],i=e.data,t=e;return t.data=Np(i,A),t.attachments=A.length,{packet:t,buffers:A}}function Np(e,A){if(!e)return e;if(Hp(e)){const i={_placeholder:!0,num:A.length};return A.push(e),i}else if(Array.isArray(e)){const i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=Np(e[t],A);return i}else if(typeof e=="object"&&!(e instanceof Date)){const i={};for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(i[t]=Np(e[t],A));return i}return e}function EhA(e,A){return e.data=xp(e.data,A),delete e.attachments,e}function xp(e,A){if(!e)return e;if(e&&e._placeholder===!0){if(typeof e.num=="number"&&e.num>=0&&e.num<A.length)return A[e.num];throw new Error("illegal attachments")}else if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=xp(e[i],A);else if(typeof e=="object")for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=xp(e[i],A));return e}const IhA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],rhA=5;var ji;(function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"})(ji||(ji={}));class nhA{constructor(A){this.replacer=A}encode(A){return(A.type===ji.EVENT||A.type===ji.ACK)&&wl(A)?this.encodeAsBinary({type:A.type===ji.EVENT?ji.BINARY_EVENT:ji.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let i=""+A.type;return(A.type===ji.BINARY_EVENT||A.type===ji.BINARY_ACK)&&(i+=A.attachments+"-"),A.nsp&&A.nsp!=="/"&&(i+=A.nsp+","),A.id!=null&&(i+=A.id),A.data!=null&&(i+=JSON.stringify(A.data,this.replacer)),i}encodeAsBinary(A){const i=BhA(A),t=this.encodeAsString(i.packet),g=i.buffers;return g.unshift(t),g}}function gq(e){return Object.prototype.toString.call(e)==="[object Object]"}class Op extends Sg{constructor(A){super(),this.reviver=A}add(A){let i;if(typeof A=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");i=this.decodeString(A);const t=i.type===ji.BINARY_EVENT;t||i.type===ji.BINARY_ACK?(i.type=t?ji.EVENT:ji.ACK,this.reconstructor=new ahA(i),i.attachments===0&&super.emitReserved("decoded",i)):super.emitReserved("decoded",i)}else if(Hp(A)||A.base64)if(this.reconstructor)i=this.reconstructor.takeBinaryData(A),i&&(this.reconstructor=null,super.emitReserved("decoded",i));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+A)}decodeString(A){let i=0;const t={type:Number(A.charAt(0))};if(ji[t.type]===void 0)throw new Error("unknown packet type "+t.type);if(t.type===ji.BINARY_EVENT||t.type===ji.BINARY_ACK){const o=i+1;for(;A.charAt(++i)!=="-"&&i!=A.length;);const B=A.substring(o,i);if(B!=Number(B)||A.charAt(i)!=="-")throw new Error("Illegal attachments");t.attachments=Number(B)}if(A.charAt(i+1)==="/"){const o=i+1;for(;++i&&!(A.charAt(i)===","||i===A.length););t.nsp=A.substring(o,i)}else t.nsp="/";const g=A.charAt(i+1);if(g!==""&&Number(g)==g){const o=i+1;for(;++i;){const B=A.charAt(i);if(B==null||Number(B)!=B){--i;break}if(i===A.length)break}t.id=Number(A.substring(o,i+1))}if(A.charAt(++i)){const o=this.tryParse(A.substr(i));if(Op.isPayloadValid(t.type,o))t.data=o;else throw new Error("invalid payload")}return t}tryParse(A){try{return JSON.parse(A,this.reviver)}catch{return!1}}static isPayloadValid(A,i){switch(A){case ji.CONNECT:return gq(i);case ji.DISCONNECT:return i===void 0;case ji.CONNECT_ERROR:return typeof i=="string"||gq(i);case ji.EVENT:case ji.BINARY_EVENT:return Array.isArray(i)&&(typeof i[0]=="number"||typeof i[0]=="string"&&IhA.indexOf(i[0])===-1);case ji.ACK:case ji.BINARY_ACK:return Array.isArray(i)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ahA{constructor(A){this.packet=A,this.buffers=[],this.reconPack=A}takeBinaryData(A){if(this.buffers.push(A),this.buffers.length===this.reconPack.attachments){const i=EhA(this.reconPack,this.buffers);return this.finishedReconstruction(),i}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ChA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Op,Encoder:nhA,get PacketType(){return ji},protocol:rhA},Symbol.toStringTag,{value:"Module"}));function LE(e,A,i){return e.on(A,i),function(){e.off(A,i)}}const QhA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class oq extends Sg{constructor(A,i,t){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=A,this.nsp=i,t&&t.auth&&(this.auth=t.auth),this._opts=Object.assign({},t),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const A=this.io;this.subs=[LE(A,"open",this.onopen.bind(this)),LE(A,"packet",this.onpacket.bind(this)),LE(A,"error",this.onerror.bind(this)),LE(A,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...A){return A.unshift("message"),this.emit.apply(this,A),this}emit(A,...i){var t,g,o;if(QhA.hasOwnProperty(A))throw new Error('"'+A.toString()+'" is a reserved event name');if(i.unshift(A),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(i),this;const B={type:ji.EVENT,data:i};if(B.options={},B.options.compress=this.flags.compress!==!1,typeof i[i.length-1]=="function"){const C=this.ids++,s=i.pop();this._registerAckCallback(C,s),B.id=C}const I=(g=(t=this.io.engine)===null||t===void 0?void 0:t.transport)===null||g===void 0?void 0:g.writable,r=this.connected&&!(!((o=this.io.engine)===null||o===void 0)&&o._hasPingExpired());return this.flags.volatile&&!I||(r?(this.notifyOutgoingListeners(B),this.packet(B)):this.sendBuffer.push(B)),this.flags={},this}_registerAckCallback(A,i){var t;const g=(t=this.flags.timeout)!==null&&t!==void 0?t:this._opts.ackTimeout;if(g===void 0){this.acks[A]=i;return}const o=this.io.setTimeoutFn(()=>{delete this.acks[A];for(let I=0;I<this.sendBuffer.length;I++)this.sendBuffer[I].id===A&&this.sendBuffer.splice(I,1);i.call(this,new Error("operation has timed out"))},g),B=(...I)=>{this.io.clearTimeoutFn(o),i.apply(this,I)};B.withError=!0,this.acks[A]=B}emitWithAck(A,...i){return new Promise((t,g)=>{const o=(B,I)=>B?g(B):t(I);o.withError=!0,i.push(o),this.emit(A,...i)})}_addToQueue(A){let i;typeof A[A.length-1]=="function"&&(i=A.pop());const t={id:this._queueSeq++,tryCount:0,pending:!1,args:A,flags:Object.assign({fromQueue:!0},this.flags)};A.push((g,...o)=>t!==this._queue[0]?void 0:(g!==null?t.tryCount>this._opts.retries&&(this._queue.shift(),i&&i(g)):(this._queue.shift(),i&&i(null,...o)),t.pending=!1,this._drainQueue())),this._queue.push(t),this._drainQueue()}_drainQueue(A=!1){if(!this.connected||this._queue.length===0)return;const i=this._queue[0];i.pending&&!A||(i.pending=!0,i.tryCount++,this.flags=i.flags,this.emit.apply(this,i.args))}packet(A){A.nsp=this.nsp,this.io._packet(A)}onopen(){typeof this.auth=="function"?this.auth(A=>{this._sendConnectPacket(A)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(A){this.packet({type:ji.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},A):A})}onerror(A){this.connected||this.emitReserved("connect_error",A)}onclose(A,i){this.connected=!1,delete this.id,this.emitReserved("disconnect",A,i),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(A=>{if(!this.sendBuffer.some(t=>String(t.id)===A)){const t=this.acks[A];delete this.acks[A],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(A){if(A.nsp===this.nsp)switch(A.type){case ji.CONNECT:A.data&&A.data.sid?this.onconnect(A.data.sid,A.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ji.EVENT:case ji.BINARY_EVENT:this.onevent(A);break;case ji.ACK:case ji.BINARY_ACK:this.onack(A);break;case ji.DISCONNECT:this.ondisconnect();break;case ji.CONNECT_ERROR:this.destroy();const t=new Error(A.data.message);t.data=A.data.data,this.emitReserved("connect_error",t);break}}onevent(A){const i=A.data||[];A.id!=null&&i.push(this.ack(A.id)),this.connected?this.emitEvent(i):this.receiveBuffer.push(Object.freeze(i))}emitEvent(A){if(this._anyListeners&&this._anyListeners.length){const i=this._anyListeners.slice();for(const t of i)t.apply(this,A)}super.emit.apply(this,A),this._pid&&A.length&&typeof A[A.length-1]=="string"&&(this._lastOffset=A[A.length-1])}ack(A){const i=this;let t=!1;return function(...g){t||(t=!0,i.packet({type:ji.ACK,id:A,data:g}))}}onack(A){const i=this.acks[A.id];typeof i=="function"&&(delete this.acks[A.id],i.withError&&A.data.unshift(null),i.apply(this,A.data))}onconnect(A,i){this.id=A,this.recovered=i&&this._pid===i,this._pid=i,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(A=>this.emitEvent(A)),this.receiveBuffer=[],this.sendBuffer.forEach(A=>{this.notifyOutgoingListeners(A),this.packet(A)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(A=>A()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ji.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(A){return this.flags.compress=A,this}get volatile(){return this.flags.volatile=!0,this}timeout(A){return this.flags.timeout=A,this}onAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(A),this}prependAny(A){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(A),this}offAny(A){if(!this._anyListeners)return this;if(A){const i=this._anyListeners;for(let t=0;t<i.length;t++)if(A===i[t])return i.splice(t,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(A),this}prependAnyOutgoing(A){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(A),this}offAnyOutgoing(A){if(!this._anyOutgoingListeners)return this;if(A){const i=this._anyOutgoingListeners;for(let t=0;t<i.length;t++)if(A===i[t])return i.splice(t,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(A){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const i=this._anyOutgoingListeners.slice();for(const t of i)t.apply(this,A.data)}}}function oQ(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}oQ.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var A=Math.random(),i=Math.floor(A*this.jitter*e);e=(Math.floor(A*10)&1)==0?e-i:e+i}return Math.min(e,this.max)|0},oQ.prototype.reset=function(){this.attempts=0},oQ.prototype.setMin=function(e){this.ms=e},oQ.prototype.setMax=function(e){this.max=e},oQ.prototype.setJitter=function(e){this.jitter=e};class Jp extends Sg{constructor(A,i){var t;super(),this.nsps={},this.subs=[],A&&typeof A=="object"&&(i=A,A=void 0),i=i||{},i.path=i.path||"/socket.io",this.opts=i,Ql(this,i),this.reconnection(i.reconnection!==!1),this.reconnectionAttempts(i.reconnectionAttempts||1/0),this.reconnectionDelay(i.reconnectionDelay||1e3),this.reconnectionDelayMax(i.reconnectionDelayMax||5e3),this.randomizationFactor((t=i.randomizationFactor)!==null&&t!==void 0?t:.5),this.backoff=new oQ({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(i.timeout==null?2e4:i.timeout),this._readyState="closed",this.uri=A;const g=i.parser||ChA;this.encoder=new g.Encoder,this.decoder=new g.Decoder,this._autoConnect=i.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(A){return arguments.length?(this._reconnection=!!A,A||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(A){return A===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=A,this)}reconnectionDelay(A){var i;return A===void 0?this._reconnectionDelay:(this._reconnectionDelay=A,(i=this.backoff)===null||i===void 0||i.setMin(A),this)}randomizationFactor(A){var i;return A===void 0?this._randomizationFactor:(this._randomizationFactor=A,(i=this.backoff)===null||i===void 0||i.setJitter(A),this)}reconnectionDelayMax(A){var i;return A===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=A,(i=this.backoff)===null||i===void 0||i.setMax(A),this)}timeout(A){return arguments.length?(this._timeout=A,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(A){if(~this._readyState.indexOf("open"))return this;this.engine=new AhA(this.uri,this.opts);const i=this.engine,t=this;this._readyState="opening",this.skipReconnect=!1;const g=LE(i,"open",function(){t.onopen(),A&&A()}),o=I=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",I),A?A(I):this.maybeReconnectOnOpen()},B=LE(i,"error",o);if(this._timeout!==!1){const I=this._timeout,r=this.setTimeoutFn(()=>{g(),o(new Error("timeout")),i.close()},I);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(g),this.subs.push(B),this}connect(A){return this.open(A)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const A=this.engine;this.subs.push(LE(A,"ping",this.onping.bind(this)),LE(A,"data",this.ondata.bind(this)),LE(A,"error",this.onerror.bind(this)),LE(A,"close",this.onclose.bind(this)),LE(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(A){try{this.decoder.add(A)}catch(i){this.onclose("parse error",i)}}ondecoded(A){Cl(()=>{this.emitReserved("packet",A)},this.setTimeoutFn)}onerror(A){this.emitReserved("error",A)}socket(A,i){let t=this.nsps[A];return t?this._autoConnect&&!t.active&&t.connect():(t=new oq(this,A,i),this.nsps[A]=t),t}_destroy(A){const i=Object.keys(this.nsps);for(const t of i)if(this.nsps[t].active)return;this._close()}_packet(A){const i=this.encoder.encode(A);for(let t=0;t<i.length;t++)this.engine.write(i[t],A.options)}cleanup(){this.subs.forEach(A=>A()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(A,i){var t;this.cleanup(),(t=this.engine)===null||t===void 0||t.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",A,i),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const A=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const i=this.backoff.duration();this._reconnecting=!0;const t=this.setTimeoutFn(()=>{A.skipReconnect||(this.emitReserved("reconnect_attempt",A.backoff.attempts),!A.skipReconnect&&A.open(g=>{g?(A._reconnecting=!1,A.reconnect(),this.emitReserved("reconnect_error",g)):A.onreconnect()}))},i);this.opts.autoUnref&&t.unref(),this.subs.push(()=>{this.clearTimeoutFn(t)})}}onreconnect(){const A=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",A)}}const ew={};function cl(e,A){typeof e=="object"&&(A=e,e=void 0),A=A||{};const i=ehA(e,A.path||"/socket.io"),t=i.source,g=i.id,o=i.path,B=ew[g]&&o in ew[g].nsps,I=A.forceNew||A["force new connection"]||A.multiplex===!1||B;let r;return I?r=new Jp(t,A):(ew[g]||(ew[g]=new Jp(t,A)),r=ew[g]),i.query&&!A.query&&(A.query=i.queryKey),r.socket(i.path,A)}Object.assign(cl,{Manager:Jp,Socket:oq,io:cl,connect:cl});const BQ="https://api.tybotflow.com/api/v1",shA="https://api.tybotflow.com/api/v1/chatbots-config",Bq="https://migration-meta.tybotflow.com/",Eq=Bq+"ucc/v",EQ=cl(Bq,{transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:3,autoConnect:!0,reconnectionDelay:2e3}),Iq=new Rr,fp=e=>{if(!e||!e.message)return"👋 Hey there! how can I help you?";const A=e.message;if(typeof A=="string")return A;if(Array.isArray(A)){const i=window.location.href,t=window.location.origin,g=window.location.pathname,o=t+g;for(const I of A){if(!I.urls||I.urls.length===0)continue;if(I.urls.some(a=>{if(!a||a.trim()==="")return!1;try{let C=a.trim();!C.startsWith("http://")&&!C.startsWith("https://")&&(C="https://"+C);const s=new URL(C),c=s.origin,w=s.pathname,l=c+w;return o===l||i===C?!0:w==="/"||w===""?t===c:!!i.startsWith(C)}catch{return console.warn("Invalid URL in message:",a),!1}}))return I.text||"👋 Hey there! how can I help you?"}const B=A.find(I=>!I.urls||I.urls.length===0||I.urls.every(r=>!r||r.trim()===""));if(B)return B.text||"👋 Hey there! how can I help you?";if(A.length>0)return A[0].text||"👋 Hey there! how can I help you?"}return"👋 Hey there! how can I help you?"},rq=(e,A)=>{const i={className:"w-5 h-5",style:{color:A}};switch(e?.toLowerCase()){case"pdf":return U.jsx(Bn,{...i});case"doc":case"docx":return U.jsx(Bn,{...i});case"xls":case"xlsx":case"csv":return U.jsx(KiA,{...i});case"ppt":case"pptx":return U.jsx(fiA,{...i});case"zip":case"rar":case"7z":case"tar":case"gz":return U.jsx(FiA,{...i});case"txt":case"md":case"rtf":return U.jsx(hx,{...i});default:return U.jsx(Bn,{...i})}},whA=({config:e})=>{const A=vA.useRef(null),i=vA.useRef(null),t=vA.useRef(null),g=vA.useRef(null),o=vA.useRef(null),[B,I]=vA.useState(null),[r,a]=vA.useState(!0),[C,s]=vA.useState(!1);vA.useEffect(()=>{(async()=>{a(!0),await Ft.get(`${shA}/bot/${e.bot?.botId}`,{}).then(jA=>{I(jA.data)}).catch(jA=>{console.error("Error fetching bot config:",jA)}).finally(()=>{a(!1)})})()},[e.bot?.botId,e?.token]);const c=B?.mainColor||"#59168b",w=B?.secondaryColor||"#6366f1",l=B?.thirdColor||"#0f172b",D=B?.headerFirstColor||"#6e11b0",d=B?.headerSecondColor||"#372aac",u=B?.inputBackgroundColor||"#1f2937",G=B?.inputTextColor||"#fff",F=B?.roundness||24,K=B?.chatRoundness||16,k=(B?.minPanelWidth||434)>window.innerWidth?window.innerWidth:B?.minPanelWidth||434,S=(B?.maxPanelWidth||window.innerWidth)>window.innerWidth?window.innerWidth:B?.maxPanelWidth||window.innerWidth,f=B?.chatMaxWidth||88,j=B?.toggleBtnBorderTopLeftRadius||12,O=B?.toggleBtnBorderTopRightRadius||0,b=B?.toggleBtnBorderBottomLeftRadius||12,x=B?.toggleBtnBorderBottomRightRadius||0,V=B?.menuBackgroundColor||"#1f2937",q=B?.menuTextColor||"#e5e7eb",z=B?.menuHoverBackgroundColor||"#374151",v=B?.agentChatResponseColor||"#e5e7eb",P=B?.agentChatResponseBgColor||"#1f2937",gA=B?.agentIconBgColor||"#59168b",$=B?.agentIconColor||"#fff",IA=B?.userChatMessagesColor||"#fff",H=B?.userChatMessagesBgColor||"#7a1ebe",AA=B?.userIconBgColor||"#7a1ebe",T=B?.userIconColor||"#fff",y=B?.ButtonColor||"#fff",X=B?.ButtonsBgColor||"#59168b",EA=qg(P,10),rA=B?.fontSize||13,wA=B?.toggleBtnPosition||"bottom-right",DA=B?.autoOpenPanel??!0,UA=B?.tempToken||"",PA=(()=>{const J=B?.firstMessageKeyword;if(Array.isArray(J)){const jA=window.location.href,RA=J.find(ce=>ce.url&&ce.url===jA);if(RA)return RA.message;const FA=J.find(ce=>!ce.url||ce.url==="");return FA?FA.message:J[0]?.message||"hi"}return J||"hi"})(),le=J=>({ip:J.ip||"",flag:{img:J.flag||"",emoji:J.emoji_flag||"",emoji_unicode:J.emoji_unicode||""},is_eu:J.is_eu??!1,postal:J.postal||"",borders:"",latitude:J.latitude||0,platform:J?.platform||"",timezone:{id:J.time_zone?.name||"",utc:J.time_zone?.offset||"",abbr:J.time_zone?.abbr||"",is_dst:J.time_zone?.is_dst??!1,offset:J.time_zone?.offset||0,current_time:J.time_zone?.current_time||""},continent:J.continent_name||"",longitude:J.longitude||0,connection:{asn:J.asn?.asn||0,isp:J.asn?.name||"",org:J.asn?.name||"",domain:J.asn?.domain||""}}),[ZA,kA]=vA.useState(k),tA=vA.useRef(!1),ge=vA.useRef(0),De=vA.useRef(k),ae=J=>{tA.current=!0,ge.current=J.clientX,De.current=ZA,document.body.style.cursor="ew-resize"};vA.useEffect(()=>{const J=RA=>{if(!tA.current)return;const FA=ge.current-RA.clientX;let ce=De.current+FA;ce=Math.max(k,Math.min(S,ce)),kA(ce)},jA=()=>{tA.current&&(tA.current=!1,document.body.style.cursor="")};return window.addEventListener("mousemove",J),window.addEventListener("mouseup",jA),()=>{window.removeEventListener("mousemove",J),window.removeEventListener("mouseup",jA)}},[ZA,k,S]);const[KA,Ee]=vA.useState(!1),[ie,Fe]=vA.useState(!1),[Qe,NA]=vA.useState(!1),[bA,hA]=vA.useState(()=>wA==="bottom-left"?{x:48,y:window.innerHeight-120}:wA==="middle-right"?{x:window.innerWidth-80,y:window.innerHeight/2-35}:{x:window.innerWidth-123,y:window.innerHeight-100}),[uA,yA]=vA.useState(!1),[VA,ue]=vA.useState({x:0,y:0}),Ge=vA.useRef(null),[Ve,je]=vA.useState(""),[Re,Ye]=vA.useState(!1),[ze,me]=vA.useState(!1),[Ne,ye]=vA.useState([]),[Ai,Di]=vA.useState(!1),Xe=vA.useRef(0),[We,ui]=vA.useState(!1),[vg,ri]=vA.useState(!1),Ot=vA.useRef(!1),[ao,Pe]=vA.useState("00:00"),zi=vA.useRef(null),yi=vA.useRef(0),[qi,Jt]=vA.useState(null),[ni,At]=vA.useState(!1),[_i,Xg]=vA.useState(new Set),[Et,Zi]=vA.useState([]),[et,vt]=vA.useState(null),[Xt,ft]=vA.useState("up"),{startRecording:it,stopRecording:_g,pauseRecording:xe,resumeRecording:lA,status:$A,error:Se}=sEA.useReactMediaRecorder({video:!1,blobPropertyBag:{type:"audio/mp3"},onStop(J,jA){if(Ot.current){Ot.current=!1,Pe("00:00"),yi.current=0;return}ye(RA=>[...RA,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:jA,type:"audio",url:J,name:`recording-${new Date().toISOString()}.webm`,size:jA.size}]),Pe("00:00"),yi.current=0}}),Fi=B?.icon||e?.icon||e?.bot.avatar_url||AQA,wt=B?.headerIcon||e?.headerIcon||Fi,rt=B?.headerImageStyle||e?.headerImageStyle||"compact",Rt=B?.launcherImageHeight??e?.launcherImageHeight??130,It=B?.launcherImageDesktopHeight??e?.launcherImageDesktopHeight??150,kt=B?.imageType||e?.imageType||"icon",Co={"--launcher-image-height":`${Rt}px`,"--launcher-image-desktop-height":`${It}px`,"--launcher-welcome-top":`${Math.round(Rt*.28)}px`,"--launcher-welcome-desktop-top":`${Math.round(It*.4)}px`},Li=B?.title||e?.bot.name||"Tybot webchat",[Ti,_o]=vA.useState(null),[$o,vE]=vA.useState(()=>{const J=localStorage.getItem("phone_client");if(e.bot?.botId==="rockskin"&&J)return J;if(!B?.botNeedsAuth){let jA=localStorage.getItem("externalUser");if(!jA){const RA=new Uint8Array(16);window.crypto.getRandomValues(RA),jA=Array.from(RA).map(FA=>FA.toString(16).padStart(2,"0")).join("")}return localStorage.setItem("externalUser",jA),jA}});vA.useEffect(()=>{if(!Ti)return;const J=jA=>{if(jA.bot.conversationId!==parseInt(Ti)||jA.bot.botId!==e?.bot?.botId){Ye(!1);return}const RA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:jA.bot.item,timestamp:new Date,seen:xo.current,nMessage:Array.isArray(jA.bot.item)?jA.bot.item.length:1};Zi(FA=>FA.some(pA=>pA.id===RA.id)?FA:[...FA,RA]),Ye(!1)};return EQ.on("bot-message",J),()=>{EQ.off("bot-message",J)}},[Ti,e?.bot?.botId]),vA.useEffect(()=>{if(!Ti)return;const J=jA=>{const RA=jA.conversationId!==void 0?jA.conversationId:jA.bot?.conversationId,FA=jA.botId!==void 0?jA.botId:jA.bot?.botId;RA!==parseInt(Ti)||FA!==e?.bot?.botId&&FA!==e.bot?.botId||Zi(ce=>{const pA=[...ce].reverse().findIndex(aA=>aA.sender==="agent");if(pA===-1)return ce;const p=ce.length-1-pA,Z=[...ce];return Z[p]={...Z[p],timingMetrics:jA.latencies},Z})};return EQ.on("timing_metrics",J),()=>{EQ.off("timing_metrics",J)}},[Ti,e?.bot?.botId,e.bot?.botId]),vA.useEffect(()=>{(async()=>{if(!(Ti||!e.bot?.botId||!$o))try{const RA=(await Ft.post(`${BQ}/conversations/start-conversation`,{bot_id:e.bot?.botId,externalUser:$o})).data.conversationId;_o(RA),localStorage.setItem("conversationId",RA),EQ.emit("join_room",parseInt(RA))}catch(jA){console.error("Error initializing conversation:",jA)}})()},[Ti,e.bot?.botId,$o]);const[AB,bi]=vA.useState(()=>B?.botNeedsAuth?!!localStorage.getItem("conversationId"):!0),[eB,xn]=vA.useState(""),[fg,aE]=vA.useState(""),[Mg,XE]=vA.useState(""),[Ri,_E]=vA.useState(null),xo=vA.useRef(!1),Qo=Et.reduce((J,jA)=>jA.seen?J:J+(jA.sender==="agent"?jA.nMessage||1:0),0),YB=()=>{Zi(J=>J.map(jA=>({...jA,seen:!0})))};vA.useEffect(()=>{let J;return!localStorage.getItem("webChatOpen")&&B&&DA&&(J=setTimeout(()=>{Ee(!0),xo.current=!0,YB(),localStorage.setItem("webChatOpen","true")},3200)),()=>clearTimeout(J)},[B]),vA.useEffect(()=>{const J=B?.widgetLoadBehavior;if(!J||!(()=>{const FA=J.message;if(typeof FA=="string"){if(!J.urls||J.urls.length===0)return!0;const ce=window.location.origin,pA=window.location.href;return J.urls.some(p=>{if(!p||p.trim()==="")return!0;try{return ce.includes(p)||pA.includes(p)||p.includes(ce)}catch{return console.warn("Invalid URL in widgetLoadBehavior:",p),!1}})}if(Array.isArray(FA)){const ce=window.location.href,pA=window.location.origin,p=window.location.pathname,Z=pA+p;for(const aA of FA)if(!aA.urls||aA.urls.length===0||aA.urls.every(dA=>!dA||dA.trim()==="")||aA.urls.some(dA=>{if(!dA||dA.trim()==="")return!1;try{let zA=dA.trim();!zA.startsWith("http://")&&!zA.startsWith("https://")&&(zA="https://"+zA);const Be=new URL(zA),te=Be.origin,Oe=Be.pathname,pe=te+Oe;return Z===pe||ce===zA?!0:Oe==="/"||Oe===""?pA===te:!!ce.startsWith(zA)}catch{return console.warn("Invalid URL in message:",dA),!1}}))return!0;return!1}return!0})())return;let RA;if(J.behavior==="after seconds")RA=setTimeout(()=>{NA(!0)},J.value*1e3);else if(J.behavior==="after scroll"){const FA=()=>{const ce=window.pageYOffset||document.documentElement.scrollTop,pA=document.documentElement.scrollHeight-document.documentElement.clientHeight;ce/pA*100>=J.value&&(NA(!0),window.removeEventListener("scroll",FA))};return window.addEventListener("scroll",FA),()=>{window.removeEventListener("scroll",FA)}}return()=>{RA&&clearTimeout(RA)}},[B?.widgetLoadBehavior]),vA.useEffect(()=>{KA&&NA(!1)},[KA]),vA.useEffect(()=>{fetch("https://api.ipdata.co/?api-key=7930ffd0621dafcb6cd830a503d726bf514b74c1cae21ffff8131890").then(function(J){J.json().then(jA=>{_E({...jA,platform:Iq.getOS().name+" "+Iq.getOS().version})})}).catch(function(J){console.log(J)})},[]);const so=vA.useCallback(async(J,jA=[],RA)=>{if(!e.bot.botId||!Ti){Ye(!1),Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:[{type:"text",text:"⚠️ Unable to send message: No bot selected or conversation not initialized."}],timestamp:new Date}]);return}if(jA.length>0||RA&&typeof RA=="object"&&RA.attachment!==void 0){const ce=RA&&typeof RA!="string"?RA.attachment.file:jA[0]?.file,pA=RA&&typeof RA!="string"?RA.attachment.type:jA[0]?.type||"file";let p=RA;if(RA&&typeof RA=="object"&&RA.attachment!==void 0){const{attachment:aA,...sA}=RA;p=sA}const Z=new FormData;Z.append("type",pA),Z.append("file",ce),Z.append("botId",e.bot.botId),Z.append("external_id",$o||""),Z.append("isintern",e.token?"true":"false"),Z.append("host",window.location.origin),Z.append("channel","web"),Z.append("payload",p?JSON.stringify(p):""),await Ft.post(Eq,Z,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"multipart/form-data"}})}else{const ce={type:"text",messageText:J,botId:e.bot.botId,external_id:$o||"",isintern:!!e.token,host:window.location.origin,channel:"web"};RA&&(ce.payload=RA),await Ft.post(Eq,ce,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"}})}},[e.bot.botId,Ti,e.token,e.user?.id]),jI=vA.useCallback(async()=>{if(e.bot.botId&&Ti){Ye(!0);try{await so(PA)}catch(J){console.error("Error sending first message:",J),Ye(!1)}}},[e.bot.botId,PA,Ti,so]);vA.useEffect(()=>{Ti&&AB&&e?.bot&&Et.length===0&&B&&DA&&(jI(),localStorage.getItem("webChatAuth")&&JSON.parse(localStorage.getItem("webChatAuth"))&&B?.botNeedsAuth&&Ti&&(eB||Mg||fg)&&(setTimeout(()=>{VB(Ti)},2e3),localStorage.setItem("webChatAuth","true")))},[AB,e?.bot,Ti,B]),vA.useEffect(()=>($A==="recording"?zi.current||(zi.current=setInterval(()=>{yi.current+=1;const J=Math.floor(yi.current/60).toString().padStart(2,"0"),jA=(yi.current%60).toString().padStart(2,"0");Pe(`${J}:${jA}`)},1e3)):zi.current&&(clearInterval(zi.current),zi.current=null),()=>{zi.current&&(clearInterval(zi.current),zi.current=null)}),[$A]),vA.useEffect(()=>{Se&&Se.toLowerCase().includes("permission_denied")&&(ri(!1),Pe("00:00"),yi.current=0,zi.current&&(clearInterval(zi.current),zi.current=null),alert("Microphone permission denied. Please allow access to record audio."))},[Se]),vA.useEffect(()=>{$A!=="recording"&&$A!=="paused"&&(Pe("00:00"),yi.current=0)},[$A]);const Oo=vA.useRef(null);vA.useEffect(()=>{if(Oo&&Oo.current){const J=Oo.current;J.style.height="auto";const jA=120;J.scrollHeight>jA?(J.style.height=jA+"px",J.style.overflowY="auto"):(J.style.height=J.scrollHeight+"px",J.style.overflowY="hidden")}},[Ve]),vA.useEffect(()=>{(KA||Re)&&A.current&&(A.current.scrollTop=A.current.scrollHeight)},[Et,Re,KA]);const CE=J=>{const jA=J.type.toLowerCase();return jA.startsWith("image/")?"image":jA.startsWith("video/")?"video":jA.startsWith("audio/")?"audio":"document"},iB=vA.useCallback((J,jA)=>{const RA=[];Array.from(J).forEach(FA=>{if(FA.size>10*1024*1024){alert(`File ${FA.name} is too large. Maximum size is 10MB.`);return}const ce={id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:FA,type:CE(FA),url:URL.createObjectURL(FA),name:FA.name,size:FA.size};RA.push(ce)}),ye(FA=>[...FA,...RA]),jA&&jA.current&&(jA.current.value="")},[]),On=vA.useCallback(J=>{J.preventDefault(),Xe.current=0,Di(!1);const jA=J.dataTransfer.files;jA.length>0&&iB(jA)},[iB]),yr=vA.useCallback(J=>{J.preventDefault(),Xe.current+=1,Di(!0)},[]),AC=vA.useCallback(J=>{J.preventDefault()},[]),Hr=vA.useCallback(J=>{J.preventDefault(),Xe.current-=1,Xe.current<=0&&Di(!1)},[]),dB=vA.useCallback(J=>{ye(jA=>{const RA=jA.find(FA=>FA.id===J);return RA&&URL.revokeObjectURL(RA.url),jA.filter(FA=>FA.id!==J)})},[]),GB=J=>{if(J===0)return"0 Bytes";const jA=1024,RA=["Bytes","KB","MB","GB"],FA=Math.floor(Math.log(J)/Math.log(jA));return Number.parseFloat((J/Math.pow(jA,FA)).toFixed(2))+" "+RA[FA]},Ui=async(J=Ve,jA)=>{if(J.trim()||Ne.length!==0){const FA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"user",content:J,attachments:[...Ne],timestamp:new Date};if(Zi(ce=>[...ce,FA]),je(""),ye([]),Ye(!0),e?.bot)try{if(!Ti){Ye(!1),Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"⚠️ Conversation not initialized. Please try again later.",timestamp:new Date,seen:xo.current,nMessage:1}]);return}await so(J,Ne,jA)}catch{Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Erreur du serveur",timestamp:new Date,seen:xo.current,nMessage:1}]),Ye(!1)}else Zi(ce=>[...ce,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Aucun bot sélectionné",timestamp:new Date,seen:xo.current,nMessage:1}]),Ye(!1)}else return},jg=J=>{switch(ui(!1),J){case"image":i.current?.click();break;case"video":t.current?.click();break;case"audio":g.current?.click();break;case"document":o.current?.click();break}};vA.useEffect(()=>{const J=Et.slice().reverse().find(jA=>jA.sender==="agent");if(J){let jA=!1;Array.isArray(J.content)&&(jA=J.content.some(RA=>RA.type==="text"&&typeof RA.text=="object"&&RA.text.type==="EVFORM")),me(jA)}else me(!1)},[Et]);const[FB,ei]=vA.useState(!1),UB=vA.useRef({x:0,y:0}),Jn=J=>{J.preventDefault(),J.stopPropagation(),yA(!0),ei(!1),UB.current={x:J.clientX,y:J.clientY},ue({x:J.clientX-bA.x,y:J.clientY-bA.y}),document.body.style.cursor="grabbing",document.body.style.userSelect="none"},$E=J=>{J.preventDefault(),J.stopPropagation();const jA=J.touches[0];yA(!0),ei(!1),UB.current={x:jA.clientX,y:jA.clientY},ue({x:jA.clientX-bA.x,y:jA.clientY-bA.y})},Hg=J=>{if(J.preventDefault(),J.stopPropagation(),FB){ei(!1);return}Ee(jA=>!jA),xo.current=!KA,KA||YB(),!DA&&Et.length===0&&jI()};vA.useEffect(()=>{const J=ce=>{if(!uA)return;const pA=Math.abs(ce.clientX-UB.current.x),p=Math.abs(ce.clientY-UB.current.y);(pA>5||p>5)&&ei(!0);const Z=ce.clientX-VA.x,aA=ce.clientY-VA.y,sA=67,dA=window.innerWidth-document.body.clientWidth,zA=Math.max(0,Math.min(window.innerWidth-sA-dA,Z)),Be=Math.max(0,Math.min(window.innerHeight-sA,aA));hA({x:zA,y:Be})},jA=ce=>{if(!uA)return;ce.preventDefault();const pA=ce.touches[0],p=Math.abs(pA.clientX-UB.current.x),Z=Math.abs(pA.clientY-UB.current.y);(p>5||Z>5)&&ei(!0);const aA=pA.clientX-VA.x,sA=pA.clientY-VA.y,dA=67,zA=window.innerWidth-document.body.clientWidth,Be=Math.max(0,Math.min(window.innerWidth-dA-zA,aA)),te=Math.max(0,Math.min(window.innerHeight-dA,sA));hA({x:Be,y:te})},RA=()=>{uA&&(yA(!1),document.body.style.cursor="",document.body.style.userSelect="")},FA=()=>{uA&&yA(!1)};return uA&&(document.addEventListener("mousemove",J),document.addEventListener("touchmove",jA,{passive:!1}),document.addEventListener("mouseup",RA),document.addEventListener("touchend",FA)),()=>{document.removeEventListener("mousemove",J),document.removeEventListener("touchmove",jA),document.removeEventListener("mouseup",RA),document.removeEventListener("touchend",FA)}},[uA,VA,bA]),vA.useEffect(()=>{const J=()=>{const RA=window.innerWidth-67,FA=window.innerHeight-67;hA(ce=>({x:Math.max(0,Math.min(RA,ce.x)),y:Math.max(0,Math.min(FA,ce.y))}))};return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),vA.useEffect(()=>{const J=async()=>{try{await Ft.patch(`${BQ}/widget/endusers/${$o}`,{fiche_contact:{city:Ri.city,platform:Ri.platform,region:Ri.region,country:Ri.country_name,age:0,full_name:eB,gender:"",address:"",company:"","phone 2":"",facebook:"",whatsapp:"",job_title:"",avatar_url:""},user_info:le(Ri)},{headers:{Authorization:`Bearer ${UA}`}}),localStorage.setItem("enduserUpdated","true")}catch(RA){console.error("Error updating end user info:",RA)}};let jA;return Ri&&Ti&&UA&&Et.length>0&&!localStorage.getItem("enduserUpdated")&&(jA=setTimeout(()=>{J()},5e3)),()=>clearTimeout(jA)},[Ri,B,Et,Ti]);const _t=vA.useMemo(()=>({h1:({children:J})=>U.jsx("h1",{className:"sm:text-2xl text-xl font-bold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h2:({children:J})=>U.jsx("h2",{className:"sm:text-xl text-lg font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h3:({children:J})=>U.jsx("h3",{className:"sm:text-lg text-base font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h4:({children:J})=>U.jsx("h4",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h5:({children:J})=>U.jsx("h5",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h6:({children:J})=>U.jsx("h6",{className:"sm:text-base text-sm font-semibold my-2",dir:sr(J)?"rtl":"ltr",children:U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),p:({children:J})=>{const jA=(FA,ce)=>{const pA=wr(FA);return U.jsx("span",{dir:pA?"rtl":"ltr",style:{display:"block",textAlign:pA?"right":"left"},children:U.jsx(ag,{sequence:[FA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70})},ce)};if(typeof J=="string")return U.jsx("div",{className:"leading-relaxed my-0.5",children:jA(J,0)});if(Array.isArray(J)){const FA=[[]];for(const ce of J)ce?.type==="br"?FA.push([]):FA[FA.length-1].push(ce);return U.jsx("div",{className:"leading-relaxed my-0.5",children:FA.map((ce,pA)=>{const p=ce.map(sA=>typeof sA=="string"?sA:"").join(""),Z=wr(p),aA=ce.every(sA=>typeof sA=="string");return U.jsx("span",{dir:Z?"rtl":"ltr",style:{display:"block",textAlign:Z?"right":"left"},children:aA&&p?U.jsx(ag,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70}):ce},pA)})})}const RA=!!(J?.props?.children&&wr(String(J?.props?.children??"")));return U.jsx("div",{className:"leading-relaxed my-0.5",dir:RA?"rtl":"ltr",children:J})},ul:({children:J})=>U.jsx("ul",{className:"list-disc list-inside ml-2 my-2",style:{color:v},dir:wr(J)?"rtl":"ltr",children:J}),ol:({children:J})=>{let jA=!1;return J.filter(RA=>typeof RA!="string").every(RA=>wr(RA?.props?.children))?jA=!0:jA=!1,U.jsx("ol",{className:"list-decimal list-inside ml-2 my-2",style:{color:v},dir:jA?"rtl":"ltr",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J})},li:({children:J})=>U.jsx("li",{className:"my-1",dir:sr(J)?"rtl":"ltr",style:{color:v},children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),a:({href:J,children:jA})=>U.jsx("a",{href:J,className:"text-blue-400 underline hover:text-blue-300",target:"_blank",rel:"noopener noreferrer",children:typeof jA=="string"?U.jsx(ag,{sequence:[jA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):jA}),blockquote:({children:J})=>U.jsx("blockquote",{className:"border-l-4 pl-4 italic my-2",style:{borderColor:X,color:v},children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),code({node:J,className:jA,children:RA,...FA}){const ce=/language-(\w+)/.exec(jA||"");return ce?U.jsx(oV,{...FA,PreTag:"div",children:String(RA).replace(/\n$/,""),language:ce[1],style:_CA,customStyle:{scrollbarWidth:"thin"}}):U.jsx("code",{className:"px-1 rounded font-mono inline",style:{backgroundColor:u,color:v},...FA,children:typeof RA=="string"?U.jsx(ag,{sequence:[RA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):RA})},table:({children:J})=>U.jsx("table",{className:"min-w-full my-2",style:{border:`1px solid ${v}`,color:P,backgroundColor:v},children:J}),thead:({children:J})=>U.jsx("thead",{children:J}),tbody:({children:J})=>U.jsx("tbody",{children:J}),tr:({children:J})=>U.jsx("tr",{style:{border:`1px solid ${P}`},children:J}),th:({children:J})=>U.jsx("th",{className:"px-3 py-2 font-bold text-left",children:J}),td:({children:J})=>U.jsx("td",{className:"px-3 py-2",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),strong:({children:J})=>U.jsx("strong",{className:"font-bold",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),em:({children:J})=>U.jsx("em",{className:"italic ",children:typeof J=="string"?U.jsx(ag,{sequence:[J,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):J}),hr:()=>U.jsx("hr",{className:"my-4",style:{borderColor:`1px solid ${v}`}})}),[G,v,X,u,K]);vA.useEffect(()=>{const J=jA=>{We&&jA.target instanceof Element&&!jA.composedPath().some(RA=>RA?.id==="upload-button-toggle"||RA?.id==="document-button"||RA?.id==="image-button"||RA?.id==="video-button"||RA?.id==="audio-button")&&ui(!1)};return document.addEventListener("mousedown",J),()=>{document.removeEventListener("mousedown",J)}},[We]);const $g=(J,jA="formulaire soumis")=>{if(!J||typeof J!="object")return null;const RA=J;return Array.isArray(RA.fields)?U.jsx(rcA,{definition:RA,onValidate:FA=>{const ce=RA.submitType?{...FA,type:RA.submitType}:FA;Ui(RA.submitMessage||jA,ce)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u}):null},Jo=J=>{switch(J.type){case"text":if(Array.isArray(J.text))switch(J.text[0].type){case"form":const RA=$g(J.text[0].definition||J.text[0].items||J.text[0],"formulaire soumis");if(RA)return RA;break;case"products":return U.jsx(El,{products:J.text[0].items||[],onValidate:FA=>{Ui("cart",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA});case"easyspaceform":return U.jsx(IV,{onValidate:FA=>{Ui("easyspace-form-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"xcmgform":return U.jsx(y1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,formVars:JSON.parse(J.text[0])});case"auditec-form":return U.jsx(K1,{onValidate:FA=>{Ui("auditec-form-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"auditec-form-ar":return U.jsx(k1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"nousserform":return U.jsx(x1,{onValidate:FA=>{Ui("nousserform-data",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadaraform":case"Jadaraform":case"JadaraForm":return U.jsx(H1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadara-form-ar":return U.jsx(N1,{onValidate:FA=>{Ui("✅ تم استلام الطلب بنجاح",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}else try{const RA=typeof J.text=="string"?JSON.parse(J.text):J.text;switch(RA.type.toLowerCase()){case"form":{const FA=$g(RA.definition||RA.items||RA,"formulaire soumis");return FA||U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}case"products":return U.jsx(El,{products:RA[0].items||[],onValidate:FA=>{Ui("cart",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA});case"easyspaceform":return U.jsx(IV,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"evform":return U.jsx(tcA,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,mainColor:H});case"evform-visiteur":return U.jsx(gcA,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,mainColor:H});case"xcmgform":return U.jsx(y1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u,formVars:RA?.items||{}});case"auditec-form":return U.jsx(K1,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"auditec-form-ar":return U.jsx(k1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"nousserform":return U.jsx(x1,{onValidate:FA=>{Ui("formulaire soumis",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadaraform":case"Jadaraform":case"JadaraForm":return U.jsx(H1,{onValidate:FA=>{Ui("Demande bien reçue ✅",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"jadara-form-ar":return U.jsx(N1,{onValidate:FA=>{Ui("تم إرسال النموذج",FA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}}catch{return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)})}case"single-choice":return U.jsxs(U.Fragment,{children:[U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.text)||""}),U.jsx("div",{className:"mt-2 flex flex-col gap-1",dir:sr(J.text||"")?"rtl":"ltr",children:J.choices?.map((RA,FA)=>U.jsxs("button",{onClick:()=>Ui(RA.title),className:"w-full flex items-center justify-between px-4 py-2.5 hover:opacity-95 transition-all duration-100",style:{background:EA,borderRadius:"18px",color:v,border:`2px solid ${qg(EA,20)}`},onMouseEnter:ce=>{ce.currentTarget.style.borderColor=`${X}`},onMouseLeave:ce=>{ce.currentTarget.style.border=`2px solid ${qg(EA,15)}`},dir:wr(RA.title)?"rtl":"ltr",children:[U.jsx("div",{className:"w-full flex items-start gap-2",children:U.jsx(ag,{sequence:[RA.title,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92})}),U.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center"},children:wr(RA.title)?U.jsx(wx,{className:"w-4 h-4",color:X}):U.jsx(cx,{className:"w-4 h-4",color:X})})]},FA))})]});case"image":return U.jsx(U.Fragment,{children:U.jsx("div",{className:"relative group",children:U.jsx("img",{src:J.image,className:"max-w-full max-h-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(J.image,"_blank")})})});case"dropdown":return U.jsxs(U.Fragment,{children:[U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.message)}),U.jsx(ncA,{options:J.options||[],message:J.message,allowMultiple:J.allowMultiple||!1,chatRoundness:K,buttonsBgColor:X,buttonColor:y,agentChatResponseColor:v,agentChatResponseBgColor:P,isRtl:sr(J.message||""),onSend:Ui,onScroll:()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}})]});case"carousel":return U.jsx(up,{items:J.items||[],chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"card":return U.jsx("div",{className:"mt-2 w-full",children:U.jsx("div",{className:"grid grid-cols-1 gap-3",children:U.jsxs("div",{className:"flex-shrink-0 border rounded-lg p-3 shadow-md",style:{background:P},children:[U.jsx("img",{src:J.image,alt:J.title,className:"max-h-48 w-full object-contain rounded-md mb-2"}),U.jsx("h3",{className:"font-bold",children:J.title}),J.actions?.map((RA,FA)=>U.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{RA.action==="Open URL"?window.open(RA.url,"_blank"):RA.title==="scan"?J.image&&fetch(J.image).then(ce=>ce.blob()).then(ce=>{const pA=URL.createObjectURL(ce),p=document.createElement("a");p.href=pA,p.download="qrcode.png",document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(pA)}).catch(()=>{alert("Failed to download image.")}):Ui(J.title,RA.payload||void 0)},style:{background:X,borderRadius:`${K}px`,color:y},children:RA.title},FA))]})})});case"video":return U.jsx("div",{className:"relative group w-[250px]",children:U.jsx("video",{src:J.video,className:"w-full rounded-lg cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"file":const jA=J.file?.split(".").pop?.()?.toLowerCase()||"";return U.jsx("div",{className:"p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(J.file,"_blank"),onMouseEnter:RA=>RA.currentTarget.style.backgroundColor=X,onMouseLeave:RA=>RA.currentTarget.style.backgroundColor="transparent",title:J.title,children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{background:X},children:rq(jA,v)}),U.jsx("div",{className:"flex-1 min-w-0",children:U.jsx("p",{className:"text-sm font-medium truncate",style:{color:v},children:J.title})})]})});case"products":return U.jsx(El,{products:J.products||[],onValidate:RA=>{Ui("cart ",RA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});case"json":switch(J.json?.type){case"text":return U.jsx(Er,{remarkPlugins:[rr],components:_t,children:cr(J.json.content)});case"image":return U.jsx("div",{className:"relative group",children:U.jsx("img",{src:J.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(J.json?.content,"_blank")})});case"video":return U.jsx("div",{className:"relative group",children:U.jsx("video",{src:J.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"document":const RA=J.json.content.split(".").pop?.()?.toLowerCase();return U.jsx("div",{className:"w-[300px] p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(J.json?.content,"_blank"),onMouseEnter:pA=>pA.currentTarget.style.backgroundColor=X,onMouseLeave:pA=>pA.currentTarget.style.backgroundColor="transparent",title:J.json?.title,children:U.jsxs("div",{className:"flex items-center gap-3",children:[U.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{background:X},children:rq(RA||"",v)}),U.jsx("div",{className:"flex-1 min-w-0",children:U.jsx("p",{className:"text-sm font-medium truncate",style:{color:v},children:J.json.title})})]})});case"audio":return U.jsx("div",{className:"w-[300px]",children:U.jsx(L1,{src:J.json.content,mainColor:c,secondaryColor:w,controlsColor:v})});case"cards":return J.json.content.map((pA,p)=>U.jsx("div",{className:"mt-2 w-full",children:U.jsx("div",{className:"grid grid-cols-1 gap-3",children:U.jsxs("div",{className:"flex-shrink-0 border rounded-lg p-3 shadow-md",style:{background:P},children:[U.jsx("img",{src:pA.image,alt:pA.title,className:"max-h-48 w-full rounded-md mb-2"}),U.jsx("h3",{className:"font-bold",children:pA.title}),pA.button?.map((Z,aA)=>U.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{if(Z.type==="link"&&typeof Z.action=="string")window.open(Z.action,"_blank");else if(Z.type==="postback"){const sA=(typeof Z.action=="string",Z.action);Ui(Z.label,sA)}else Z.type==="say-something"&&typeof Z.action=="string"&&Zi(sA=>[...sA,{sender:"agent",content:Z.action,id:`msg-${Date.now()}`,timestamp:new Date,seen:!0}])},style:{background:X,borderRadius:`${K}px`,color:y},children:Z.label},aA))]})})},p));case"slider":const FA=J.json.content.map(pA=>({image:pA.image,title:pA.caption,subtitle:"",actions:[]}));return U.jsx(up,{items:FA,chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"carousel":const ce=J.json.content.map(pA=>({image:pA.image,title:pA.title,subtitle:pA.description||"",actions:pA.button?.map(p=>({title:p.label,payload:p.action,action:p.type,url:typeof p.action=="string"?p.action:""}))||[]}));return U.jsx(up,{items:ce,chatRoundness:K,agentChatResponseBgColor:P,agentChatResponseColor:v,buttonsBgColor:X,buttonColor:y,inputBackgroundColor:u,onButtonClick:Ui,setMessages:Zi});case"products":return U.jsx(El,{products:J.json.content,onValidate:pA=>{Ui("cart ",pA)},agentChatResponseColor:v,agentChatResponseBgColor:P,buttonsBgColor:X,buttonColor:y,chatRoundness:K,panelWidth:ZA,inputBackgroundColor:u});default:return null}}},Nr=async J=>{if(!AB)return;const jA=await fetch(`${BQ}/endusers/get-by-username`,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({username:`web_user_${J}`})});if(!jA.ok)throw new Error(`HTTP error! status: ${jA.status}`);return(await jA.json()).id},VB=async J=>{if(!AB)return;const jA=await Nr(J);let RA;eB&&(RA={last_name:eB.split(" ")[1]||eB.split(" ")[0]||`web_user_${J}`,first_name:eB.split(" ")[0]||`web_user_${J}`}),fg&&(RA={...RA,phone:fg}),Mg&&(RA={...RA,email:Mg});const FA=await fetch(`${BQ}/endusers/${jA}`,{headers:{Authorization:`Bearer ${e?.token}`,"Content-Type":"application/json"},method:"PUT",body:JSON.stringify(RA)});if(!FA.ok)throw new Error(`HTTP error! status: ${FA.status}`);return await FA.json()},LI=async J=>{J.preventDefault();try{const RA=(await Ft.post(`${BQ}/conversations/start-conversation`,{bot_id:e.bot?.botId,externalUser:e.user.id})).data.conversationId;_o(RA),localStorage.setItem("conversationId",RA),localStorage.setItem("webChatAuth","true"),bi(!0),EQ.emit("join_room",parseInt(RA))}catch(jA){console.error("Error during login:",jA)}},[mB,wo]=vA.useState(!1),AI=async()=>{Zi([]),localStorage.removeItem("enduserUpdated");const J=localStorage.getItem("phone_client");if(e.bot?.botId==="rockskin"&&J)return vE(J),localStorage.setItem("externalUser",J),J;const jA=new Uint8Array(16);window.crypto.getRandomValues(jA);const RA=Array.from(jA).map(FA=>FA.toString(16).padStart(2,"0")).join("");vE(RA),localStorage.setItem("externalUser",RA),localStorage.removeItem("conversationId"),_o(null)},Ng=`linear-gradient(to bottom right, ${l}, ${c}, ${l})`,fo=`linear-gradient(to right, ${c}, ${w})`,QE=`linear-gradient(to right, ${D}, ${d})`,tB=async(J,jA)=>{try{let RA="";if(typeof J=="string")RA=J;else for(const FA of J)FA.type==="text"&&FA.text?RA+=`
|
|
636
636
|
`+FA.text||"":FA.type==="single-choice"&&FA.choices&&FA.choices.length>0?(RA+=`
|
|
637
637
|
`+FA.text||"",RA+=`
|
|
638
638
|
|