tybotflow-widget 0.8.7 → 0.8.8

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 CHANGED
@@ -64306,6 +64306,9 @@ const wh = "https://api.tybotflow.com/api/v1", jRA = "https://api.tybotflow.com/
64306
64306
  }, [TA, k, O]);
64307
64307
  const [mA, Cg] = fA.useState(!1), [Bg, lg] = fA.useState(!1), [eg, dA] = fA.useState(!1), [ZA, sA] = fA.useState(() => tA === "bottom-left" ? { x: 48, y: window.innerHeight - 120 } : tA === "middle-right" ? { x: window.innerWidth - 80, y: window.innerHeight / 2 - 35 } : { x: window.innerWidth - 123, y: window.innerHeight - 100 }), [RA, NA] = fA.useState(!1), [zA, Yg] = fA.useState({ x: 0, y: 0 }), Fg = fA.useRef(null), [Lg, jg] = fA.useState(""), [Rg, ng] = fA.useState(!1), [qg, ug] = fA.useState(!1), [Ng, kg] = fA.useState([]), [$g, FB] = fA.useState(!1), Xg = fA.useRef(0), [Wg, UB] = fA.useState(!1), [_E, MB] = fA.useState(!1), LI = fA.useRef(!1), [DC, Tg] = fA.useState("00:00"), fB = fA.useRef(null), dB = fA.useRef(0), [XB, qI] = fA.useState(null), [eB, QI] = fA.useState(!1), [II, $E] = fA.useState(/* @__PURE__ */ new Set()), [wI, gI] = fA.useState([]), { startRecording: DI, stopRecording: VI, pauseRecording: wE, resumeRecording: ZI, status: QB, error: zE } = uwA.useReactMediaRecorder({
64308
64308
  video: !1,
64309
+ blobPropertyBag: {
64310
+ type: "audio/mp3"
64311
+ },
64309
64312
  onStop(p, HA) {
64310
64313
  if (LI.current) {
64311
64314
  LI.current = !1, Tg("00:00"), dB.current = 0;
package/dist/index.umd.js CHANGED
@@ -632,7 +632,7 @@ end`};A.events.push(["putFont",function(C){(function(Q){var o=Q.font,w=Q.out,e=Q
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 yT(g,A){const[B,I]=fA.useState(null),E=fA.useMemo(()=>Object.entries(A).flat(),[A]);return fA.useEffect(()=>{if(!g?.current)return;const C=U4.create(Object.assign(Object.assign({},A),{container:g.current}));return I(C),()=>{C.destroy()}},[g,...E]),B}const LT=/^on([A-Z])/,RsA=g=>LT.test(g);function nsA(g,A){const B=fA.useMemo(()=>Object.entries(A).flat(),[A]);fA.useEffect(()=>{if(!g)return;const I=Object.entries(A);if(!I.length)return;const E=I.map(([C,Q])=>{const o=C.replace(LT,(w,e)=>e.toLowerCase());return g.on(o,(...w)=>Q(g,...w))});return()=>{E.forEach(C=>C())}},[g,...B])}fA.memo(g=>{const A=fA.useRef(null),[B,I]=function(E){return fA.useMemo(()=>{const C=Object.assign({},E),Q=Object.assign({},E);for(const o in C)RsA(o)?delete C[o]:delete Q[o];return[C,Q]},[E])}(g);return nsA(yT(A,B),I),u.jsx("div",{ref:A})});function FsA(g){var{container:A}=g;const B=yT(A,function(E,C){var Q={};for(var o in E)Object.prototype.hasOwnProperty.call(E,o)&&C.indexOf(o)<0&&(Q[o]=E[o]);if(E!=null&&typeof Object.getOwnPropertySymbols=="function"){var w=0;for(o=Object.getOwnPropertySymbols(E);w<o.length;w++)C.indexOf(o[w])<0&&Object.prototype.propertyIsEnumerable.call(E,o[w])&&(Q[o[w]]=E[o[w]])}return Q}(g,["container"])),I=function(E){const[C,Q]=fA.useState(!1),[o,w]=fA.useState(!1),[e,D]=fA.useState(!1),[t,s]=fA.useState(0);return fA.useEffect(()=>{if(!E)return;const a=[E.on("load",()=>{Q(!1),w(!1),s(0)}),E.on("ready",()=>{Q(!0),w(!1),D(!1),s(0)}),E.on("finish",()=>{D(!0)}),E.on("play",()=>{w(!0)}),E.on("pause",()=>{w(!1)}),E.on("timeupdate",()=>{s(E.getCurrentTime())}),E.on("destroy",()=>{Q(!1),w(!1)})];return()=>{a.forEach(G=>G())}},[E]),fA.useMemo(()=>({isReady:C,isPlaying:o,hasFinished:e,currentTime:t}),[o,e,t,C])}(B);return fA.useMemo(()=>Object.assign(Object.assign({},I),{wavesurfer:B}),[I,B])}const qT=({src:g,mainColor:A,secondaryColor:B,controlsColor:I})=>{const E=fA.useRef(null),[C,Q]=fA.useState(1),{wavesurfer:o,isPlaying:w}=FsA({container:E,waveColor:A,progressColor:B,barWidth:2,height:50,url:g}),e=()=>{o&&o.playPause()},D=()=>{const a=C===0?1:0;Q(a),o?.setVolume(a)},t=()=>{o?.skip(-.096)},s=()=>{o?.skip(.096)};return u.jsxs("div",{className:"flex w-full flex-col items-center rounded-xl pt-1",children:[u.jsx("div",{ref:E,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:I},onClick:D,"aria-label":"Toggle volume",children:C===0?u.jsx(bBA,{size:20}):u.jsx(TBA,{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:t,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":"Step back",children:u.jsx(ZBA,{})}),u.jsx("button",{onClick:e,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":w?"Pause":"Play",children:w?u.jsx(pBA,{}):u.jsx(yBA,{})}),u.jsx("button",{onClick:s,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":"Step forward",children:u.jsx(zBA,{})})]})]})]})},UsA=({attachment:g,formatFileSize:A,mainColor:B,secondaryColor:I,controlsColor:E})=>{const{type:C,url:Q,name:o,size:w}=g;switch(C){case"image":return u.jsxs("div",{className:"relative group",children:[u.jsx("img",{src:Q,alt:o,className:"max-w-xs max-h-48 size-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(Q,"_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(w)})]});case"video":return u.jsxs("div",{className:"max-w-xs",children:[u.jsx("video",{src:Q,controls:!0,className:"w-full max-h-48 rounded-lg",preload:"metadata",onError:()=>{console.error("Video failed to load:",Q)},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:o,children:o}),u.jsxs("span",{className:"ml-2",children:["• ",A(w)]})]})]});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(zR,{className:"w-4 h-4",style:{color:B}}),u.jsx("span",{className:"text-sm font-medium truncate text-white",title:o,children:o})]}),u.jsx(qT,{src:Q,mainColor:B,secondaryColor:I,controlsColor:E}),u.jsx("p",{className:"text-xs text-gray-400 mt-1",children:A(w)})]});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(Q,"_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(oM,{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:o}),u.jsx("p",{className:"text-xs text-gray-400",children:A(w)})]})]})});default:return null}},lsA=fA.memo(({attachment:g,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:[g.type==="image"&&g.url?u.jsx("img",{src:g.url,alt:g.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:[g.type==="video"&&u.jsx(nj,{className:"w-5 h-5 mb-1 text-red-400"}),g.type==="audio"&&u.jsx(zR,{className:"w-5 h-5 mb-1 text-green-400"}),g.type==="document"&&u.jsx(cj,{className:"w-5 h-5 mb-1 text-yellow-400"}),u.jsx("span",{className:"w-full truncate",title:g.name,children:g.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(tw,{className:"w-3 h-3"})})]})),xo=Object.create(null);xo.open="0",xo.close="1",xo.ping="2",xo.pong="3",xo.message="4",xo.upgrade="5",xo.noop="6";const iG=Object.create(null);Object.keys(xo).forEach(g=>{iG[xo[g]]=g});const l4={type:"error",data:"parser error"},VT=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ZT=typeof ArrayBuffer=="function",zT=g=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(g):g&&g.buffer instanceof ArrayBuffer,K4=({type:g,data:A},B,I)=>VT&&A instanceof Blob?B?I(A):WT(A,I):ZT&&(A instanceof ArrayBuffer||zT(A))?B?I(A):WT(new Blob([A]),I):I(xo[g]+(A||"")),WT=(g,A)=>{const B=new FileReader;return B.onload=function(){const I=B.result.split(",")[1];A("b"+(I||""))},B.readAsDataURL(g)};function TT(g){return g instanceof Uint8Array?g:g instanceof ArrayBuffer?new Uint8Array(g):new Uint8Array(g.buffer,g.byteOffset,g.byteLength)}let u4;function KsA(g,A){if(VT&&g.data instanceof Blob)return g.data.arrayBuffer().then(TT).then(A);if(ZT&&(g.data instanceof ArrayBuffer||zT(g.data)))return A(TT(g.data));K4(g,!1,B=>{u4||(u4=new TextEncoder),A(u4.encode(B))})}const bT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_t=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let g=0;g<bT.length;g++)_t[bT.charCodeAt(g)]=g;const usA=g=>{let A=g.length*.75,B=g.length,I,E=0,C,Q,o,w;g[g.length-1]==="="&&(A--,g[g.length-2]==="="&&A--);const e=new ArrayBuffer(A),D=new Uint8Array(e);for(I=0;I<B;I+=4)C=_t[g.charCodeAt(I)],Q=_t[g.charCodeAt(I+1)],o=_t[g.charCodeAt(I+2)],w=_t[g.charCodeAt(I+3)],D[E++]=C<<2|Q>>4,D[E++]=(Q&15)<<4|o>>2,D[E++]=(o&3)<<6|w&63;return e},SsA=typeof ArrayBuffer=="function",S4=(g,A)=>{if(typeof g!="string")return{type:"message",data:PT(g,A)};const B=g.charAt(0);return B==="b"?{type:"message",data:OsA(g.substring(1),A)}:iG[B]?g.length>1?{type:iG[B],data:g.substring(1)}:{type:iG[B]}:l4},OsA=(g,A)=>{if(SsA){const B=usA(g);return PT(B,A)}else return{base64:!0,data:g}},PT=(g,A)=>{switch(A){case"blob":return g instanceof Blob?g:new Blob([g]);case"arraybuffer":default:return g instanceof ArrayBuffer?g:g.buffer}},fT="",msA=(g,A)=>{const B=g.length,I=new Array(B);let E=0;g.forEach((C,Q)=>{K4(C,!1,o=>{I[Q]=o,++E===B&&A(I.join(fT))})})},ksA=(g,A)=>{const B=g.split(fT),I=[];for(let E=0;E<B.length;E++){const C=S4(B[E],A);if(I.push(C),C.type==="error")break}return I};function HsA(){return new TransformStream({transform(g,A){KsA(g,B=>{const I=B.length;let E;if(I<126)E=new Uint8Array(1),new DataView(E.buffer).setUint8(0,I);else if(I<65536){E=new Uint8Array(3);const C=new DataView(E.buffer);C.setUint8(0,126),C.setUint16(1,I)}else{E=new Uint8Array(9);const C=new DataView(E.buffer);C.setUint8(0,127),C.setBigUint64(1,BigInt(I))}g.data&&typeof g.data!="string"&&(E[0]|=128),A.enqueue(E),A.enqueue(B)})}})}let O4;function oG(g){return g.reduce((A,B)=>A+B.length,0)}function wG(g,A){if(g[0].length===A)return g.shift();const B=new Uint8Array(A);let I=0;for(let E=0;E<A;E++)B[E]=g[0][I++],I===g[0].length&&(g.shift(),I=0);return g.length&&I<g[0].length&&(g[0]=g[0].slice(I)),B}function JsA(g,A){O4||(O4=new TextDecoder);const B=[];let I=0,E=-1,C=!1;return new TransformStream({transform(Q,o){for(B.push(Q);;){if(I===0){if(oG(B)<1)break;const w=wG(B,1);C=(w[0]&128)===128,E=w[0]&127,E<126?I=3:E===126?I=1:I=2}else if(I===1){if(oG(B)<2)break;const w=wG(B,2);E=new DataView(w.buffer,w.byteOffset,w.length).getUint16(0),I=3}else if(I===2){if(oG(B)<8)break;const w=wG(B,8),e=new DataView(w.buffer,w.byteOffset,w.length),D=e.getUint32(0);if(D>Math.pow(2,21)-1){o.enqueue(l4);break}E=D*Math.pow(2,32)+e.getUint32(4),I=3}else{if(oG(B)<E)break;const w=wG(B,E);o.enqueue(S4(C?w:O4.decode(w),A)),I=0}if(E===0||E>g){o.enqueue(l4);break}}}})}const XT=4;function jE(g){if(g)return NsA(g)}function NsA(g){for(var A in jE.prototype)g[A]=jE.prototype[A];return g}jE.prototype.on=jE.prototype.addEventListener=function(g,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+g]=this._callbacks["$"+g]||[]).push(A),this},jE.prototype.once=function(g,A){function B(){this.off(g,B),A.apply(this,arguments)}return B.fn=A,this.on(g,B),this},jE.prototype.off=jE.prototype.removeListener=jE.prototype.removeAllListeners=jE.prototype.removeEventListener=function(g,A){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var B=this._callbacks["$"+g];if(!B)return this;if(arguments.length==1)return delete this._callbacks["$"+g],this;for(var I,E=0;E<B.length;E++)if(I=B[E],I===A||I.fn===A){B.splice(E,1);break}return B.length===0&&delete this._callbacks["$"+g],this},jE.prototype.emit=function(g){this._callbacks=this._callbacks||{};for(var A=new Array(arguments.length-1),B=this._callbacks["$"+g],I=1;I<arguments.length;I++)A[I-1]=arguments[I];if(B){B=B.slice(0);for(var I=0,E=B.length;I<E;++I)B[I].apply(this,A)}return this},jE.prototype.emitReserved=jE.prototype.emit,jE.prototype.listeners=function(g){return this._callbacks=this._callbacks||{},this._callbacks["$"+g]||[]},jE.prototype.hasListeners=function(g){return!!this.listeners(g).length};const MG=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,B)=>B(A,0),ii=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),xsA="arraybuffer";function QOA(){}function vT(g,...A){return A.reduce((B,I)=>(g.hasOwnProperty(I)&&(B[I]=g[I]),B),{})}const dsA=ii.setTimeout,jsA=ii.clearTimeout;function eG(g,A){A.useNativeTimers?(g.setTimeoutFn=dsA.bind(ii),g.clearTimeoutFn=jsA.bind(ii)):(g.setTimeoutFn=ii.setTimeout.bind(ii),g.clearTimeoutFn=ii.clearTimeout.bind(ii))}const psA=1.33;function ysA(g){return typeof g=="string"?LsA(g):Math.ceil((g.byteLength||g.size)*psA)}function LsA(g){let A=0,B=0;for(let I=0,E=g.length;I<E;I++)A=g.charCodeAt(I),A<128?B+=1:A<2048?B+=2:A<55296||A>=57344?B+=3:(I++,B+=4);return B}function _T(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function qsA(g){let A="";for(let B in g)g.hasOwnProperty(B)&&(A.length&&(A+="&"),A+=encodeURIComponent(B)+"="+encodeURIComponent(g[B]));return A}function VsA(g){let A={},B=g.split("&");for(let I=0,E=B.length;I<E;I++){let C=B[I].split("=");A[decodeURIComponent(C[0])]=decodeURIComponent(C[1])}return A}class ZsA extends Error{constructor(A,B,I){super(A),this.description=B,this.context=I,this.type="TransportError"}}class m4 extends jE{constructor(A){super(),this.writable=!1,eG(this,A),this.opts=A,this.query=A.query,this.socket=A.socket,this.supportsBinary=!A.forceBase64}onError(A,B,I){return super.emitReserved("error",new ZsA(A,B,I)),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 B=S4(A,this.socket.binaryType);this.onPacket(B)}onPacket(A){super.emitReserved("packet",A)}onClose(A){this.readyState="closed",super.emitReserved("close",A)}pause(A){}createUri(A,B={}){return A+"://"+this._hostname()+this._port()+this.opts.path+this._query(B)}_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 B=qsA(A);return B.length?"?"+B:""}}class zsA extends m4{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(A){this.readyState="pausing";const B=()=>{this.readyState="paused",A()};if(this._polling||!this.writable){let I=0;this._polling&&(I++,this.once("pollComplete",function(){--I||B()})),this.writable||(I++,this.once("drain",function(){--I||B()}))}else B()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(A){const B=I=>{if(this.readyState==="opening"&&I.type==="open"&&this.onOpen(),I.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(I)};ksA(A,this.socket.binaryType).forEach(B),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,msA(A,B=>{this.doWrite(B,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const A=this.opts.secure?"https":"http",B=this.query||{};return this.opts.timestampRequests!==!1&&(B[this.opts.timestampParam]=_T()),!this.supportsBinary&&!B.sid&&(B.b64=1),this.createUri(A,B)}}let $T=!1;try{$T=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const WsA=$T;function TsA(){}class bsA extends zsA{constructor(A){if(super(A),typeof location<"u"){const B=location.protocol==="https:";let I=location.port;I||(I=B?"443":"80"),this.xd=typeof location<"u"&&A.hostname!==location.hostname||I!==A.port}}doWrite(A,B){const I=this.request({method:"POST",data:A});I.on("success",B),I.on("error",(E,C)=>{this.onError("xhr post error",E,C)})}doPoll(){const A=this.request();A.on("data",this.onData.bind(this)),A.on("error",(B,I)=>{this.onError("xhr poll error",B,I)}),this.pollXhr=A}}let Ih=class Jr extends jE{constructor(A,B,I){super(),this.createRequest=A,eG(this,I),this._opts=I,this._method=I.method||"GET",this._uri=B,this._data=I.data!==void 0?I.data:null,this._create()}_create(){var A;const B=vT(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");B.xdomain=!!this._opts.xd;const I=this._xhr=this.createRequest(B);try{I.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){I.setDisableHeaderCheck&&I.setDisableHeaderCheck(!0);for(let E in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(E)&&I.setRequestHeader(E,this._opts.extraHeaders[E])}}catch{}if(this._method==="POST")try{I.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{I.setRequestHeader("Accept","*/*")}catch{}(A=this._opts.cookieJar)===null||A===void 0||A.addCookies(I),"withCredentials"in I&&(I.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(I.timeout=this._opts.requestTimeout),I.onreadystatechange=()=>{var E;I.readyState===3&&((E=this._opts.cookieJar)===null||E===void 0||E.parseCookies(I.getResponseHeader("set-cookie"))),I.readyState===4&&(I.status===200||I.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof I.status=="number"?I.status:0)},0))},I.send(this._data)}catch(E){this.setTimeoutFn(()=>{this._onError(E)},0);return}typeof document<"u"&&(this._index=Jr.requestsCount++,Jr.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=TsA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Jr.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(Ih.requestsCount=0,Ih.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ab);else if(typeof addEventListener=="function"){const g="onpagehide"in ii?"pagehide":"unload";addEventListener(g,Ab,!1)}}function Ab(){for(let g in Ih.requests)Ih.requests.hasOwnProperty(g)&&Ih.requests[g].abort()}const PsA=function(){const g=gb({xdomain:!1});return g&&g.responseType!==null}();class fsA extends bsA{constructor(A){super(A);const B=A&&A.forceBase64;this.supportsBinary=PsA&&!B}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new Ih(gb,this.uri(),A)}}function gb(g){const A=g.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||WsA))return new XMLHttpRequest}catch{}if(!A)try{return new ii[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Bb=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class XsA extends m4{get name(){return"websocket"}doOpen(){const A=this.uri(),B=this.opts.protocols,I=Bb?{}:vT(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(I.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(A,B,I)}catch(E){return this.emitReserved("error",E)}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 B=0;B<A.length;B++){const I=A[B],E=B===A.length-1;K4(I,this.supportsBinary,C=>{try{this.doWrite(I,C)}catch{}E&&MG(()=>{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",B=this.query||{};return this.opts.timestampRequests&&(B[this.opts.timestampParam]=_T()),this.supportsBinary||(B.b64=1),this.createUri(A,B)}}const k4=ii.WebSocket||ii.MozWebSocket;class vsA extends XsA{createSocket(A,B,I){return Bb?new k4(A,B,I):B?new k4(A,B):new k4(A)}doWrite(A,B){this.ws.send(B)}}class _sA extends m4{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 B=JsA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),I=A.readable.pipeThrough(B).getReader(),E=HsA();E.readable.pipeTo(A.writable),this._writer=E.writable.getWriter();const C=()=>{I.read().then(({done:o,value:w})=>{o||(this.onPacket(w),C())}).catch(o=>{})};C();const Q={type:"open"};this.query.sid&&(Q.data=`{"sid":"${this.query.sid}"}`),this._writer.write(Q).then(()=>this.onOpen())})})}write(A){this.writable=!1;for(let B=0;B<A.length;B++){const I=A[B],E=B===A.length-1;this._writer.write(I).then(()=>{E&&MG(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const $sA={websocket:vsA,webtransport:_sA,polling:fsA},AcA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,gcA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function H4(g){if(g.length>8e3)throw"URI too long";const A=g,B=g.indexOf("["),I=g.indexOf("]");B!=-1&&I!=-1&&(g=g.substring(0,B)+g.substring(B,I).replace(/:/g,";")+g.substring(I,g.length));let E=AcA.exec(g||""),C={},Q=14;for(;Q--;)C[gcA[Q]]=E[Q]||"";return B!=-1&&I!=-1&&(C.source=A,C.host=C.host.substring(1,C.host.length-1).replace(/;/g,":"),C.authority=C.authority.replace("[","").replace("]","").replace(/;/g,":"),C.ipv6uri=!0),C.pathNames=BcA(C,C.path),C.queryKey=IcA(C,C.query),C}function BcA(g,A){const B=/\/{2,9}/g,I=A.replace(B,"/").split("/");return(A.slice(0,1)=="/"||A.length===0)&&I.splice(0,1),A.slice(-1)=="/"&&I.splice(I.length-1,1),I}function IcA(g,A){const B={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(I,E,C){E&&(B[E]=C)}),B}const J4=typeof addEventListener=="function"&&typeof removeEventListener=="function",DG=[];J4&&addEventListener("offline",()=>{DG.forEach(g=>g())},!1);class UM extends jE{constructor(A,B){if(super(),this.binaryType=xsA,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,A&&typeof A=="object"&&(B=A,A=null),A){const I=H4(A);B.hostname=I.host,B.secure=I.protocol==="https"||I.protocol==="wss",B.port=I.port,I.query&&(B.query=I.query)}else B.host&&(B.hostname=H4(B.host).host);eG(this,B),this.secure=B.secure!=null?B.secure:typeof location<"u"&&location.protocol==="https:",B.hostname&&!B.port&&(B.port=this.secure?"443":"80"),this.hostname=B.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=B.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},B.transports.forEach(I=>{const E=I.prototype.name;this.transports.push(E),this._transportsByName[E]=I}),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},B),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VsA(this.opts.query)),J4&&(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"})},DG.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const B=Object.assign({},this.opts.query);B.EIO=XT,B.transport=A,this.id&&(B.sid=this.id);const I=Object.assign({},this.opts,{query:B,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[A]);return new this._transportsByName[A](I)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const A=this.opts.rememberUpgrade&&UM.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const B=this.createTransport(A);B.open(),this.setTransport(B)}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",B=>this._onClose("transport close",B))}onOpen(){this.readyState="open",UM.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 B=new Error("server error");B.code=A.data,this._onError(B);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 B=1;for(let I=0;I<this.writeBuffer.length;I++){const E=this.writeBuffer[I].data;if(E&&(B+=ysA(E)),I>0&&B>this._maxPayload)return this.writeBuffer.slice(0,I);B+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const A=Date.now()>this._pingTimeoutTime;return A&&(this._pingTimeoutTime=0,MG(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),A}write(A,B,I){return this._sendPacket("message",A,B,I),this}send(A,B,I){return this._sendPacket("message",A,B,I),this}_sendPacket(A,B,I,E){if(typeof B=="function"&&(E=B,B=void 0),typeof I=="function"&&(E=I,I=null),this.readyState==="closing"||this.readyState==="closed")return;I=I||{},I.compress=I.compress!==!1;const C={type:A,data:B,options:I};this.emitReserved("packetCreate",C),this.writeBuffer.push(C),E&&this.once("flush",E),this.flush()}close(){const A=()=>{this._onClose("forced close"),this.transport.close()},B=()=>{this.off("upgrade",B),this.off("upgradeError",B),A()},I=()=>{this.once("upgrade",B),this.once("upgradeError",B)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?I():A()}):this.upgrading?I():A()),this}_onError(A){if(UM.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,B){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(),J4&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const I=DG.indexOf(this._offlineEventListener);I!==-1&&DG.splice(I,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,B),this.writeBuffer=[],this._prevBufferLen=0}}}UM.protocol=XT;class EcA extends UM{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 B=this.createTransport(A),I=!1;UM.priorWebsocketSuccess=!1;const E=()=>{I||(B.send([{type:"ping",data:"probe"}]),B.once("packet",t=>{if(!I)if(t.type==="pong"&&t.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",B),!B)return;UM.priorWebsocketSuccess=B.name==="websocket",this.transport.pause(()=>{I||this.readyState!=="closed"&&(D(),this.setTransport(B),B.send([{type:"upgrade"}]),this.emitReserved("upgrade",B),B=null,this.upgrading=!1,this.flush())})}else{const s=new Error("probe error");s.transport=B.name,this.emitReserved("upgradeError",s)}}))};function C(){I||(I=!0,D(),B.close(),B=null)}const Q=t=>{const s=new Error("probe error: "+t);s.transport=B.name,C(),this.emitReserved("upgradeError",s)};function o(){Q("transport closed")}function w(){Q("socket closed")}function e(t){B&&t.name!==B.name&&C()}const D=()=>{B.removeListener("open",E),B.removeListener("error",Q),B.removeListener("close",o),this.off("close",w),this.off("upgrading",e)};B.once("open",E),B.once("error",Q),B.once("close",o),this.once("close",w),this.once("upgrading",e),this._upgrades.indexOf("webtransport")!==-1&&A!=="webtransport"?this.setTimeoutFn(()=>{I||B.open()},200):B.open()}onHandshake(A){this._upgrades=this._filterUpgrades(A.upgrades),super.onHandshake(A)}_filterUpgrades(A){const B=[];for(let I=0;I<A.length;I++)~this.transports.indexOf(A[I])&&B.push(A[I]);return B}}let CcA=class extends EcA{constructor(A,B={}){const I=typeof A=="object"?A:B;(!I.transports||I.transports&&typeof I.transports[0]=="string")&&(I.transports=(I.transports||["polling","websocket","webtransport"]).map(E=>$sA[E]).filter(E=>!!E)),super(A,I)}};function QcA(g,A="",B){let I=g;B=B||typeof location<"u"&&location,g==null&&(g=B.protocol+"//"+B.host),typeof g=="string"&&(g.charAt(0)==="/"&&(g.charAt(1)==="/"?g=B.protocol+g:g=B.host+g),/^(https?|wss?):\/\//.test(g)||(typeof B<"u"?g=B.protocol+"//"+g:g="https://"+g),I=H4(g)),I.port||(/^(http|ws)$/.test(I.protocol)?I.port="80":/^(http|ws)s$/.test(I.protocol)&&(I.port="443")),I.path=I.path||"/";const C=I.host.indexOf(":")!==-1?"["+I.host+"]":I.host;return I.id=I.protocol+"://"+C+":"+I.port+A,I.href=I.protocol+"://"+C+(B&&B.port===I.port?"":":"+I.port),I}const icA=typeof ArrayBuffer=="function",ocA=g=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(g):g.buffer instanceof ArrayBuffer,Ib=Object.prototype.toString,wcA=typeof Blob=="function"||typeof Blob<"u"&&Ib.call(Blob)==="[object BlobConstructor]",McA=typeof File=="function"||typeof File<"u"&&Ib.call(File)==="[object FileConstructor]";function N4(g){return icA&&(g instanceof ArrayBuffer||ocA(g))||wcA&&g instanceof Blob||McA&&g instanceof File}function hG(g,A){if(!g||typeof g!="object")return!1;if(Array.isArray(g)){for(let B=0,I=g.length;B<I;B++)if(hG(g[B]))return!0;return!1}if(N4(g))return!0;if(g.toJSON&&typeof g.toJSON=="function"&&arguments.length===1)return hG(g.toJSON(),!0);for(const B in g)if(Object.prototype.hasOwnProperty.call(g,B)&&hG(g[B]))return!0;return!1}function ecA(g){const A=[],B=g.data,I=g;return I.data=x4(B,A),I.attachments=A.length,{packet:I,buffers:A}}function x4(g,A){if(!g)return g;if(N4(g)){const B={_placeholder:!0,num:A.length};return A.push(g),B}else if(Array.isArray(g)){const B=new Array(g.length);for(let I=0;I<g.length;I++)B[I]=x4(g[I],A);return B}else if(typeof g=="object"&&!(g instanceof Date)){const B={};for(const I in g)Object.prototype.hasOwnProperty.call(g,I)&&(B[I]=x4(g[I],A));return B}return g}function DcA(g,A){return g.data=d4(g.data,A),delete g.attachments,g}function d4(g,A){if(!g)return g;if(g&&g._placeholder===!0){if(typeof g.num=="number"&&g.num>=0&&g.num<A.length)return A[g.num];throw new Error("illegal attachments")}else if(Array.isArray(g))for(let B=0;B<g.length;B++)g[B]=d4(g[B],A);else if(typeof g=="object")for(const B in g)Object.prototype.hasOwnProperty.call(g,B)&&(g[B]=d4(g[B],A));return g}const hcA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],tcA=5;var bB;(function(g){g[g.CONNECT=0]="CONNECT",g[g.DISCONNECT=1]="DISCONNECT",g[g.EVENT=2]="EVENT",g[g.ACK=3]="ACK",g[g.CONNECT_ERROR=4]="CONNECT_ERROR",g[g.BINARY_EVENT=5]="BINARY_EVENT",g[g.BINARY_ACK=6]="BINARY_ACK"})(bB||(bB={}));class acA{constructor(A){this.replacer=A}encode(A){return(A.type===bB.EVENT||A.type===bB.ACK)&&hG(A)?this.encodeAsBinary({type:A.type===bB.EVENT?bB.BINARY_EVENT:bB.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let B=""+A.type;return(A.type===bB.BINARY_EVENT||A.type===bB.BINARY_ACK)&&(B+=A.attachments+"-"),A.nsp&&A.nsp!=="/"&&(B+=A.nsp+","),A.id!=null&&(B+=A.id),A.data!=null&&(B+=JSON.stringify(A.data,this.replacer)),B}encodeAsBinary(A){const B=ecA(A),I=this.encodeAsString(B.packet),E=B.buffers;return E.unshift(I),E}}function Eb(g){return Object.prototype.toString.call(g)==="[object Object]"}class j4 extends jE{constructor(A){super(),this.reviver=A}add(A){let B;if(typeof A=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");B=this.decodeString(A);const I=B.type===bB.BINARY_EVENT;I||B.type===bB.BINARY_ACK?(B.type=I?bB.EVENT:bB.ACK,this.reconstructor=new scA(B),B.attachments===0&&super.emitReserved("decoded",B)):super.emitReserved("decoded",B)}else if(N4(A)||A.base64)if(this.reconstructor)B=this.reconstructor.takeBinaryData(A),B&&(this.reconstructor=null,super.emitReserved("decoded",B));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+A)}decodeString(A){let B=0;const I={type:Number(A.charAt(0))};if(bB[I.type]===void 0)throw new Error("unknown packet type "+I.type);if(I.type===bB.BINARY_EVENT||I.type===bB.BINARY_ACK){const C=B+1;for(;A.charAt(++B)!=="-"&&B!=A.length;);const Q=A.substring(C,B);if(Q!=Number(Q)||A.charAt(B)!=="-")throw new Error("Illegal attachments");I.attachments=Number(Q)}if(A.charAt(B+1)==="/"){const C=B+1;for(;++B&&!(A.charAt(B)===","||B===A.length););I.nsp=A.substring(C,B)}else I.nsp="/";const E=A.charAt(B+1);if(E!==""&&Number(E)==E){const C=B+1;for(;++B;){const Q=A.charAt(B);if(Q==null||Number(Q)!=Q){--B;break}if(B===A.length)break}I.id=Number(A.substring(C,B+1))}if(A.charAt(++B)){const C=this.tryParse(A.substr(B));if(j4.isPayloadValid(I.type,C))I.data=C;else throw new Error("invalid payload")}return I}tryParse(A){try{return JSON.parse(A,this.reviver)}catch{return!1}}static isPayloadValid(A,B){switch(A){case bB.CONNECT:return Eb(B);case bB.DISCONNECT:return B===void 0;case bB.CONNECT_ERROR:return typeof B=="string"||Eb(B);case bB.EVENT:case bB.BINARY_EVENT:return Array.isArray(B)&&(typeof B[0]=="number"||typeof B[0]=="string"&&hcA.indexOf(B[0])===-1);case bB.ACK:case bB.BINARY_ACK:return Array.isArray(B)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class scA{constructor(A){this.packet=A,this.buffers=[],this.reconPack=A}takeBinaryData(A){if(this.buffers.push(A),this.buffers.length===this.reconPack.attachments){const B=DcA(this.reconPack,this.buffers);return this.finishedReconstruction(),B}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ccA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:j4,Encoder:acA,get PacketType(){return bB},protocol:tcA},Symbol.toStringTag,{value:"Module"}));function Vi(g,A,B){return g.on(A,B),function(){g.off(A,B)}}const GcA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Cb extends jE{constructor(A,B,I){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=B,I&&I.auth&&(this.auth=I.auth),this._opts=Object.assign({},I),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const A=this.io;this.subs=[Vi(A,"open",this.onopen.bind(this)),Vi(A,"packet",this.onpacket.bind(this)),Vi(A,"error",this.onerror.bind(this)),Vi(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,...B){var I,E,C;if(GcA.hasOwnProperty(A))throw new Error('"'+A.toString()+'" is a reserved event name');if(B.unshift(A),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(B),this;const Q={type:bB.EVENT,data:B};if(Q.options={},Q.options.compress=this.flags.compress!==!1,typeof B[B.length-1]=="function"){const D=this.ids++,t=B.pop();this._registerAckCallback(D,t),Q.id=D}const o=(E=(I=this.io.engine)===null||I===void 0?void 0:I.transport)===null||E===void 0?void 0:E.writable,w=this.connected&&!(!((C=this.io.engine)===null||C===void 0)&&C._hasPingExpired());return this.flags.volatile&&!o||(w?(this.notifyOutgoingListeners(Q),this.packet(Q)):this.sendBuffer.push(Q)),this.flags={},this}_registerAckCallback(A,B){var I;const E=(I=this.flags.timeout)!==null&&I!==void 0?I:this._opts.ackTimeout;if(E===void 0){this.acks[A]=B;return}const C=this.io.setTimeoutFn(()=>{delete this.acks[A];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===A&&this.sendBuffer.splice(o,1);B.call(this,new Error("operation has timed out"))},E),Q=(...o)=>{this.io.clearTimeoutFn(C),B.apply(this,o)};Q.withError=!0,this.acks[A]=Q}emitWithAck(A,...B){return new Promise((I,E)=>{const C=(Q,o)=>Q?E(Q):I(o);C.withError=!0,B.push(C),this.emit(A,...B)})}_addToQueue(A){let B;typeof A[A.length-1]=="function"&&(B=A.pop());const I={id:this._queueSeq++,tryCount:0,pending:!1,args:A,flags:Object.assign({fromQueue:!0},this.flags)};A.push((E,...C)=>I!==this._queue[0]?void 0:(E!==null?I.tryCount>this._opts.retries&&(this._queue.shift(),B&&B(E)):(this._queue.shift(),B&&B(null,...C)),I.pending=!1,this._drainQueue())),this._queue.push(I),this._drainQueue()}_drainQueue(A=!1){if(!this.connected||this._queue.length===0)return;const B=this._queue[0];B.pending&&!A||(B.pending=!0,B.tryCount++,this.flags=B.flags,this.emit.apply(this,B.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:bB.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,B){this.connected=!1,delete this.id,this.emitReserved("disconnect",A,B),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(A=>{if(!this.sendBuffer.some(I=>String(I.id)===A)){const I=this.acks[A];delete this.acks[A],I.withError&&I.call(this,new Error("socket has been disconnected"))}})}onpacket(A){if(A.nsp===this.nsp)switch(A.type){case bB.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 bB.EVENT:case bB.BINARY_EVENT:this.onevent(A);break;case bB.ACK:case bB.BINARY_ACK:this.onack(A);break;case bB.DISCONNECT:this.ondisconnect();break;case bB.CONNECT_ERROR:this.destroy();const I=new Error(A.data.message);I.data=A.data.data,this.emitReserved("connect_error",I);break}}onevent(A){const B=A.data||[];A.id!=null&&B.push(this.ack(A.id)),this.connected?this.emitEvent(B):this.receiveBuffer.push(Object.freeze(B))}emitEvent(A){if(this._anyListeners&&this._anyListeners.length){const B=this._anyListeners.slice();for(const I of B)I.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 B=this;let I=!1;return function(...E){I||(I=!0,B.packet({type:bB.ACK,id:A,data:E}))}}onack(A){const B=this.acks[A.id];typeof B=="function"&&(delete this.acks[A.id],B.withError&&A.data.unshift(null),B.apply(this,A.data))}onconnect(A,B){this.id=A,this.recovered=B&&this._pid===B,this._pid=B,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:bB.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 B=this._anyListeners;for(let I=0;I<B.length;I++)if(A===B[I])return B.splice(I,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 B=this._anyOutgoingListeners;for(let I=0;I<B.length;I++)if(A===B[I])return B.splice(I,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(A){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const B=this._anyOutgoingListeners.slice();for(const I of B)I.apply(this,A.data)}}}function Eh(g){g=g||{},this.ms=g.min||100,this.max=g.max||1e4,this.factor=g.factor||2,this.jitter=g.jitter>0&&g.jitter<=1?g.jitter:0,this.attempts=0}Eh.prototype.duration=function(){var g=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var A=Math.random(),B=Math.floor(A*this.jitter*g);g=(Math.floor(A*10)&1)==0?g-B:g+B}return Math.min(g,this.max)|0},Eh.prototype.reset=function(){this.attempts=0},Eh.prototype.setMin=function(g){this.ms=g},Eh.prototype.setMax=function(g){this.max=g},Eh.prototype.setJitter=function(g){this.jitter=g};class p4 extends jE{constructor(A,B){var I;super(),this.nsps={},this.subs=[],A&&typeof A=="object"&&(B=A,A=void 0),B=B||{},B.path=B.path||"/socket.io",this.opts=B,eG(this,B),this.reconnection(B.reconnection!==!1),this.reconnectionAttempts(B.reconnectionAttempts||1/0),this.reconnectionDelay(B.reconnectionDelay||1e3),this.reconnectionDelayMax(B.reconnectionDelayMax||5e3),this.randomizationFactor((I=B.randomizationFactor)!==null&&I!==void 0?I:.5),this.backoff=new Eh({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(B.timeout==null?2e4:B.timeout),this._readyState="closed",this.uri=A;const E=B.parser||ccA;this.encoder=new E.Encoder,this.decoder=new E.Decoder,this._autoConnect=B.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 B;return A===void 0?this._reconnectionDelay:(this._reconnectionDelay=A,(B=this.backoff)===null||B===void 0||B.setMin(A),this)}randomizationFactor(A){var B;return A===void 0?this._randomizationFactor:(this._randomizationFactor=A,(B=this.backoff)===null||B===void 0||B.setJitter(A),this)}reconnectionDelayMax(A){var B;return A===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=A,(B=this.backoff)===null||B===void 0||B.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 CcA(this.uri,this.opts);const B=this.engine,I=this;this._readyState="opening",this.skipReconnect=!1;const E=Vi(B,"open",function(){I.onopen(),A&&A()}),C=o=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",o),A?A(o):this.maybeReconnectOnOpen()},Q=Vi(B,"error",C);if(this._timeout!==!1){const o=this._timeout,w=this.setTimeoutFn(()=>{E(),C(new Error("timeout")),B.close()},o);this.opts.autoUnref&&w.unref(),this.subs.push(()=>{this.clearTimeoutFn(w)})}return this.subs.push(E),this.subs.push(Q),this}connect(A){return this.open(A)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const A=this.engine;this.subs.push(Vi(A,"ping",this.onping.bind(this)),Vi(A,"data",this.ondata.bind(this)),Vi(A,"error",this.onerror.bind(this)),Vi(A,"close",this.onclose.bind(this)),Vi(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(A){try{this.decoder.add(A)}catch(B){this.onclose("parse error",B)}}ondecoded(A){MG(()=>{this.emitReserved("packet",A)},this.setTimeoutFn)}onerror(A){this.emitReserved("error",A)}socket(A,B){let I=this.nsps[A];return I?this._autoConnect&&!I.active&&I.connect():(I=new Cb(this,A,B),this.nsps[A]=I),I}_destroy(A){const B=Object.keys(this.nsps);for(const I of B)if(this.nsps[I].active)return;this._close()}_packet(A){const B=this.encoder.encode(A);for(let I=0;I<B.length;I++)this.engine.write(B[I],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,B){var I;this.cleanup(),(I=this.engine)===null||I===void 0||I.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",A,B),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 B=this.backoff.duration();this._reconnecting=!0;const I=this.setTimeoutFn(()=>{A.skipReconnect||(this.emitReserved("reconnect_attempt",A.backoff.attempts),!A.skipReconnect&&A.open(E=>{E?(A._reconnecting=!1,A.reconnect(),this.emitReserved("reconnect_error",E)):A.onreconnect()}))},B);this.opts.autoUnref&&I.unref(),this.subs.push(()=>{this.clearTimeoutFn(I)})}}onreconnect(){const A=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",A)}}const $t={};function tG(g,A){typeof g=="object"&&(A=g,g=void 0),A=A||{};const B=QcA(g,A.path||"/socket.io"),I=B.source,E=B.id,C=B.path,Q=$t[E]&&C in $t[E].nsps,o=A.forceNew||A["force new connection"]||A.multiplex===!1||Q;let w;return o?w=new p4(I,A):($t[E]||($t[E]=new p4(I,A)),w=$t[E]),B.query&&!A.query&&(A.query=B.queryKey),w.socket(B.path,A)}Object.assign(tG,{Manager:p4,Socket:Cb,io:tG,connect:tG});const Ch="https://api.tybotflow.com/api/v1",YcA="https://api.tybotflow.com/api/v1/chatbots-config",Qb="https://migration-meta.tybotflow.com/",ib=Qb+"webhook/v",aG=tG(Qb,{transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:3,autoConnect:!0,reconnectionDelay:2e3}),ob=new Kw,y4=g=>{if(!g||!g.message)return"👋 Hey there! how can I help you?";const A=g.message;if(typeof A=="string")return A;if(Array.isArray(A)){const B=window.location.href,I=window.location.origin,E=window.location.pathname,C=I+E;for(const o of A){if(!o.urls||o.urls.length===0)continue;if(o.urls.some(e=>{if(!e||e.trim()==="")return!1;try{let D=e.trim();!D.startsWith("http://")&&!D.startsWith("https://")&&(D="https://"+D);const t=new URL(D),s=t.origin,a=t.pathname,G=s+a;return C===G||B===D?!0:a==="/"||a===""?I===s:!!B.startsWith(D)}catch{return console.warn("Invalid URL in message:",e),!1}}))return o.text||"👋 Hey there! how can I help you?"}const Q=A.find(o=>!o.urls||o.urls.length===0||o.urls.every(w=>!w||w.trim()===""));if(Q)return Q.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?"},wb=(g,A)=>{const B={className:"w-5 h-5",style:{color:A}};switch(g?.toLowerCase()){case"pdf":return u.jsx(oM,{...B});case"doc":case"docx":return u.jsx(oM,{...B});case"xls":case"xlsx":case"csv":return u.jsx(HBA,{...B});case"ppt":case"pptx":return u.jsx(LBA,{...B});case"zip":case"rar":case"7z":case"tar":case"gz":return u.jsx(uBA,{...B});case"txt":case"md":case"rtf":return u.jsx(cj,{...B});default:return u.jsx(oM,{...B})}},rcA=({config:g})=>{const A=fA.useRef(null),B=fA.useRef(null),I=fA.useRef(null),E=fA.useRef(null),C=fA.useRef(null),[Q,o]=fA.useState(null),[w,e]=fA.useState(!0),[D,t]=fA.useState(!1);fA.useEffect(()=>{(async()=>{e(!0),await kI.get(`${YcA}/bot/${g.bot?.botId}`,{}).then(HA=>{o(HA.data)}).catch(HA=>{console.error("Error fetching bot config:",HA)}).finally(()=>{e(!1)})})()},[g.bot?.botId,g?.token]);const s=Q?.mainColor||"#59168b",a=Q?.secondaryColor||"#6366f1",G=Q?.thirdColor||"#0f172b",r=Q?.headerFirstColor||"#6e11b0",U=Q?.headerSecondColor||"#372aac",R=Q?.inputBackgroundColor||"#1f2937",l=Q?.inputTextColor||"#fff",K=Q?.roundness||24,m=Q?.chatRoundness||16,k=(Q?.minPanelWidth||434)>window.innerWidth?window.innerWidth:Q?.minPanelWidth||434,O=(Q?.maxPanelWidth||window.innerWidth)>window.innerWidth?window.innerWidth:Q?.maxPanelWidth||window.innerWidth,y=Q?.chatMaxWidth||88,L=Q?.toggleBtnBorderTopLeftRadius||12,j=Q?.toggleBtnBorderTopRightRadius||0,Z=Q?.toggleBtnBorderBottomLeftRadius||12,d=Q?.toggleBtnBorderBottomRightRadius||0,z=Q?.menuBackgroundColor||"#1f2937",T=Q?.menuTextColor||"#e5e7eb",W=Q?.menuHoverBackgroundColor||"#374151",X=Q?.agentChatResponseColor||"#e5e7eb",P=Q?.agentChatResponseBgColor||"#1f2937",EA=Q?.agentIconBgColor||"#59168b",$=Q?.agentIconColor||"#fff",oA=Q?.userChatMessagesColor||"#fff",N=Q?.userChatMessagesBgColor||"#7a1ebe",AA=Q?.userIconBgColor||"#7a1ebe",V=Q?.userIconColor||"#fff",J=Q?.ButtonColor||"#fff",f=Q?.ButtonsBgColor||"#59168b",iA=_E(P,10),wA=Q?.fontSize||13,tA=Q?.toggleBtnPosition||"bottom-right",rA=Q?.autoOpenPanel??!0,UA=Q?.tempToken||"",PA=(()=>{const p=Q?.firstMessageKeyword;if(Array.isArray(p)){const HA=window.location.href,lA=p.find(rg=>rg.url&&rg.url===HA);if(lA)return lA.message;const uA=p.find(rg=>!rg.url||rg.url==="");return uA?uA.message:p[0]?.message||"hi"}return p||"hi"})(),sg=p=>({ip:p.ip||"",flag:{img:p.flag||"",emoji:p.emoji_flag||"",emoji_unicode:p.emoji_unicode||""},is_eu:p.is_eu??!1,postal:p.postal||"",borders:"",latitude:p.latitude||0,platform:p?.platform||"",timezone:{id:p.time_zone?.name||"",utc:p.time_zone?.offset||"",abbr:p.time_zone?.abbr||"",is_dst:p.time_zone?.is_dst??!1,offset:p.time_zone?.offset||0,current_time:p.time_zone?.current_time||""},continent:p.continent_name||"",longitude:p.longitude||0,connection:{asn:p.asn?.asn||0,isp:p.asn?.name||"",org:p.asn?.name||"",domain:p.asn?.domain||""}}),[TA,JA]=fA.useState(k),IA=fA.useRef(!1),Ig=fA.useRef(0),Gg=fA.useRef(k),wg=p=>{IA.current=!0,Ig.current=p.clientX,Gg.current=TA,document.body.style.cursor="ew-resize"};fA.useEffect(()=>{const p=lA=>{if(!IA.current)return;const uA=Ig.current-lA.clientX;let rg=Gg.current+uA;rg=Math.max(k,Math.min(O,rg)),JA(rg)},HA=()=>{IA.current&&(IA.current=!1,document.body.style.cursor="")};return window.addEventListener("mousemove",p),window.addEventListener("mouseup",HA),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",HA)}},[TA,k,O]);const[mA,Cg]=fA.useState(!1),[Bg,lg]=fA.useState(!1),[Dg,dA]=fA.useState(!1),[ZA,sA]=fA.useState(()=>tA==="bottom-left"?{x:48,y:window.innerHeight-120}:tA==="middle-right"?{x:window.innerWidth-80,y:window.innerHeight/2-35}:{x:window.innerWidth-123,y:window.innerHeight-100}),[RA,NA]=fA.useState(!1),[zA,Yg]=fA.useState({x:0,y:0}),Ug=fA.useRef(null),[qg,jg]=fA.useState(""),[Rg,ng]=fA.useState(!1),[Vg,ug]=fA.useState(!1),[Ng,Hg]=fA.useState([]),[$g,lB]=fA.useState(!1),Xg=fA.useRef(0),[Wg,KB]=fA.useState(!1),[BC,eB]=fA.useState(!1),ZI=fA.useRef(!1),[sC,Tg]=fA.useState("00:00"),XB=fA.useRef(null),pB=fA.useRef(0),[vB,zI]=fA.useState(null),[DB,QI]=fA.useState(!1),[EI,IC]=fA.useState(new Set),[eI,gI]=fA.useState([]),{startRecording:DI,stopRecording:WI,pauseRecording:hE,resumeRecording:TI,status:QB,error:WE}=aiA.useReactMediaRecorder({video:!1,onStop(p,HA){if(ZI.current){ZI.current=!1,Tg("00:00"),pB.current=0;return}Hg(lA=>[...lA,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:HA,type:"audio",url:p,name:`recording-${new Date().toISOString()}.webm`,size:HA.size}]),Tg("00:00"),pB.current=0}}),mg=Q?.icon||g?.bot.avatar_url||Cz,cA=Q?.title||g?.bot.name||"Tybot webchat",[$A,Sg]=fA.useState(null),[HB,GI]=fA.useState(()=>{const p=localStorage.getItem("phone_client");if(g.bot?.botId==="rockskin"&&p)return p;if(!Q?.botNeedsAuth){let HA=localStorage.getItem("externalUser");if(!HA){const lA=new Uint8Array(16);window.crypto.getRandomValues(lA),HA=Array.from(lA).map(uA=>uA.toString(16).padStart(2,"0")).join("")}return localStorage.setItem("externalUser",HA),HA}});fA.useEffect(()=>{if(!$A)return;const p=HA=>{if(HA.bot.conversationId!==parseInt($A)||HA.bot.botId!==g?.bot?.botId){ng(!1);return}const lA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:HA.bot.item,timestamp:new Date,seen:LC.current,nMessage:Array.isArray(HA.bot.item)?HA.bot.item.length:1};gI(uA=>uA.some(kA=>kA.id===lA.id)?uA:[...uA,lA]),ng(!1)};return aG.on("bot-message",p),()=>{aG.off("bot-message",p)}},[$A,g?.bot?.botId]),fA.useEffect(()=>{(async()=>{if(!($A||!g.bot?.botId||!HB))try{const lA=(await kI.post(`${Ch}/conversations/start-conversation`,{bot_id:g.bot?.botId,externalUser:HB})).data.conversationId;Sg(lA),localStorage.setItem("conversationId",lA),aG.emit("join_room",parseInt(lA))}catch(HA){console.error("Error initializing conversation:",HA)}})()},[$A,g.bot?.botId,HB]);const[ZB,NI]=fA.useState(()=>Q?.botNeedsAuth?!!localStorage.getItem("conversationId"):!0),[PB,bI]=fA.useState(""),[cC,YI]=fA.useState(""),[TE,TQ]=fA.useState(""),[yC,Vo]=fA.useState(null),LC=fA.useRef(!1),RB=eI.reduce((p,HA)=>HA.seen?p:p+(HA.sender==="agent"?HA.nMessage||1:0),0),vi=()=>{gI(p=>p.map(HA=>({...HA,seen:!0})))};fA.useEffect(()=>{let p;return!localStorage.getItem("webChatOpen")&&Q&&rA&&(p=setTimeout(()=>{Cg(!0),LC.current=!0,vi(),localStorage.setItem("webChatOpen","true")},3200)),()=>clearTimeout(p)},[Q]),fA.useEffect(()=>{const p=Q?.widgetLoadBehavior;if(!p||!(()=>{const uA=p.message;if(typeof uA=="string"){if(!p.urls||p.urls.length===0)return!0;const rg=window.location.origin,kA=window.location.href;return p.urls.some(AB=>{if(!AB||AB.trim()==="")return!0;try{return rg.includes(AB)||kA.includes(AB)||AB.includes(rg)}catch{return console.warn("Invalid URL in widgetLoadBehavior:",AB),!1}})}if(Array.isArray(uA)){const rg=window.location.href,kA=window.location.origin,AB=window.location.pathname,hB=kA+AB;for(const rI of uA)if(!rI.urls||rI.urls.length===0||rI.urls.every(IE=>!IE||IE.trim()==="")||rI.urls.some(IE=>{if(!IE||IE.trim()==="")return!1;try{let xI=IE.trim();!xI.startsWith("http://")&&!xI.startsWith("https://")&&(xI="https://"+xI);const qE=new URL(xI),Pg=qE.origin,fQ=qE.pathname,OB=Pg+fQ;return hB===OB||rg===xI?!0:fQ==="/"||fQ===""?kA===Pg:!!rg.startsWith(xI)}catch{return console.warn("Invalid URL in message:",IE),!1}}))return!0;return!1}return!0})())return;let lA;if(p.behavior==="after seconds")lA=setTimeout(()=>{dA(!0)},p.value*1e3);else if(p.behavior==="after scroll"){const uA=()=>{const rg=window.pageYOffset||document.documentElement.scrollTop,kA=document.documentElement.scrollHeight-document.documentElement.clientHeight;rg/kA*100>=p.value&&(dA(!0),window.removeEventListener("scroll",uA))};return window.addEventListener("scroll",uA),()=>{window.removeEventListener("scroll",uA)}}return()=>{lA&&clearTimeout(lA)}},[Q?.widgetLoadBehavior]),fA.useEffect(()=>{mA&&dA(!1)},[mA]),fA.useEffect(()=>{fetch("https://api.ipdata.co/?api-key=7930ffd0621dafcb6cd830a503d726bf514b74c1cae21ffff8131890").then(function(p){p.json().then(HA=>{Vo({...HA,platform:ob.getOS().name+" "+ob.getOS().version})})}).catch(function(p){console.log(p)})},[]);const Zo=fA.useCallback(async(p,HA=[],lA)=>{if(!g.bot.botId||!$A){ng(!1),gI(rg=>[...rg,{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(HA.length>0||lA&&typeof lA=="object"&&lA.attachment!==void 0){const rg=lA&&typeof lA!="string"?lA.attachment.file:HA[0]?.file,kA=lA&&typeof lA!="string"?lA.attachment.type:HA[0]?.type||"file";let AB=lA;if(lA&&typeof lA=="object"&&lA.attachment!==void 0){const{attachment:rI,...mB}=lA;AB=mB}const hB=new FormData;hB.append("type",kA),hB.append("file",rg),hB.append("botId",g.bot.botId),hB.append("external_id",HB||""),hB.append("isintern",g.token?"true":"false"),hB.append("host",window.location.origin),hB.append("channel","web"),hB.append("payload",AB?JSON.stringify(AB):""),await kI.post(ib,hB,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"multipart/form-data"}})}else{const rg={type:"text",messageText:p,botId:g.bot.botId,external_id:HB||"",isintern:!!g.token,host:window.location.origin,channel:"web"};lA&&(rg.payload=lA),await kI.post(ib,rg,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"}})}},[g.bot.botId,$A,g.token,g.user?.id]),GC=fA.useCallback(async()=>{if(g.bot.botId&&$A){ng(!0);try{await Zo(PA)}catch(p){console.error("Error sending first message:",p),ng(!1)}}},[g.bot.botId,PA,$A,Zo]);fA.useEffect(()=>{$A&&ZB&&g?.bot&&eI.length===0&&Q&&rA&&(GC(),localStorage.getItem("webChatAuth")&&JSON.parse(localStorage.getItem("webChatAuth"))&&Q?.botNeedsAuth&&$A&&(PB||TE||cC)&&(setTimeout(()=>{OQ($A)},2e3),localStorage.setItem("webChatAuth","true")))},[ZB,g?.bot,$A,Q]),fA.useEffect(()=>(QB==="recording"?XB.current||(XB.current=setInterval(()=>{pB.current+=1;const p=Math.floor(pB.current/60).toString().padStart(2,"0"),HA=(pB.current%60).toString().padStart(2,"0");Tg(`${p}:${HA}`)},1e3)):XB.current&&(clearInterval(XB.current),XB.current=null),()=>{XB.current&&(clearInterval(XB.current),XB.current=null)}),[QB]),fA.useEffect(()=>{WE&&WE.toLowerCase().includes("permission_denied")&&(eB(!1),Tg("00:00"),pB.current=0,XB.current&&(clearInterval(XB.current),XB.current=null),alert("Microphone permission denied. Please allow access to record audio."))},[WE]),fA.useEffect(()=>{QB!=="recording"&&QB!=="paused"&&(Tg("00:00"),pB.current=0)},[QB]);const IQ=fA.useRef(null);fA.useEffect(()=>{if(IQ&&IQ.current){const p=IQ.current;p.style.height="auto";const HA=120;p.scrollHeight>HA?(p.style.height=HA+"px",p.style.overflowY="auto"):(p.style.height=p.scrollHeight+"px",p.style.overflowY="hidden")}},[qg]),fA.useEffect(()=>{(mA||Rg)&&A.current&&(A.current.scrollTop=A.current.scrollHeight)},[eI,Rg,mA]);const EC=p=>{const HA=p.type.toLowerCase();return HA.startsWith("image/")?"image":HA.startsWith("video/")?"video":HA.startsWith("audio/")?"audio":"document"},qC=fA.useCallback((p,HA)=>{const lA=[];Array.from(p).forEach(uA=>{if(uA.size>10*1024*1024){alert(`File ${uA.name} is too large. Maximum size is 10MB.`);return}const rg={id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:uA,type:EC(uA),url:URL.createObjectURL(uA),name:uA.name,size:uA.size};lA.push(rg)}),Hg(uA=>[...uA,...lA]),HA&&HA.current&&(HA.current.value="")},[]),zB=fA.useCallback(p=>{p.preventDefault(),Xg.current=0,lB(!1);const HA=p.dataTransfer.files;HA.length>0&&qC(HA)},[qC]),_i=fA.useCallback(p=>{p.preventDefault(),Xg.current+=1,lB(!0)},[]),pM=fA.useCallback(p=>{p.preventDefault()},[]),jw=fA.useCallback(p=>{p.preventDefault(),Xg.current-=1,Xg.current<=0&&lB(!1)},[]),ti=fA.useCallback(p=>{Hg(HA=>{const lA=HA.find(uA=>uA.id===p);return lA&&URL.revokeObjectURL(lA.url),HA.filter(uA=>uA.id!==p)})},[]),EQ=p=>{if(p===0)return"0 Bytes";const HA=1024,lA=["Bytes","KB","MB","GB"],uA=Math.floor(Math.log(p)/Math.log(HA));return Number.parseFloat((p/Math.pow(HA,uA)).toFixed(2))+" "+lA[uA]},JB=async(p=qg,HA)=>{if(p.trim()||Ng.length!==0){const uA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"user",content:p,attachments:[...Ng],timestamp:new Date};if(gI(rg=>[...rg,uA]),jg(""),Hg([]),ng(!0),g?.bot)try{if(!$A){ng(!1),gI(rg=>[...rg,{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:LC.current,nMessage:1}]);return}await Zo(p,Ng,HA)}catch{gI(rg=>[...rg,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Erreur du serveur",timestamp:new Date,seen:LC.current,nMessage:1}]),ng(!1)}else gI(rg=>[...rg,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Aucun bot sélectionné",timestamp:new Date,seen:LC.current,nMessage:1}]),ng(!1)}else return},VC=p=>{switch(KB(!1),p){case"image":B.current?.click();break;case"video":I.current?.click();break;case"audio":E.current?.click();break;case"document":C.current?.click();break}};fA.useEffect(()=>{const p=eI.slice().reverse().find(HA=>HA.sender==="agent");if(p){let HA=!1;Array.isArray(p.content)&&(HA=p.content.some(lA=>lA.type==="text"&&typeof lA.text=="object"&&lA.text.type==="EVFORM")),ug(HA)}else ug(!1)},[eI]);const[ai,uQ]=fA.useState(!1),bQ=fA.useRef({x:0,y:0}),pw=p=>{p.preventDefault(),p.stopPropagation(),NA(!0),uQ(!1),bQ.current={x:p.clientX,y:p.clientY},Yg({x:p.clientX-ZA.x,y:p.clientY-ZA.y}),document.body.style.cursor="grabbing",document.body.style.userSelect="none"},$e=p=>{p.preventDefault(),p.stopPropagation();const HA=p.touches[0];NA(!0),uQ(!1),bQ.current={x:HA.clientX,y:HA.clientY},Yg({x:HA.clientX-ZA.x,y:HA.clientY-ZA.y})},SQ=p=>{if(p.preventDefault(),p.stopPropagation(),ai){uQ(!1);return}Cg(HA=>!HA),LC.current=!mA,mA||vi(),!rA&&eI.length===0&&GC()};fA.useEffect(()=>{const p=rg=>{if(!RA)return;const kA=Math.abs(rg.clientX-bQ.current.x),AB=Math.abs(rg.clientY-bQ.current.y);(kA>5||AB>5)&&uQ(!0);const hB=rg.clientX-zA.x,rI=rg.clientY-zA.y,mB=67,IE=window.innerWidth-document.body.clientWidth,xI=Math.max(0,Math.min(window.innerWidth-mB-IE,hB)),qE=Math.max(0,Math.min(window.innerHeight-mB,rI));sA({x:xI,y:qE})},HA=rg=>{if(!RA)return;rg.preventDefault();const kA=rg.touches[0],AB=Math.abs(kA.clientX-bQ.current.x),hB=Math.abs(kA.clientY-bQ.current.y);(AB>5||hB>5)&&uQ(!0);const rI=kA.clientX-zA.x,mB=kA.clientY-zA.y,IE=67,xI=window.innerWidth-document.body.clientWidth,qE=Math.max(0,Math.min(window.innerWidth-IE-xI,rI)),Pg=Math.max(0,Math.min(window.innerHeight-IE,mB));sA({x:qE,y:Pg})},lA=()=>{RA&&(NA(!1),document.body.style.cursor="",document.body.style.userSelect="")},uA=()=>{RA&&NA(!1)};return RA&&(document.addEventListener("mousemove",p),document.addEventListener("touchmove",HA,{passive:!1}),document.addEventListener("mouseup",lA),document.addEventListener("touchend",uA)),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("touchmove",HA),document.removeEventListener("mouseup",lA),document.removeEventListener("touchend",uA)}},[RA,zA,ZA]),fA.useEffect(()=>{const p=()=>{const lA=window.innerWidth-67,uA=window.innerHeight-67;sA(rg=>({x:Math.max(0,Math.min(lA,rg.x)),y:Math.max(0,Math.min(uA,rg.y))}))};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]),fA.useEffect(()=>{const p=async()=>{try{await kI.patch(`${Ch}/widget/endusers/${HB}`,{fiche_contact:{city:yC.city,platform:yC.platform,region:yC.region,country:yC.country_name,age:0,full_name:PB,gender:"",address:"",company:"","phone 2":"",facebook:"",whatsapp:"",job_title:"",avatar_url:""},user_info:sg(yC)},{headers:{Authorization:`Bearer ${UA}`}}),localStorage.setItem("enduserUpdated","true")}catch(lA){console.error("Error updating end user info:",lA)}};let HA;return yC&&$A&&UA&&eI.length>0&&!localStorage.getItem("enduserUpdated")&&(HA=setTimeout(()=>{p()},5e3)),()=>clearTimeout(HA)},[yC,Q,eI,$A]);const tE=fA.useMemo(()=>({h1:({children:p})=>u.jsx("h1",{className:"sm:text-2xl text-xl font-bold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h2:({children:p})=>u.jsx("h2",{className:"sm:text-xl text-lg font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h3:({children:p})=>u.jsx("h3",{className:"sm:text-lg text-base font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h4:({children:p})=>u.jsx("h4",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h5:({children:p})=>u.jsx("h5",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h6:({children:p})=>u.jsx("h6",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),p:({children:p})=>{const HA=(uA,rg)=>{const kA=Yw(uA);return u.jsx("span",{dir:kA?"rtl":"ltr",style:{display:"block",textAlign:kA?"right":"left"},children:u.jsx(YE,{sequence:[uA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70})},rg)};if(typeof p=="string")return u.jsx("div",{className:"leading-relaxed my-0.5",children:HA(p,0)});if(Array.isArray(p)){const uA=[[]];for(const rg of p)rg?.type==="br"?uA.push([]):uA[uA.length-1].push(rg);return u.jsx("div",{className:"leading-relaxed my-0.5",children:uA.map((rg,kA)=>{const AB=rg.map(mB=>typeof mB=="string"?mB:"").join(""),hB=Yw(AB),rI=rg.every(mB=>typeof mB=="string");return u.jsx("span",{dir:hB?"rtl":"ltr",style:{display:"block",textAlign:hB?"right":"left"},children:rI&&AB?u.jsx(YE,{sequence:[AB,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70}):rg},kA)})})}const lA=!!(p?.props?.children&&Yw(String(p?.props?.children??"")));return u.jsx("div",{className:"leading-relaxed my-0.5",dir:lA?"rtl":"ltr",children:p})},ul:({children:p})=>u.jsx("ul",{className:"list-disc list-inside ml-2 my-2",style:{color:X},dir:Yw(p)?"rtl":"ltr",children:p}),ol:({children:p})=>{let HA=!1;return p.filter(lA=>typeof lA!="string").every(lA=>Yw(lA?.props?.children))?HA=!0:HA=!1,u.jsx("ol",{className:"list-decimal list-inside ml-2 my-2",style:{color:X},dir:HA?"rtl":"ltr",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p})},li:({children:p})=>u.jsx("li",{className:"my-1",dir:Gw(p)?"rtl":"ltr",style:{color:X},children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),a:({href:p,children:HA})=>u.jsx("a",{href:p,className:"text-blue-400 underline hover:text-blue-300",target:"_blank",rel:"noopener noreferrer",children:typeof HA=="string"?u.jsx(YE,{sequence:[HA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):HA}),blockquote:({children:p})=>u.jsx("blockquote",{className:"border-l-4 pl-4 italic my-2",style:{borderColor:f,color:X},children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),code({node:p,className:HA,children:lA,...uA}){const rg=/language-(\w+)/.exec(HA||"");return rg?u.jsx(Ez,{...uA,PreTag:"div",children:String(lA).replace(/\n$/,""),language:rg[1],style:$DA,customStyle:{scrollbarWidth:"thin"}}):u.jsx("code",{className:"px-1 rounded font-mono inline",style:{backgroundColor:R,color:X},...uA,children:typeof lA=="string"?u.jsx(YE,{sequence:[lA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):lA})},table:({children:p})=>u.jsx("table",{className:"min-w-full my-2",style:{border:`1px solid ${X}`,color:P,backgroundColor:X},children:p}),thead:({children:p})=>u.jsx("thead",{children:p}),tbody:({children:p})=>u.jsx("tbody",{children:p}),tr:({children:p})=>u.jsx("tr",{style:{border:`1px solid ${P}`},children:p}),th:({children:p})=>u.jsx("th",{className:"px-3 py-2 font-bold text-left",children:p}),td:({children:p})=>u.jsx("td",{className:"px-3 py-2",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),strong:({children:p})=>u.jsx("strong",{className:"font-bold",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),em:({children:p})=>u.jsx("em",{className:"italic ",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),hr:()=>u.jsx("hr",{className:"my-4",style:{borderColor:`1px solid ${X}`}})}),[l,X,f,R,m]);fA.useEffect(()=>{const p=HA=>{Wg&&HA.target instanceof Element&&!HA.composedPath().some(lA=>lA?.id==="upload-button-toggle"||lA?.id==="document-button"||lA?.id==="image-button"||lA?.id==="video-button"||lA?.id==="audio-button")&&KB(!1)};return document.addEventListener("mousedown",p),()=>{document.removeEventListener("mousedown",p)}},[Wg]);const CQ=(p,HA="formulaire soumis")=>{if(!p||typeof p!="object")return null;const lA=p;return Array.isArray(lA.fields)?u.jsx(tsA,{definition:lA,onValidate:uA=>{const rg=lA.submitType?{...uA,type:lA.submitType}:uA;JB(lA.submitMessage||HA,rg)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R}):null},$i=p=>{switch(p.type){case"text":if(Array.isArray(p.text))switch(p.text[0].type){case"form":const lA=CQ(p.text[0].definition||p.text[0].items||p.text[0],"formulaire soumis");if(lA)return lA;break;case"products":return u.jsx(CG,{products:p.text[0].items||[],onValidate:uA=>{JB("cart",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA});case"easyspaceform":return u.jsx(oz,{onValidate:uA=>{JB("easyspace-form-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"xcmgform":return u.jsx(JT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,formVars:JSON.parse(p.text[0])});case"auditec-form":return u.jsx(kT,{onValidate:uA=>{JB("auditec-form-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"auditec-form-ar":return u.jsx(HT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"nousserform":return u.jsx(dT,{onValidate:uA=>{JB("nousserform-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadaraform":case"Jadaraform":case"JadaraForm":return u.jsx(NT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadara-form-ar":return u.jsx(xT,{onValidate:uA=>{JB("✅ تم استلام الطلب بنجاح",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}else try{const lA=typeof p.text=="string"?JSON.parse(p.text):p.text;switch(lA.type.toLowerCase()){case"form":{const uA=CQ(lA.definition||lA.items||lA,"formulaire soumis");return uA||u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}case"products":return u.jsx(CG,{products:lA[0].items||[],onValidate:uA=>{JB("cart",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA});case"easyspaceform":return u.jsx(oz,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"evform":return u.jsx(osA,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,mainColor:N});case"evform-visiteur":return u.jsx(wsA,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,mainColor:N});case"xcmgform":return u.jsx(JT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,formVars:lA?.items||{}});case"auditec-form":return u.jsx(kT,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"auditec-form-ar":return u.jsx(HT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"nousserform":return u.jsx(dT,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadaraform":case"Jadaraform":case"JadaraForm":return u.jsx(NT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadara-form-ar":return u.jsx(xT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}}catch{return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}case"single-choice":return u.jsxs(u.Fragment,{children:[u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)||""}),u.jsx("div",{className:"mt-2 flex flex-col gap-1",dir:Gw(p.text||"")?"rtl":"ltr",children:p.choices?.map((lA,uA)=>u.jsxs("button",{onClick:()=>JB(lA.title),className:"w-full flex items-center justify-between px-4 py-2.5 hover:opacity-95 transition-all duration-100",style:{background:iA,borderRadius:"18px",color:X,border:`2px solid ${_E(iA,20)}`},onMouseEnter:rg=>{rg.currentTarget.style.borderColor=`${f}`},onMouseLeave:rg=>{rg.currentTarget.style.border=`2px solid ${_E(iA,15)}`},dir:Yw(lA.title)?"rtl":"ltr",children:[u.jsx("div",{className:"w-full flex items-start gap-2",children:u.jsx(YE,{sequence:[lA.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:Yw(lA.title)?u.jsx(aj,{className:"w-4 h-4",color:f}):u.jsx(sj,{className:"w-4 h-4",color:f})})]},uA))})]});case"image":return u.jsx(u.Fragment,{children:u.jsx("div",{className:"relative group",children:u.jsx("img",{src:p.image,className:"max-w-full max-h-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(p.image,"_blank")})})});case"dropdown":return u.jsxs(u.Fragment,{children:[u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.message)}),u.jsx(asA,{options:p.options||[],message:p.message,allowMultiple:p.allowMultiple||!1,chatRoundness:m,buttonsBgColor:f,buttonColor:J,agentChatResponseColor:X,agentChatResponseBgColor:P,isRtl:Gw(p.message||""),onSend:JB,onScroll:()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}})]});case"carousel":return u.jsx(R4,{items:p.items||[],chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});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:p.image,alt:p.title,className:"max-h-48 w-full object-contain rounded-md mb-2"}),u.jsx("h3",{className:"font-bold",children:p.title}),p.actions?.map((lA,uA)=>u.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{lA.action==="Open URL"?window.open(lA.url,"_blank"):lA.title==="scan"?p.image&&fetch(p.image).then(rg=>rg.blob()).then(rg=>{const kA=URL.createObjectURL(rg),AB=document.createElement("a");AB.href=kA,AB.download="qrcode.png",document.body.appendChild(AB),AB.click(),document.body.removeChild(AB),URL.revokeObjectURL(kA)}).catch(()=>{alert("Failed to download image.")}):JB(p.title,lA.payload||void 0)},style:{background:f,borderRadius:`${m}px`,color:J},children:lA.title},uA))]})})});case"video":return u.jsx("div",{className:"relative group w-[250px]",children:u.jsx("video",{src:p.video,className:"w-full rounded-lg cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"file":const HA=p.file?.split(".").pop?.()?.toLowerCase()||"";return u.jsx("div",{className:"p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(p.file,"_blank"),onMouseEnter:lA=>lA.currentTarget.style.backgroundColor=f,onMouseLeave:lA=>lA.currentTarget.style.backgroundColor="transparent",title:p.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:f},children:wb(HA,X)}),u.jsx("div",{className:"flex-1 min-w-0",children:u.jsx("p",{className:"text-sm font-medium truncate",style:{color:X},children:p.title})})]})});case"products":return u.jsx(CG,{products:p.products||[],onValidate:lA=>{JB("cart ",lA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"json":switch(p.json?.type){case"text":return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.json.content)});case"image":return u.jsx("div",{className:"relative group",children:u.jsx("img",{src:p.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(p.json?.content,"_blank")})});case"video":return u.jsx("div",{className:"relative group",children:u.jsx("video",{src:p.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"document":const lA=p.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(p.json?.content,"_blank"),onMouseEnter:kA=>kA.currentTarget.style.backgroundColor=f,onMouseLeave:kA=>kA.currentTarget.style.backgroundColor="transparent",title:p.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:f},children:wb(lA||"",X)}),u.jsx("div",{className:"flex-1 min-w-0",children:u.jsx("p",{className:"text-sm font-medium truncate",style:{color:X},children:p.json.title})})]})});case"audio":return u.jsx("div",{className:"w-[300px]",children:u.jsx(qT,{src:p.json.content,mainColor:s,secondaryColor:a,controlsColor:X})});case"cards":return p.json.content.map((kA,AB)=>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:kA.image,alt:kA.title,className:"max-h-48 w-full rounded-md mb-2"}),u.jsx("h3",{className:"font-bold",children:kA.title}),kA.button?.map((hB,rI)=>u.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{if(hB.type==="link"&&typeof hB.action=="string")window.open(hB.action,"_blank");else if(hB.type==="postback"){const mB=(typeof hB.action=="string",hB.action);JB(hB.label,mB)}else hB.type==="say-something"&&typeof hB.action=="string"&&gI(mB=>[...mB,{sender:"agent",content:hB.action,id:`msg-${Date.now()}`,timestamp:new Date,seen:!0}])},style:{background:f,borderRadius:`${m}px`,color:J},children:hB.label},rI))]})})},AB));case"slider":const uA=p.json.content.map(kA=>({image:kA.image,title:kA.caption,subtitle:"",actions:[]}));return u.jsx(R4,{items:uA,chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});case"carousel":const rg=p.json.content.map(kA=>({image:kA.image,title:kA.title,subtitle:kA.description||"",actions:kA.button?.map(AB=>({title:AB.label,payload:AB.action,action:AB.type,url:typeof AB.action=="string"?AB.action:""}))||[]}));return u.jsx(R4,{items:rg,chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});case"products":return u.jsx(CG,{products:p.json.content,onValidate:kA=>{JB("cart ",kA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return null}}},ZC=async p=>{if(!ZB)return;const HA=await fetch(`${Ch}/endusers/get-by-username`,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({username:`web_user_${p}`})});if(!HA.ok)throw new Error(`HTTP error! status: ${HA.status}`);return(await HA.json()).id},OQ=async p=>{if(!ZB)return;const HA=await ZC(p);let lA;PB&&(lA={last_name:PB.split(" ")[1]||PB.split(" ")[0]||`web_user_${p}`,first_name:PB.split(" ")[0]||`web_user_${p}`}),cC&&(lA={...lA,phone:cC}),TE&&(lA={...lA,email:TE});const uA=await fetch(`${Ch}/endusers/${HA}`,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"},method:"PUT",body:JSON.stringify(lA)});if(!uA.ok)throw new Error(`HTTP error! status: ${uA.status}`);return await uA.json()},EB=async p=>{p.preventDefault();try{const lA=(await kI.post(`${Ch}/conversations/start-conversation`,{bot_id:g.bot?.botId,externalUser:g.user.id})).data.conversationId;Sg(lA),localStorage.setItem("conversationId",lA),localStorage.setItem("webChatAuth","true"),NI(!0),aG.emit("join_room",parseInt(lA))}catch(HA){console.error("Error during login:",HA)}},[yw,si]=fA.useState(!1),Ao=async()=>{gI([]),localStorage.removeItem("enduserUpdated");const p=localStorage.getItem("phone_client");if(g.bot?.botId==="rockskin"&&p)return GI(p),localStorage.setItem("externalUser",p),p;const HA=new Uint8Array(16);window.crypto.getRandomValues(HA);const lA=Array.from(HA).map(uA=>uA.toString(16).padStart(2,"0")).join("");GI(lA),localStorage.setItem("externalUser",lA),localStorage.removeItem("conversationId"),Sg(null)},QQ=`linear-gradient(to bottom right, ${G}, ${s}, ${G})`,zC=`linear-gradient(to right, ${s}, ${a})`,YC=`linear-gradient(to right, ${r}, ${U})`,mQ=async(p,HA)=>{try{let lA="";if(typeof p=="string")lA=p;else for(const uA of p)uA.type==="text"&&uA.text?lA+=`
635
+ ***************************************************************************** */function yT(g,A){const[B,I]=fA.useState(null),E=fA.useMemo(()=>Object.entries(A).flat(),[A]);return fA.useEffect(()=>{if(!g?.current)return;const C=U4.create(Object.assign(Object.assign({},A),{container:g.current}));return I(C),()=>{C.destroy()}},[g,...E]),B}const LT=/^on([A-Z])/,RsA=g=>LT.test(g);function nsA(g,A){const B=fA.useMemo(()=>Object.entries(A).flat(),[A]);fA.useEffect(()=>{if(!g)return;const I=Object.entries(A);if(!I.length)return;const E=I.map(([C,Q])=>{const o=C.replace(LT,(w,e)=>e.toLowerCase());return g.on(o,(...w)=>Q(g,...w))});return()=>{E.forEach(C=>C())}},[g,...B])}fA.memo(g=>{const A=fA.useRef(null),[B,I]=function(E){return fA.useMemo(()=>{const C=Object.assign({},E),Q=Object.assign({},E);for(const o in C)RsA(o)?delete C[o]:delete Q[o];return[C,Q]},[E])}(g);return nsA(yT(A,B),I),u.jsx("div",{ref:A})});function FsA(g){var{container:A}=g;const B=yT(A,function(E,C){var Q={};for(var o in E)Object.prototype.hasOwnProperty.call(E,o)&&C.indexOf(o)<0&&(Q[o]=E[o]);if(E!=null&&typeof Object.getOwnPropertySymbols=="function"){var w=0;for(o=Object.getOwnPropertySymbols(E);w<o.length;w++)C.indexOf(o[w])<0&&Object.prototype.propertyIsEnumerable.call(E,o[w])&&(Q[o[w]]=E[o[w]])}return Q}(g,["container"])),I=function(E){const[C,Q]=fA.useState(!1),[o,w]=fA.useState(!1),[e,D]=fA.useState(!1),[t,s]=fA.useState(0);return fA.useEffect(()=>{if(!E)return;const a=[E.on("load",()=>{Q(!1),w(!1),s(0)}),E.on("ready",()=>{Q(!0),w(!1),D(!1),s(0)}),E.on("finish",()=>{D(!0)}),E.on("play",()=>{w(!0)}),E.on("pause",()=>{w(!1)}),E.on("timeupdate",()=>{s(E.getCurrentTime())}),E.on("destroy",()=>{Q(!1),w(!1)})];return()=>{a.forEach(G=>G())}},[E]),fA.useMemo(()=>({isReady:C,isPlaying:o,hasFinished:e,currentTime:t}),[o,e,t,C])}(B);return fA.useMemo(()=>Object.assign(Object.assign({},I),{wavesurfer:B}),[I,B])}const qT=({src:g,mainColor:A,secondaryColor:B,controlsColor:I})=>{const E=fA.useRef(null),[C,Q]=fA.useState(1),{wavesurfer:o,isPlaying:w}=FsA({container:E,waveColor:A,progressColor:B,barWidth:2,height:50,url:g}),e=()=>{o&&o.playPause()},D=()=>{const a=C===0?1:0;Q(a),o?.setVolume(a)},t=()=>{o?.skip(-.096)},s=()=>{o?.skip(.096)};return u.jsxs("div",{className:"flex w-full flex-col items-center rounded-xl pt-1",children:[u.jsx("div",{ref:E,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:I},onClick:D,"aria-label":"Toggle volume",children:C===0?u.jsx(bBA,{size:20}):u.jsx(TBA,{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:t,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":"Step back",children:u.jsx(ZBA,{})}),u.jsx("button",{onClick:e,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":w?"Pause":"Play",children:w?u.jsx(pBA,{}):u.jsx(yBA,{})}),u.jsx("button",{onClick:s,className:"cursor-pointer hover:scale-110 transition-colors",style:{color:I},"aria-label":"Step forward",children:u.jsx(zBA,{})})]})]})]})},UsA=({attachment:g,formatFileSize:A,mainColor:B,secondaryColor:I,controlsColor:E})=>{const{type:C,url:Q,name:o,size:w}=g;switch(C){case"image":return u.jsxs("div",{className:"relative group",children:[u.jsx("img",{src:Q,alt:o,className:"max-w-xs max-h-48 size-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(Q,"_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(w)})]});case"video":return u.jsxs("div",{className:"max-w-xs",children:[u.jsx("video",{src:Q,controls:!0,className:"w-full max-h-48 rounded-lg",preload:"metadata",onError:()=>{console.error("Video failed to load:",Q)},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:o,children:o}),u.jsxs("span",{className:"ml-2",children:["• ",A(w)]})]})]});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(zR,{className:"w-4 h-4",style:{color:B}}),u.jsx("span",{className:"text-sm font-medium truncate text-white",title:o,children:o})]}),u.jsx(qT,{src:Q,mainColor:B,secondaryColor:I,controlsColor:E}),u.jsx("p",{className:"text-xs text-gray-400 mt-1",children:A(w)})]});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(Q,"_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(oM,{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:o}),u.jsx("p",{className:"text-xs text-gray-400",children:A(w)})]})]})});default:return null}},lsA=fA.memo(({attachment:g,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:[g.type==="image"&&g.url?u.jsx("img",{src:g.url,alt:g.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:[g.type==="video"&&u.jsx(nj,{className:"w-5 h-5 mb-1 text-red-400"}),g.type==="audio"&&u.jsx(zR,{className:"w-5 h-5 mb-1 text-green-400"}),g.type==="document"&&u.jsx(cj,{className:"w-5 h-5 mb-1 text-yellow-400"}),u.jsx("span",{className:"w-full truncate",title:g.name,children:g.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(tw,{className:"w-3 h-3"})})]})),xo=Object.create(null);xo.open="0",xo.close="1",xo.ping="2",xo.pong="3",xo.message="4",xo.upgrade="5",xo.noop="6";const iG=Object.create(null);Object.keys(xo).forEach(g=>{iG[xo[g]]=g});const l4={type:"error",data:"parser error"},VT=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",ZT=typeof ArrayBuffer=="function",zT=g=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(g):g&&g.buffer instanceof ArrayBuffer,K4=({type:g,data:A},B,I)=>VT&&A instanceof Blob?B?I(A):WT(A,I):ZT&&(A instanceof ArrayBuffer||zT(A))?B?I(A):WT(new Blob([A]),I):I(xo[g]+(A||"")),WT=(g,A)=>{const B=new FileReader;return B.onload=function(){const I=B.result.split(",")[1];A("b"+(I||""))},B.readAsDataURL(g)};function TT(g){return g instanceof Uint8Array?g:g instanceof ArrayBuffer?new Uint8Array(g):new Uint8Array(g.buffer,g.byteOffset,g.byteLength)}let u4;function KsA(g,A){if(VT&&g.data instanceof Blob)return g.data.arrayBuffer().then(TT).then(A);if(ZT&&(g.data instanceof ArrayBuffer||zT(g.data)))return A(TT(g.data));K4(g,!1,B=>{u4||(u4=new TextEncoder),A(u4.encode(B))})}const bT="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_t=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let g=0;g<bT.length;g++)_t[bT.charCodeAt(g)]=g;const usA=g=>{let A=g.length*.75,B=g.length,I,E=0,C,Q,o,w;g[g.length-1]==="="&&(A--,g[g.length-2]==="="&&A--);const e=new ArrayBuffer(A),D=new Uint8Array(e);for(I=0;I<B;I+=4)C=_t[g.charCodeAt(I)],Q=_t[g.charCodeAt(I+1)],o=_t[g.charCodeAt(I+2)],w=_t[g.charCodeAt(I+3)],D[E++]=C<<2|Q>>4,D[E++]=(Q&15)<<4|o>>2,D[E++]=(o&3)<<6|w&63;return e},SsA=typeof ArrayBuffer=="function",S4=(g,A)=>{if(typeof g!="string")return{type:"message",data:PT(g,A)};const B=g.charAt(0);return B==="b"?{type:"message",data:OsA(g.substring(1),A)}:iG[B]?g.length>1?{type:iG[B],data:g.substring(1)}:{type:iG[B]}:l4},OsA=(g,A)=>{if(SsA){const B=usA(g);return PT(B,A)}else return{base64:!0,data:g}},PT=(g,A)=>{switch(A){case"blob":return g instanceof Blob?g:new Blob([g]);case"arraybuffer":default:return g instanceof ArrayBuffer?g:g.buffer}},fT="",msA=(g,A)=>{const B=g.length,I=new Array(B);let E=0;g.forEach((C,Q)=>{K4(C,!1,o=>{I[Q]=o,++E===B&&A(I.join(fT))})})},ksA=(g,A)=>{const B=g.split(fT),I=[];for(let E=0;E<B.length;E++){const C=S4(B[E],A);if(I.push(C),C.type==="error")break}return I};function HsA(){return new TransformStream({transform(g,A){KsA(g,B=>{const I=B.length;let E;if(I<126)E=new Uint8Array(1),new DataView(E.buffer).setUint8(0,I);else if(I<65536){E=new Uint8Array(3);const C=new DataView(E.buffer);C.setUint8(0,126),C.setUint16(1,I)}else{E=new Uint8Array(9);const C=new DataView(E.buffer);C.setUint8(0,127),C.setBigUint64(1,BigInt(I))}g.data&&typeof g.data!="string"&&(E[0]|=128),A.enqueue(E),A.enqueue(B)})}})}let O4;function oG(g){return g.reduce((A,B)=>A+B.length,0)}function wG(g,A){if(g[0].length===A)return g.shift();const B=new Uint8Array(A);let I=0;for(let E=0;E<A;E++)B[E]=g[0][I++],I===g[0].length&&(g.shift(),I=0);return g.length&&I<g[0].length&&(g[0]=g[0].slice(I)),B}function JsA(g,A){O4||(O4=new TextDecoder);const B=[];let I=0,E=-1,C=!1;return new TransformStream({transform(Q,o){for(B.push(Q);;){if(I===0){if(oG(B)<1)break;const w=wG(B,1);C=(w[0]&128)===128,E=w[0]&127,E<126?I=3:E===126?I=1:I=2}else if(I===1){if(oG(B)<2)break;const w=wG(B,2);E=new DataView(w.buffer,w.byteOffset,w.length).getUint16(0),I=3}else if(I===2){if(oG(B)<8)break;const w=wG(B,8),e=new DataView(w.buffer,w.byteOffset,w.length),D=e.getUint32(0);if(D>Math.pow(2,21)-1){o.enqueue(l4);break}E=D*Math.pow(2,32)+e.getUint32(4),I=3}else{if(oG(B)<E)break;const w=wG(B,E);o.enqueue(S4(C?w:O4.decode(w),A)),I=0}if(E===0||E>g){o.enqueue(l4);break}}}})}const XT=4;function jE(g){if(g)return NsA(g)}function NsA(g){for(var A in jE.prototype)g[A]=jE.prototype[A];return g}jE.prototype.on=jE.prototype.addEventListener=function(g,A){return this._callbacks=this._callbacks||{},(this._callbacks["$"+g]=this._callbacks["$"+g]||[]).push(A),this},jE.prototype.once=function(g,A){function B(){this.off(g,B),A.apply(this,arguments)}return B.fn=A,this.on(g,B),this},jE.prototype.off=jE.prototype.removeListener=jE.prototype.removeAllListeners=jE.prototype.removeEventListener=function(g,A){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var B=this._callbacks["$"+g];if(!B)return this;if(arguments.length==1)return delete this._callbacks["$"+g],this;for(var I,E=0;E<B.length;E++)if(I=B[E],I===A||I.fn===A){B.splice(E,1);break}return B.length===0&&delete this._callbacks["$"+g],this},jE.prototype.emit=function(g){this._callbacks=this._callbacks||{};for(var A=new Array(arguments.length-1),B=this._callbacks["$"+g],I=1;I<arguments.length;I++)A[I-1]=arguments[I];if(B){B=B.slice(0);for(var I=0,E=B.length;I<E;++I)B[I].apply(this,A)}return this},jE.prototype.emitReserved=jE.prototype.emit,jE.prototype.listeners=function(g){return this._callbacks=this._callbacks||{},this._callbacks["$"+g]||[]},jE.prototype.hasListeners=function(g){return!!this.listeners(g).length};const MG=typeof Promise=="function"&&typeof Promise.resolve=="function"?A=>Promise.resolve().then(A):(A,B)=>B(A,0),ii=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),xsA="arraybuffer";function QOA(){}function vT(g,...A){return A.reduce((B,I)=>(g.hasOwnProperty(I)&&(B[I]=g[I]),B),{})}const dsA=ii.setTimeout,jsA=ii.clearTimeout;function eG(g,A){A.useNativeTimers?(g.setTimeoutFn=dsA.bind(ii),g.clearTimeoutFn=jsA.bind(ii)):(g.setTimeoutFn=ii.setTimeout.bind(ii),g.clearTimeoutFn=ii.clearTimeout.bind(ii))}const psA=1.33;function ysA(g){return typeof g=="string"?LsA(g):Math.ceil((g.byteLength||g.size)*psA)}function LsA(g){let A=0,B=0;for(let I=0,E=g.length;I<E;I++)A=g.charCodeAt(I),A<128?B+=1:A<2048?B+=2:A<55296||A>=57344?B+=3:(I++,B+=4);return B}function _T(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function qsA(g){let A="";for(let B in g)g.hasOwnProperty(B)&&(A.length&&(A+="&"),A+=encodeURIComponent(B)+"="+encodeURIComponent(g[B]));return A}function VsA(g){let A={},B=g.split("&");for(let I=0,E=B.length;I<E;I++){let C=B[I].split("=");A[decodeURIComponent(C[0])]=decodeURIComponent(C[1])}return A}class ZsA extends Error{constructor(A,B,I){super(A),this.description=B,this.context=I,this.type="TransportError"}}class m4 extends jE{constructor(A){super(),this.writable=!1,eG(this,A),this.opts=A,this.query=A.query,this.socket=A.socket,this.supportsBinary=!A.forceBase64}onError(A,B,I){return super.emitReserved("error",new ZsA(A,B,I)),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 B=S4(A,this.socket.binaryType);this.onPacket(B)}onPacket(A){super.emitReserved("packet",A)}onClose(A){this.readyState="closed",super.emitReserved("close",A)}pause(A){}createUri(A,B={}){return A+"://"+this._hostname()+this._port()+this.opts.path+this._query(B)}_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 B=qsA(A);return B.length?"?"+B:""}}class zsA extends m4{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(A){this.readyState="pausing";const B=()=>{this.readyState="paused",A()};if(this._polling||!this.writable){let I=0;this._polling&&(I++,this.once("pollComplete",function(){--I||B()})),this.writable||(I++,this.once("drain",function(){--I||B()}))}else B()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(A){const B=I=>{if(this.readyState==="opening"&&I.type==="open"&&this.onOpen(),I.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(I)};ksA(A,this.socket.binaryType).forEach(B),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,msA(A,B=>{this.doWrite(B,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const A=this.opts.secure?"https":"http",B=this.query||{};return this.opts.timestampRequests!==!1&&(B[this.opts.timestampParam]=_T()),!this.supportsBinary&&!B.sid&&(B.b64=1),this.createUri(A,B)}}let $T=!1;try{$T=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const WsA=$T;function TsA(){}class bsA extends zsA{constructor(A){if(super(A),typeof location<"u"){const B=location.protocol==="https:";let I=location.port;I||(I=B?"443":"80"),this.xd=typeof location<"u"&&A.hostname!==location.hostname||I!==A.port}}doWrite(A,B){const I=this.request({method:"POST",data:A});I.on("success",B),I.on("error",(E,C)=>{this.onError("xhr post error",E,C)})}doPoll(){const A=this.request();A.on("data",this.onData.bind(this)),A.on("error",(B,I)=>{this.onError("xhr poll error",B,I)}),this.pollXhr=A}}let Ih=class Jr extends jE{constructor(A,B,I){super(),this.createRequest=A,eG(this,I),this._opts=I,this._method=I.method||"GET",this._uri=B,this._data=I.data!==void 0?I.data:null,this._create()}_create(){var A;const B=vT(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");B.xdomain=!!this._opts.xd;const I=this._xhr=this.createRequest(B);try{I.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){I.setDisableHeaderCheck&&I.setDisableHeaderCheck(!0);for(let E in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(E)&&I.setRequestHeader(E,this._opts.extraHeaders[E])}}catch{}if(this._method==="POST")try{I.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{I.setRequestHeader("Accept","*/*")}catch{}(A=this._opts.cookieJar)===null||A===void 0||A.addCookies(I),"withCredentials"in I&&(I.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(I.timeout=this._opts.requestTimeout),I.onreadystatechange=()=>{var E;I.readyState===3&&((E=this._opts.cookieJar)===null||E===void 0||E.parseCookies(I.getResponseHeader("set-cookie"))),I.readyState===4&&(I.status===200||I.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof I.status=="number"?I.status:0)},0))},I.send(this._data)}catch(E){this.setTimeoutFn(()=>{this._onError(E)},0);return}typeof document<"u"&&(this._index=Jr.requestsCount++,Jr.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=TsA,A)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Jr.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(Ih.requestsCount=0,Ih.requests={},typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ab);else if(typeof addEventListener=="function"){const g="onpagehide"in ii?"pagehide":"unload";addEventListener(g,Ab,!1)}}function Ab(){for(let g in Ih.requests)Ih.requests.hasOwnProperty(g)&&Ih.requests[g].abort()}const PsA=function(){const g=gb({xdomain:!1});return g&&g.responseType!==null}();class fsA extends bsA{constructor(A){super(A);const B=A&&A.forceBase64;this.supportsBinary=PsA&&!B}request(A={}){return Object.assign(A,{xd:this.xd},this.opts),new Ih(gb,this.uri(),A)}}function gb(g){const A=g.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!A||WsA))return new XMLHttpRequest}catch{}if(!A)try{return new ii[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const Bb=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class XsA extends m4{get name(){return"websocket"}doOpen(){const A=this.uri(),B=this.opts.protocols,I=Bb?{}:vT(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(I.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(A,B,I)}catch(E){return this.emitReserved("error",E)}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 B=0;B<A.length;B++){const I=A[B],E=B===A.length-1;K4(I,this.supportsBinary,C=>{try{this.doWrite(I,C)}catch{}E&&MG(()=>{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",B=this.query||{};return this.opts.timestampRequests&&(B[this.opts.timestampParam]=_T()),this.supportsBinary||(B.b64=1),this.createUri(A,B)}}const k4=ii.WebSocket||ii.MozWebSocket;class vsA extends XsA{createSocket(A,B,I){return Bb?new k4(A,B,I):B?new k4(A,B):new k4(A)}doWrite(A,B){this.ws.send(B)}}class _sA extends m4{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 B=JsA(Number.MAX_SAFE_INTEGER,this.socket.binaryType),I=A.readable.pipeThrough(B).getReader(),E=HsA();E.readable.pipeTo(A.writable),this._writer=E.writable.getWriter();const C=()=>{I.read().then(({done:o,value:w})=>{o||(this.onPacket(w),C())}).catch(o=>{})};C();const Q={type:"open"};this.query.sid&&(Q.data=`{"sid":"${this.query.sid}"}`),this._writer.write(Q).then(()=>this.onOpen())})})}write(A){this.writable=!1;for(let B=0;B<A.length;B++){const I=A[B],E=B===A.length-1;this._writer.write(I).then(()=>{E&&MG(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var A;(A=this._transport)===null||A===void 0||A.close()}}const $sA={websocket:vsA,webtransport:_sA,polling:fsA},AcA=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,gcA=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function H4(g){if(g.length>8e3)throw"URI too long";const A=g,B=g.indexOf("["),I=g.indexOf("]");B!=-1&&I!=-1&&(g=g.substring(0,B)+g.substring(B,I).replace(/:/g,";")+g.substring(I,g.length));let E=AcA.exec(g||""),C={},Q=14;for(;Q--;)C[gcA[Q]]=E[Q]||"";return B!=-1&&I!=-1&&(C.source=A,C.host=C.host.substring(1,C.host.length-1).replace(/;/g,":"),C.authority=C.authority.replace("[","").replace("]","").replace(/;/g,":"),C.ipv6uri=!0),C.pathNames=BcA(C,C.path),C.queryKey=IcA(C,C.query),C}function BcA(g,A){const B=/\/{2,9}/g,I=A.replace(B,"/").split("/");return(A.slice(0,1)=="/"||A.length===0)&&I.splice(0,1),A.slice(-1)=="/"&&I.splice(I.length-1,1),I}function IcA(g,A){const B={};return A.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(I,E,C){E&&(B[E]=C)}),B}const J4=typeof addEventListener=="function"&&typeof removeEventListener=="function",DG=[];J4&&addEventListener("offline",()=>{DG.forEach(g=>g())},!1);class UM extends jE{constructor(A,B){if(super(),this.binaryType=xsA,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,A&&typeof A=="object"&&(B=A,A=null),A){const I=H4(A);B.hostname=I.host,B.secure=I.protocol==="https"||I.protocol==="wss",B.port=I.port,I.query&&(B.query=I.query)}else B.host&&(B.hostname=H4(B.host).host);eG(this,B),this.secure=B.secure!=null?B.secure:typeof location<"u"&&location.protocol==="https:",B.hostname&&!B.port&&(B.port=this.secure?"443":"80"),this.hostname=B.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=B.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},B.transports.forEach(I=>{const E=I.prototype.name;this.transports.push(E),this._transportsByName[E]=I}),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},B),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VsA(this.opts.query)),J4&&(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"})},DG.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(A){const B=Object.assign({},this.opts.query);B.EIO=XT,B.transport=A,this.id&&(B.sid=this.id);const I=Object.assign({},this.opts,{query:B,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[A]);return new this._transportsByName[A](I)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const A=this.opts.rememberUpgrade&&UM.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const B=this.createTransport(A);B.open(),this.setTransport(B)}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",B=>this._onClose("transport close",B))}onOpen(){this.readyState="open",UM.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 B=new Error("server error");B.code=A.data,this._onError(B);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 B=1;for(let I=0;I<this.writeBuffer.length;I++){const E=this.writeBuffer[I].data;if(E&&(B+=ysA(E)),I>0&&B>this._maxPayload)return this.writeBuffer.slice(0,I);B+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const A=Date.now()>this._pingTimeoutTime;return A&&(this._pingTimeoutTime=0,MG(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),A}write(A,B,I){return this._sendPacket("message",A,B,I),this}send(A,B,I){return this._sendPacket("message",A,B,I),this}_sendPacket(A,B,I,E){if(typeof B=="function"&&(E=B,B=void 0),typeof I=="function"&&(E=I,I=null),this.readyState==="closing"||this.readyState==="closed")return;I=I||{},I.compress=I.compress!==!1;const C={type:A,data:B,options:I};this.emitReserved("packetCreate",C),this.writeBuffer.push(C),E&&this.once("flush",E),this.flush()}close(){const A=()=>{this._onClose("forced close"),this.transport.close()},B=()=>{this.off("upgrade",B),this.off("upgradeError",B),A()},I=()=>{this.once("upgrade",B),this.once("upgradeError",B)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?I():A()}):this.upgrading?I():A()),this}_onError(A){if(UM.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,B){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(),J4&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const I=DG.indexOf(this._offlineEventListener);I!==-1&&DG.splice(I,1)}this.readyState="closed",this.id=null,this.emitReserved("close",A,B),this.writeBuffer=[],this._prevBufferLen=0}}}UM.protocol=XT;class EcA extends UM{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 B=this.createTransport(A),I=!1;UM.priorWebsocketSuccess=!1;const E=()=>{I||(B.send([{type:"ping",data:"probe"}]),B.once("packet",t=>{if(!I)if(t.type==="pong"&&t.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",B),!B)return;UM.priorWebsocketSuccess=B.name==="websocket",this.transport.pause(()=>{I||this.readyState!=="closed"&&(D(),this.setTransport(B),B.send([{type:"upgrade"}]),this.emitReserved("upgrade",B),B=null,this.upgrading=!1,this.flush())})}else{const s=new Error("probe error");s.transport=B.name,this.emitReserved("upgradeError",s)}}))};function C(){I||(I=!0,D(),B.close(),B=null)}const Q=t=>{const s=new Error("probe error: "+t);s.transport=B.name,C(),this.emitReserved("upgradeError",s)};function o(){Q("transport closed")}function w(){Q("socket closed")}function e(t){B&&t.name!==B.name&&C()}const D=()=>{B.removeListener("open",E),B.removeListener("error",Q),B.removeListener("close",o),this.off("close",w),this.off("upgrading",e)};B.once("open",E),B.once("error",Q),B.once("close",o),this.once("close",w),this.once("upgrading",e),this._upgrades.indexOf("webtransport")!==-1&&A!=="webtransport"?this.setTimeoutFn(()=>{I||B.open()},200):B.open()}onHandshake(A){this._upgrades=this._filterUpgrades(A.upgrades),super.onHandshake(A)}_filterUpgrades(A){const B=[];for(let I=0;I<A.length;I++)~this.transports.indexOf(A[I])&&B.push(A[I]);return B}}let CcA=class extends EcA{constructor(A,B={}){const I=typeof A=="object"?A:B;(!I.transports||I.transports&&typeof I.transports[0]=="string")&&(I.transports=(I.transports||["polling","websocket","webtransport"]).map(E=>$sA[E]).filter(E=>!!E)),super(A,I)}};function QcA(g,A="",B){let I=g;B=B||typeof location<"u"&&location,g==null&&(g=B.protocol+"//"+B.host),typeof g=="string"&&(g.charAt(0)==="/"&&(g.charAt(1)==="/"?g=B.protocol+g:g=B.host+g),/^(https?|wss?):\/\//.test(g)||(typeof B<"u"?g=B.protocol+"//"+g:g="https://"+g),I=H4(g)),I.port||(/^(http|ws)$/.test(I.protocol)?I.port="80":/^(http|ws)s$/.test(I.protocol)&&(I.port="443")),I.path=I.path||"/";const C=I.host.indexOf(":")!==-1?"["+I.host+"]":I.host;return I.id=I.protocol+"://"+C+":"+I.port+A,I.href=I.protocol+"://"+C+(B&&B.port===I.port?"":":"+I.port),I}const icA=typeof ArrayBuffer=="function",ocA=g=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(g):g.buffer instanceof ArrayBuffer,Ib=Object.prototype.toString,wcA=typeof Blob=="function"||typeof Blob<"u"&&Ib.call(Blob)==="[object BlobConstructor]",McA=typeof File=="function"||typeof File<"u"&&Ib.call(File)==="[object FileConstructor]";function N4(g){return icA&&(g instanceof ArrayBuffer||ocA(g))||wcA&&g instanceof Blob||McA&&g instanceof File}function hG(g,A){if(!g||typeof g!="object")return!1;if(Array.isArray(g)){for(let B=0,I=g.length;B<I;B++)if(hG(g[B]))return!0;return!1}if(N4(g))return!0;if(g.toJSON&&typeof g.toJSON=="function"&&arguments.length===1)return hG(g.toJSON(),!0);for(const B in g)if(Object.prototype.hasOwnProperty.call(g,B)&&hG(g[B]))return!0;return!1}function ecA(g){const A=[],B=g.data,I=g;return I.data=x4(B,A),I.attachments=A.length,{packet:I,buffers:A}}function x4(g,A){if(!g)return g;if(N4(g)){const B={_placeholder:!0,num:A.length};return A.push(g),B}else if(Array.isArray(g)){const B=new Array(g.length);for(let I=0;I<g.length;I++)B[I]=x4(g[I],A);return B}else if(typeof g=="object"&&!(g instanceof Date)){const B={};for(const I in g)Object.prototype.hasOwnProperty.call(g,I)&&(B[I]=x4(g[I],A));return B}return g}function DcA(g,A){return g.data=d4(g.data,A),delete g.attachments,g}function d4(g,A){if(!g)return g;if(g&&g._placeholder===!0){if(typeof g.num=="number"&&g.num>=0&&g.num<A.length)return A[g.num];throw new Error("illegal attachments")}else if(Array.isArray(g))for(let B=0;B<g.length;B++)g[B]=d4(g[B],A);else if(typeof g=="object")for(const B in g)Object.prototype.hasOwnProperty.call(g,B)&&(g[B]=d4(g[B],A));return g}const hcA=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],tcA=5;var bB;(function(g){g[g.CONNECT=0]="CONNECT",g[g.DISCONNECT=1]="DISCONNECT",g[g.EVENT=2]="EVENT",g[g.ACK=3]="ACK",g[g.CONNECT_ERROR=4]="CONNECT_ERROR",g[g.BINARY_EVENT=5]="BINARY_EVENT",g[g.BINARY_ACK=6]="BINARY_ACK"})(bB||(bB={}));class acA{constructor(A){this.replacer=A}encode(A){return(A.type===bB.EVENT||A.type===bB.ACK)&&hG(A)?this.encodeAsBinary({type:A.type===bB.EVENT?bB.BINARY_EVENT:bB.BINARY_ACK,nsp:A.nsp,data:A.data,id:A.id}):[this.encodeAsString(A)]}encodeAsString(A){let B=""+A.type;return(A.type===bB.BINARY_EVENT||A.type===bB.BINARY_ACK)&&(B+=A.attachments+"-"),A.nsp&&A.nsp!=="/"&&(B+=A.nsp+","),A.id!=null&&(B+=A.id),A.data!=null&&(B+=JSON.stringify(A.data,this.replacer)),B}encodeAsBinary(A){const B=ecA(A),I=this.encodeAsString(B.packet),E=B.buffers;return E.unshift(I),E}}function Eb(g){return Object.prototype.toString.call(g)==="[object Object]"}class j4 extends jE{constructor(A){super(),this.reviver=A}add(A){let B;if(typeof A=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");B=this.decodeString(A);const I=B.type===bB.BINARY_EVENT;I||B.type===bB.BINARY_ACK?(B.type=I?bB.EVENT:bB.ACK,this.reconstructor=new scA(B),B.attachments===0&&super.emitReserved("decoded",B)):super.emitReserved("decoded",B)}else if(N4(A)||A.base64)if(this.reconstructor)B=this.reconstructor.takeBinaryData(A),B&&(this.reconstructor=null,super.emitReserved("decoded",B));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+A)}decodeString(A){let B=0;const I={type:Number(A.charAt(0))};if(bB[I.type]===void 0)throw new Error("unknown packet type "+I.type);if(I.type===bB.BINARY_EVENT||I.type===bB.BINARY_ACK){const C=B+1;for(;A.charAt(++B)!=="-"&&B!=A.length;);const Q=A.substring(C,B);if(Q!=Number(Q)||A.charAt(B)!=="-")throw new Error("Illegal attachments");I.attachments=Number(Q)}if(A.charAt(B+1)==="/"){const C=B+1;for(;++B&&!(A.charAt(B)===","||B===A.length););I.nsp=A.substring(C,B)}else I.nsp="/";const E=A.charAt(B+1);if(E!==""&&Number(E)==E){const C=B+1;for(;++B;){const Q=A.charAt(B);if(Q==null||Number(Q)!=Q){--B;break}if(B===A.length)break}I.id=Number(A.substring(C,B+1))}if(A.charAt(++B)){const C=this.tryParse(A.substr(B));if(j4.isPayloadValid(I.type,C))I.data=C;else throw new Error("invalid payload")}return I}tryParse(A){try{return JSON.parse(A,this.reviver)}catch{return!1}}static isPayloadValid(A,B){switch(A){case bB.CONNECT:return Eb(B);case bB.DISCONNECT:return B===void 0;case bB.CONNECT_ERROR:return typeof B=="string"||Eb(B);case bB.EVENT:case bB.BINARY_EVENT:return Array.isArray(B)&&(typeof B[0]=="number"||typeof B[0]=="string"&&hcA.indexOf(B[0])===-1);case bB.ACK:case bB.BINARY_ACK:return Array.isArray(B)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class scA{constructor(A){this.packet=A,this.buffers=[],this.reconPack=A}takeBinaryData(A){if(this.buffers.push(A),this.buffers.length===this.reconPack.attachments){const B=DcA(this.reconPack,this.buffers);return this.finishedReconstruction(),B}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ccA=Object.freeze(Object.defineProperty({__proto__:null,Decoder:j4,Encoder:acA,get PacketType(){return bB},protocol:tcA},Symbol.toStringTag,{value:"Module"}));function Vi(g,A,B){return g.on(A,B),function(){g.off(A,B)}}const GcA=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Cb extends jE{constructor(A,B,I){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=B,I&&I.auth&&(this.auth=I.auth),this._opts=Object.assign({},I),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const A=this.io;this.subs=[Vi(A,"open",this.onopen.bind(this)),Vi(A,"packet",this.onpacket.bind(this)),Vi(A,"error",this.onerror.bind(this)),Vi(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,...B){var I,E,C;if(GcA.hasOwnProperty(A))throw new Error('"'+A.toString()+'" is a reserved event name');if(B.unshift(A),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(B),this;const Q={type:bB.EVENT,data:B};if(Q.options={},Q.options.compress=this.flags.compress!==!1,typeof B[B.length-1]=="function"){const D=this.ids++,t=B.pop();this._registerAckCallback(D,t),Q.id=D}const o=(E=(I=this.io.engine)===null||I===void 0?void 0:I.transport)===null||E===void 0?void 0:E.writable,w=this.connected&&!(!((C=this.io.engine)===null||C===void 0)&&C._hasPingExpired());return this.flags.volatile&&!o||(w?(this.notifyOutgoingListeners(Q),this.packet(Q)):this.sendBuffer.push(Q)),this.flags={},this}_registerAckCallback(A,B){var I;const E=(I=this.flags.timeout)!==null&&I!==void 0?I:this._opts.ackTimeout;if(E===void 0){this.acks[A]=B;return}const C=this.io.setTimeoutFn(()=>{delete this.acks[A];for(let o=0;o<this.sendBuffer.length;o++)this.sendBuffer[o].id===A&&this.sendBuffer.splice(o,1);B.call(this,new Error("operation has timed out"))},E),Q=(...o)=>{this.io.clearTimeoutFn(C),B.apply(this,o)};Q.withError=!0,this.acks[A]=Q}emitWithAck(A,...B){return new Promise((I,E)=>{const C=(Q,o)=>Q?E(Q):I(o);C.withError=!0,B.push(C),this.emit(A,...B)})}_addToQueue(A){let B;typeof A[A.length-1]=="function"&&(B=A.pop());const I={id:this._queueSeq++,tryCount:0,pending:!1,args:A,flags:Object.assign({fromQueue:!0},this.flags)};A.push((E,...C)=>I!==this._queue[0]?void 0:(E!==null?I.tryCount>this._opts.retries&&(this._queue.shift(),B&&B(E)):(this._queue.shift(),B&&B(null,...C)),I.pending=!1,this._drainQueue())),this._queue.push(I),this._drainQueue()}_drainQueue(A=!1){if(!this.connected||this._queue.length===0)return;const B=this._queue[0];B.pending&&!A||(B.pending=!0,B.tryCount++,this.flags=B.flags,this.emit.apply(this,B.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:bB.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,B){this.connected=!1,delete this.id,this.emitReserved("disconnect",A,B),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(A=>{if(!this.sendBuffer.some(I=>String(I.id)===A)){const I=this.acks[A];delete this.acks[A],I.withError&&I.call(this,new Error("socket has been disconnected"))}})}onpacket(A){if(A.nsp===this.nsp)switch(A.type){case bB.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 bB.EVENT:case bB.BINARY_EVENT:this.onevent(A);break;case bB.ACK:case bB.BINARY_ACK:this.onack(A);break;case bB.DISCONNECT:this.ondisconnect();break;case bB.CONNECT_ERROR:this.destroy();const I=new Error(A.data.message);I.data=A.data.data,this.emitReserved("connect_error",I);break}}onevent(A){const B=A.data||[];A.id!=null&&B.push(this.ack(A.id)),this.connected?this.emitEvent(B):this.receiveBuffer.push(Object.freeze(B))}emitEvent(A){if(this._anyListeners&&this._anyListeners.length){const B=this._anyListeners.slice();for(const I of B)I.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 B=this;let I=!1;return function(...E){I||(I=!0,B.packet({type:bB.ACK,id:A,data:E}))}}onack(A){const B=this.acks[A.id];typeof B=="function"&&(delete this.acks[A.id],B.withError&&A.data.unshift(null),B.apply(this,A.data))}onconnect(A,B){this.id=A,this.recovered=B&&this._pid===B,this._pid=B,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:bB.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 B=this._anyListeners;for(let I=0;I<B.length;I++)if(A===B[I])return B.splice(I,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 B=this._anyOutgoingListeners;for(let I=0;I<B.length;I++)if(A===B[I])return B.splice(I,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(A){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const B=this._anyOutgoingListeners.slice();for(const I of B)I.apply(this,A.data)}}}function Eh(g){g=g||{},this.ms=g.min||100,this.max=g.max||1e4,this.factor=g.factor||2,this.jitter=g.jitter>0&&g.jitter<=1?g.jitter:0,this.attempts=0}Eh.prototype.duration=function(){var g=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var A=Math.random(),B=Math.floor(A*this.jitter*g);g=(Math.floor(A*10)&1)==0?g-B:g+B}return Math.min(g,this.max)|0},Eh.prototype.reset=function(){this.attempts=0},Eh.prototype.setMin=function(g){this.ms=g},Eh.prototype.setMax=function(g){this.max=g},Eh.prototype.setJitter=function(g){this.jitter=g};class p4 extends jE{constructor(A,B){var I;super(),this.nsps={},this.subs=[],A&&typeof A=="object"&&(B=A,A=void 0),B=B||{},B.path=B.path||"/socket.io",this.opts=B,eG(this,B),this.reconnection(B.reconnection!==!1),this.reconnectionAttempts(B.reconnectionAttempts||1/0),this.reconnectionDelay(B.reconnectionDelay||1e3),this.reconnectionDelayMax(B.reconnectionDelayMax||5e3),this.randomizationFactor((I=B.randomizationFactor)!==null&&I!==void 0?I:.5),this.backoff=new Eh({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(B.timeout==null?2e4:B.timeout),this._readyState="closed",this.uri=A;const E=B.parser||ccA;this.encoder=new E.Encoder,this.decoder=new E.Decoder,this._autoConnect=B.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 B;return A===void 0?this._reconnectionDelay:(this._reconnectionDelay=A,(B=this.backoff)===null||B===void 0||B.setMin(A),this)}randomizationFactor(A){var B;return A===void 0?this._randomizationFactor:(this._randomizationFactor=A,(B=this.backoff)===null||B===void 0||B.setJitter(A),this)}reconnectionDelayMax(A){var B;return A===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=A,(B=this.backoff)===null||B===void 0||B.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 CcA(this.uri,this.opts);const B=this.engine,I=this;this._readyState="opening",this.skipReconnect=!1;const E=Vi(B,"open",function(){I.onopen(),A&&A()}),C=o=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",o),A?A(o):this.maybeReconnectOnOpen()},Q=Vi(B,"error",C);if(this._timeout!==!1){const o=this._timeout,w=this.setTimeoutFn(()=>{E(),C(new Error("timeout")),B.close()},o);this.opts.autoUnref&&w.unref(),this.subs.push(()=>{this.clearTimeoutFn(w)})}return this.subs.push(E),this.subs.push(Q),this}connect(A){return this.open(A)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const A=this.engine;this.subs.push(Vi(A,"ping",this.onping.bind(this)),Vi(A,"data",this.ondata.bind(this)),Vi(A,"error",this.onerror.bind(this)),Vi(A,"close",this.onclose.bind(this)),Vi(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(A){try{this.decoder.add(A)}catch(B){this.onclose("parse error",B)}}ondecoded(A){MG(()=>{this.emitReserved("packet",A)},this.setTimeoutFn)}onerror(A){this.emitReserved("error",A)}socket(A,B){let I=this.nsps[A];return I?this._autoConnect&&!I.active&&I.connect():(I=new Cb(this,A,B),this.nsps[A]=I),I}_destroy(A){const B=Object.keys(this.nsps);for(const I of B)if(this.nsps[I].active)return;this._close()}_packet(A){const B=this.encoder.encode(A);for(let I=0;I<B.length;I++)this.engine.write(B[I],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,B){var I;this.cleanup(),(I=this.engine)===null||I===void 0||I.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",A,B),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 B=this.backoff.duration();this._reconnecting=!0;const I=this.setTimeoutFn(()=>{A.skipReconnect||(this.emitReserved("reconnect_attempt",A.backoff.attempts),!A.skipReconnect&&A.open(E=>{E?(A._reconnecting=!1,A.reconnect(),this.emitReserved("reconnect_error",E)):A.onreconnect()}))},B);this.opts.autoUnref&&I.unref(),this.subs.push(()=>{this.clearTimeoutFn(I)})}}onreconnect(){const A=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",A)}}const $t={};function tG(g,A){typeof g=="object"&&(A=g,g=void 0),A=A||{};const B=QcA(g,A.path||"/socket.io"),I=B.source,E=B.id,C=B.path,Q=$t[E]&&C in $t[E].nsps,o=A.forceNew||A["force new connection"]||A.multiplex===!1||Q;let w;return o?w=new p4(I,A):($t[E]||($t[E]=new p4(I,A)),w=$t[E]),B.query&&!A.query&&(A.query=B.queryKey),w.socket(B.path,A)}Object.assign(tG,{Manager:p4,Socket:Cb,io:tG,connect:tG});const Ch="https://api.tybotflow.com/api/v1",YcA="https://api.tybotflow.com/api/v1/chatbots-config",Qb="https://migration-meta.tybotflow.com/",ib=Qb+"webhook/v",aG=tG(Qb,{transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:3,autoConnect:!0,reconnectionDelay:2e3}),ob=new Kw,y4=g=>{if(!g||!g.message)return"👋 Hey there! how can I help you?";const A=g.message;if(typeof A=="string")return A;if(Array.isArray(A)){const B=window.location.href,I=window.location.origin,E=window.location.pathname,C=I+E;for(const o of A){if(!o.urls||o.urls.length===0)continue;if(o.urls.some(e=>{if(!e||e.trim()==="")return!1;try{let D=e.trim();!D.startsWith("http://")&&!D.startsWith("https://")&&(D="https://"+D);const t=new URL(D),s=t.origin,a=t.pathname,G=s+a;return C===G||B===D?!0:a==="/"||a===""?I===s:!!B.startsWith(D)}catch{return console.warn("Invalid URL in message:",e),!1}}))return o.text||"👋 Hey there! how can I help you?"}const Q=A.find(o=>!o.urls||o.urls.length===0||o.urls.every(w=>!w||w.trim()===""));if(Q)return Q.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?"},wb=(g,A)=>{const B={className:"w-5 h-5",style:{color:A}};switch(g?.toLowerCase()){case"pdf":return u.jsx(oM,{...B});case"doc":case"docx":return u.jsx(oM,{...B});case"xls":case"xlsx":case"csv":return u.jsx(HBA,{...B});case"ppt":case"pptx":return u.jsx(LBA,{...B});case"zip":case"rar":case"7z":case"tar":case"gz":return u.jsx(uBA,{...B});case"txt":case"md":case"rtf":return u.jsx(cj,{...B});default:return u.jsx(oM,{...B})}},rcA=({config:g})=>{const A=fA.useRef(null),B=fA.useRef(null),I=fA.useRef(null),E=fA.useRef(null),C=fA.useRef(null),[Q,o]=fA.useState(null),[w,e]=fA.useState(!0),[D,t]=fA.useState(!1);fA.useEffect(()=>{(async()=>{e(!0),await kI.get(`${YcA}/bot/${g.bot?.botId}`,{}).then(HA=>{o(HA.data)}).catch(HA=>{console.error("Error fetching bot config:",HA)}).finally(()=>{e(!1)})})()},[g.bot?.botId,g?.token]);const s=Q?.mainColor||"#59168b",a=Q?.secondaryColor||"#6366f1",G=Q?.thirdColor||"#0f172b",r=Q?.headerFirstColor||"#6e11b0",U=Q?.headerSecondColor||"#372aac",R=Q?.inputBackgroundColor||"#1f2937",l=Q?.inputTextColor||"#fff",K=Q?.roundness||24,m=Q?.chatRoundness||16,k=(Q?.minPanelWidth||434)>window.innerWidth?window.innerWidth:Q?.minPanelWidth||434,O=(Q?.maxPanelWidth||window.innerWidth)>window.innerWidth?window.innerWidth:Q?.maxPanelWidth||window.innerWidth,y=Q?.chatMaxWidth||88,L=Q?.toggleBtnBorderTopLeftRadius||12,j=Q?.toggleBtnBorderTopRightRadius||0,Z=Q?.toggleBtnBorderBottomLeftRadius||12,d=Q?.toggleBtnBorderBottomRightRadius||0,z=Q?.menuBackgroundColor||"#1f2937",T=Q?.menuTextColor||"#e5e7eb",W=Q?.menuHoverBackgroundColor||"#374151",X=Q?.agentChatResponseColor||"#e5e7eb",P=Q?.agentChatResponseBgColor||"#1f2937",EA=Q?.agentIconBgColor||"#59168b",$=Q?.agentIconColor||"#fff",oA=Q?.userChatMessagesColor||"#fff",N=Q?.userChatMessagesBgColor||"#7a1ebe",AA=Q?.userIconBgColor||"#7a1ebe",V=Q?.userIconColor||"#fff",J=Q?.ButtonColor||"#fff",f=Q?.ButtonsBgColor||"#59168b",iA=_E(P,10),wA=Q?.fontSize||13,tA=Q?.toggleBtnPosition||"bottom-right",rA=Q?.autoOpenPanel??!0,UA=Q?.tempToken||"",PA=(()=>{const p=Q?.firstMessageKeyword;if(Array.isArray(p)){const HA=window.location.href,lA=p.find(rg=>rg.url&&rg.url===HA);if(lA)return lA.message;const uA=p.find(rg=>!rg.url||rg.url==="");return uA?uA.message:p[0]?.message||"hi"}return p||"hi"})(),sg=p=>({ip:p.ip||"",flag:{img:p.flag||"",emoji:p.emoji_flag||"",emoji_unicode:p.emoji_unicode||""},is_eu:p.is_eu??!1,postal:p.postal||"",borders:"",latitude:p.latitude||0,platform:p?.platform||"",timezone:{id:p.time_zone?.name||"",utc:p.time_zone?.offset||"",abbr:p.time_zone?.abbr||"",is_dst:p.time_zone?.is_dst??!1,offset:p.time_zone?.offset||0,current_time:p.time_zone?.current_time||""},continent:p.continent_name||"",longitude:p.longitude||0,connection:{asn:p.asn?.asn||0,isp:p.asn?.name||"",org:p.asn?.name||"",domain:p.asn?.domain||""}}),[TA,JA]=fA.useState(k),IA=fA.useRef(!1),Ig=fA.useRef(0),Gg=fA.useRef(k),wg=p=>{IA.current=!0,Ig.current=p.clientX,Gg.current=TA,document.body.style.cursor="ew-resize"};fA.useEffect(()=>{const p=lA=>{if(!IA.current)return;const uA=Ig.current-lA.clientX;let rg=Gg.current+uA;rg=Math.max(k,Math.min(O,rg)),JA(rg)},HA=()=>{IA.current&&(IA.current=!1,document.body.style.cursor="")};return window.addEventListener("mousemove",p),window.addEventListener("mouseup",HA),()=>{window.removeEventListener("mousemove",p),window.removeEventListener("mouseup",HA)}},[TA,k,O]);const[mA,Cg]=fA.useState(!1),[Bg,lg]=fA.useState(!1),[Dg,dA]=fA.useState(!1),[ZA,sA]=fA.useState(()=>tA==="bottom-left"?{x:48,y:window.innerHeight-120}:tA==="middle-right"?{x:window.innerWidth-80,y:window.innerHeight/2-35}:{x:window.innerWidth-123,y:window.innerHeight-100}),[RA,NA]=fA.useState(!1),[zA,Yg]=fA.useState({x:0,y:0}),Ug=fA.useRef(null),[qg,jg]=fA.useState(""),[Rg,ng]=fA.useState(!1),[Vg,ug]=fA.useState(!1),[Ng,Hg]=fA.useState([]),[$g,lB]=fA.useState(!1),Xg=fA.useRef(0),[Wg,KB]=fA.useState(!1),[BC,eB]=fA.useState(!1),ZI=fA.useRef(!1),[sC,Tg]=fA.useState("00:00"),XB=fA.useRef(null),pB=fA.useRef(0),[vB,zI]=fA.useState(null),[DB,QI]=fA.useState(!1),[EI,IC]=fA.useState(new Set),[eI,gI]=fA.useState([]),{startRecording:DI,stopRecording:WI,pauseRecording:hE,resumeRecording:TI,status:QB,error:WE}=aiA.useReactMediaRecorder({video:!1,blobPropertyBag:{type:"audio/mp3"},onStop(p,HA){if(ZI.current){ZI.current=!1,Tg("00:00"),pB.current=0;return}Hg(lA=>[...lA,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:HA,type:"audio",url:p,name:`recording-${new Date().toISOString()}.webm`,size:HA.size}]),Tg("00:00"),pB.current=0}}),mg=Q?.icon||g?.bot.avatar_url||Cz,cA=Q?.title||g?.bot.name||"Tybot webchat",[$A,Sg]=fA.useState(null),[HB,GI]=fA.useState(()=>{const p=localStorage.getItem("phone_client");if(g.bot?.botId==="rockskin"&&p)return p;if(!Q?.botNeedsAuth){let HA=localStorage.getItem("externalUser");if(!HA){const lA=new Uint8Array(16);window.crypto.getRandomValues(lA),HA=Array.from(lA).map(uA=>uA.toString(16).padStart(2,"0")).join("")}return localStorage.setItem("externalUser",HA),HA}});fA.useEffect(()=>{if(!$A)return;const p=HA=>{if(HA.bot.conversationId!==parseInt($A)||HA.bot.botId!==g?.bot?.botId){ng(!1);return}const lA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:HA.bot.item,timestamp:new Date,seen:LC.current,nMessage:Array.isArray(HA.bot.item)?HA.bot.item.length:1};gI(uA=>uA.some(kA=>kA.id===lA.id)?uA:[...uA,lA]),ng(!1)};return aG.on("bot-message",p),()=>{aG.off("bot-message",p)}},[$A,g?.bot?.botId]),fA.useEffect(()=>{(async()=>{if(!($A||!g.bot?.botId||!HB))try{const lA=(await kI.post(`${Ch}/conversations/start-conversation`,{bot_id:g.bot?.botId,externalUser:HB})).data.conversationId;Sg(lA),localStorage.setItem("conversationId",lA),aG.emit("join_room",parseInt(lA))}catch(HA){console.error("Error initializing conversation:",HA)}})()},[$A,g.bot?.botId,HB]);const[ZB,NI]=fA.useState(()=>Q?.botNeedsAuth?!!localStorage.getItem("conversationId"):!0),[PB,bI]=fA.useState(""),[cC,YI]=fA.useState(""),[TE,TQ]=fA.useState(""),[yC,Vo]=fA.useState(null),LC=fA.useRef(!1),RB=eI.reduce((p,HA)=>HA.seen?p:p+(HA.sender==="agent"?HA.nMessage||1:0),0),vi=()=>{gI(p=>p.map(HA=>({...HA,seen:!0})))};fA.useEffect(()=>{let p;return!localStorage.getItem("webChatOpen")&&Q&&rA&&(p=setTimeout(()=>{Cg(!0),LC.current=!0,vi(),localStorage.setItem("webChatOpen","true")},3200)),()=>clearTimeout(p)},[Q]),fA.useEffect(()=>{const p=Q?.widgetLoadBehavior;if(!p||!(()=>{const uA=p.message;if(typeof uA=="string"){if(!p.urls||p.urls.length===0)return!0;const rg=window.location.origin,kA=window.location.href;return p.urls.some(AB=>{if(!AB||AB.trim()==="")return!0;try{return rg.includes(AB)||kA.includes(AB)||AB.includes(rg)}catch{return console.warn("Invalid URL in widgetLoadBehavior:",AB),!1}})}if(Array.isArray(uA)){const rg=window.location.href,kA=window.location.origin,AB=window.location.pathname,hB=kA+AB;for(const rI of uA)if(!rI.urls||rI.urls.length===0||rI.urls.every(IE=>!IE||IE.trim()==="")||rI.urls.some(IE=>{if(!IE||IE.trim()==="")return!1;try{let xI=IE.trim();!xI.startsWith("http://")&&!xI.startsWith("https://")&&(xI="https://"+xI);const qE=new URL(xI),Pg=qE.origin,fQ=qE.pathname,OB=Pg+fQ;return hB===OB||rg===xI?!0:fQ==="/"||fQ===""?kA===Pg:!!rg.startsWith(xI)}catch{return console.warn("Invalid URL in message:",IE),!1}}))return!0;return!1}return!0})())return;let lA;if(p.behavior==="after seconds")lA=setTimeout(()=>{dA(!0)},p.value*1e3);else if(p.behavior==="after scroll"){const uA=()=>{const rg=window.pageYOffset||document.documentElement.scrollTop,kA=document.documentElement.scrollHeight-document.documentElement.clientHeight;rg/kA*100>=p.value&&(dA(!0),window.removeEventListener("scroll",uA))};return window.addEventListener("scroll",uA),()=>{window.removeEventListener("scroll",uA)}}return()=>{lA&&clearTimeout(lA)}},[Q?.widgetLoadBehavior]),fA.useEffect(()=>{mA&&dA(!1)},[mA]),fA.useEffect(()=>{fetch("https://api.ipdata.co/?api-key=7930ffd0621dafcb6cd830a503d726bf514b74c1cae21ffff8131890").then(function(p){p.json().then(HA=>{Vo({...HA,platform:ob.getOS().name+" "+ob.getOS().version})})}).catch(function(p){console.log(p)})},[]);const Zo=fA.useCallback(async(p,HA=[],lA)=>{if(!g.bot.botId||!$A){ng(!1),gI(rg=>[...rg,{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(HA.length>0||lA&&typeof lA=="object"&&lA.attachment!==void 0){const rg=lA&&typeof lA!="string"?lA.attachment.file:HA[0]?.file,kA=lA&&typeof lA!="string"?lA.attachment.type:HA[0]?.type||"file";let AB=lA;if(lA&&typeof lA=="object"&&lA.attachment!==void 0){const{attachment:rI,...mB}=lA;AB=mB}const hB=new FormData;hB.append("type",kA),hB.append("file",rg),hB.append("botId",g.bot.botId),hB.append("external_id",HB||""),hB.append("isintern",g.token?"true":"false"),hB.append("host",window.location.origin),hB.append("channel","web"),hB.append("payload",AB?JSON.stringify(AB):""),await kI.post(ib,hB,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"multipart/form-data"}})}else{const rg={type:"text",messageText:p,botId:g.bot.botId,external_id:HB||"",isintern:!!g.token,host:window.location.origin,channel:"web"};lA&&(rg.payload=lA),await kI.post(ib,rg,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"}})}},[g.bot.botId,$A,g.token,g.user?.id]),GC=fA.useCallback(async()=>{if(g.bot.botId&&$A){ng(!0);try{await Zo(PA)}catch(p){console.error("Error sending first message:",p),ng(!1)}}},[g.bot.botId,PA,$A,Zo]);fA.useEffect(()=>{$A&&ZB&&g?.bot&&eI.length===0&&Q&&rA&&(GC(),localStorage.getItem("webChatAuth")&&JSON.parse(localStorage.getItem("webChatAuth"))&&Q?.botNeedsAuth&&$A&&(PB||TE||cC)&&(setTimeout(()=>{OQ($A)},2e3),localStorage.setItem("webChatAuth","true")))},[ZB,g?.bot,$A,Q]),fA.useEffect(()=>(QB==="recording"?XB.current||(XB.current=setInterval(()=>{pB.current+=1;const p=Math.floor(pB.current/60).toString().padStart(2,"0"),HA=(pB.current%60).toString().padStart(2,"0");Tg(`${p}:${HA}`)},1e3)):XB.current&&(clearInterval(XB.current),XB.current=null),()=>{XB.current&&(clearInterval(XB.current),XB.current=null)}),[QB]),fA.useEffect(()=>{WE&&WE.toLowerCase().includes("permission_denied")&&(eB(!1),Tg("00:00"),pB.current=0,XB.current&&(clearInterval(XB.current),XB.current=null),alert("Microphone permission denied. Please allow access to record audio."))},[WE]),fA.useEffect(()=>{QB!=="recording"&&QB!=="paused"&&(Tg("00:00"),pB.current=0)},[QB]);const IQ=fA.useRef(null);fA.useEffect(()=>{if(IQ&&IQ.current){const p=IQ.current;p.style.height="auto";const HA=120;p.scrollHeight>HA?(p.style.height=HA+"px",p.style.overflowY="auto"):(p.style.height=p.scrollHeight+"px",p.style.overflowY="hidden")}},[qg]),fA.useEffect(()=>{(mA||Rg)&&A.current&&(A.current.scrollTop=A.current.scrollHeight)},[eI,Rg,mA]);const EC=p=>{const HA=p.type.toLowerCase();return HA.startsWith("image/")?"image":HA.startsWith("video/")?"video":HA.startsWith("audio/")?"audio":"document"},qC=fA.useCallback((p,HA)=>{const lA=[];Array.from(p).forEach(uA=>{if(uA.size>10*1024*1024){alert(`File ${uA.name} is too large. Maximum size is 10MB.`);return}const rg={id:Date.now().toString()+Math.random().toString(36).substring(2,9),file:uA,type:EC(uA),url:URL.createObjectURL(uA),name:uA.name,size:uA.size};lA.push(rg)}),Hg(uA=>[...uA,...lA]),HA&&HA.current&&(HA.current.value="")},[]),zB=fA.useCallback(p=>{p.preventDefault(),Xg.current=0,lB(!1);const HA=p.dataTransfer.files;HA.length>0&&qC(HA)},[qC]),_i=fA.useCallback(p=>{p.preventDefault(),Xg.current+=1,lB(!0)},[]),pM=fA.useCallback(p=>{p.preventDefault()},[]),jw=fA.useCallback(p=>{p.preventDefault(),Xg.current-=1,Xg.current<=0&&lB(!1)},[]),ti=fA.useCallback(p=>{Hg(HA=>{const lA=HA.find(uA=>uA.id===p);return lA&&URL.revokeObjectURL(lA.url),HA.filter(uA=>uA.id!==p)})},[]),EQ=p=>{if(p===0)return"0 Bytes";const HA=1024,lA=["Bytes","KB","MB","GB"],uA=Math.floor(Math.log(p)/Math.log(HA));return Number.parseFloat((p/Math.pow(HA,uA)).toFixed(2))+" "+lA[uA]},JB=async(p=qg,HA)=>{if(p.trim()||Ng.length!==0){const uA={id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"user",content:p,attachments:[...Ng],timestamp:new Date};if(gI(rg=>[...rg,uA]),jg(""),Hg([]),ng(!0),g?.bot)try{if(!$A){ng(!1),gI(rg=>[...rg,{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:LC.current,nMessage:1}]);return}await Zo(p,Ng,HA)}catch{gI(rg=>[...rg,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Erreur du serveur",timestamp:new Date,seen:LC.current,nMessage:1}]),ng(!1)}else gI(rg=>[...rg,{id:Date.now().toString()+Math.random().toString(36).substring(2,9),sender:"agent",content:"Aucun bot sélectionné",timestamp:new Date,seen:LC.current,nMessage:1}]),ng(!1)}else return},VC=p=>{switch(KB(!1),p){case"image":B.current?.click();break;case"video":I.current?.click();break;case"audio":E.current?.click();break;case"document":C.current?.click();break}};fA.useEffect(()=>{const p=eI.slice().reverse().find(HA=>HA.sender==="agent");if(p){let HA=!1;Array.isArray(p.content)&&(HA=p.content.some(lA=>lA.type==="text"&&typeof lA.text=="object"&&lA.text.type==="EVFORM")),ug(HA)}else ug(!1)},[eI]);const[ai,uQ]=fA.useState(!1),bQ=fA.useRef({x:0,y:0}),pw=p=>{p.preventDefault(),p.stopPropagation(),NA(!0),uQ(!1),bQ.current={x:p.clientX,y:p.clientY},Yg({x:p.clientX-ZA.x,y:p.clientY-ZA.y}),document.body.style.cursor="grabbing",document.body.style.userSelect="none"},$e=p=>{p.preventDefault(),p.stopPropagation();const HA=p.touches[0];NA(!0),uQ(!1),bQ.current={x:HA.clientX,y:HA.clientY},Yg({x:HA.clientX-ZA.x,y:HA.clientY-ZA.y})},SQ=p=>{if(p.preventDefault(),p.stopPropagation(),ai){uQ(!1);return}Cg(HA=>!HA),LC.current=!mA,mA||vi(),!rA&&eI.length===0&&GC()};fA.useEffect(()=>{const p=rg=>{if(!RA)return;const kA=Math.abs(rg.clientX-bQ.current.x),AB=Math.abs(rg.clientY-bQ.current.y);(kA>5||AB>5)&&uQ(!0);const hB=rg.clientX-zA.x,rI=rg.clientY-zA.y,mB=67,IE=window.innerWidth-document.body.clientWidth,xI=Math.max(0,Math.min(window.innerWidth-mB-IE,hB)),qE=Math.max(0,Math.min(window.innerHeight-mB,rI));sA({x:xI,y:qE})},HA=rg=>{if(!RA)return;rg.preventDefault();const kA=rg.touches[0],AB=Math.abs(kA.clientX-bQ.current.x),hB=Math.abs(kA.clientY-bQ.current.y);(AB>5||hB>5)&&uQ(!0);const rI=kA.clientX-zA.x,mB=kA.clientY-zA.y,IE=67,xI=window.innerWidth-document.body.clientWidth,qE=Math.max(0,Math.min(window.innerWidth-IE-xI,rI)),Pg=Math.max(0,Math.min(window.innerHeight-IE,mB));sA({x:qE,y:Pg})},lA=()=>{RA&&(NA(!1),document.body.style.cursor="",document.body.style.userSelect="")},uA=()=>{RA&&NA(!1)};return RA&&(document.addEventListener("mousemove",p),document.addEventListener("touchmove",HA,{passive:!1}),document.addEventListener("mouseup",lA),document.addEventListener("touchend",uA)),()=>{document.removeEventListener("mousemove",p),document.removeEventListener("touchmove",HA),document.removeEventListener("mouseup",lA),document.removeEventListener("touchend",uA)}},[RA,zA,ZA]),fA.useEffect(()=>{const p=()=>{const lA=window.innerWidth-67,uA=window.innerHeight-67;sA(rg=>({x:Math.max(0,Math.min(lA,rg.x)),y:Math.max(0,Math.min(uA,rg.y))}))};return window.addEventListener("resize",p),()=>window.removeEventListener("resize",p)},[]),fA.useEffect(()=>{const p=async()=>{try{await kI.patch(`${Ch}/widget/endusers/${HB}`,{fiche_contact:{city:yC.city,platform:yC.platform,region:yC.region,country:yC.country_name,age:0,full_name:PB,gender:"",address:"",company:"","phone 2":"",facebook:"",whatsapp:"",job_title:"",avatar_url:""},user_info:sg(yC)},{headers:{Authorization:`Bearer ${UA}`}}),localStorage.setItem("enduserUpdated","true")}catch(lA){console.error("Error updating end user info:",lA)}};let HA;return yC&&$A&&UA&&eI.length>0&&!localStorage.getItem("enduserUpdated")&&(HA=setTimeout(()=>{p()},5e3)),()=>clearTimeout(HA)},[yC,Q,eI,$A]);const tE=fA.useMemo(()=>({h1:({children:p})=>u.jsx("h1",{className:"sm:text-2xl text-xl font-bold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h2:({children:p})=>u.jsx("h2",{className:"sm:text-xl text-lg font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h3:({children:p})=>u.jsx("h3",{className:"sm:text-lg text-base font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h4:({children:p})=>u.jsx("h4",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h5:({children:p})=>u.jsx("h5",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),h6:({children:p})=>u.jsx("h6",{className:"sm:text-base text-sm font-semibold my-2",dir:Gw(p)?"rtl":"ltr",children:u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:70})}),p:({children:p})=>{const HA=(uA,rg)=>{const kA=Yw(uA);return u.jsx("span",{dir:kA?"rtl":"ltr",style:{display:"block",textAlign:kA?"right":"left"},children:u.jsx(YE,{sequence:[uA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70})},rg)};if(typeof p=="string")return u.jsx("div",{className:"leading-relaxed my-0.5",children:HA(p,0)});if(Array.isArray(p)){const uA=[[]];for(const rg of p)rg?.type==="br"?uA.push([]):uA[uA.length-1].push(rg);return u.jsx("div",{className:"leading-relaxed my-0.5",children:uA.map((rg,kA)=>{const AB=rg.map(mB=>typeof mB=="string"?mB:"").join(""),hB=Yw(AB),rI=rg.every(mB=>typeof mB=="string");return u.jsx("span",{dir:hB?"rtl":"ltr",style:{display:"block",textAlign:hB?"right":"left"},children:rI&&AB?u.jsx(YE,{sequence:[AB,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],wrapper:"span",cursor:!1,speed:70}):rg},kA)})})}const lA=!!(p?.props?.children&&Yw(String(p?.props?.children??"")));return u.jsx("div",{className:"leading-relaxed my-0.5",dir:lA?"rtl":"ltr",children:p})},ul:({children:p})=>u.jsx("ul",{className:"list-disc list-inside ml-2 my-2",style:{color:X},dir:Yw(p)?"rtl":"ltr",children:p}),ol:({children:p})=>{let HA=!1;return p.filter(lA=>typeof lA!="string").every(lA=>Yw(lA?.props?.children))?HA=!0:HA=!1,u.jsx("ol",{className:"list-decimal list-inside ml-2 my-2",style:{color:X},dir:HA?"rtl":"ltr",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p})},li:({children:p})=>u.jsx("li",{className:"my-1",dir:Gw(p)?"rtl":"ltr",style:{color:X},children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),a:({href:p,children:HA})=>u.jsx("a",{href:p,className:"text-blue-400 underline hover:text-blue-300",target:"_blank",rel:"noopener noreferrer",children:typeof HA=="string"?u.jsx(YE,{sequence:[HA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):HA}),blockquote:({children:p})=>u.jsx("blockquote",{className:"border-l-4 pl-4 italic my-2",style:{borderColor:f,color:X},children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),code({node:p,className:HA,children:lA,...uA}){const rg=/language-(\w+)/.exec(HA||"");return rg?u.jsx(Ez,{...uA,PreTag:"div",children:String(lA).replace(/\n$/,""),language:rg[1],style:$DA,customStyle:{scrollbarWidth:"thin"}}):u.jsx("code",{className:"px-1 rounded font-mono inline",style:{backgroundColor:R,color:X},...uA,children:typeof lA=="string"?u.jsx(YE,{sequence:[lA,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):lA})},table:({children:p})=>u.jsx("table",{className:"min-w-full my-2",style:{border:`1px solid ${X}`,color:P,backgroundColor:X},children:p}),thead:({children:p})=>u.jsx("thead",{children:p}),tbody:({children:p})=>u.jsx("tbody",{children:p}),tr:({children:p})=>u.jsx("tr",{style:{border:`1px solid ${P}`},children:p}),th:({children:p})=>u.jsx("th",{className:"px-3 py-2 font-bold text-left",children:p}),td:({children:p})=>u.jsx("td",{className:"px-3 py-2",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),strong:({children:p})=>u.jsx("strong",{className:"font-bold",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),em:({children:p})=>u.jsx("em",{className:"italic ",children:typeof p=="string"?u.jsx(YE,{sequence:[p,0,()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}],cursor:!1,speed:92}):p}),hr:()=>u.jsx("hr",{className:"my-4",style:{borderColor:`1px solid ${X}`}})}),[l,X,f,R,m]);fA.useEffect(()=>{const p=HA=>{Wg&&HA.target instanceof Element&&!HA.composedPath().some(lA=>lA?.id==="upload-button-toggle"||lA?.id==="document-button"||lA?.id==="image-button"||lA?.id==="video-button"||lA?.id==="audio-button")&&KB(!1)};return document.addEventListener("mousedown",p),()=>{document.removeEventListener("mousedown",p)}},[Wg]);const CQ=(p,HA="formulaire soumis")=>{if(!p||typeof p!="object")return null;const lA=p;return Array.isArray(lA.fields)?u.jsx(tsA,{definition:lA,onValidate:uA=>{const rg=lA.submitType?{...uA,type:lA.submitType}:uA;JB(lA.submitMessage||HA,rg)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R}):null},$i=p=>{switch(p.type){case"text":if(Array.isArray(p.text))switch(p.text[0].type){case"form":const lA=CQ(p.text[0].definition||p.text[0].items||p.text[0],"formulaire soumis");if(lA)return lA;break;case"products":return u.jsx(CG,{products:p.text[0].items||[],onValidate:uA=>{JB("cart",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA});case"easyspaceform":return u.jsx(oz,{onValidate:uA=>{JB("easyspace-form-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"xcmgform":return u.jsx(JT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,formVars:JSON.parse(p.text[0])});case"auditec-form":return u.jsx(kT,{onValidate:uA=>{JB("auditec-form-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"auditec-form-ar":return u.jsx(HT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"nousserform":return u.jsx(dT,{onValidate:uA=>{JB("nousserform-data",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadaraform":case"Jadaraform":case"JadaraForm":return u.jsx(NT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadara-form-ar":return u.jsx(xT,{onValidate:uA=>{JB("✅ تم استلام الطلب بنجاح",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}else try{const lA=typeof p.text=="string"?JSON.parse(p.text):p.text;switch(lA.type.toLowerCase()){case"form":{const uA=CQ(lA.definition||lA.items||lA,"formulaire soumis");return uA||u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}case"products":return u.jsx(CG,{products:lA[0].items||[],onValidate:uA=>{JB("cart",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA});case"easyspaceform":return u.jsx(oz,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"evform":return u.jsx(osA,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,mainColor:N});case"evform-visiteur":return u.jsx(wsA,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,mainColor:N});case"xcmgform":return u.jsx(JT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R,formVars:lA?.items||{}});case"auditec-form":return u.jsx(kT,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"auditec-form-ar":return u.jsx(HT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"nousserform":return u.jsx(dT,{onValidate:uA=>{JB("formulaire soumis",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadaraform":case"Jadaraform":case"JadaraForm":return u.jsx(NT,{onValidate:uA=>{JB("Demande bien reçue ✅",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"jadara-form-ar":return u.jsx(xT,{onValidate:uA=>{JB("تم إرسال النموذج",uA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}}catch{return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)})}case"single-choice":return u.jsxs(u.Fragment,{children:[u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.text)||""}),u.jsx("div",{className:"mt-2 flex flex-col gap-1",dir:Gw(p.text||"")?"rtl":"ltr",children:p.choices?.map((lA,uA)=>u.jsxs("button",{onClick:()=>JB(lA.title),className:"w-full flex items-center justify-between px-4 py-2.5 hover:opacity-95 transition-all duration-100",style:{background:iA,borderRadius:"18px",color:X,border:`2px solid ${_E(iA,20)}`},onMouseEnter:rg=>{rg.currentTarget.style.borderColor=`${f}`},onMouseLeave:rg=>{rg.currentTarget.style.border=`2px solid ${_E(iA,15)}`},dir:Yw(lA.title)?"rtl":"ltr",children:[u.jsx("div",{className:"w-full flex items-start gap-2",children:u.jsx(YE,{sequence:[lA.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:Yw(lA.title)?u.jsx(aj,{className:"w-4 h-4",color:f}):u.jsx(sj,{className:"w-4 h-4",color:f})})]},uA))})]});case"image":return u.jsx(u.Fragment,{children:u.jsx("div",{className:"relative group",children:u.jsx("img",{src:p.image,className:"max-w-full max-h-full rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(p.image,"_blank")})})});case"dropdown":return u.jsxs(u.Fragment,{children:[u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.message)}),u.jsx(asA,{options:p.options||[],message:p.message,allowMultiple:p.allowMultiple||!1,chatRoundness:m,buttonsBgColor:f,buttonColor:J,agentChatResponseColor:X,agentChatResponseBgColor:P,isRtl:Gw(p.message||""),onSend:JB,onScroll:()=>{A.current&&(A.current.scrollTop=A.current.scrollHeight)}})]});case"carousel":return u.jsx(R4,{items:p.items||[],chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});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:p.image,alt:p.title,className:"max-h-48 w-full object-contain rounded-md mb-2"}),u.jsx("h3",{className:"font-bold",children:p.title}),p.actions?.map((lA,uA)=>u.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{lA.action==="Open URL"?window.open(lA.url,"_blank"):lA.title==="scan"?p.image&&fetch(p.image).then(rg=>rg.blob()).then(rg=>{const kA=URL.createObjectURL(rg),AB=document.createElement("a");AB.href=kA,AB.download="qrcode.png",document.body.appendChild(AB),AB.click(),document.body.removeChild(AB),URL.revokeObjectURL(kA)}).catch(()=>{alert("Failed to download image.")}):JB(p.title,lA.payload||void 0)},style:{background:f,borderRadius:`${m}px`,color:J},children:lA.title},uA))]})})});case"video":return u.jsx("div",{className:"relative group w-[250px]",children:u.jsx("video",{src:p.video,className:"w-full rounded-lg cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"file":const HA=p.file?.split(".").pop?.()?.toLowerCase()||"";return u.jsx("div",{className:"p-2 rounded-lg max-w-xs cursor-pointer transition-colors",onClick:()=>window.open(p.file,"_blank"),onMouseEnter:lA=>lA.currentTarget.style.backgroundColor=f,onMouseLeave:lA=>lA.currentTarget.style.backgroundColor="transparent",title:p.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:f},children:wb(HA,X)}),u.jsx("div",{className:"flex-1 min-w-0",children:u.jsx("p",{className:"text-sm font-medium truncate",style:{color:X},children:p.title})})]})});case"products":return u.jsx(CG,{products:p.products||[],onValidate:lA=>{JB("cart ",lA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});case"json":switch(p.json?.type){case"text":return u.jsx(ew,{remarkPlugins:[hw],components:tE,children:rw(p.json.content)});case"image":return u.jsx("div",{className:"relative group",children:u.jsx("img",{src:p.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",onClick:()=>window.open(p.json?.content,"_blank")})});case"video":return u.jsx("div",{className:"relative group",children:u.jsx("video",{src:p.json.content,className:"max-h-48 rounded-lg object-cover cursor-pointer hover:opacity-90 transition-opacity",controls:!0})});case"document":const lA=p.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(p.json?.content,"_blank"),onMouseEnter:kA=>kA.currentTarget.style.backgroundColor=f,onMouseLeave:kA=>kA.currentTarget.style.backgroundColor="transparent",title:p.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:f},children:wb(lA||"",X)}),u.jsx("div",{className:"flex-1 min-w-0",children:u.jsx("p",{className:"text-sm font-medium truncate",style:{color:X},children:p.json.title})})]})});case"audio":return u.jsx("div",{className:"w-[300px]",children:u.jsx(qT,{src:p.json.content,mainColor:s,secondaryColor:a,controlsColor:X})});case"cards":return p.json.content.map((kA,AB)=>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:kA.image,alt:kA.title,className:"max-h-48 w-full rounded-md mb-2"}),u.jsx("h3",{className:"font-bold",children:kA.title}),kA.button?.map((hB,rI)=>u.jsx("button",{className:"mb-1 mr-1 px-4 py-1 hover:scale-105 transition-all duration-100",onClick:()=>{if(hB.type==="link"&&typeof hB.action=="string")window.open(hB.action,"_blank");else if(hB.type==="postback"){const mB=(typeof hB.action=="string",hB.action);JB(hB.label,mB)}else hB.type==="say-something"&&typeof hB.action=="string"&&gI(mB=>[...mB,{sender:"agent",content:hB.action,id:`msg-${Date.now()}`,timestamp:new Date,seen:!0}])},style:{background:f,borderRadius:`${m}px`,color:J},children:hB.label},rI))]})})},AB));case"slider":const uA=p.json.content.map(kA=>({image:kA.image,title:kA.caption,subtitle:"",actions:[]}));return u.jsx(R4,{items:uA,chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});case"carousel":const rg=p.json.content.map(kA=>({image:kA.image,title:kA.title,subtitle:kA.description||"",actions:kA.button?.map(AB=>({title:AB.label,payload:AB.action,action:AB.type,url:typeof AB.action=="string"?AB.action:""}))||[]}));return u.jsx(R4,{items:rg,chatRoundness:m,agentChatResponseBgColor:P,agentChatResponseColor:X,buttonsBgColor:f,buttonColor:J,inputBackgroundColor:R,onButtonClick:JB,setMessages:gI});case"products":return u.jsx(CG,{products:p.json.content,onValidate:kA=>{JB("cart ",kA)},agentChatResponseColor:X,agentChatResponseBgColor:P,buttonsBgColor:f,buttonColor:J,chatRoundness:m,panelWidth:TA,inputBackgroundColor:R});default:return null}}},ZC=async p=>{if(!ZB)return;const HA=await fetch(`${Ch}/endusers/get-by-username`,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"},method:"POST",body:JSON.stringify({username:`web_user_${p}`})});if(!HA.ok)throw new Error(`HTTP error! status: ${HA.status}`);return(await HA.json()).id},OQ=async p=>{if(!ZB)return;const HA=await ZC(p);let lA;PB&&(lA={last_name:PB.split(" ")[1]||PB.split(" ")[0]||`web_user_${p}`,first_name:PB.split(" ")[0]||`web_user_${p}`}),cC&&(lA={...lA,phone:cC}),TE&&(lA={...lA,email:TE});const uA=await fetch(`${Ch}/endusers/${HA}`,{headers:{Authorization:`Bearer ${g?.token}`,"Content-Type":"application/json"},method:"PUT",body:JSON.stringify(lA)});if(!uA.ok)throw new Error(`HTTP error! status: ${uA.status}`);return await uA.json()},EB=async p=>{p.preventDefault();try{const lA=(await kI.post(`${Ch}/conversations/start-conversation`,{bot_id:g.bot?.botId,externalUser:g.user.id})).data.conversationId;Sg(lA),localStorage.setItem("conversationId",lA),localStorage.setItem("webChatAuth","true"),NI(!0),aG.emit("join_room",parseInt(lA))}catch(HA){console.error("Error during login:",HA)}},[yw,si]=fA.useState(!1),Ao=async()=>{gI([]),localStorage.removeItem("enduserUpdated");const p=localStorage.getItem("phone_client");if(g.bot?.botId==="rockskin"&&p)return GI(p),localStorage.setItem("externalUser",p),p;const HA=new Uint8Array(16);window.crypto.getRandomValues(HA);const lA=Array.from(HA).map(uA=>uA.toString(16).padStart(2,"0")).join("");GI(lA),localStorage.setItem("externalUser",lA),localStorage.removeItem("conversationId"),Sg(null)},QQ=`linear-gradient(to bottom right, ${G}, ${s}, ${G})`,zC=`linear-gradient(to right, ${s}, ${a})`,YC=`linear-gradient(to right, ${r}, ${U})`,mQ=async(p,HA)=>{try{let lA="";if(typeof p=="string")lA=p;else for(const uA of p)uA.type==="text"&&uA.text?lA+=`
636
636
  `+uA.text||"":uA.type==="single-choice"&&uA.choices&&uA.choices.length>0?(lA+=`
637
637
  `+uA.text||"",lA+=`
638
638
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tybotflow-widget",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "A modern, customizable React widget for Tybot chat integration.",
5
5
  "license": "ISC",
6
6
  "main": "dist/index.umd.js",