From 0e9cd21981dc42a40ef1fda40379b7af803afa6c Mon Sep 17 00:00:00 2001 From: Davidson Gomes Date: Thu, 22 Aug 2024 19:49:51 -0300 Subject: [PATCH] feat: evolution channel in instance create --- CHANGELOG.md | 1 + .../{index-CfE0Jl7j.js => index-BmAfUzu7.js} | 4 +- manager/dist/index.html | 2 +- src/api/controllers/instance.controller.ts | 6 +- .../channel/channel.controller.ts | 23 +- .../evolution/evolution.channel.service.ts | 475 ++++++++++++++++++ .../business/whatsapp.business.service.ts | 15 +- .../chatbot/dify/services/dify.service.ts | 41 +- .../flowise/services/flowise.service.ts | 11 +- .../generic/services/generic.service.ts | 11 +- .../chatbot/openai/services/openai.service.ts | 21 +- .../webhook/controllers/webhook.controller.ts | 30 +- .../event/webhook/routes/webhook.router.ts | 12 +- src/api/services/monitor.service.ts | 8 +- src/api/types/wa.types.ts | 1 + 15 files changed, 597 insertions(+), 64 deletions(-) rename manager/dist/assets/{index-CfE0Jl7j.js => index-BmAfUzu7.js} (84%) create mode 100644 src/api/integrations/channel/evolution/evolution.channel.service.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f838f78..d741dee1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ * Generic Bot Integration * Option to disable chatwoot bot contact with CHATWOOT_BOT_CONTACT * Added flowise integration +* Added evolution channel on instance create ### Fixed diff --git a/manager/dist/assets/index-CfE0Jl7j.js b/manager/dist/assets/index-BmAfUzu7.js similarity index 84% rename from manager/dist/assets/index-CfE0Jl7j.js rename to manager/dist/assets/index-BmAfUzu7.js index df65ebbe..2edd6760 100644 --- a/manager/dist/assets/index-CfE0Jl7j.js +++ b/manager/dist/assets/index-BmAfUzu7.js @@ -357,7 +357,7 @@ lodash-es/lodash.js: * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors *) -*/var Iq="Label",kI=m.forwardRef((e,t)=>i.jsx(Ie.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));kI.displayName=Iq;var EI=kI;const Nq=ng("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),TI=m.forwardRef(({className:e,...t},n)=>i.jsx(EI,{ref:n,className:me(Nq(),e),...t}));TI.displayName=EI.displayName;function jI(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Pq="VisuallyHidden",_I=m.forwardRef((e,t)=>i.jsx(Ie.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));_I.displayName=Pq;var Oq=[" ","Enter","ArrowUp","ArrowDown"],Mq=[" ","Enter"],nd="Select",[Og,Mg,Dq]=pb(nd),[Pl,Vee]=Ir(nd,[Dq,cg]),Dg=cg(),[Aq,sa]=Pl(nd),[Fq,Lq]=Pl(nd),RI=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:l,onValueChange:c,dir:u,name:d,autoComplete:f,disabled:p,required:h}=e,v=Dg(t),[g,b]=m.useState(null),[y,x]=m.useState(null),[w,S]=m.useState(!1),E=Zu(u),[C=!1,T]=Bo({prop:r,defaultProp:s,onChange:o}),[j,I]=Bo({prop:a,defaultProp:l,onChange:c}),P=m.useRef(null),V=g?!!g.closest("form"):!0,[O,Z]=m.useState(new Set),H=Array.from(O).map(K=>K.props.value).join(";");return i.jsx(YT,{...v,children:i.jsxs(Aq,{required:h,scope:t,trigger:g,onTriggerChange:b,valueNode:y,onValueNodeChange:x,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:Vr(),value:j,onValueChange:I,open:C,onOpenChange:T,dir:E,triggerPointerDownPosRef:P,disabled:p,children:[i.jsx(Og.Provider,{scope:t,children:i.jsx(Fq,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(K=>{Z(Y=>new Set(Y).add(K))},[]),onNativeOptionRemove:m.useCallback(K=>{Z(Y=>{const G=new Set(Y);return G.delete(K),G})},[]),children:n})}),V?i.jsxs(eN,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:j,onChange:K=>I(K.target.value),disabled:p,children:[j===void 0?i.jsx("option",{value:""}):null,Array.from(O)]},H):null]})})};RI.displayName=nd;var II="SelectTrigger",NI=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=Dg(n),a=sa(II,n),l=a.disabled||r,c=tt(t,a.onTriggerChange),u=Mg(n),[d,f,p]=tN(v=>{const g=u().filter(x=>!x.disabled),b=g.find(x=>x.value===a.value),y=nN(g,v,b);y!==void 0&&a.onValueChange(y.value)}),h=()=>{l||(a.onOpenChange(!0),p())};return i.jsx(XT,{asChild:!0,...o,children:i.jsx(Ie.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":XI(a.value)?"":void 0,...s,ref:c,onClick:xe(s.onClick,v=>{v.currentTarget.focus()}),onPointerDown:xe(s.onPointerDown,v=>{const g=v.target;g.hasPointerCapture(v.pointerId)&&g.releasePointerCapture(v.pointerId),v.button===0&&v.ctrlKey===!1&&(h(),a.triggerPointerDownPosRef.current={x:Math.round(v.pageX),y:Math.round(v.pageY)},v.preventDefault())}),onKeyDown:xe(s.onKeyDown,v=>{const g=d.current!=="";!(v.ctrlKey||v.altKey||v.metaKey)&&v.key.length===1&&f(v.key),!(g&&v.key===" ")&&Oq.includes(v.key)&&(h(),v.preventDefault())})})})});NI.displayName=II;var PI="SelectValue",OI=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...l}=e,c=sa(PI,n),{onValueNodeHasChildrenChange:u}=c,d=o!==void 0,f=tt(t,c.onValueNodeChange);return tn(()=>{u(d)},[u,d]),i.jsx(Ie.span,{...l,ref:f,style:{pointerEvents:"none"},children:XI(c.value)?i.jsx(i.Fragment,{children:a}):o})});OI.displayName=PI;var $q="SelectIcon",MI=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return i.jsx(Ie.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});MI.displayName=$q;var Bq="SelectPortal",DI=e=>i.jsx(ug,{asChild:!0,...e});DI.displayName=Bq;var Ga="SelectContent",AI=m.forwardRef((e,t)=>{const n=sa(Ga,e.__scopeSelect),[r,s]=m.useState();if(tn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Xo.createPortal(i.jsx(FI,{scope:e.__scopeSelect,children:i.jsx(Og.Slot,{scope:e.__scopeSelect,children:i.jsx("div",{children:e.children})})}),o):null}return i.jsx(LI,{...e,ref:t})});AI.displayName=Ga;var Is=10,[FI,oa]=Pl(Ga),zq="SelectContentImpl",LI=m.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:b,...y}=e,x=sa(Ga,n),[w,S]=m.useState(null),[E,C]=m.useState(null),T=tt(t,q=>S(q)),[j,I]=m.useState(null),[P,V]=m.useState(null),O=Mg(n),[Z,H]=m.useState(!1),K=m.useRef(!1);m.useEffect(()=>{if(w)return Cb(w)},[w]),gb();const Y=m.useCallback(q=>{const[we,...je]=O().map(pe=>pe.ref.current),[Me]=je.slice(-1),_e=document.activeElement;for(const pe of q)if(pe===_e||(pe==null||pe.scrollIntoView({block:"nearest"}),pe===we&&E&&(E.scrollTop=0),pe===Me&&E&&(E.scrollTop=E.scrollHeight),pe==null||pe.focus(),document.activeElement!==_e))return},[O,E]),G=m.useCallback(()=>Y([j,w]),[Y,j,w]);m.useEffect(()=>{Z&&G()},[Z,G]);const{onOpenChange:L,triggerPointerDownPosRef:F}=x;m.useEffect(()=>{if(w){let q={x:0,y:0};const we=Me=>{var _e,pe;q={x:Math.abs(Math.round(Me.pageX)-(((_e=F.current)==null?void 0:_e.x)??0)),y:Math.abs(Math.round(Me.pageY)-(((pe=F.current)==null?void 0:pe.y)??0))}},je=Me=>{q.x<=10&&q.y<=10?Me.preventDefault():w.contains(Me.target)||L(!1),document.removeEventListener("pointermove",we),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",we),document.addEventListener("pointerup",je,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",we),document.removeEventListener("pointerup",je,{capture:!0})}}},[w,L,F]),m.useEffect(()=>{const q=()=>L(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[L]);const[Q,ue]=tN(q=>{const we=O().filter(_e=>!_e.disabled),je=we.find(_e=>_e.ref.current===document.activeElement),Me=nN(we,q,je);Me&&setTimeout(()=>Me.ref.current.focus())}),U=m.useCallback((q,we,je)=>{const Me=!K.current&&!je;(x.value!==void 0&&x.value===we||Me)&&(I(q),Me&&(K.current=!0))},[x.value]),re=m.useCallback(()=>w==null?void 0:w.focus(),[w]),te=m.useCallback((q,we,je)=>{const Me=!K.current&&!je;(x.value!==void 0&&x.value===we||Me)&&V(q)},[x.value]),ae=r==="popper"?qv:$I,se=ae===qv?{side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:b}:{};return i.jsx(FI,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:U,selectedItem:j,onItemLeave:re,itemTextRefCallback:te,focusSelectedItem:G,selectedItemText:P,position:r,isPositioned:Z,searchRef:Q,children:i.jsx(gg,{as:Gs,allowPinchZoom:!0,children:i.jsx(ag,{asChild:!0,trapped:x.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:xe(s,q=>{var we;(we=x.trigger)==null||we.focus({preventScroll:!0}),q.preventDefault()}),children:i.jsx(og,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>x.onOpenChange(!1),children:i.jsx(ae,{role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:q=>q.preventDefault(),...y,...se,onPlaced:()=>H(!0),ref:T,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:xe(y.onKeyDown,q=>{const we=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!we&&q.key.length===1&&ue(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let Me=O().filter(_e=>!_e.disabled).map(_e=>_e.ref.current);if(["ArrowUp","End"].includes(q.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const _e=q.target,pe=Me.indexOf(_e);Me=Me.slice(pe+1)}setTimeout(()=>Y(Me)),q.preventDefault()}})})})})})})});LI.displayName=zq;var Uq="SelectItemAlignedPosition",$I=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=sa(Ga,n),a=oa(Ga,n),[l,c]=m.useState(null),[u,d]=m.useState(null),f=tt(t,T=>d(T)),p=Mg(n),h=m.useRef(!1),v=m.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:y,focusSelectedItem:x}=a,w=m.useCallback(()=>{if(o.trigger&&o.valueNode&&l&&u&&g&&b&&y){const T=o.trigger.getBoundingClientRect(),j=u.getBoundingClientRect(),I=o.valueNode.getBoundingClientRect(),P=y.getBoundingClientRect();if(o.dir!=="rtl"){const _e=P.left-j.left,pe=I.left-_e,Qe=T.left-pe,It=T.width+Qe,Vt=Math.max(It,j.width),Bt=window.innerWidth-Is,Zt=Iv(pe,[Is,Bt-Vt]);l.style.minWidth=It+"px",l.style.left=Zt+"px"}else{const _e=j.right-P.right,pe=window.innerWidth-I.right-_e,Qe=window.innerWidth-T.right-pe,It=T.width+Qe,Vt=Math.max(It,j.width),Bt=window.innerWidth-Is,Zt=Iv(pe,[Is,Bt-Vt]);l.style.minWidth=It+"px",l.style.right=Zt+"px"}const V=p(),O=window.innerHeight-Is*2,Z=g.scrollHeight,H=window.getComputedStyle(u),K=parseInt(H.borderTopWidth,10),Y=parseInt(H.paddingTop,10),G=parseInt(H.borderBottomWidth,10),L=parseInt(H.paddingBottom,10),F=K+Y+Z+L+G,Q=Math.min(b.offsetHeight*5,F),ue=window.getComputedStyle(g),U=parseInt(ue.paddingTop,10),re=parseInt(ue.paddingBottom,10),te=T.top+T.height/2-Is,ae=O-te,se=b.offsetHeight/2,q=b.offsetTop+se,we=K+Y+q,je=F-we;if(we<=te){const _e=b===V[V.length-1].ref.current;l.style.bottom="0px";const pe=u.clientHeight-g.offsetTop-g.offsetHeight,Qe=Math.max(ae,se+(_e?re:0)+pe+G),It=we+Qe;l.style.height=It+"px"}else{const _e=b===V[0].ref.current;l.style.top="0px";const Qe=Math.max(te,K+g.offsetTop+(_e?U:0)+se)+je;l.style.height=Qe+"px",g.scrollTop=we-te+g.offsetTop}l.style.margin=`${Is}px 0`,l.style.minHeight=Q+"px",l.style.maxHeight=O+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,o.trigger,o.valueNode,l,u,g,b,y,o.dir,r]);tn(()=>w(),[w]);const[S,E]=m.useState();tn(()=>{u&&E(window.getComputedStyle(u).zIndex)},[u]);const C=m.useCallback(T=>{T&&v.current===!0&&(w(),x==null||x(),v.current=!1)},[w,x]);return i.jsx(Hq,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:h,onScrollButtonChange:C,children:i.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:i.jsx(Ie.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});$I.displayName=Uq;var Vq="SelectPopperPosition",qv=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Is,...o}=e,a=Dg(n);return i.jsx(ej,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});qv.displayName=Vq;var[Hq,ax]=Pl(Ga,{}),Kv="SelectViewport",BI=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=oa(Kv,n),a=ax(Kv,n),l=tt(t,o.onViewportChange),c=m.useRef(0);return i.jsxs(i.Fragment,{children:[i.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),i.jsx(Og.Slot,{scope:n,children:i.jsx(Ie.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:xe(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=a;if(p!=null&&p.current&&f){const h=Math.abs(c.current-d.scrollTop);if(h>0){const v=window.innerHeight-Is*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),y=Math.max(g,b);if(y0?S:0,f.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});BI.displayName=Kv;var zI="SelectGroup",[Wq,Gq]=Pl(zI),qq=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Vr();return i.jsx(Wq,{scope:n,id:s,children:i.jsx(Ie.div,{role:"group","aria-labelledby":s,...r,ref:t})})});qq.displayName=zI;var UI="SelectLabel",VI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Gq(UI,n);return i.jsx(Ie.div,{id:s.id,...r,ref:t})});VI.displayName=UI;var bp="SelectItem",[Kq,HI]=Pl(bp),WI=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,l=sa(bp,n),c=oa(bp,n),u=l.value===r,[d,f]=m.useState(o??""),[p,h]=m.useState(!1),v=tt(t,y=>{var x;return(x=c.itemRefCallback)==null?void 0:x.call(c,y,r,s)}),g=Vr(),b=()=>{s||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return i.jsx(Kq,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:m.useCallback(y=>{f(x=>x||((y==null?void 0:y.textContent)??"").trim())},[]),children:i.jsx(Og.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:i.jsx(Ie.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":u&&p,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:v,onFocus:xe(a.onFocus,()=>h(!0)),onBlur:xe(a.onBlur,()=>h(!1)),onPointerUp:xe(a.onPointerUp,b),onPointerMove:xe(a.onPointerMove,y=>{var x;s?(x=c.onItemLeave)==null||x.call(c):y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:xe(a.onPointerLeave,y=>{var x;y.currentTarget===document.activeElement&&((x=c.onItemLeave)==null||x.call(c))}),onKeyDown:xe(a.onKeyDown,y=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(Mq.includes(y.key)&&b(),y.key===" "&&y.preventDefault())})})})})});WI.displayName=bp;var Sc="SelectItemText",GI=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=sa(Sc,n),l=oa(Sc,n),c=HI(Sc,n),u=Lq(Sc,n),[d,f]=m.useState(null),p=tt(t,y=>f(y),c.onItemTextChange,y=>{var x;return(x=l.itemTextRefCallback)==null?void 0:x.call(l,y,c.value,c.disabled)}),h=d==null?void 0:d.textContent,v=m.useMemo(()=>i.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return tn(()=>(g(v),()=>b(v)),[g,b,v]),i.jsxs(i.Fragment,{children:[i.jsx(Ie.span,{id:c.textId,...o,ref:p}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren?Xo.createPortal(o.children,a.valueNode):null]})});GI.displayName=Sc;var qI="SelectItemIndicator",KI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return HI(qI,n).isSelected?i.jsx(Ie.span,{"aria-hidden":!0,...r,ref:t}):null});KI.displayName=qI;var Jv="SelectScrollUpButton",JI=m.forwardRef((e,t)=>{const n=oa(Jv,e.__scopeSelect),r=ax(Jv,e.__scopeSelect),[s,o]=m.useState(!1),a=tt(t,r.onScrollButtonChange);return tn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollTop>0;o(u)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?i.jsx(QI,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});JI.displayName=Jv;var Zv="SelectScrollDownButton",ZI=m.forwardRef((e,t)=>{const n=oa(Zv,e.__scopeSelect),r=ax(Zv,e.__scopeSelect),[s,o]=m.useState(!1),a=tt(t,r.onScrollButtonChange);return tn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?i.jsx(QI,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});ZI.displayName=Zv;var QI=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=oa("SelectScrollButton",n),a=m.useRef(null),l=Mg(n),c=m.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return m.useEffect(()=>()=>c(),[c]),tn(()=>{var d;const u=l().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),i.jsx(Ie.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:xe(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:xe(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:xe(s.onPointerLeave,()=>{c()})})}),Jq="SelectSeparator",YI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return i.jsx(Ie.div,{"aria-hidden":!0,...r,ref:t})});YI.displayName=Jq;var Qv="SelectArrow",Zq=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Dg(n),o=sa(Qv,n),a=oa(Qv,n);return o.open&&a.position==="popper"?i.jsx(tj,{...s,...r,ref:t}):null});Zq.displayName=Qv;function XI(e){return e===""||e===void 0}var eN=m.forwardRef((e,t)=>{const{value:n,...r}=e,s=m.useRef(null),o=tt(t,s),a=jI(n);return m.useEffect(()=>{const l=s.current,c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(a!==n&&d){const f=new Event("change",{bubbles:!0});d.call(l,n),l.dispatchEvent(f)}},[a,n]),i.jsx(_I,{asChild:!0,children:i.jsx("select",{...r,ref:o,defaultValue:n})})});eN.displayName="BubbleSelect";function tN(e){const t=Kt(e),n=m.useRef(""),r=m.useRef(0),s=m.useCallback(a=>{const l=n.current+a;t(l),function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),o=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function nN(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=Qq(e,Math.max(o,0));s.length===1&&(a=a.filter(u=>u!==n));const c=a.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function Qq(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Yq=RI,rN=NI,Xq=OI,eK=MI,tK=DI,sN=AI,nK=BI,oN=VI,aN=WI,rK=GI,sK=KI,iN=JI,lN=ZI,cN=YI;const oK=Yq,aK=Xq,uN=m.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(rN,{ref:r,className:me("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,i.jsx(eK,{asChild:!0,children:i.jsx(rg,{className:"h-4 w-4 opacity-50"})})]}));uN.displayName=rN.displayName;const dN=m.forwardRef(({className:e,...t},n)=>i.jsx(iN,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(r4,{className:"h-4 w-4"})}));dN.displayName=iN.displayName;const fN=m.forwardRef(({className:e,...t},n)=>i.jsx(lN,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(rg,{className:"h-4 w-4"})}));fN.displayName=lN.displayName;const pN=m.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>i.jsx(tK,{children:i.jsxs(sN,{ref:s,className:me("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[i.jsx(dN,{}),i.jsx(nK,{className:me("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),i.jsx(fN,{})]})}));pN.displayName=sN.displayName;const iK=m.forwardRef(({className:e,...t},n)=>i.jsx(oN,{ref:n,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));iK.displayName=oN.displayName;const gN=m.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(aN,{ref:r,className:me("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[i.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:i.jsx(sK,{children:i.jsx(ST,{className:"h-4 w-4"})})}),i.jsx(rK,{children:t})]}));gN.displayName=aN.displayName;const lK=m.forwardRef(({className:e,...t},n)=>i.jsx(cN,{ref:n,className:me("-mx-1 my-1 h-px bg-muted",e),...t}));lK.displayName=cN.displayName;var ix="Switch",[cK,Hee]=Ir(ix),[uK,dK]=cK(ix),hN=m.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:l,value:c="on",onCheckedChange:u,...d}=e,[f,p]=m.useState(null),h=tt(t,x=>p(x)),v=m.useRef(!1),g=f?!!f.closest("form"):!0,[b=!1,y]=Bo({prop:s,defaultProp:o,onChange:u});return i.jsxs(uK,{scope:n,checked:b,disabled:l,children:[i.jsx(Ie.button,{type:"button",role:"switch","aria-checked":b,"aria-required":a,"data-state":yN(b),"data-disabled":l?"":void 0,disabled:l,value:c,...d,ref:h,onClick:xe(e.onClick,x=>{y(w=>!w),g&&(v.current=x.isPropagationStopped(),v.current||x.stopPropagation())})}),g&&i.jsx(fK,{control:f,bubbles:!v.current,name:r,value:c,checked:b,required:a,disabled:l,style:{transform:"translateX(-100%)"}})]})});hN.displayName=ix;var mN="SwitchThumb",vN=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=dK(mN,n);return i.jsx(Ie.span,{"data-state":yN(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});vN.displayName=mN;var fK=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=m.useRef(null),a=jI(n),l=UT(t);return m.useEffect(()=>{const c=o.current,u=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(u,"checked").set;if(a!==n&&f){const p=new Event("click",{bubbles:r});f.call(c,n),c.dispatchEvent(p)}},[a,n,r]),i.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function yN(e){return e?"checked":"unchecked"}var bN=hN,pK=vN;const Ol=m.forwardRef(({className:e,...t},n)=>i.jsx(bN,{className:me("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:i.jsx(pK,{className:me("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Ol.displayName=bN.displayName;const fr=dr,xN=m.createContext({}),aa=({...e})=>i.jsx(xN.Provider,{value:{name:e.name},children:i.jsx(i5,{...e})}),Ag=()=>{const e=m.useContext(xN),t=m.useContext(wN),{getFieldState:n,formState:r}=Cg(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},wN=m.createContext({}),so=m.forwardRef(({className:e,...t},n)=>{const r=m.useId();return i.jsx(wN.Provider,{value:{id:r},children:i.jsx("div",{ref:n,className:me("space-y-2",e),...t})})});so.displayName="FormItem";const sr=m.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Ag();return i.jsx(TI,{ref:n,className:me(r&&"text-rose-600",e),htmlFor:s,...t})});sr.displayName="FormLabel";const Ss=m.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Ag();return i.jsx(Gs,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});Ss.displayName="FormControl";const Fg=m.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Ag();return i.jsx("p",{ref:n,id:r,className:me("text-sm text-muted-foreground",e),...t})});Fg.displayName="FormDescription";const rd=m.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Ag(),a=s?String(s==null?void 0:s.message):t;return a?i.jsx("p",{ref:r,id:o,className:me("text-sm font-medium text-rose-600",e),...n,children:a}):null});rd.displayName="FormMessage";const D=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{className:o,children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:m.isValidElement(n)&&m.cloneElement(n,{...l,value:l.value??"",required:r,readOnly:s,checked:l.value,onCheckedChange:l.onChange})}),i.jsx(rd,{})]})}),he=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{className:me("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[i.jsx("div",{className:"flex flex-col gap-2",children:t&&i.jsxs(sr,{children:[i.jsxs("p",{className:"break-all",children:[t,n&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&i.jsx(Fg,{className:"mt-2",children:s})]})}),i.jsx(Ss,{children:i.jsx(Ol,{checked:l.value,onCheckedChange:l.onChange,required:n})}),i.jsx(rd,{})]})}),et=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:i.jsxs(oK,{onValueChange:l.onChange,defaultValue:l.value,children:[i.jsx(Ss,{children:i.jsx(uN,{children:i.jsx(aK,{placeholder:o})})}),i.jsx(pN,{children:s.map(c=>i.jsx(gN,{value:c.value,children:c.label},c.value))})]})}),n&&i.jsx(Fg,{children:n}),i.jsx(rd,{})]})}),Ml=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>i.jsx(aa,{...o,name:e,render:({field:a})=>{let l=[];return Array.isArray(a.value)&&(l=a.value),i.jsxs(so,{children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:i.jsx(Rq,{tags:l.map(c=>({id:c,text:c,className:""})),handleDelete:c=>a.onChange(l.filter((u,d)=>d!==c)),handleAddition:c=>a.onChange([...l,c.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[cs.ENTER,cs.TAB,cs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:cR,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&i.jsx(Fg,{children:n}),i.jsx(rd,{})]})}});function xp(){return localStorage.getItem("facebookAppId")||""}function gK(){return localStorage.getItem("facebookConfigId")||""}function em(){return localStorage.getItem("facebookUserToken")||""}function hK({setUserID:e,setToken:t}){const{t:n}=Le(),[r,s]=m.useState(!1);m.useEffect(()=>{const l=document.createElement("script"),c="https://connect.facebook.net/en_US/sdk.js";l.src=c,l.async=!0,document.body.appendChild(l),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})}},[]);function o(){s(!0),window.FB.login(l=>{a(l)},{scope:"public_profile,pages_messaging,pages_show_list,pages_manage_metadata,pages_read_engagement"})}async function a(l){if(l.authResponse){const{userID:c,accessToken:u}=l.authResponse;try{window.FB.api("/me",{fields:"name, email"},function(d){console.log("Good to see you, "+d.name+". I see your email address is "+d.email)}),e(c),t(u)}catch(d){console.log(d)}finally{s(!1)}}else s(!1),console.log("User cancelled login or did not fully authorize.")}return i.jsx(J,{variant:"default",onClick:o,className:"bg-blue-600 text-white hover:bg-blue-700",type:"button",disabled:r,children:n(r?"instance.button.connecting":"instance.button.facebook")})}function mK({setUserID:e,setToken:t}){const{t:n}=Le(),[r,s]=m.useState(!1);m.useEffect(()=>{const l=document.createElement("script"),c="https://connect.facebook.net/en_US/sdk.js";l.src=c,l.async=!0,document.body.appendChild(l),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})}},[]);function o(){s(!0),window.FB.login(l=>{a(l)},{scope:"public_profile,instagram_basic,instagram_manage_messages,pages_messaging,pages_show_list,pages_manage_metadata,pages_read_engagement"})}async function a(l){if(l.authResponse){const{userID:c,accessToken:u}=l.authResponse;try{window.FB.api("/me",{fields:"name, email"},function(d){console.log("Good to see you, "+d.name+". I see your email address is "+d.email)}),e(c),t(u)}catch(d){console.log(d)}finally{s(!1)}}else s(!1),console.log("User cancelled login or did not fully authorize.")}return i.jsx(J,{variant:"default",onClick:o,className:"bg-[#983b71] text-white hover:bg-[#5a2d6f]",type:"button",disabled:r,children:n(r?"instance.button.connecting":"instance.button.instagram")})}function vK({setNumber:e,setBusiness:t,setToken:n}){const{t:r}=Le(),[s,o]=m.useState(!1);m.useEffect(()=>{const u=document.createElement("script"),d="https://connect.facebook.net/en_US/sdk.js";return u.src=d,u.async=!0,document.body.appendChild(u),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})},((f,p,h)=>{let v=f.getElementById(h);const g=f.getElementsByTagName(p)[0];v||(v=f.createElement(p),v.id=h,v.src="https://connect.facebook.net/en_US/sdk.js",g.parentNode&&g.parentNode.insertBefore(v,g))})(document,"script","facebook-jssdk"),window.addEventListener("message",a),()=>{window.removeEventListener("message",a)}},[]);const a=u=>{if(!(u.origin!=="https://www.facebook.com"&&u.origin!=="https://web.facebook.com"))try{const d=JSON.parse(u.data);if(d.type==="WA_EMBEDDED_SIGNUP"){if(d.event==="FINISH"){const{phone_number_id:f,waba_id:p}=d.data;l(f,p)}}else o(!1)}catch{o(!1)}};async function l(u,d){if(!(!u||!d))try{await _t.post(`https://graph.facebook.com/v20.0/${u}/register`,{messaging_product:"whatsapp",pin:"123456"},{headers:{Authorization:`Bearer ${em()}`}}),await _t.post(`https://graph.facebook.com/v20.0/${d}/subscribed_apps`,{},{headers:{Authorization:`Bearer ${em()}`}}),e(u),t(d),n(em())}catch(f){console.log(f)}finally{o(!1)}}function c(){o(!0),window.fbq&&window.fbq("trackCustom","WhatsAppOnboardingStart",{appId:xp(),feature:"whatsapp_embedded_signup"}),window.FB.login(u=>{u.authResponse||console.log("User cancelled login or did not fully authorize.")},{config_id:gK(),response_type:"code",override_default_response_type:!0,extras:{feature:"whatsapp_embedded_signup",sessionInfoVersion:2}})}return i.jsx(J,{variant:"default",onClick:c,className:"bg-green-600 text-white hover:bg-green-700",type:"button",disabled:s,children:r(s?"instance.button.connecting":"instance.button.whatsapp")})}const tm=k.string().optional().transform(e=>e===""?void 0:e),yK=k.object({name:k.string(),token:tm,number:tm,businessId:tm,integration:k.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","META-FACEBOOK","META-INSTAGRAM"])});function bK({resetTable:e}){const{t}=Le(),[n,r]=m.useState(!1),[s,o]=m.useState([{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")}]),a=kt({resolver:Et(yK),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:r0().replace("-","").toUpperCase(),number:"",businessId:""}}),l=localStorage.getItem("facebookUserToken")&&localStorage.getItem("facebookConfigId")&&localStorage.getItem("facebookAppId");m.useEffect(()=>{l&&o([...s,{value:"META-FACEBOOK",label:t("instance.form.integration.facebook")},{value:"META-INSTAGRAM",label:t("instance.form.integration.instagram")}])},[l]);const c=a.watch("integration"),u=async f=>{var p,h,v;try{const g={instanceName:f.name,integration:f.integration,token:f.token===""?null:f.token,number:f.number===""?null:f.number,businessId:f.businessId===""?null:f.businessId};await k4(g),X.success(t("toast.instance.created")),r(!1),d(),e()}catch(g){console.error("Error:",g),X.error(`Error : ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}},d=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:r0().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"default",size:"sm",children:[t("instance.button.create")," ",i.jsx(Qa,{size:"18"})]})}),i.jsxs(pt,{className:"sm:max-w-[650px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:t("instance.modal.title")})}),i.jsx(dr,{...a,children:i.jsxs("form",{onSubmit:a.handleSubmit(u),className:"grid gap-4 py-4",children:[i.jsx(D,{required:!0,name:"name",label:t("instance.form.name"),children:i.jsx(A,{})}),i.jsx(et,{name:"integration",label:t("instance.form.integration.label"),options:s}),i.jsx(D,{required:!0,name:"token",label:t("instance.form.token"),children:i.jsx(A,{})}),i.jsx(D,{name:"number",label:t("instance.form.number"),children:i.jsx(A,{type:"tel"})}),c==="WHATSAPP-BUSINESS"&&i.jsx(D,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:i.jsx(A,{})}),i.jsxs(Jt,{children:[l&&i.jsxs(i.Fragment,{children:[c==="WHATSAPP-BUSINESS"&&i.jsx(vK,{setNumber:f=>a.setValue("number",f),setBusiness:f=>a.setValue("businessId",f),setToken:f=>a.setValue("token",f)}),c==="META-FACEBOOK"&&i.jsx(hK,{setUserID:f=>a.setValue("number",f),setToken:f=>a.setValue("token",f)}),c==="META-INSTAGRAM"&&i.jsx(mK,{setUserID:f=>a.setValue("number",f),setToken:f=>a.setValue("token",f)})]}),i.jsx(J,{type:"submit",children:t("instance.button.save")})]})]})})]})]})}const nm=async e=>{try{const t=await E4();e(t)}catch(t){console.error("Error fetchData:",t)}};function xK(){const{t:e}=Le(),[t,n]=m.useState(null),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState("all");m.useEffect(()=>{(async()=>{await nm(g=>{s(g)})})()},[]);const u=async()=>{await nm(v=>{s(v)})},d=async v=>{var g,b,y;n(null),a([...o,v]);try{try{await jT(v)}catch(x){console.error("Error logout:",x)}await j4(v),await new Promise(x=>setTimeout(x,1e3)),u()}catch(x){console.error("Error instance delete:",x),X.error(`Error : ${(y=(b=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:b.response)==null?void 0:y.message}`)}finally{a(o.filter(x=>x!==v))}},f=async v=>{if(v===""){await u();return}const g=r.filter(b=>b.name.toLowerCase().includes(v.toLowerCase()));s(g)},p=async v=>{if(c(v),v==="all"){await u();return}await nm(g=>{const b=g.filter(y=>y.connectionStatus===v);s(b)})},h=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return i.jsxs("div",{className:"my-4 px-4",children:[i.jsxs("div",{className:"flex w-full items-center justify-between",children:[i.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(J,{variant:"outline",size:"icon",children:i.jsx(kT,{onClick:u,size:"20"})}),i.jsx(bK,{resetTable:u})]})]}),i.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx(A,{placeholder:e("dashboard.search"),onChange:v=>f(v.target.value)})}),i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"secondary",children:[e("dashboard.status")," ",i.jsx(s4,{size:"15"})]})}),i.jsx(Qr,{children:h.map(v=>i.jsx(i_,{checked:l===v.value,onCheckedChange:g=>{g&&p(v.value)},children:v.label},v.value))})]})]}),i.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r&&r.length>0&&Array.isArray(r)&&r.map(v=>{var g,b;return i.jsxs(wa,{children:[i.jsx(Sa,{children:i.jsxs(lu,{to:`/manager/instance/${v.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[i.jsx("h3",{className:"text-wrap font-semibold",children:v.name}),i.jsx(J,{variant:"ghost",size:"icon",children:i.jsx(Za,{className:"card-icon",size:"20"})})]})}),i.jsxs(Ca,{className:"flex-1 space-y-6",children:[i.jsx(iR,{token:v.token}),i.jsxs("div",{className:"flex w-full flex-wrap",children:[i.jsx("div",{className:"flex flex-1 gap-2",children:v.profileName&&i.jsxs(i.Fragment,{children:[i.jsx(vg,{children:i.jsx(yg,{src:v.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:v.profileName}),i.jsx("p",{className:"text-sm text-muted-foreground",children:v.ownerJid&&v.ownerJid.split("@")[0]})]})]})}),i.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(CT,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((g=v==null?void 0:v._count)==null?void 0:g.Contact)||0)})]}),i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(sg,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((b=v==null?void 0:v._count)==null?void 0:b.Message)||0)})]})]})]})]}),i.jsxs(wg,{className:"justify-between",children:[i.jsx(aR,{status:v.connectionStatus}),i.jsx(J,{variant:"destructive",size:"sm",onClick:()=>n(v.name),disabled:o.includes(v.name),children:o.includes(v.name)?i.jsx("span",{children:e("button.deleting")}):i.jsx("span",{children:e("button.delete")})})]})]},v.id)})}),!!t&&i.jsx(yt,{onOpenChange:()=>n(null),open:!0,children:i.jsxs(pt,{children:[i.jsx(L_,{}),i.jsx(gt,{children:e("modal.delete.title")}),i.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),i.jsx(Jt,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(J,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),i.jsx(J,{onClick:()=>d(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:fl,createContext:wK,createRef:Wee,forwardRef:SN,useCallback:Gn,useContext:CN,useEffect:Pa,useImperativeHandle:kN,useLayoutEffect:SK,useMemo:CK,useRef:Fn,useState:$c}=_p,d1=_p.useId,kK=SK,Lg=wK(null);Lg.displayName="PanelGroupContext";const Oa=kK,EK=typeof d1=="function"?d1:()=>null;let TK=0;function lx(e=null){const t=EK(),n=Fn(e||t||null);return n.current===null&&(n.current=""+TK++),e??n.current}function EN({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:l,minSize:c,onCollapse:u,onExpand:d,onResize:f,order:p,style:h,tagName:v="div",...g}){const b=CN(Lg);if(b===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:x,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:T,registerPanel:j,resizePanel:I,unregisterPanel:P}=b,V=lx(a),O=Fn({callbacks:{onCollapse:u,onExpand:d,onResize:f},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:l,minSize:c},id:V,idIsFromProps:a!==void 0,order:p});Fn({didLogMissingDefaultSizeWarning:!1}),Oa(()=>{const{callbacks:H,constraints:K}=O.current,Y={...K};O.current.id=V,O.current.idIsFromProps=a!==void 0,O.current.order=p,H.onCollapse=u,H.onExpand=d,H.onResize=f,K.collapsedSize=n,K.collapsible=r,K.defaultSize=s,K.maxSize=l,K.minSize=c,(Y.collapsedSize!==K.collapsedSize||Y.collapsible!==K.collapsible||Y.maxSize!==K.maxSize||Y.minSize!==K.minSize)&&T(O.current,Y)}),Oa(()=>{const H=O.current;return j(H),()=>{P(H)}},[p,V,j,P]),kN(o,()=>({collapse:()=>{y(O.current)},expand:H=>{x(O.current,H)},getId(){return V},getSize(){return w(O.current)},isCollapsed(){return C(O.current)},isExpanded(){return!C(O.current)},resize:H=>{I(O.current,H)}}),[y,x,w,C,V,I]);const Z=S(O.current,s);return fl(v,{...g,children:e,className:t,id:a,style:{...Z,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":V,"data-panel-size":parseFloat(""+Z.flexGrow).toFixed(1)})}const TN=SN((e,t)=>fl(EN,{...e,forwardedRef:t}));EN.displayName="Panel";TN.displayName="forwardRef(Panel)";let Yv=null,Ea=null;function jK(e,t){if(t){const n=(t&NN)!==0,r=(t&PN)!==0,s=(t&ON)!==0,o=(t&MN)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function _K(){Ea!==null&&(document.head.removeChild(Ea),Yv=null,Ea=null)}function rm(e,t){const n=jK(e,t);Yv!==n&&(Yv=n,Ea===null&&(Ea=document.createElement("style"),document.head.appendChild(Ea)),Ea.innerHTML=`*{cursor: ${n}!important;}`)}function jN(e){return e.type==="keydown"}function _N(e){return e.type.startsWith("pointer")}function RN(e){return e.type.startsWith("mouse")}function $g(e){if(_N(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(RN(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function RK(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function IK(e,t,n){return e.xt.x&&e.yt.y}function NK(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:g1(e),b:g1(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Je(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:p1(f1(n.a)),b:p1(f1(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const c=o[l];if(c===a.a)return 1;if(c===a.b)return-1}}return Math.sign(s.a-s.b)}const PK=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function OK(e){var t;const n=getComputedStyle((t=IN(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function MK(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||OK(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||PK.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function f1(e){let t=e.length;for(;t--;){const n=e[t];if(Je(n,"Missing node"),MK(n))return n}return null}function p1(e){return e&&Number(getComputedStyle(e).zIndex)||0}function g1(e){const t=[];for(;e;)t.push(e),e=IN(e);return t}function IN(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const NN=1,PN=2,ON=4,MN=8,DK=RK()==="coarse";let Wr=[],Ou=!1,Eo=new Map,Bg=new Map;const Mu=new Set;function AK(e,t,n,r,s){var o;const{ownerDocument:a}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},c=(o=Eo.get(a))!==null&&o!==void 0?o:0;return Eo.set(a,c+1),Mu.add(l),wp(),function(){var d;Bg.delete(e),Mu.delete(l);const f=(d=Eo.get(a))!==null&&d!==void 0?d:1;if(Eo.set(a,f-1),wp(),f===1&&Eo.delete(a),Wr.includes(l)){const p=Wr.indexOf(l);p>=0&&Wr.splice(p,1),ux()}}}function h1(e){const{target:t}=e,{x:n,y:r}=$g(e);Ou=!0,cx({target:t,x:n,y:r}),wp(),Wr.length>0&&(Sp("down",e),e.preventDefault(),e.stopPropagation())}function dc(e){const{x:t,y:n}=$g(e);if(e.buttons===0&&(Ou=!1,Sp("up",e)),!Ou){const{target:r}=e;cx({target:r,x:t,y:n})}Sp("move",e),ux(),Wr.length>0&&e.preventDefault()}function bi(e){const{target:t}=e,{x:n,y:r}=$g(e);Bg.clear(),Ou=!1,Wr.length>0&&e.preventDefault(),Sp("up",e),cx({target:t,x:n,y:r}),ux(),wp()}function cx({target:e,x:t,y:n}){Wr.splice(0);let r=null;e instanceof HTMLElement&&(r=e),Mu.forEach(s=>{const{element:o,hitAreaMargins:a}=s,l=o.getBoundingClientRect(),{bottom:c,left:u,right:d,top:f}=l,p=DK?a.coarse:a.fine;if(t>=u-p&&t<=d+p&&n>=f-p&&n<=c+p){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&NK(r,o)>0){let v=r,g=!1;for(;v&&!v.contains(o);){if(IK(v.getBoundingClientRect(),l)){g=!0;break}v=v.parentElement}if(g)return}Wr.push(s)}})}function sm(e,t){Bg.set(e,t)}function ux(){let e=!1,t=!1;Wr.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;Bg.forEach(r=>{n|=r}),e&&t?rm("intersection",n):e?rm("horizontal",n):t?rm("vertical",n):_K()}function wp(){Eo.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",bi),n.removeEventListener("pointerdown",h1),n.removeEventListener("pointerleave",dc),n.removeEventListener("pointermove",dc)}),window.removeEventListener("pointerup",bi),window.removeEventListener("pointercancel",bi),Mu.size>0&&(Ou?(Wr.length>0&&Eo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",bi),n.addEventListener("pointerleave",dc),n.addEventListener("pointermove",dc))}),window.addEventListener("pointerup",bi),window.addEventListener("pointercancel",bi)):Eo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",h1,{capture:!0}),n.addEventListener("pointermove",dc))}))}function Sp(e,t){Mu.forEach(n=>{const{setResizeHandlerState:r}=n,s=Wr.includes(n);r(e,s,t)})}function Je(e,t){if(!e)throw console.error(t),Error(t)}const dx=10;function qa(e,t,n=dx){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Os(e,t,n=dx){return qa(e,t,n)===0}function Jn(e,t,n){return qa(e,t,n)===0}function FK(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-y:y)}}}{const f=e<0?l:c,p=n[f];Je(p,`No panel constraints found for index ${f}`);const{collapsedSize:h=0,collapsible:v,minSize:g=0}=p;if(v){const b=t[f];if(Je(b!=null,`Previous layout not found for panel index ${f}`),Jn(b,g)){const y=b-h;qa(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}}{const f=e<0?1:-1;let p=e<0?c:l,h=0;for(;;){const g=t[p];Je(g!=null,`Previous layout not found for panel index ${p}`);const y=Bi({panelConstraints:n,panelIndex:p,size:100})-g;if(h+=y,p+=f,p<0||p>=n.length)break}const v=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-v:v}{let p=e<0?l:c;for(;p>=0&&p=0))break;e<0?p--:p++}}if(FK(s,a))return s;{const f=e<0?c:l,p=t[f];Je(p!=null,`Previous layout not found for panel index ${f}`);const h=p+u,v=Bi({panelConstraints:n,panelIndex:f,size:h});if(a[f]=v,!Jn(v,h)){let g=h-v,y=e<0?c:l;for(;y>=0&&y0?y--:y++}}}const d=a.reduce((f,p)=>p+f,0);return Jn(d,100)?a:s}function LK({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const l=n[0];Je(l!=null,"No pivot index found"),t.forEach((f,p)=>{const{constraints:h}=f,{maxSize:v=100,minSize:g=0}=h;p===l?(r=g,s=v):(o+=g,a+=v)});const c=Math.min(s,100-o),u=Math.max(r,100-a),d=e[l];return{valueMax:c,valueMin:u,valueNow:d}}function Du(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function DN(e,t,n=document){const s=Du(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function AN(e,t,n){const r=DN(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function FN(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function zg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function $K(e,t,n,r=document){var s,o,a,l;const c=zg(t,r),u=Du(e,r),d=c?u.indexOf(c):-1,f=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,p=(a=(l=n[d+1])===null||l===void 0?void 0:l.id)!==null&&a!==void 0?a:null;return[f,p]}function BK({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){Fn({didWarnAboutMissingResizeHandle:!1}),Oa(()=>{if(!o)return;const l=Du(n,o);for(let c=0;c{l.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,s,o]),Pa(()=>{if(!o)return;const l=t.current;Je(l,"Eager values not found");const{panelDataArray:c}=l,u=FN(n,o);Je(u!=null,`No group found for id "${n}"`);const d=Du(n,o);Je(d,`No resize handles found for group id "${n}"`);const f=d.map(p=>{const h=p.getAttribute("data-panel-resize-handle-id");Je(h,"Resize handle element has no handle id attribute");const[v,g]=$K(n,h,c,o);if(v==null||g==null)return()=>{};const b=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const x=c.findIndex(w=>w.id===v);if(x>=0){const w=c[x];Je(w,`No panel data found for index ${x}`);const S=r[x],{collapsedSize:E=0,collapsible:C,minSize:T=0}=w.constraints;if(S!=null&&C){const j=Cc({delta:Jn(S,E)?T-E:E-S,initialLayout:r,panelConstraints:c.map(I=>I.constraints),pivotIndices:AN(n,h,o),prevLayout:r,trigger:"keyboard"});r!==j&&a(j)}}break}}};return p.addEventListener("keydown",b),()=>{p.removeEventListener("keydown",b)}});return()=>{f.forEach(p=>p())}},[o,e,t,n,r,s,a])}function m1(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];Je(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:l,id:c}=o,{collapsedSize:u=0,collapsible:d}=l,f=n[c];if(f==null||r!==f){n[c]=r;const{onCollapse:p,onExpand:h,onResize:v}=a;v&&v(r,f),d&&(p||h)&&(h&&(f==null||Os(f,u))&&!Os(r,u)&&h(),p&&(f==null||!Os(f,u))&&Os(r,u)&&p())}})}function zd(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function v1(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function $N(e){return`react-resizable-panels:${e}`}function BN(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function zN(e,t){try{const n=$N(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function GK(e,t,n){var r,s;const o=(r=zN(e,n))!==null&&r!==void 0?r:{},a=BN(t);return(s=o[a])!==null&&s!==void 0?s:null}function qK(e,t,n,r,s){var o;const a=$N(e),l=BN(t),c=(o=zN(e,s))!==null&&o!==void 0?o:{};c[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(c))}catch(u){console.error(u)}}function y1({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!Jn(r,100))for(let o=0;o(v1(kc),kc.getItem(e)),setItem:(e,t)=>{v1(kc),kc.setItem(e,t)}},b1={};function UN({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:l=null,storage:c=kc,style:u,tagName:d="div",...f}){const p=lx(o),h=Fn(null),[v,g]=$c(null),[b,y]=$c([]),x=Fn({}),w=Fn(new Map),S=Fn(0),E=Fn({autoSaveId:e,direction:r,dragState:v,id:p,keyboardResizeBy:l,onLayout:a,storage:c}),C=Fn({layout:b,panelDataArray:[],panelDataArrayChanged:!1});Fn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),kN(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:U}=C.current;return U},setLayout:U=>{const{onLayout:re}=E.current,{layout:te,panelDataArray:ae}=C.current,se=y1({layout:U,panelConstraints:ae.map(q=>q.constraints)});m1(te,se)||(y(se),C.current.layout=se,re&&re(se),xi(ae,se,x.current))}}),[]),Oa(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=v,E.current.id=p,E.current.onLayout=a,E.current.storage=c}),BK({committedValuesRef:E,eagerValuesRef:C,groupId:p,layout:b,panelDataArray:C.current.panelDataArray,setLayout:y,panelGroupElement:h.current}),Pa(()=>{const{panelDataArray:U}=C.current;if(e){if(b.length===0||b.length!==U.length)return;let re=b1[e];re==null&&(re=WK(qK,KK),b1[e]=re);const te=[...U],ae=new Map(w.current);re(e,te,ae,b,c)}},[e,b,c]),Pa(()=>{});const T=Gn(U=>{const{onLayout:re}=E.current,{layout:te,panelDataArray:ae}=C.current;if(U.constraints.collapsible){const se=ae.map(Me=>Me.constraints),{collapsedSize:q=0,panelSize:we,pivotIndices:je}=ca(ae,U,te);if(Je(we!=null,`Panel size not found for panel "${U.id}"`),!Os(we,q)){w.current.set(U.id,we);const _e=ki(ae,U)===ae.length-1?we-q:q-we,pe=Cc({delta:_e,initialLayout:te,panelConstraints:se,pivotIndices:je,prevLayout:te,trigger:"imperative-api"});zd(te,pe)||(y(pe),C.current.layout=pe,re&&re(pe),xi(ae,pe,x.current))}}},[]),j=Gn((U,re)=>{const{onLayout:te}=E.current,{layout:ae,panelDataArray:se}=C.current;if(U.constraints.collapsible){const q=se.map(Qe=>Qe.constraints),{collapsedSize:we=0,panelSize:je=0,minSize:Me=0,pivotIndices:_e}=ca(se,U,ae),pe=re??Me;if(Os(je,we)){const Qe=w.current.get(U.id),It=Qe!=null&&Qe>=pe?Qe:pe,Bt=ki(se,U)===se.length-1?je-It:It-je,Zt=Cc({delta:Bt,initialLayout:ae,panelConstraints:q,pivotIndices:_e,prevLayout:ae,trigger:"imperative-api"});zd(ae,Zt)||(y(Zt),C.current.layout=Zt,te&&te(Zt),xi(se,Zt,x.current))}}},[]),I=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{panelSize:ae}=ca(te,U,re);return Je(ae!=null,`Panel size not found for panel "${U.id}"`),ae},[]),P=Gn((U,re)=>{const{panelDataArray:te}=C.current,ae=ki(te,U);return HK({defaultSize:re,dragState:v,layout:b,panelData:te,panelIndex:ae})},[v,b]),V=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{collapsedSize:ae=0,collapsible:se,panelSize:q}=ca(te,U,re);return Je(q!=null,`Panel size not found for panel "${U.id}"`),se===!0&&Os(q,ae)},[]),O=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{collapsedSize:ae=0,collapsible:se,panelSize:q}=ca(te,U,re);return Je(q!=null,`Panel size not found for panel "${U.id}"`),!se||qa(q,ae)>0},[]),Z=Gn(U=>{const{panelDataArray:re}=C.current;re.push(U),re.sort((te,ae)=>{const se=te.order,q=ae.order;return se==null&&q==null?0:se==null?-1:q==null?1:se-q}),C.current.panelDataArrayChanged=!0},[]);Oa(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:U,onLayout:re,storage:te}=E.current,{layout:ae,panelDataArray:se}=C.current;let q=null;if(U){const je=GK(U,se,te);je&&(w.current=new Map(Object.entries(je.expandToSizes)),q=je.layout)}q==null&&(q=VK({panelDataArray:se}));const we=y1({layout:q,panelConstraints:se.map(je=>je.constraints)});m1(ae,we)||(y(we),C.current.layout=we,re&&re(we),xi(se,we,x.current))}}),Oa(()=>{const U=C.current;return()=>{U.layout=[]}},[]);const H=Gn(U=>function(te){te.preventDefault();const ae=h.current;if(!ae)return()=>null;const{direction:se,dragState:q,id:we,keyboardResizeBy:je,onLayout:Me}=E.current,{layout:_e,panelDataArray:pe}=C.current,{initialLayout:Qe}=q??{},It=AN(we,U,ae);let Vt=UK(te,U,se,q,je,ae);const Bt=se==="horizontal";document.dir==="rtl"&&Bt&&(Vt=-Vt);const Zt=pe.map(z=>z.constraints),_=Cc({delta:Vt,initialLayout:Qe??_e,panelConstraints:Zt,pivotIndices:It,prevLayout:_e,trigger:jN(te)?"keyboard":"mouse-or-touch"}),M=!zd(_e,_);(_N(te)||RN(te))&&S.current!=Vt&&(S.current=Vt,M?sm(U,0):Bt?sm(U,Vt<0?NN:PN):sm(U,Vt<0?ON:MN)),M&&(y(_),C.current.layout=_,Me&&Me(_),xi(pe,_,x.current))},[]),K=Gn((U,re)=>{const{onLayout:te}=E.current,{layout:ae,panelDataArray:se}=C.current,q=se.map(Qe=>Qe.constraints),{panelSize:we,pivotIndices:je}=ca(se,U,ae);Je(we!=null,`Panel size not found for panel "${U.id}"`);const _e=ki(se,U)===se.length-1?we-re:re-we,pe=Cc({delta:_e,initialLayout:ae,panelConstraints:q,pivotIndices:je,prevLayout:ae,trigger:"imperative-api"});zd(ae,pe)||(y(pe),C.current.layout=pe,te&&te(pe),xi(se,pe,x.current))},[]),Y=Gn((U,re)=>{const{layout:te,panelDataArray:ae}=C.current,{collapsedSize:se=0,collapsible:q}=re,{collapsedSize:we=0,collapsible:je,maxSize:Me=100,minSize:_e=0}=U.constraints,{panelSize:pe}=ca(ae,U,te);pe!=null&&(q&&je&&Os(pe,se)?Os(se,we)||K(U,we):pe<_e?K(U,_e):pe>Me&&K(U,Me))},[K]),G=Gn((U,re)=>{const{direction:te}=E.current,{layout:ae}=C.current;if(!h.current)return;const se=zg(U,h.current);Je(se,`Drag handle element not found for id "${U}"`);const q=LN(te,re);g({dragHandleId:U,dragHandleRect:se.getBoundingClientRect(),initialCursorPosition:q,initialLayout:ae})},[]),L=Gn(()=>{g(null)},[]),F=Gn(U=>{const{panelDataArray:re}=C.current,te=ki(re,U);te>=0&&(re.splice(te,1),delete x.current[U.id],C.current.panelDataArrayChanged=!0)},[]),Q=CK(()=>({collapsePanel:T,direction:r,dragState:v,expandPanel:j,getPanelSize:I,getPanelStyle:P,groupId:p,isPanelCollapsed:V,isPanelExpanded:O,reevaluatePanelConstraints:Y,registerPanel:Z,registerResizeHandle:H,resizePanel:K,startDragging:G,stopDragging:L,unregisterPanel:F,panelGroupElement:h.current}),[T,v,r,j,I,P,p,V,O,Y,Z,H,K,G,L,F]),ue={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return fl(Lg.Provider,{value:Q},fl(d,{...f,children:t,className:n,id:o,ref:h,style:{...ue,...u},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":p}))}const VN=SN((e,t)=>fl(UN,{...e,forwardedRef:t}));UN.displayName="PanelGroup";VN.displayName="forwardRef(PanelGroup)";function ki(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function ca(e,t,n){const r=ki(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function JK({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){Pa(()=>{if(e||n==null||r==null)return;const s=zg(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const l=s.getAttribute("data-panel-group-id");Je(l,`No group element found for id "${l}"`);const c=Du(l,r),u=DN(l,t,r);Je(u!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?u>0?u-1:c.length-1:u+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function HN({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:l,style:c={},tabIndex:u=0,tagName:d="div",...f}){var p,h;const v=Fn(null),g=Fn({onDragging:a});Pa(()=>{g.current.onDragging=a});const b=CN(Lg);if(b===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:y,groupId:x,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=b,T=lx(s),[j,I]=$c("inactive"),[P,V]=$c(!1),[O,Z]=$c(null),H=Fn({state:j});Oa(()=>{H.current.state=j}),Pa(()=>{if(n)Z(null);else{const L=w(T);Z(()=>L)}},[n,T,w]);const K=(p=r==null?void 0:r.coarse)!==null&&p!==void 0?p:15,Y=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return Pa(()=>{if(n||O==null)return;const L=v.current;return Je(L,"Element ref not attached"),AK(T,L,y,{coarse:K,fine:Y},(Q,ue,U)=>{if(ue)switch(Q){case"down":{I("drag"),S(T,U);const{onDragging:re}=g.current;re&&re(!0);break}case"move":{const{state:re}=H.current;re!=="drag"&&I("hover"),O(U);break}case"up":{I("hover"),E();const{onDragging:re}=g.current;re&&re(!1);break}}else I("inactive")})},[K,y,n,Y,w,T,O,S,E]),JK({disabled:n,handleId:T,resizeHandler:O,panelGroupElement:C}),fl(d,{...f,children:e,className:t,id:s,onBlur:()=>{V(!1),o==null||o()},onFocus:()=>{V(!0),l==null||l()},ref:v,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:u,"data-panel-group-direction":y,"data-panel-group-id":x,"data-resize-handle":"","data-resize-handle-active":j==="drag"?"pointer":P?"keyboard":void 0,"data-resize-handle-state":j,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":T})}HN.displayName="PanelResizeHandle";const Dl=({className:e,...t})=>i.jsx(VN,{className:me("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),_r=TN,Al=({withHandle:e,className:t,...n})=>i.jsx(HN,{className:me("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&i.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:i.jsx(f4,{className:"h-2.5 w-2.5"})})});var fx="Tabs",[ZK,Gee]=Ir(fx,[fg]),WN=fg(),[QK,px]=ZK(fx),GN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:l,activationMode:c="automatic",...u}=e,d=Zu(l),[f,p]=Bo({prop:r,onChange:s,defaultProp:o});return i.jsx(QK,{scope:n,baseId:Vr(),value:f,onValueChange:p,orientation:a,dir:d,activationMode:c,children:i.jsx(Ie.div,{dir:d,"data-orientation":a,...u,ref:t})})});GN.displayName=fx;var qN="TabsList",KN=m.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=px(qN,n),a=WN(n);return i.jsx(ij,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:i.jsx(Ie.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});KN.displayName=qN;var JN="TabsTrigger",ZN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=px(JN,n),l=WN(n),c=XN(a.baseId,r),u=eP(a.baseId,r),d=r===a.value;return i.jsx(lj,{asChild:!0,...l,focusable:!s,active:d,children:i.jsx(Ie.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":u,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...o,ref:t,onMouseDown:xe(e.onMouseDown,f=>{!s&&f.button===0&&f.ctrlKey===!1?a.onValueChange(r):f.preventDefault()}),onKeyDown:xe(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&a.onValueChange(r)}),onFocus:xe(e.onFocus,()=>{const f=a.activationMode!=="manual";!d&&!s&&f&&a.onValueChange(r)})})})});ZN.displayName=JN;var QN="TabsContent",YN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,l=px(QN,n),c=XN(l.baseId,r),u=eP(l.baseId,r),d=r===l.value,f=m.useRef(d);return m.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),i.jsx(Hn,{present:s||d,children:({present:p})=>i.jsx(Ie.div,{"data-state":d?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:u,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&o})})});YN.displayName=QN;function XN(e,t){return`${e}-trigger-${t}`}function eP(e,t){return`${e}-content-${t}`}var YK=GN,tP=KN,nP=ZN,rP=YN;const XK=YK,sP=m.forwardRef(({className:e,...t},n)=>i.jsx(tP,{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));sP.displayName=tP.displayName;const Xv=m.forwardRef(({className:e,...t},n)=>i.jsx(nP,{ref:n,className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));Xv.displayName=nP.displayName;const ey=m.forwardRef(({className:e,...t},n)=>i.jsx(rP,{ref:n,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));ey.displayName=rP.displayName;const gx=new ur,eJ=async e=>(await gx.getInstance().post(`/chat/findChats/${e}`,{where:{}})).data,tJ=async(e,t)=>(await gx.getInstance().post(`/chat/findChats/${e}`,{where:{remoteJid:t}},{headers:{"Content-Type":"application/json"}})).data,nJ=async(e,t)=>(await gx.getInstance().post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}})).data;function Fl(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=m.useState(t(e));function s(){r(t(e))}return m.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const zs=m.forwardRef(({className:e,...t},n)=>i.jsx("textarea",{className:me("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));zs.displayName="Textarea";function rJ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=st(),[a,l]=m.useState(null),[c,u]=m.useState([]),{remoteJid:d}=Ys();m.useEffect(()=>{const h=async(g,b)=>{try{const y=await tJ(g,b);l(y[0])}catch(y){console.error("Erro ao buscar dados:",y)}},v=async(g,b)=>{try{const y=await nJ(g,b);u(y.messages.records),s()}catch(y){console.error("Erro ao buscar dados:",y)}};o&&d&&(h(o.name,d),v(o.name,d))},[d,o,s]);const f=h=>i.jsx("div",{className:"bubble-right",children:i.jsx("div",{className:"flex items-start gap-4 self-end",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"prose text-muted-foreground",children:i.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})}),p=h=>i.jsx("div",{className:"bubble-left",children:i.jsx("div",{className:"flex items-start gap-4",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"prose text-muted-foreground",children:i.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})});return i.jsxs("div",{className:"flex min-h-screen flex-col",children:[i.jsx("div",{className:"sticky top-0 p-2",children:i.jsxs(Pb,{children:[i.jsx(Ob,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(a==null?void 0:a.pushName)||(a==null?void 0:a.remoteJid.split("@")[0]),i.jsx(rg,{className:"h-4 w-4 text-muted-foreground"})]})}),i.jsxs(Qr,{align:"start",className:"max-w-[300px]",children:[i.jsxs(at,{className:"items-start gap-2",children:[i.jsx(x4,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-4"}),i.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),i.jsx(ra,{}),i.jsxs(at,{className:"items-start gap-2",children:[i.jsx(ET,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-3"}),i.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),i.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[c.map(h=>h.key.fromMe?f(h):p(h)),i.jsx("div",{ref:r})]}),i.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:i.jsxs("div",{className:"input-message relative",children:[i.jsxs(J,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[i.jsx(b4,{className:"h-4 w-4 text-white"}),i.jsx("span",{className:"sr-only",children:"Anexar"})]}),i.jsx(zs,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),i.jsxs(J,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[i.jsx(t4,{className:"h-4 w-4"}),i.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function x1(){const e=Fl("(min-width: 768px)"),t=m.useRef(null),[n]=m.useState("auto"),r=m.useRef(null),[s,o]=m.useState([]),{instance:a}=st(),{instanceId:l,remoteJid:c}=Ys(),u=En(),d=()=>{t.current&&t.current.scrollIntoView({})},f=()=>{if(r.current){r.current.style.height="auto";const h=r.current.scrollHeight,g=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(h,g)}px`}};m.useEffect(()=>{a&&(async v=>{try{const g=await eJ(v);o(g)}catch(g){console.error("Erro ao buscar dados:",g)}})(a.name),d()},[a]);const p=h=>{u(`/manager/instance/${l}/chat/${h}`)};return i.jsxs(Dl,{direction:e?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:20,children:i.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[i.jsx("div",{className:"sticky top-0 p-2",children:i.jsxs(J,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[i.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:i.jsx(sg,{className:"h-4 w-4"})}),i.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),i.jsx(Qa,{className:"h-4 w-4"})]})}),i.jsxs(XK,{defaultValue:"contacts",children:[i.jsxs(sP,{className:"tabs-chat",children:[i.jsx(Xv,{value:"contacts",children:"Contatos"}),i.jsx(Xv,{value:"groups",children:"Grupos"})]}),i.jsx(ey,{value:"contacts",children:i.jsx("div",{className:"flex-1 overflow-auto",children:i.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[i.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),s.map(h=>h.remoteJid.includes("@s.whatsapp.net")&&i.jsxs(lu,{to:"#",onClick:()=>p(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid.split("@")[0]})]})]},h.id))]})})}),i.jsx(ey,{value:"groups",children:i.jsx("div",{className:"flex-1 overflow-auto",children:i.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:s.map(h=>h.remoteJid.includes("@g.us")&&i.jsxs(lu,{to:"#",onClick:()=>p(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid})]})]},h.id))})})})]})]})}),i.jsx(Al,{withHandle:!0,className:"border border-black"}),i.jsx(_r,{children:c&&i.jsx(rJ,{textareaRef:r,handleTextareaChange:f,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const oP=new ur,sJ=async(e,t)=>(await oP.getInstance().get(`/chatwoot/find/${e}`,{headers:{apikey:t}})).data,oJ=async(e,t,n)=>(await oP.getInstance().post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data,aJ=k.object({enabled:k.boolean(),accountId:k.string(),token:k.string(),url:k.string(),signMsg:k.boolean(),signDelimiter:k.string(),nameInbox:k.string(),organization:k.string(),logo:k.string(),reopenConversation:k.boolean(),conversationPending:k.boolean(),mergeBrazilContacts:k.boolean(),importContacts:k.boolean(),importMessages:k.boolean(),daysLimitImportMessages:k.coerce.number(),autoCreate:k.boolean(),ignoreJids:k.array(k.string()).default([])});function iJ(){const{t:e}=Le(),{instance:t}=st(),[,n]=m.useState(!1),r=kt({resolver:Et(aJ),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});m.useEffect(()=>{(async()=>{if(t){n(!0);try{const a=await sJ(t.name,t.token);r.setValue("ignoreJids",a.ignoreJids||[]),r.reset(a)}catch(a){console.error("Error:",a)}finally{n(!1)}}})()},[t,r]);const s=async o=>{var a,l,c;if(t){n(!0);try{const u={enabled:o.enabled,accountId:o.accountId,token:o.token,url:o.url,signMsg:o.signMsg,signDelimiter:o.signDelimiter,nameInbox:o.nameInbox,organization:o.organization,logo:o.logo,reopenConversation:o.reopenConversation,conversationPending:o.conversationPending,mergeBrazilContacts:o.mergeBrazilContacts,importContacts:o.importContacts,importMessages:o.importMessages,daysLimitImportMessages:o.daysLimitImportMessages,autoCreate:o.autoCreate,ignoreJids:o.ignoreJids};await oJ(t.name,t.token,u),X.success(e("chatwoot.toast.success"))}catch(u){console.error(e("chatwoot.toast.error"),u),X.error(`Error: ${(c=(l=(a=u==null?void 0:u.response)==null?void 0:a.data)==null?void 0:l.response)==null?void 0:c.message}`)}finally{n(!1)}}};return i.jsx(i.Fragment,{children:i.jsx(fr,{...r,children:i.jsxs("form",{onSubmit:r.handleSubmit(s),className:"w-full space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[i.jsx(he,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),i.jsx(D,{name:"url",label:e("chatwoot.form.url.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"token",label:e("chatwoot.form.token.label"),children:i.jsx(A,{type:"password"})}),i.jsx(he,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),i.jsx(D,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"organization",label:e("chatwoot.form.organization.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"logo",label:e("chatwoot.form.logo.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),i.jsx(he,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),i.jsx(he,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),i.jsx(he,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),i.jsx(D,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),i.jsx(he,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),i.jsx("div",{className:"mx-4 flex justify-end",children:i.jsx(J,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Ug={},aP={exports:{}},lJ="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",cJ=lJ,uJ=cJ;function iP(){}function lP(){}lP.resetWarningCache=iP;var dJ=function(){function e(r,s,o,a,l,c){if(c!==uJ){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:lP,resetWarningCache:iP};return n.PropTypes=n,n};aP.exports=dJ();var cP=aP.exports,uP={L:1,M:0,Q:3,H:2},dP={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},fJ=dP;function fP(e){this.mode=fJ.MODE_8BIT_BYTE,this.data=e}fP.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var hJ=pP,Lr={glog:function(e){if(e<1)throw new Error("glog("+e+")");return Lr.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return Lr.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var pn=0;pn<8;pn++)Lr.EXP_TABLE[pn]=1<=0;)t^=dn.G15<=0;)t^=dn.G18<>>=1;return t},getPatternPosition:function(e){return dn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case vo.PATTERN000:return(t+n)%2==0;case vo.PATTERN001:return t%2==0;case vo.PATTERN010:return n%3==0;case vo.PATTERN011:return(t+n)%3==0;case vo.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case vo.PATTERN101:return t*n%2+t*n%3==0;case vo.PATTERN110:return(t*n%2+t*n%3)%2==0;case vo.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new w1([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=ps.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};pr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};pr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=ia.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};pr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};pr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=ia.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};pr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var l=0;l<2;l++)if(this.modules[r][a-l]==null){var c=!1;o>>s&1)==1);var u=ia.getMask(t,r,a-l);u&&(c=!c),this.modules[r][a-l]=c,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};ps.PAD0=236;ps.PAD1=17;ps.createData=function(e,t,n){for(var r=mP.getRSBlocks(e,t),s=new vP,o=0;ol*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+l*8+")");for(s.getLengthInBits()+4<=l*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=l*8||(s.put(ps.PAD0,8),s.getLengthInBits()>=l*8));)s.put(ps.PAD1,8);return ps.createBytes(s,r)};ps.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),l=0;l=0?h.get(v):0}}for(var g=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var kJ={bgColor:yr.default.oneOfType([yr.default.object,yr.default.string]).isRequired,bgD:yr.default.string.isRequired,fgColor:yr.default.oneOfType([yr.default.object,yr.default.string]).isRequired,fgD:yr.default.string.isRequired,size:yr.default.number.isRequired,title:yr.default.string,viewBoxSize:yr.default.number.isRequired,xmlns:yr.default.string},mx=(0,yP.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,l=e.title,c=e.viewBoxSize,u=e.xmlns,d=u===void 0?"http://www.w3.org/2000/svg":u,f=CJ(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return Vd.default.createElement("svg",wJ({},f,{height:a,ref:t,viewBox:"0 0 "+c+" "+c,width:a,xmlns:d}),l?Vd.default.createElement("title",null,l):null,Vd.default.createElement("path",{d:r,fill:n}),Vd.default.createElement("path",{d:s,fill:o}))});mx.displayName="QRCodeSvg";mx.propTypes=kJ;hx.default=mx;Object.defineProperty(Ug,"__esModule",{value:!0});Ug.QRCode=void 0;var EJ=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var DJ={bgColor:js.default.oneOfType([js.default.object,js.default.string]),fgColor:js.default.oneOfType([js.default.object,js.default.string]),level:js.default.string,size:js.default.number,value:js.default.string.isRequired},Vg=(0,xP.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,l=a===void 0?"L":a,c=e.size,u=c===void 0?256:c,d=e.value,f=MJ(e,["bgColor","fgColor","level","size","value"]),p=new IJ.default(-1,_J.default[l]);p.addData(d),p.make();var h=p.modules;return NJ.default.createElement(OJ.default,EJ({},f,{bgColor:r,bgD:h.map(function(v,g){return v.map(function(b,y){return b?"":"M "+y+" "+g+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:h.map(function(v,g){return v.map(function(b,y){return b?"M "+y+" "+g+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:u,viewBoxSize:h.length}))});Ug.QRCode=Vg;Vg.displayName="QRCode";Vg.propTypes=DJ;var AJ=Ug.default=Vg;const FJ=ng("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),wP=m.forwardRef(({className:e,variant:t,...n},r)=>i.jsx("div",{ref:r,role:"alert",className:me(FJ({variant:t}),e),...n}));wP.displayName="Alert";const SP=m.forwardRef(({className:e,...t},n)=>i.jsx("h5",{ref:n,className:me("font-medium leading-none tracking-tight",e),...t}));SP.displayName="AlertTitle";const LJ=m.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:me("text-sm [&_p]:leading-relaxed",e),...t}));LJ.displayName="AlertDescription";const or=({size:e=45,className:t,...n})=>i.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:me("animate-spin",t),children:i.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}),om=new Intl.NumberFormat("pt-BR");function $J(){const{t:e}=Le(),[t,n]=m.useState(null),[r,s]=m.useState(""),o=localStorage.getItem("token"),{theme:a}=VE(),{instance:l}=st(),c=()=>{window.location.reload()},u=async g=>{try{await T4(g),window.location.reload()}catch(b){console.error("Error:",b)}},d=async g=>{try{await jT(g),window.location.reload()}catch(b){console.error("Error:",b)}},f=async(g,b)=>{try{if(n(null),!o){console.error("Token not found.");return}if(b){const y=await CS(g,o,l==null?void 0:l.number);s(y.pairingCode)}else{const y=await CS(g,o);n(y.code)}}catch(y){console.error("Error:",y)}},p=()=>{n(null),s(""),window.location.reload()},h=m.useMemo(()=>{var g,b,y;return l?{contacts:((g=l._count)==null?void 0:g.Contact)||0,chats:((b=l._count)==null?void 0:b.Chat)||0,messages:((y=l._count)==null?void 0:y.Message)||0}:{contacts:0,chats:0,messages:0}},[l]),v=m.useMemo(()=>a==="dark"?"#fff":a==="light"?"#000":"#189d68",[a]);return l?i.jsxs("main",{className:"flex flex-col gap-8",children:[i.jsx("section",{children:i.jsxs(wa,{children:[i.jsx(Sa,{children:i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsx("h2",{className:"break-all text-lg font-semibold",children:l.name}),i.jsx(aR,{status:l.connectionStatus})]})}),i.jsxs(Ca,{className:"flex flex-col items-start space-y-6",children:[i.jsx("div",{className:"flex w-full flex-1",children:i.jsx(iR,{token:l.token})}),l.profileName&&i.jsxs("div",{className:"flex flex-1 gap-2",children:[i.jsx(vg,{children:i.jsx(yg,{src:l.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:l.profileName}),i.jsx("p",{className:"break-all text-sm text-muted-foreground",children:l.ownerJid})]})]}),l.connectionStatus!=="open"&&i.jsxs(wP,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx(SP,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),i.jsxs(yt,{children:[i.jsx(Rt,{onClick:()=>f(l.name,!1),asChild:!0,children:i.jsx(J,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),i.jsxs(pt,{onCloseAutoFocus:p,children:[i.jsx(gt,{children:e("instance.dashboard.button.qrcode.title")}),i.jsx("div",{className:"flex items-center justify-center",children:t&&i.jsx(AJ,{value:t,size:256,bgColor:"transparent",fgColor:v,className:"rounded-sm"})})]})]}),l.number&&i.jsxs(yt,{children:[i.jsx(Rt,{className:"connect-code-button",onClick:()=>f(l.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),i.jsx(pt,{onCloseAutoFocus:p,children:i.jsx(gt,{children:i.jsx(ti,{children:r?i.jsxs("div",{className:"py-3",children:[i.jsx("p",{className:"text-center",children:i.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),i.jsxs("p",{className:"pairing-code text-center",children:[r.substring(0,4),"-",r.substring(4,8)]})]}):i.jsx(or,{})})})})]})]})]}),i.jsxs(wg,{className:"flex flex-wrap items-center justify-end gap-3",children:[i.jsx(J,{variant:"outline",className:"refresh-button",size:"icon",onClick:c,children:i.jsx(kT,{size:"20"})}),i.jsx(J,{className:"action-button",variant:"secondary",onClick:()=>u(l.name),children:e("instance.dashboard.button.restart").toUpperCase()}),i.jsx(J,{variant:"destructive",onClick:()=>d(l.name),disabled:l.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),i.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(CT,{size:"20"}),e("instance.dashboard.contacts")]})}),i.jsx(Ca,{children:om.format(h.contacts)})]}),i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(S4,{size:"20"}),e("instance.dashboard.chats")]})}),i.jsx(Ca,{children:om.format(h.chats)})]}),i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(sg,{size:"20"}),e("instance.dashboard.messages")]})}),i.jsx(Ca,{children:om.format(h.messages)})]})]})]}):i.jsx(or,{})}var BJ="Separator",S1="horizontal",zJ=["horizontal","vertical"],CP=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=S1,...s}=e,o=UJ(r)?r:S1,l=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return i.jsx(Ie.div,{"data-orientation":o,...l,...s,ref:t})});CP.displayName=BJ;function UJ(e){return zJ.includes(e)}var kP=CP;const Ze=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>i.jsx(kP,{ref:s,decorative:n,orientation:t,className:me("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Ze.displayName=kP.displayName;const oo=new ur,EP=async(e,t)=>(await oo.getInstance().get(`/dify/find/${e}`,{headers:{apikey:t}})).data,VJ=async(e,t,n)=>(await oo.getInstance().get(`/dify/fetch/${n}/${e}`,{headers:{apikey:t}})).data,HJ=async(e,t,n)=>(await oo.getInstance().post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,WJ=async(e,t,n,r)=>(await oo.getInstance().put(`/dify/update/${n}/${e}`,r,{headers:{apikey:t}})).data,GJ=async(e,t,n)=>(await oo.getInstance().delete(`/dify/delete/${n}/${e}`,{headers:{apikey:t}})).data,qJ=async(e,t)=>(await oo.getInstance().get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,KJ=async(e,t,n)=>(await oo.getInstance().post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,JJ=async(e,t,n)=>(await oo.getInstance().get(`/dify/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,ZJ=async(e,t,n,r)=>(await oo.getInstance().post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,QJ=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),difyIdFallback:k.union([k.null(),k.string()]).optional()}),C1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await qJ(e.name,r);t(s);const o=await EP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function YJ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(QJ),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0}});m.useEffect(()=>{n&&C1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,difyIdFallback:s.difyIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids};await KJ(t.name,t.token,g),X.success(e("dify.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){C1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("dify.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("dify.button.save")})})]})})]})]})}const XJ=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function eZ({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(XJ),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,botType:f.botType,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await HJ(n.name,n.token,g),X.success(t("dify.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("dify.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("dify.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("dify.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.difySettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:t("dify.form.botType.label"),options:[{label:t("dify.form.botType.chatBot"),value:"chatBot"},{label:t("dify.form.botType.textGenerator"),value:"textGenerator"},{label:t("dify.form.botType.agent"),value:"agent"},{label:t("dify.form.botType.workflow"),value:"workflow"}]}),i.jsx(D,{name:"apiUrl",label:t("dify.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("dify.form.apiKey.label"),required:!0,children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("dify.form.triggerType.label"),options:[{label:t("dify.form.triggerType.keyword"),value:"keyword"},{label:t("dify.form.triggerType.all"),value:"all"},{label:t("dify.form.triggerType.advanced"),value:"advanced"},{label:t("dify.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("dify.form.triggerOperator.label"),options:[{label:t("dify.form.triggerOperator.contains"),value:"contains"},{label:t("dify.form.triggerOperator.equals"),value:"equals"},{label:t("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("dify.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("dify.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("dify.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("dify.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("dify.button.save")})})]})})]})]})}/** +*/var Iq="Label",kI=m.forwardRef((e,t)=>i.jsx(Ie.label,{...e,ref:t,onMouseDown:n=>{var s;n.target.closest("button, input, select, textarea")||((s=e.onMouseDown)==null||s.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));kI.displayName=Iq;var EI=kI;const Nq=ng("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),TI=m.forwardRef(({className:e,...t},n)=>i.jsx(EI,{ref:n,className:me(Nq(),e),...t}));TI.displayName=EI.displayName;function jI(e){const t=m.useRef({value:e,previous:e});return m.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Pq="VisuallyHidden",_I=m.forwardRef((e,t)=>i.jsx(Ie.span,{...e,ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));_I.displayName=Pq;var Oq=[" ","Enter","ArrowUp","ArrowDown"],Mq=[" ","Enter"],nd="Select",[Og,Mg,Dq]=pb(nd),[Pl,Vee]=Ir(nd,[Dq,cg]),Dg=cg(),[Aq,sa]=Pl(nd),[Fq,Lq]=Pl(nd),RI=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:a,defaultValue:l,onValueChange:c,dir:u,name:d,autoComplete:f,disabled:p,required:h}=e,v=Dg(t),[g,b]=m.useState(null),[y,x]=m.useState(null),[w,S]=m.useState(!1),E=Zu(u),[C=!1,T]=Bo({prop:r,defaultProp:s,onChange:o}),[j,I]=Bo({prop:a,defaultProp:l,onChange:c}),P=m.useRef(null),V=g?!!g.closest("form"):!0,[O,Z]=m.useState(new Set),H=Array.from(O).map(K=>K.props.value).join(";");return i.jsx(YT,{...v,children:i.jsxs(Aq,{required:h,scope:t,trigger:g,onTriggerChange:b,valueNode:y,onValueNodeChange:x,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:Vr(),value:j,onValueChange:I,open:C,onOpenChange:T,dir:E,triggerPointerDownPosRef:P,disabled:p,children:[i.jsx(Og.Provider,{scope:t,children:i.jsx(Fq,{scope:e.__scopeSelect,onNativeOptionAdd:m.useCallback(K=>{Z(Y=>new Set(Y).add(K))},[]),onNativeOptionRemove:m.useCallback(K=>{Z(Y=>{const G=new Set(Y);return G.delete(K),G})},[]),children:n})}),V?i.jsxs(eN,{"aria-hidden":!0,required:h,tabIndex:-1,name:d,autoComplete:f,value:j,onChange:K=>I(K.target.value),disabled:p,children:[j===void 0?i.jsx("option",{value:""}):null,Array.from(O)]},H):null]})})};RI.displayName=nd;var II="SelectTrigger",NI=m.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=Dg(n),a=sa(II,n),l=a.disabled||r,c=tt(t,a.onTriggerChange),u=Mg(n),[d,f,p]=tN(v=>{const g=u().filter(x=>!x.disabled),b=g.find(x=>x.value===a.value),y=nN(g,v,b);y!==void 0&&a.onValueChange(y.value)}),h=()=>{l||(a.onOpenChange(!0),p())};return i.jsx(XT,{asChild:!0,...o,children:i.jsx(Ie.button,{type:"button",role:"combobox","aria-controls":a.contentId,"aria-expanded":a.open,"aria-required":a.required,"aria-autocomplete":"none",dir:a.dir,"data-state":a.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":XI(a.value)?"":void 0,...s,ref:c,onClick:xe(s.onClick,v=>{v.currentTarget.focus()}),onPointerDown:xe(s.onPointerDown,v=>{const g=v.target;g.hasPointerCapture(v.pointerId)&&g.releasePointerCapture(v.pointerId),v.button===0&&v.ctrlKey===!1&&(h(),a.triggerPointerDownPosRef.current={x:Math.round(v.pageX),y:Math.round(v.pageY)},v.preventDefault())}),onKeyDown:xe(s.onKeyDown,v=>{const g=d.current!=="";!(v.ctrlKey||v.altKey||v.metaKey)&&v.key.length===1&&f(v.key),!(g&&v.key===" ")&&Oq.includes(v.key)&&(h(),v.preventDefault())})})})});NI.displayName=II;var PI="SelectValue",OI=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:a="",...l}=e,c=sa(PI,n),{onValueNodeHasChildrenChange:u}=c,d=o!==void 0,f=tt(t,c.onValueNodeChange);return tn(()=>{u(d)},[u,d]),i.jsx(Ie.span,{...l,ref:f,style:{pointerEvents:"none"},children:XI(c.value)?i.jsx(i.Fragment,{children:a}):o})});OI.displayName=PI;var $q="SelectIcon",MI=m.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return i.jsx(Ie.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});MI.displayName=$q;var Bq="SelectPortal",DI=e=>i.jsx(ug,{asChild:!0,...e});DI.displayName=Bq;var Ga="SelectContent",AI=m.forwardRef((e,t)=>{const n=sa(Ga,e.__scopeSelect),[r,s]=m.useState();if(tn(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Xo.createPortal(i.jsx(FI,{scope:e.__scopeSelect,children:i.jsx(Og.Slot,{scope:e.__scopeSelect,children:i.jsx("div",{children:e.children})})}),o):null}return i.jsx(LI,{...e,ref:t})});AI.displayName=Ga;var Is=10,[FI,oa]=Pl(Ga),zq="SelectContentImpl",LI=m.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:a,side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:b,...y}=e,x=sa(Ga,n),[w,S]=m.useState(null),[E,C]=m.useState(null),T=tt(t,q=>S(q)),[j,I]=m.useState(null),[P,V]=m.useState(null),O=Mg(n),[Z,H]=m.useState(!1),K=m.useRef(!1);m.useEffect(()=>{if(w)return Cb(w)},[w]),gb();const Y=m.useCallback(q=>{const[we,...je]=O().map(pe=>pe.ref.current),[Me]=je.slice(-1),_e=document.activeElement;for(const pe of q)if(pe===_e||(pe==null||pe.scrollIntoView({block:"nearest"}),pe===we&&E&&(E.scrollTop=0),pe===Me&&E&&(E.scrollTop=E.scrollHeight),pe==null||pe.focus(),document.activeElement!==_e))return},[O,E]),G=m.useCallback(()=>Y([j,w]),[Y,j,w]);m.useEffect(()=>{Z&&G()},[Z,G]);const{onOpenChange:L,triggerPointerDownPosRef:F}=x;m.useEffect(()=>{if(w){let q={x:0,y:0};const we=Me=>{var _e,pe;q={x:Math.abs(Math.round(Me.pageX)-(((_e=F.current)==null?void 0:_e.x)??0)),y:Math.abs(Math.round(Me.pageY)-(((pe=F.current)==null?void 0:pe.y)??0))}},je=Me=>{q.x<=10&&q.y<=10?Me.preventDefault():w.contains(Me.target)||L(!1),document.removeEventListener("pointermove",we),F.current=null};return F.current!==null&&(document.addEventListener("pointermove",we),document.addEventListener("pointerup",je,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",we),document.removeEventListener("pointerup",je,{capture:!0})}}},[w,L,F]),m.useEffect(()=>{const q=()=>L(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[L]);const[Q,ue]=tN(q=>{const we=O().filter(_e=>!_e.disabled),je=we.find(_e=>_e.ref.current===document.activeElement),Me=nN(we,q,je);Me&&setTimeout(()=>Me.ref.current.focus())}),U=m.useCallback((q,we,je)=>{const Me=!K.current&&!je;(x.value!==void 0&&x.value===we||Me)&&(I(q),Me&&(K.current=!0))},[x.value]),re=m.useCallback(()=>w==null?void 0:w.focus(),[w]),te=m.useCallback((q,we,je)=>{const Me=!K.current&&!je;(x.value!==void 0&&x.value===we||Me)&&V(q)},[x.value]),ae=r==="popper"?qv:$I,se=ae===qv?{side:l,sideOffset:c,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:p,collisionPadding:h,sticky:v,hideWhenDetached:g,avoidCollisions:b}:{};return i.jsx(FI,{scope:n,content:w,viewport:E,onViewportChange:C,itemRefCallback:U,selectedItem:j,onItemLeave:re,itemTextRefCallback:te,focusSelectedItem:G,selectedItemText:P,position:r,isPositioned:Z,searchRef:Q,children:i.jsx(gg,{as:Gs,allowPinchZoom:!0,children:i.jsx(ag,{asChild:!0,trapped:x.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:xe(s,q=>{var we;(we=x.trigger)==null||we.focus({preventScroll:!0}),q.preventDefault()}),children:i.jsx(og,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:a,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>x.onOpenChange(!1),children:i.jsx(ae,{role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:q=>q.preventDefault(),...y,...se,onPlaced:()=>H(!0),ref:T,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:xe(y.onKeyDown,q=>{const we=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!we&&q.key.length===1&&ue(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let Me=O().filter(_e=>!_e.disabled).map(_e=>_e.ref.current);if(["ArrowUp","End"].includes(q.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const _e=q.target,pe=Me.indexOf(_e);Me=Me.slice(pe+1)}setTimeout(()=>Y(Me)),q.preventDefault()}})})})})})})});LI.displayName=zq;var Uq="SelectItemAlignedPosition",$I=m.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=sa(Ga,n),a=oa(Ga,n),[l,c]=m.useState(null),[u,d]=m.useState(null),f=tt(t,T=>d(T)),p=Mg(n),h=m.useRef(!1),v=m.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:y,focusSelectedItem:x}=a,w=m.useCallback(()=>{if(o.trigger&&o.valueNode&&l&&u&&g&&b&&y){const T=o.trigger.getBoundingClientRect(),j=u.getBoundingClientRect(),I=o.valueNode.getBoundingClientRect(),P=y.getBoundingClientRect();if(o.dir!=="rtl"){const _e=P.left-j.left,pe=I.left-_e,Qe=T.left-pe,It=T.width+Qe,Vt=Math.max(It,j.width),Bt=window.innerWidth-Is,Zt=Iv(pe,[Is,Bt-Vt]);l.style.minWidth=It+"px",l.style.left=Zt+"px"}else{const _e=j.right-P.right,pe=window.innerWidth-I.right-_e,Qe=window.innerWidth-T.right-pe,It=T.width+Qe,Vt=Math.max(It,j.width),Bt=window.innerWidth-Is,Zt=Iv(pe,[Is,Bt-Vt]);l.style.minWidth=It+"px",l.style.right=Zt+"px"}const V=p(),O=window.innerHeight-Is*2,Z=g.scrollHeight,H=window.getComputedStyle(u),K=parseInt(H.borderTopWidth,10),Y=parseInt(H.paddingTop,10),G=parseInt(H.borderBottomWidth,10),L=parseInt(H.paddingBottom,10),F=K+Y+Z+L+G,Q=Math.min(b.offsetHeight*5,F),ue=window.getComputedStyle(g),U=parseInt(ue.paddingTop,10),re=parseInt(ue.paddingBottom,10),te=T.top+T.height/2-Is,ae=O-te,se=b.offsetHeight/2,q=b.offsetTop+se,we=K+Y+q,je=F-we;if(we<=te){const _e=b===V[V.length-1].ref.current;l.style.bottom="0px";const pe=u.clientHeight-g.offsetTop-g.offsetHeight,Qe=Math.max(ae,se+(_e?re:0)+pe+G),It=we+Qe;l.style.height=It+"px"}else{const _e=b===V[0].ref.current;l.style.top="0px";const Qe=Math.max(te,K+g.offsetTop+(_e?U:0)+se)+je;l.style.height=Qe+"px",g.scrollTop=we-te+g.offsetTop}l.style.margin=`${Is}px 0`,l.style.minHeight=Q+"px",l.style.maxHeight=O+"px",r==null||r(),requestAnimationFrame(()=>h.current=!0)}},[p,o.trigger,o.valueNode,l,u,g,b,y,o.dir,r]);tn(()=>w(),[w]);const[S,E]=m.useState();tn(()=>{u&&E(window.getComputedStyle(u).zIndex)},[u]);const C=m.useCallback(T=>{T&&v.current===!0&&(w(),x==null||x(),v.current=!1)},[w,x]);return i.jsx(Hq,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:h,onScrollButtonChange:C,children:i.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:S},children:i.jsx(Ie.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});$I.displayName=Uq;var Vq="SelectPopperPosition",qv=m.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Is,...o}=e,a=Dg(n);return i.jsx(ej,{...a,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});qv.displayName=Vq;var[Hq,ax]=Pl(Ga,{}),Kv="SelectViewport",BI=m.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=oa(Kv,n),a=ax(Kv,n),l=tt(t,o.onViewportChange),c=m.useRef(0);return i.jsxs(i.Fragment,{children:[i.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),i.jsx(Og.Slot,{scope:n,children:i.jsx(Ie.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:l,style:{position:"relative",flex:1,overflow:"auto",...s.style},onScroll:xe(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:p}=a;if(p!=null&&p.current&&f){const h=Math.abs(c.current-d.scrollTop);if(h>0){const v=window.innerHeight-Is*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),y=Math.max(g,b);if(y0?S:0,f.style.justifyContent="flex-end")}}}c.current=d.scrollTop})})})]})});BI.displayName=Kv;var zI="SelectGroup",[Wq,Gq]=Pl(zI),qq=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Vr();return i.jsx(Wq,{scope:n,id:s,children:i.jsx(Ie.div,{role:"group","aria-labelledby":s,...r,ref:t})})});qq.displayName=zI;var UI="SelectLabel",VI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Gq(UI,n);return i.jsx(Ie.div,{id:s.id,...r,ref:t})});VI.displayName=UI;var bp="SelectItem",[Kq,HI]=Pl(bp),WI=m.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...a}=e,l=sa(bp,n),c=oa(bp,n),u=l.value===r,[d,f]=m.useState(o??""),[p,h]=m.useState(!1),v=tt(t,y=>{var x;return(x=c.itemRefCallback)==null?void 0:x.call(c,y,r,s)}),g=Vr(),b=()=>{s||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return i.jsx(Kq,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:m.useCallback(y=>{f(x=>x||((y==null?void 0:y.textContent)??"").trim())},[]),children:i.jsx(Og.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:i.jsx(Ie.div,{role:"option","aria-labelledby":g,"data-highlighted":p?"":void 0,"aria-selected":u&&p,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...a,ref:v,onFocus:xe(a.onFocus,()=>h(!0)),onBlur:xe(a.onBlur,()=>h(!1)),onPointerUp:xe(a.onPointerUp,b),onPointerMove:xe(a.onPointerMove,y=>{var x;s?(x=c.onItemLeave)==null||x.call(c):y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:xe(a.onPointerLeave,y=>{var x;y.currentTarget===document.activeElement&&((x=c.onItemLeave)==null||x.call(c))}),onKeyDown:xe(a.onKeyDown,y=>{var w;((w=c.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(Mq.includes(y.key)&&b(),y.key===" "&&y.preventDefault())})})})})});WI.displayName=bp;var Sc="SelectItemText",GI=m.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,a=sa(Sc,n),l=oa(Sc,n),c=HI(Sc,n),u=Lq(Sc,n),[d,f]=m.useState(null),p=tt(t,y=>f(y),c.onItemTextChange,y=>{var x;return(x=l.itemTextRefCallback)==null?void 0:x.call(l,y,c.value,c.disabled)}),h=d==null?void 0:d.textContent,v=m.useMemo(()=>i.jsx("option",{value:c.value,disabled:c.disabled,children:h},c.value),[c.disabled,c.value,h]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return tn(()=>(g(v),()=>b(v)),[g,b,v]),i.jsxs(i.Fragment,{children:[i.jsx(Ie.span,{id:c.textId,...o,ref:p}),c.isSelected&&a.valueNode&&!a.valueNodeHasChildren?Xo.createPortal(o.children,a.valueNode):null]})});GI.displayName=Sc;var qI="SelectItemIndicator",KI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return HI(qI,n).isSelected?i.jsx(Ie.span,{"aria-hidden":!0,...r,ref:t}):null});KI.displayName=qI;var Jv="SelectScrollUpButton",JI=m.forwardRef((e,t)=>{const n=oa(Jv,e.__scopeSelect),r=ax(Jv,e.__scopeSelect),[s,o]=m.useState(!1),a=tt(t,r.onScrollButtonChange);return tn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollTop>0;o(u)};const c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?i.jsx(QI,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop-c.offsetHeight)}}):null});JI.displayName=Jv;var Zv="SelectScrollDownButton",ZI=m.forwardRef((e,t)=>{const n=oa(Zv,e.__scopeSelect),r=ax(Zv,e.__scopeSelect),[s,o]=m.useState(!1),a=tt(t,r.onScrollButtonChange);return tn(()=>{if(n.viewport&&n.isPositioned){let l=function(){const u=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),s?i.jsx(QI,{...e,ref:a,onAutoScroll:()=>{const{viewport:l,selectedItem:c}=n;l&&c&&(l.scrollTop=l.scrollTop+c.offsetHeight)}}):null});ZI.displayName=Zv;var QI=m.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=oa("SelectScrollButton",n),a=m.useRef(null),l=Mg(n),c=m.useCallback(()=>{a.current!==null&&(window.clearInterval(a.current),a.current=null)},[]);return m.useEffect(()=>()=>c(),[c]),tn(()=>{var d;const u=l().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[l]),i.jsx(Ie.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:xe(s.onPointerDown,()=>{a.current===null&&(a.current=window.setInterval(r,50))}),onPointerMove:xe(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),a.current===null&&(a.current=window.setInterval(r,50))}),onPointerLeave:xe(s.onPointerLeave,()=>{c()})})}),Jq="SelectSeparator",YI=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return i.jsx(Ie.div,{"aria-hidden":!0,...r,ref:t})});YI.displayName=Jq;var Qv="SelectArrow",Zq=m.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=Dg(n),o=sa(Qv,n),a=oa(Qv,n);return o.open&&a.position==="popper"?i.jsx(tj,{...s,...r,ref:t}):null});Zq.displayName=Qv;function XI(e){return e===""||e===void 0}var eN=m.forwardRef((e,t)=>{const{value:n,...r}=e,s=m.useRef(null),o=tt(t,s),a=jI(n);return m.useEffect(()=>{const l=s.current,c=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(a!==n&&d){const f=new Event("change",{bubbles:!0});d.call(l,n),l.dispatchEvent(f)}},[a,n]),i.jsx(_I,{asChild:!0,children:i.jsx("select",{...r,ref:o,defaultValue:n})})});eN.displayName="BubbleSelect";function tN(e){const t=Kt(e),n=m.useRef(""),r=m.useRef(0),s=m.useCallback(a=>{const l=n.current+a;t(l),function c(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(l)},[t]),o=m.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return m.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function nN(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let a=Qq(e,Math.max(o,0));s.length===1&&(a=a.filter(u=>u!==n));const c=a.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return c!==n?c:void 0}function Qq(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Yq=RI,rN=NI,Xq=OI,eK=MI,tK=DI,sN=AI,nK=BI,oN=VI,aN=WI,rK=GI,sK=KI,iN=JI,lN=ZI,cN=YI;const oK=Yq,aK=Xq,uN=m.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(rN,{ref:r,className:me("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,i.jsx(eK,{asChild:!0,children:i.jsx(rg,{className:"h-4 w-4 opacity-50"})})]}));uN.displayName=rN.displayName;const dN=m.forwardRef(({className:e,...t},n)=>i.jsx(iN,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(r4,{className:"h-4 w-4"})}));dN.displayName=iN.displayName;const fN=m.forwardRef(({className:e,...t},n)=>i.jsx(lN,{ref:n,className:me("flex cursor-default items-center justify-center py-1",e),...t,children:i.jsx(rg,{className:"h-4 w-4"})}));fN.displayName=lN.displayName;const pN=m.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>i.jsx(tK,{children:i.jsxs(sN,{ref:s,className:me("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[i.jsx(dN,{}),i.jsx(nK,{className:me("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),i.jsx(fN,{})]})}));pN.displayName=sN.displayName;const iK=m.forwardRef(({className:e,...t},n)=>i.jsx(oN,{ref:n,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));iK.displayName=oN.displayName;const gN=m.forwardRef(({className:e,children:t,...n},r)=>i.jsxs(aN,{ref:r,className:me("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[i.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:i.jsx(sK,{children:i.jsx(ST,{className:"h-4 w-4"})})}),i.jsx(rK,{children:t})]}));gN.displayName=aN.displayName;const lK=m.forwardRef(({className:e,...t},n)=>i.jsx(cN,{ref:n,className:me("-mx-1 my-1 h-px bg-muted",e),...t}));lK.displayName=cN.displayName;var ix="Switch",[cK,Hee]=Ir(ix),[uK,dK]=cK(ix),hN=m.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:s,defaultChecked:o,required:a,disabled:l,value:c="on",onCheckedChange:u,...d}=e,[f,p]=m.useState(null),h=tt(t,x=>p(x)),v=m.useRef(!1),g=f?!!f.closest("form"):!0,[b=!1,y]=Bo({prop:s,defaultProp:o,onChange:u});return i.jsxs(uK,{scope:n,checked:b,disabled:l,children:[i.jsx(Ie.button,{type:"button",role:"switch","aria-checked":b,"aria-required":a,"data-state":yN(b),"data-disabled":l?"":void 0,disabled:l,value:c,...d,ref:h,onClick:xe(e.onClick,x=>{y(w=>!w),g&&(v.current=x.isPropagationStopped(),v.current||x.stopPropagation())})}),g&&i.jsx(fK,{control:f,bubbles:!v.current,name:r,value:c,checked:b,required:a,disabled:l,style:{transform:"translateX(-100%)"}})]})});hN.displayName=ix;var mN="SwitchThumb",vN=m.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,s=dK(mN,n);return i.jsx(Ie.span,{"data-state":yN(s.checked),"data-disabled":s.disabled?"":void 0,...r,ref:t})});vN.displayName=mN;var fK=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=m.useRef(null),a=jI(n),l=UT(t);return m.useEffect(()=>{const c=o.current,u=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(u,"checked").set;if(a!==n&&f){const p=new Event("click",{bubbles:r});f.call(c,n),c.dispatchEvent(p)}},[a,n,r]),i.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function yN(e){return e?"checked":"unchecked"}var bN=hN,pK=vN;const Ol=m.forwardRef(({className:e,...t},n)=>i.jsx(bN,{className:me("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-slate-400",e),...t,ref:n,children:i.jsx(pK,{className:me("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Ol.displayName=bN.displayName;const fr=dr,xN=m.createContext({}),aa=({...e})=>i.jsx(xN.Provider,{value:{name:e.name},children:i.jsx(i5,{...e})}),Ag=()=>{const e=m.useContext(xN),t=m.useContext(wN),{getFieldState:n,formState:r}=Cg(),s=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:o}=t;return{id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...s}},wN=m.createContext({}),so=m.forwardRef(({className:e,...t},n)=>{const r=m.useId();return i.jsx(wN.Provider,{value:{id:r},children:i.jsx("div",{ref:n,className:me("space-y-2",e),...t})})});so.displayName="FormItem";const sr=m.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:s}=Ag();return i.jsx(TI,{ref:n,className:me(r&&"text-rose-600",e),htmlFor:s,...t})});sr.displayName="FormLabel";const Ss=m.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:s,formMessageId:o}=Ag();return i.jsx(Gs,{ref:t,id:r,"aria-describedby":n?`${s} ${o}`:`${s}`,"aria-invalid":!!n,...e})});Ss.displayName="FormControl";const Fg=m.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=Ag();return i.jsx("p",{ref:n,id:r,className:me("text-sm text-muted-foreground",e),...t})});Fg.displayName="FormDescription";const rd=m.forwardRef(({className:e,children:t,...n},r)=>{const{error:s,formMessageId:o}=Ag(),a=s?String(s==null?void 0:s.message):t;return a?i.jsx("p",{ref:r,id:o,className:me("text-sm font-medium text-rose-600",e),...n,children:a}):null});rd.displayName="FormMessage";const D=({name:e,label:t,children:n,required:r,readOnly:s,className:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{className:o,children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:m.isValidElement(n)&&m.cloneElement(n,{...l,value:l.value??"",required:r,readOnly:s,checked:l.value,onCheckedChange:l.onChange})}),i.jsx(rd,{})]})}),he=({name:e,label:t,required:n,className:r,helper:s,reverse:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{className:me("flex items-center gap-3",o&&"flex-row-reverse justify-end",r),children:[i.jsx("div",{className:"flex flex-col gap-2",children:t&&i.jsxs(sr,{children:[i.jsxs("p",{className:"break-all",children:[t,n&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),s&&i.jsx(Fg,{className:"mt-2",children:s})]})}),i.jsx(Ss,{children:i.jsx(Ol,{checked:l.value,onCheckedChange:l.onChange,required:n})}),i.jsx(rd,{})]})}),et=({name:e,label:t,helper:n,required:r,options:s,placeholder:o,...a})=>i.jsx(aa,{...a,name:e,render:({field:l})=>i.jsxs(so,{children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:i.jsxs(oK,{onValueChange:l.onChange,defaultValue:l.value,children:[i.jsx(Ss,{children:i.jsx(uN,{children:i.jsx(aK,{placeholder:o})})}),i.jsx(pN,{children:s.map(c=>i.jsx(gN,{value:c.value,children:c.label},c.value))})]})}),n&&i.jsx(Fg,{children:n}),i.jsx(rd,{})]})}),Ml=({name:e,label:t,helper:n,required:r,placeholder:s,...o})=>i.jsx(aa,{...o,name:e,render:({field:a})=>{let l=[];return Array.isArray(a.value)&&(l=a.value),i.jsxs(so,{children:[t&&i.jsxs(sr,{children:[t,r&&i.jsx("span",{className:"ml-2 text-rose-600",children:"*"})]}),i.jsx(Ss,{children:i.jsx(Rq,{tags:l.map(c=>({id:c,text:c,className:""})),handleDelete:c=>a.onChange(l.filter((u,d)=>d!==c)),handleAddition:c=>a.onChange([...l,c.id]),inputFieldPosition:"bottom",placeholder:s,autoFocus:!1,allowDragDrop:!1,separators:[cs.ENTER,cs.TAB,cs.COMMA],classNames:{tags:"tagsClass",tagInput:"tagInputClass",tagInputField:cR,selected:"my-2 flex flex-wrap gap-2",tag:"flex items-center gap-2 px-2 py-1 bg-primary/30 rounded-md text-xs",remove:"[&>svg]:fill-rose-600 hover:[&>svg]:fill-rose-700",suggestions:"suggestionsClass",activeSuggestion:"activeSuggestionClass",editTagInput:"editTagInputClass",editTagInputField:"editTagInputFieldClass",clearAll:"clearAllClass"}})}),n&&i.jsx(Fg,{children:n}),i.jsx(rd,{})]})}});function xp(){return localStorage.getItem("facebookAppId")||""}function gK(){return localStorage.getItem("facebookConfigId")||""}function em(){return localStorage.getItem("facebookUserToken")||""}function hK({setUserID:e,setToken:t}){const{t:n}=Le(),[r,s]=m.useState(!1);m.useEffect(()=>{const l=document.createElement("script"),c="https://connect.facebook.net/en_US/sdk.js";l.src=c,l.async=!0,document.body.appendChild(l),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})}},[]);function o(){s(!0),window.FB.login(l=>{a(l)},{scope:"public_profile,pages_messaging,pages_show_list,pages_manage_metadata,pages_read_engagement"})}async function a(l){if(l.authResponse){const{userID:c,accessToken:u}=l.authResponse;try{window.FB.api("/me",{fields:"name, email"},function(d){console.log("Good to see you, "+d.name+". I see your email address is "+d.email)}),e(c),t(u)}catch(d){console.log(d)}finally{s(!1)}}else s(!1),console.log("User cancelled login or did not fully authorize.")}return i.jsx(J,{variant:"default",onClick:o,className:"bg-blue-600 text-white hover:bg-blue-700",type:"button",disabled:r,children:n(r?"instance.button.connecting":"instance.button.facebook")})}function mK({setUserID:e,setToken:t}){const{t:n}=Le(),[r,s]=m.useState(!1);m.useEffect(()=>{const l=document.createElement("script"),c="https://connect.facebook.net/en_US/sdk.js";l.src=c,l.async=!0,document.body.appendChild(l),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})}},[]);function o(){s(!0),window.FB.login(l=>{a(l)},{scope:"public_profile,instagram_basic,instagram_manage_messages,pages_messaging,pages_show_list,pages_manage_metadata,pages_read_engagement"})}async function a(l){if(l.authResponse){const{userID:c,accessToken:u}=l.authResponse;try{window.FB.api("/me",{fields:"name, email"},function(d){console.log("Good to see you, "+d.name+". I see your email address is "+d.email)}),e(c),t(u)}catch(d){console.log(d)}finally{s(!1)}}else s(!1),console.log("User cancelled login or did not fully authorize.")}return i.jsx(J,{variant:"default",onClick:o,className:"bg-[#983b71] text-white hover:bg-[#5a2d6f]",type:"button",disabled:r,children:n(r?"instance.button.connecting":"instance.button.instagram")})}function vK({setNumber:e,setBusiness:t,setToken:n}){const{t:r}=Le(),[s,o]=m.useState(!1);m.useEffect(()=>{const u=document.createElement("script"),d="https://connect.facebook.net/en_US/sdk.js";return u.src=d,u.async=!0,document.body.appendChild(u),window.fbAsyncInit=()=>{window.FB.init({appId:xp(),cookie:!0,xfbml:!0,version:"v20.0"})},((f,p,h)=>{let v=f.getElementById(h);const g=f.getElementsByTagName(p)[0];v||(v=f.createElement(p),v.id=h,v.src="https://connect.facebook.net/en_US/sdk.js",g.parentNode&&g.parentNode.insertBefore(v,g))})(document,"script","facebook-jssdk"),window.addEventListener("message",a),()=>{window.removeEventListener("message",a)}},[]);const a=u=>{if(!(u.origin!=="https://www.facebook.com"&&u.origin!=="https://web.facebook.com"))try{const d=JSON.parse(u.data);if(d.type==="WA_EMBEDDED_SIGNUP"){if(d.event==="FINISH"){const{phone_number_id:f,waba_id:p}=d.data;l(f,p)}}else o(!1)}catch{o(!1)}};async function l(u,d){if(!(!u||!d))try{await _t.post(`https://graph.facebook.com/v20.0/${u}/register`,{messaging_product:"whatsapp",pin:"123456"},{headers:{Authorization:`Bearer ${em()}`}}),await _t.post(`https://graph.facebook.com/v20.0/${d}/subscribed_apps`,{},{headers:{Authorization:`Bearer ${em()}`}}),e(u),t(d),n(em())}catch(f){console.log(f)}finally{o(!1)}}function c(){o(!0),window.fbq&&window.fbq("trackCustom","WhatsAppOnboardingStart",{appId:xp(),feature:"whatsapp_embedded_signup"}),window.FB.login(u=>{u.authResponse||console.log("User cancelled login or did not fully authorize.")},{config_id:gK(),response_type:"code",override_default_response_type:!0,extras:{feature:"whatsapp_embedded_signup",sessionInfoVersion:2}})}return i.jsx(J,{variant:"default",onClick:c,className:"bg-green-600 text-white hover:bg-green-700",type:"button",disabled:s,children:r(s?"instance.button.connecting":"instance.button.whatsapp")})}const tm=k.string().optional().transform(e=>e===""?void 0:e),yK=k.object({name:k.string(),token:tm,number:tm,businessId:tm,integration:k.enum(["WHATSAPP-BUSINESS","WHATSAPP-BAILEYS","META-FACEBOOK","META-INSTAGRAM","EVOLUTION"])});function bK({resetTable:e}){const{t}=Le(),[n,r]=m.useState(!1),[s,o]=m.useState([{value:"WHATSAPP-BAILEYS",label:t("instance.form.integration.baileys")},{value:"WHATSAPP-BUSINESS",label:t("instance.form.integration.whatsapp")},{value:"EVOLUTION",label:t("instance.form.integration.evolution")}]),a=kt({resolver:Et(yK),defaultValues:{name:"",integration:"WHATSAPP-BAILEYS",token:r0().replace("-","").toUpperCase(),number:"",businessId:""}}),l=localStorage.getItem("facebookUserToken")&&localStorage.getItem("facebookConfigId")&&localStorage.getItem("facebookAppId");m.useEffect(()=>{l&&o([...s,{value:"META-FACEBOOK",label:t("instance.form.integration.facebook")},{value:"META-INSTAGRAM",label:t("instance.form.integration.instagram")}])},[l]);const c=a.watch("integration"),u=async f=>{var p,h,v;try{const g={instanceName:f.name,integration:f.integration,token:f.token===""?null:f.token,number:f.number===""?null:f.number,businessId:f.businessId===""?null:f.businessId};await k4(g),X.success(t("toast.instance.created")),r(!1),d(),e()}catch(g){console.error("Error:",g),X.error(`Error : ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}},d=()=>{a.reset({name:"",integration:"WHATSAPP-BAILEYS",token:r0().replace("-","").toLocaleUpperCase(),number:"",businessId:""})};return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"default",size:"sm",children:[t("instance.button.create")," ",i.jsx(Qa,{size:"18"})]})}),i.jsxs(pt,{className:"sm:max-w-[650px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:t("instance.modal.title")})}),i.jsx(dr,{...a,children:i.jsxs("form",{onSubmit:a.handleSubmit(u),className:"grid gap-4 py-4",children:[i.jsx(D,{required:!0,name:"name",label:t("instance.form.name"),children:i.jsx(A,{})}),i.jsx(et,{name:"integration",label:t("instance.form.integration.label"),options:s}),i.jsx(D,{required:!0,name:"token",label:t("instance.form.token"),children:i.jsx(A,{})}),i.jsx(D,{name:"number",label:t("instance.form.number"),children:i.jsx(A,{type:"tel"})}),c==="WHATSAPP-BUSINESS"&&i.jsx(D,{required:!0,name:"businessId",label:t("instance.form.businessId"),children:i.jsx(A,{})}),i.jsxs(Jt,{children:[l&&i.jsxs(i.Fragment,{children:[c==="WHATSAPP-BUSINESS"&&i.jsx(vK,{setNumber:f=>a.setValue("number",f),setBusiness:f=>a.setValue("businessId",f),setToken:f=>a.setValue("token",f)}),c==="META-FACEBOOK"&&i.jsx(hK,{setUserID:f=>a.setValue("number",f),setToken:f=>a.setValue("token",f)}),c==="META-INSTAGRAM"&&i.jsx(mK,{setUserID:f=>a.setValue("number",f),setToken:f=>a.setValue("token",f)})]}),i.jsx(J,{type:"submit",children:t("instance.button.save")})]})]})})]})]})}const nm=async e=>{try{const t=await E4();e(t)}catch(t){console.error("Error fetchData:",t)}};function xK(){const{t:e}=Le(),[t,n]=m.useState(null),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState("all");m.useEffect(()=>{(async()=>{await nm(g=>{s(g)})})()},[]);const u=async()=>{await nm(v=>{s(v)})},d=async v=>{var g,b,y;n(null),a([...o,v]);try{try{await jT(v)}catch(x){console.error("Error logout:",x)}await j4(v),await new Promise(x=>setTimeout(x,1e3)),u()}catch(x){console.error("Error instance delete:",x),X.error(`Error : ${(y=(b=(g=x==null?void 0:x.response)==null?void 0:g.data)==null?void 0:b.response)==null?void 0:y.message}`)}finally{a(o.filter(x=>x!==v))}},f=async v=>{if(v===""){await u();return}const g=r.filter(b=>b.name.toLowerCase().includes(v.toLowerCase()));s(g)},p=async v=>{if(c(v),v==="all"){await u();return}await nm(g=>{const b=g.filter(y=>y.connectionStatus===v);s(b)})},h=[{value:"all",label:e("status.all")},{value:"close",label:e("status.closed")},{value:"connecting",label:e("status.connecting")},{value:"open",label:e("status.open")}];return i.jsxs("div",{className:"my-4 px-4",children:[i.jsxs("div",{className:"flex w-full items-center justify-between",children:[i.jsx("h2",{className:"text-lg",children:e("dashboard.title")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(J,{variant:"outline",size:"icon",children:i.jsx(kT,{onClick:u,size:"20"})}),i.jsx(bK,{resetTable:u})]})]}),i.jsxs("div",{className:"my-4 flex items-center justify-between gap-3 px-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx(A,{placeholder:e("dashboard.search"),onChange:v=>f(v.target.value)})}),i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"secondary",children:[e("dashboard.status")," ",i.jsx(s4,{size:"15"})]})}),i.jsx(Qr,{children:h.map(v=>i.jsx(i_,{checked:l===v.value,onCheckedChange:g=>{g&&p(v.value)},children:v.label},v.value))})]})]}),i.jsx("main",{className:"grid gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r&&r.length>0&&Array.isArray(r)&&r.map(v=>{var g,b;return i.jsxs(wa,{children:[i.jsx(Sa,{children:i.jsxs(lu,{to:`/manager/instance/${v.id}/dashboard`,className:"flex w-full flex-row items-center justify-between gap-4",children:[i.jsx("h3",{className:"text-wrap font-semibold",children:v.name}),i.jsx(J,{variant:"ghost",size:"icon",children:i.jsx(Za,{className:"card-icon",size:"20"})})]})}),i.jsxs(Ca,{className:"flex-1 space-y-6",children:[i.jsx(iR,{token:v.token}),i.jsxs("div",{className:"flex w-full flex-wrap",children:[i.jsx("div",{className:"flex flex-1 gap-2",children:v.profileName&&i.jsxs(i.Fragment,{children:[i.jsx(vg,{children:i.jsx(yg,{src:v.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:v.profileName}),i.jsx("p",{className:"text-sm text-muted-foreground",children:v.ownerJid&&v.ownerJid.split("@")[0]})]})]})}),i.jsxs("div",{className:"flex items-center justify-end gap-4 text-sm",children:[i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(CT,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((g=v==null?void 0:v._count)==null?void 0:g.Contact)||0)})]}),i.jsxs("div",{className:"flex flex-col items-center justify-center gap-1",children:[i.jsx(sg,{className:"text-muted-foreground",size:"20"}),i.jsx("span",{children:new Intl.NumberFormat("pt-BR").format(((b=v==null?void 0:v._count)==null?void 0:b.Message)||0)})]})]})]})]}),i.jsxs(wg,{className:"justify-between",children:[i.jsx(aR,{status:v.connectionStatus}),i.jsx(J,{variant:"destructive",size:"sm",onClick:()=>n(v.name),disabled:o.includes(v.name),children:o.includes(v.name)?i.jsx("span",{children:e("button.deleting")}):i.jsx("span",{children:e("button.delete")})})]})]},v.id)})}),!!t&&i.jsx(yt,{onOpenChange:()=>n(null),open:!0,children:i.jsxs(pt,{children:[i.jsx(L_,{}),i.jsx(gt,{children:e("modal.delete.title")}),i.jsx("p",{children:e("modal.delete.message",{instanceName:t})}),i.jsx(Jt,{children:i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(J,{onClick:()=>n(null),size:"sm",variant:"outline",children:e("button.cancel")}),i.jsx(J,{onClick:()=>d(t),variant:"destructive",children:e("button.delete")})]})})]})})]})}const{createElement:fl,createContext:wK,createRef:Wee,forwardRef:SN,useCallback:Gn,useContext:CN,useEffect:Pa,useImperativeHandle:kN,useLayoutEffect:SK,useMemo:CK,useRef:Fn,useState:$c}=_p,d1=_p.useId,kK=SK,Lg=wK(null);Lg.displayName="PanelGroupContext";const Oa=kK,EK=typeof d1=="function"?d1:()=>null;let TK=0;function lx(e=null){const t=EK(),n=Fn(e||t||null);return n.current===null&&(n.current=""+TK++),e??n.current}function EN({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:s,forwardedRef:o,id:a,maxSize:l,minSize:c,onCollapse:u,onExpand:d,onResize:f,order:p,style:h,tagName:v="div",...g}){const b=CN(Lg);if(b===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:x,getPanelSize:w,getPanelStyle:S,groupId:E,isPanelCollapsed:C,reevaluatePanelConstraints:T,registerPanel:j,resizePanel:I,unregisterPanel:P}=b,V=lx(a),O=Fn({callbacks:{onCollapse:u,onExpand:d,onResize:f},constraints:{collapsedSize:n,collapsible:r,defaultSize:s,maxSize:l,minSize:c},id:V,idIsFromProps:a!==void 0,order:p});Fn({didLogMissingDefaultSizeWarning:!1}),Oa(()=>{const{callbacks:H,constraints:K}=O.current,Y={...K};O.current.id=V,O.current.idIsFromProps=a!==void 0,O.current.order=p,H.onCollapse=u,H.onExpand=d,H.onResize=f,K.collapsedSize=n,K.collapsible=r,K.defaultSize=s,K.maxSize=l,K.minSize=c,(Y.collapsedSize!==K.collapsedSize||Y.collapsible!==K.collapsible||Y.maxSize!==K.maxSize||Y.minSize!==K.minSize)&&T(O.current,Y)}),Oa(()=>{const H=O.current;return j(H),()=>{P(H)}},[p,V,j,P]),kN(o,()=>({collapse:()=>{y(O.current)},expand:H=>{x(O.current,H)},getId(){return V},getSize(){return w(O.current)},isCollapsed(){return C(O.current)},isExpanded(){return!C(O.current)},resize:H=>{I(O.current,H)}}),[y,x,w,C,V,I]);const Z=S(O.current,s);return fl(v,{...g,children:e,className:t,id:a,style:{...Z,...h},"data-panel":"","data-panel-collapsible":r||void 0,"data-panel-group-id":E,"data-panel-id":V,"data-panel-size":parseFloat(""+Z.flexGrow).toFixed(1)})}const TN=SN((e,t)=>fl(EN,{...e,forwardedRef:t}));EN.displayName="Panel";TN.displayName="forwardRef(Panel)";let Yv=null,Ea=null;function jK(e,t){if(t){const n=(t&NN)!==0,r=(t&PN)!==0,s=(t&ON)!==0,o=(t&MN)!==0;if(n)return s?"se-resize":o?"ne-resize":"e-resize";if(r)return s?"sw-resize":o?"nw-resize":"w-resize";if(s)return"s-resize";if(o)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function _K(){Ea!==null&&(document.head.removeChild(Ea),Yv=null,Ea=null)}function rm(e,t){const n=jK(e,t);Yv!==n&&(Yv=n,Ea===null&&(Ea=document.createElement("style"),document.head.appendChild(Ea)),Ea.innerHTML=`*{cursor: ${n}!important;}`)}function jN(e){return e.type==="keydown"}function _N(e){return e.type.startsWith("pointer")}function RN(e){return e.type.startsWith("mouse")}function $g(e){if(_N(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(RN(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function RK(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function IK(e,t,n){return e.xt.x&&e.yt.y}function NK(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:g1(e),b:g1(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Je(r,"Stacking order can only be calculated for elements with a common ancestor");const s={a:p1(f1(n.a)),b:p1(f1(n.b))};if(s.a===s.b){const o=r.childNodes,a={a:n.a.at(-1),b:n.b.at(-1)};let l=o.length;for(;l--;){const c=o[l];if(c===a.a)return 1;if(c===a.b)return-1}}return Math.sign(s.a-s.b)}const PK=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function OK(e){var t;const n=getComputedStyle((t=IN(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function MK(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||OK(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||PK.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function f1(e){let t=e.length;for(;t--;){const n=e[t];if(Je(n,"Missing node"),MK(n))return n}return null}function p1(e){return e&&Number(getComputedStyle(e).zIndex)||0}function g1(e){const t=[];for(;e;)t.push(e),e=IN(e);return t}function IN(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const NN=1,PN=2,ON=4,MN=8,DK=RK()==="coarse";let Wr=[],Ou=!1,Eo=new Map,Bg=new Map;const Mu=new Set;function AK(e,t,n,r,s){var o;const{ownerDocument:a}=t,l={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:s},c=(o=Eo.get(a))!==null&&o!==void 0?o:0;return Eo.set(a,c+1),Mu.add(l),wp(),function(){var d;Bg.delete(e),Mu.delete(l);const f=(d=Eo.get(a))!==null&&d!==void 0?d:1;if(Eo.set(a,f-1),wp(),f===1&&Eo.delete(a),Wr.includes(l)){const p=Wr.indexOf(l);p>=0&&Wr.splice(p,1),ux()}}}function h1(e){const{target:t}=e,{x:n,y:r}=$g(e);Ou=!0,cx({target:t,x:n,y:r}),wp(),Wr.length>0&&(Sp("down",e),e.preventDefault(),e.stopPropagation())}function dc(e){const{x:t,y:n}=$g(e);if(e.buttons===0&&(Ou=!1,Sp("up",e)),!Ou){const{target:r}=e;cx({target:r,x:t,y:n})}Sp("move",e),ux(),Wr.length>0&&e.preventDefault()}function bi(e){const{target:t}=e,{x:n,y:r}=$g(e);Bg.clear(),Ou=!1,Wr.length>0&&e.preventDefault(),Sp("up",e),cx({target:t,x:n,y:r}),ux(),wp()}function cx({target:e,x:t,y:n}){Wr.splice(0);let r=null;e instanceof HTMLElement&&(r=e),Mu.forEach(s=>{const{element:o,hitAreaMargins:a}=s,l=o.getBoundingClientRect(),{bottom:c,left:u,right:d,top:f}=l,p=DK?a.coarse:a.fine;if(t>=u-p&&t<=d+p&&n>=f-p&&n<=c+p){if(r!==null&&o!==r&&!o.contains(r)&&!r.contains(o)&&NK(r,o)>0){let v=r,g=!1;for(;v&&!v.contains(o);){if(IK(v.getBoundingClientRect(),l)){g=!0;break}v=v.parentElement}if(g)return}Wr.push(s)}})}function sm(e,t){Bg.set(e,t)}function ux(){let e=!1,t=!1;Wr.forEach(r=>{const{direction:s}=r;s==="horizontal"?e=!0:t=!0});let n=0;Bg.forEach(r=>{n|=r}),e&&t?rm("intersection",n):e?rm("horizontal",n):t?rm("vertical",n):_K()}function wp(){Eo.forEach((e,t)=>{const{body:n}=t;n.removeEventListener("contextmenu",bi),n.removeEventListener("pointerdown",h1),n.removeEventListener("pointerleave",dc),n.removeEventListener("pointermove",dc)}),window.removeEventListener("pointerup",bi),window.removeEventListener("pointercancel",bi),Mu.size>0&&(Ou?(Wr.length>0&&Eo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("contextmenu",bi),n.addEventListener("pointerleave",dc),n.addEventListener("pointermove",dc))}),window.addEventListener("pointerup",bi),window.addEventListener("pointercancel",bi)):Eo.forEach((e,t)=>{const{body:n}=t;e>0&&(n.addEventListener("pointerdown",h1,{capture:!0}),n.addEventListener("pointermove",dc))}))}function Sp(e,t){Mu.forEach(n=>{const{setResizeHandlerState:r}=n,s=Wr.includes(n);r(e,s,t)})}function Je(e,t){if(!e)throw console.error(t),Error(t)}const dx=10;function qa(e,t,n=dx){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Os(e,t,n=dx){return qa(e,t,n)===0}function Jn(e,t,n){return qa(e,t,n)===0}function FK(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r0&&(e=e<0?0-y:y)}}}{const f=e<0?l:c,p=n[f];Je(p,`No panel constraints found for index ${f}`);const{collapsedSize:h=0,collapsible:v,minSize:g=0}=p;if(v){const b=t[f];if(Je(b!=null,`Previous layout not found for panel index ${f}`),Jn(b,g)){const y=b-h;qa(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}}{const f=e<0?1:-1;let p=e<0?c:l,h=0;for(;;){const g=t[p];Je(g!=null,`Previous layout not found for panel index ${p}`);const y=Bi({panelConstraints:n,panelIndex:p,size:100})-g;if(h+=y,p+=f,p<0||p>=n.length)break}const v=Math.min(Math.abs(e),Math.abs(h));e=e<0?0-v:v}{let p=e<0?l:c;for(;p>=0&&p=0))break;e<0?p--:p++}}if(FK(s,a))return s;{const f=e<0?c:l,p=t[f];Je(p!=null,`Previous layout not found for panel index ${f}`);const h=p+u,v=Bi({panelConstraints:n,panelIndex:f,size:h});if(a[f]=v,!Jn(v,h)){let g=h-v,y=e<0?c:l;for(;y>=0&&y0?y--:y++}}}const d=a.reduce((f,p)=>p+f,0);return Jn(d,100)?a:s}function LK({layout:e,panelsArray:t,pivotIndices:n}){let r=0,s=100,o=0,a=0;const l=n[0];Je(l!=null,"No pivot index found"),t.forEach((f,p)=>{const{constraints:h}=f,{maxSize:v=100,minSize:g=0}=h;p===l?(r=g,s=v):(o+=g,a+=v)});const c=Math.min(s,100-o),u=Math.max(r,100-a),d=e[l];return{valueMax:c,valueMin:u,valueNow:d}}function Du(e,t=document){return Array.from(t.querySelectorAll(`[data-panel-resize-handle-id][data-panel-group-id="${e}"]`))}function DN(e,t,n=document){const s=Du(e,n).findIndex(o=>o.getAttribute("data-panel-resize-handle-id")===t);return s??null}function AN(e,t,n){const r=DN(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function FN(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function zg(e,t=document){const n=t.querySelector(`[data-panel-resize-handle-id="${e}"]`);return n||null}function $K(e,t,n,r=document){var s,o,a,l;const c=zg(t,r),u=Du(e,r),d=c?u.indexOf(c):-1,f=(s=(o=n[d])===null||o===void 0?void 0:o.id)!==null&&s!==void 0?s:null,p=(a=(l=n[d+1])===null||l===void 0?void 0:l.id)!==null&&a!==void 0?a:null;return[f,p]}function BK({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:s,panelGroupElement:o,setLayout:a}){Fn({didWarnAboutMissingResizeHandle:!1}),Oa(()=>{if(!o)return;const l=Du(n,o);for(let c=0;c{l.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,s,o]),Pa(()=>{if(!o)return;const l=t.current;Je(l,"Eager values not found");const{panelDataArray:c}=l,u=FN(n,o);Je(u!=null,`No group found for id "${n}"`);const d=Du(n,o);Je(d,`No resize handles found for group id "${n}"`);const f=d.map(p=>{const h=p.getAttribute("data-panel-resize-handle-id");Je(h,"Resize handle element has no handle id attribute");const[v,g]=$K(n,h,c,o);if(v==null||g==null)return()=>{};const b=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const x=c.findIndex(w=>w.id===v);if(x>=0){const w=c[x];Je(w,`No panel data found for index ${x}`);const S=r[x],{collapsedSize:E=0,collapsible:C,minSize:T=0}=w.constraints;if(S!=null&&C){const j=Cc({delta:Jn(S,E)?T-E:E-S,initialLayout:r,panelConstraints:c.map(I=>I.constraints),pivotIndices:AN(n,h,o),prevLayout:r,trigger:"keyboard"});r!==j&&a(j)}}break}}};return p.addEventListener("keydown",b),()=>{p.removeEventListener("keydown",b)}});return()=>{f.forEach(p=>p())}},[o,e,t,n,r,s,a])}function m1(e,t){if(e.length!==t.length)return!1;for(let n=0;no.constraints);let r=0,s=100;for(let o=0;o{const o=e[s];Je(o,`Panel data not found for index ${s}`);const{callbacks:a,constraints:l,id:c}=o,{collapsedSize:u=0,collapsible:d}=l,f=n[c];if(f==null||r!==f){n[c]=r;const{onCollapse:p,onExpand:h,onResize:v}=a;v&&v(r,f),d&&(p||h)&&(h&&(f==null||Os(f,u))&&!Os(r,u)&&h(),p&&(f==null||!Os(f,u))&&Os(r,u)&&p())}})}function zd(e,t){if(e.length!==t.length)return!1;for(let n=0;n{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...s)},t)}}function v1(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function $N(e){return`react-resizable-panels:${e}`}function BN(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:s,order:o}=t;return s?r:o?`${o}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function zN(e,t){try{const n=$N(e),r=t.getItem(n);if(r){const s=JSON.parse(r);if(typeof s=="object"&&s!=null)return s}}catch{}return null}function GK(e,t,n){var r,s;const o=(r=zN(e,n))!==null&&r!==void 0?r:{},a=BN(t);return(s=o[a])!==null&&s!==void 0?s:null}function qK(e,t,n,r,s){var o;const a=$N(e),l=BN(t),c=(o=zN(e,s))!==null&&o!==void 0?o:{};c[l]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{s.setItem(a,JSON.stringify(c))}catch(u){console.error(u)}}function y1({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((o,a)=>o+a,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(o=>`${o}%`).join(", ")}`);if(!Jn(r,100))for(let o=0;o(v1(kc),kc.getItem(e)),setItem:(e,t)=>{v1(kc),kc.setItem(e,t)}},b1={};function UN({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:s,id:o=null,onLayout:a=null,keyboardResizeBy:l=null,storage:c=kc,style:u,tagName:d="div",...f}){const p=lx(o),h=Fn(null),[v,g]=$c(null),[b,y]=$c([]),x=Fn({}),w=Fn(new Map),S=Fn(0),E=Fn({autoSaveId:e,direction:r,dragState:v,id:p,keyboardResizeBy:l,onLayout:a,storage:c}),C=Fn({layout:b,panelDataArray:[],panelDataArrayChanged:!1});Fn({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),kN(s,()=>({getId:()=>E.current.id,getLayout:()=>{const{layout:U}=C.current;return U},setLayout:U=>{const{onLayout:re}=E.current,{layout:te,panelDataArray:ae}=C.current,se=y1({layout:U,panelConstraints:ae.map(q=>q.constraints)});m1(te,se)||(y(se),C.current.layout=se,re&&re(se),xi(ae,se,x.current))}}),[]),Oa(()=>{E.current.autoSaveId=e,E.current.direction=r,E.current.dragState=v,E.current.id=p,E.current.onLayout=a,E.current.storage=c}),BK({committedValuesRef:E,eagerValuesRef:C,groupId:p,layout:b,panelDataArray:C.current.panelDataArray,setLayout:y,panelGroupElement:h.current}),Pa(()=>{const{panelDataArray:U}=C.current;if(e){if(b.length===0||b.length!==U.length)return;let re=b1[e];re==null&&(re=WK(qK,KK),b1[e]=re);const te=[...U],ae=new Map(w.current);re(e,te,ae,b,c)}},[e,b,c]),Pa(()=>{});const T=Gn(U=>{const{onLayout:re}=E.current,{layout:te,panelDataArray:ae}=C.current;if(U.constraints.collapsible){const se=ae.map(Me=>Me.constraints),{collapsedSize:q=0,panelSize:we,pivotIndices:je}=ca(ae,U,te);if(Je(we!=null,`Panel size not found for panel "${U.id}"`),!Os(we,q)){w.current.set(U.id,we);const _e=ki(ae,U)===ae.length-1?we-q:q-we,pe=Cc({delta:_e,initialLayout:te,panelConstraints:se,pivotIndices:je,prevLayout:te,trigger:"imperative-api"});zd(te,pe)||(y(pe),C.current.layout=pe,re&&re(pe),xi(ae,pe,x.current))}}},[]),j=Gn((U,re)=>{const{onLayout:te}=E.current,{layout:ae,panelDataArray:se}=C.current;if(U.constraints.collapsible){const q=se.map(Qe=>Qe.constraints),{collapsedSize:we=0,panelSize:je=0,minSize:Me=0,pivotIndices:_e}=ca(se,U,ae),pe=re??Me;if(Os(je,we)){const Qe=w.current.get(U.id),It=Qe!=null&&Qe>=pe?Qe:pe,Bt=ki(se,U)===se.length-1?je-It:It-je,Zt=Cc({delta:Bt,initialLayout:ae,panelConstraints:q,pivotIndices:_e,prevLayout:ae,trigger:"imperative-api"});zd(ae,Zt)||(y(Zt),C.current.layout=Zt,te&&te(Zt),xi(se,Zt,x.current))}}},[]),I=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{panelSize:ae}=ca(te,U,re);return Je(ae!=null,`Panel size not found for panel "${U.id}"`),ae},[]),P=Gn((U,re)=>{const{panelDataArray:te}=C.current,ae=ki(te,U);return HK({defaultSize:re,dragState:v,layout:b,panelData:te,panelIndex:ae})},[v,b]),V=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{collapsedSize:ae=0,collapsible:se,panelSize:q}=ca(te,U,re);return Je(q!=null,`Panel size not found for panel "${U.id}"`),se===!0&&Os(q,ae)},[]),O=Gn(U=>{const{layout:re,panelDataArray:te}=C.current,{collapsedSize:ae=0,collapsible:se,panelSize:q}=ca(te,U,re);return Je(q!=null,`Panel size not found for panel "${U.id}"`),!se||qa(q,ae)>0},[]),Z=Gn(U=>{const{panelDataArray:re}=C.current;re.push(U),re.sort((te,ae)=>{const se=te.order,q=ae.order;return se==null&&q==null?0:se==null?-1:q==null?1:se-q}),C.current.panelDataArrayChanged=!0},[]);Oa(()=>{if(C.current.panelDataArrayChanged){C.current.panelDataArrayChanged=!1;const{autoSaveId:U,onLayout:re,storage:te}=E.current,{layout:ae,panelDataArray:se}=C.current;let q=null;if(U){const je=GK(U,se,te);je&&(w.current=new Map(Object.entries(je.expandToSizes)),q=je.layout)}q==null&&(q=VK({panelDataArray:se}));const we=y1({layout:q,panelConstraints:se.map(je=>je.constraints)});m1(ae,we)||(y(we),C.current.layout=we,re&&re(we),xi(se,we,x.current))}}),Oa(()=>{const U=C.current;return()=>{U.layout=[]}},[]);const H=Gn(U=>function(te){te.preventDefault();const ae=h.current;if(!ae)return()=>null;const{direction:se,dragState:q,id:we,keyboardResizeBy:je,onLayout:Me}=E.current,{layout:_e,panelDataArray:pe}=C.current,{initialLayout:Qe}=q??{},It=AN(we,U,ae);let Vt=UK(te,U,se,q,je,ae);const Bt=se==="horizontal";document.dir==="rtl"&&Bt&&(Vt=-Vt);const Zt=pe.map(z=>z.constraints),_=Cc({delta:Vt,initialLayout:Qe??_e,panelConstraints:Zt,pivotIndices:It,prevLayout:_e,trigger:jN(te)?"keyboard":"mouse-or-touch"}),M=!zd(_e,_);(_N(te)||RN(te))&&S.current!=Vt&&(S.current=Vt,M?sm(U,0):Bt?sm(U,Vt<0?NN:PN):sm(U,Vt<0?ON:MN)),M&&(y(_),C.current.layout=_,Me&&Me(_),xi(pe,_,x.current))},[]),K=Gn((U,re)=>{const{onLayout:te}=E.current,{layout:ae,panelDataArray:se}=C.current,q=se.map(Qe=>Qe.constraints),{panelSize:we,pivotIndices:je}=ca(se,U,ae);Je(we!=null,`Panel size not found for panel "${U.id}"`);const _e=ki(se,U)===se.length-1?we-re:re-we,pe=Cc({delta:_e,initialLayout:ae,panelConstraints:q,pivotIndices:je,prevLayout:ae,trigger:"imperative-api"});zd(ae,pe)||(y(pe),C.current.layout=pe,te&&te(pe),xi(se,pe,x.current))},[]),Y=Gn((U,re)=>{const{layout:te,panelDataArray:ae}=C.current,{collapsedSize:se=0,collapsible:q}=re,{collapsedSize:we=0,collapsible:je,maxSize:Me=100,minSize:_e=0}=U.constraints,{panelSize:pe}=ca(ae,U,te);pe!=null&&(q&&je&&Os(pe,se)?Os(se,we)||K(U,we):pe<_e?K(U,_e):pe>Me&&K(U,Me))},[K]),G=Gn((U,re)=>{const{direction:te}=E.current,{layout:ae}=C.current;if(!h.current)return;const se=zg(U,h.current);Je(se,`Drag handle element not found for id "${U}"`);const q=LN(te,re);g({dragHandleId:U,dragHandleRect:se.getBoundingClientRect(),initialCursorPosition:q,initialLayout:ae})},[]),L=Gn(()=>{g(null)},[]),F=Gn(U=>{const{panelDataArray:re}=C.current,te=ki(re,U);te>=0&&(re.splice(te,1),delete x.current[U.id],C.current.panelDataArrayChanged=!0)},[]),Q=CK(()=>({collapsePanel:T,direction:r,dragState:v,expandPanel:j,getPanelSize:I,getPanelStyle:P,groupId:p,isPanelCollapsed:V,isPanelExpanded:O,reevaluatePanelConstraints:Y,registerPanel:Z,registerResizeHandle:H,resizePanel:K,startDragging:G,stopDragging:L,unregisterPanel:F,panelGroupElement:h.current}),[T,v,r,j,I,P,p,V,O,Y,Z,H,K,G,L,F]),ue={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return fl(Lg.Provider,{value:Q},fl(d,{...f,children:t,className:n,id:o,ref:h,style:{...ue,...u},"data-panel-group":"","data-panel-group-direction":r,"data-panel-group-id":p}))}const VN=SN((e,t)=>fl(UN,{...e,forwardedRef:t}));UN.displayName="PanelGroup";VN.displayName="forwardRef(PanelGroup)";function ki(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function ca(e,t,n){const r=ki(e,t),o=r===e.length-1?[r-1,r]:[r,r+1],a=n[r];return{...t.constraints,panelSize:a,pivotIndices:o}}function JK({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){Pa(()=>{if(e||n==null||r==null)return;const s=zg(t,r);if(s==null)return;const o=a=>{if(!a.defaultPrevented)switch(a.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{a.preventDefault(),n(a);break}case"F6":{a.preventDefault();const l=s.getAttribute("data-panel-group-id");Je(l,`No group element found for id "${l}"`);const c=Du(l,r),u=DN(l,t,r);Je(u!==null,`No resize element found for id "${t}"`);const d=a.shiftKey?u>0?u-1:c.length-1:u+1{s.removeEventListener("keydown",o)}},[r,e,t,n])}function HN({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:s,onBlur:o,onDragging:a,onFocus:l,style:c={},tabIndex:u=0,tagName:d="div",...f}){var p,h;const v=Fn(null),g=Fn({onDragging:a});Pa(()=>{g.current.onDragging=a});const b=CN(Lg);if(b===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:y,groupId:x,registerResizeHandle:w,startDragging:S,stopDragging:E,panelGroupElement:C}=b,T=lx(s),[j,I]=$c("inactive"),[P,V]=$c(!1),[O,Z]=$c(null),H=Fn({state:j});Oa(()=>{H.current.state=j}),Pa(()=>{if(n)Z(null);else{const L=w(T);Z(()=>L)}},[n,T,w]);const K=(p=r==null?void 0:r.coarse)!==null&&p!==void 0?p:15,Y=(h=r==null?void 0:r.fine)!==null&&h!==void 0?h:5;return Pa(()=>{if(n||O==null)return;const L=v.current;return Je(L,"Element ref not attached"),AK(T,L,y,{coarse:K,fine:Y},(Q,ue,U)=>{if(ue)switch(Q){case"down":{I("drag"),S(T,U);const{onDragging:re}=g.current;re&&re(!0);break}case"move":{const{state:re}=H.current;re!=="drag"&&I("hover"),O(U);break}case"up":{I("hover"),E();const{onDragging:re}=g.current;re&&re(!1);break}}else I("inactive")})},[K,y,n,Y,w,T,O,S,E]),JK({disabled:n,handleId:T,resizeHandler:O,panelGroupElement:C}),fl(d,{...f,children:e,className:t,id:s,onBlur:()=>{V(!1),o==null||o()},onFocus:()=>{V(!0),l==null||l()},ref:v,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...c},tabIndex:u,"data-panel-group-direction":y,"data-panel-group-id":x,"data-resize-handle":"","data-resize-handle-active":j==="drag"?"pointer":P?"keyboard":void 0,"data-resize-handle-state":j,"data-panel-resize-handle-enabled":!n,"data-panel-resize-handle-id":T})}HN.displayName="PanelResizeHandle";const Dl=({className:e,...t})=>i.jsx(VN,{className:me("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),_r=TN,Al=({withHandle:e,className:t,...n})=>i.jsx(HN,{className:me("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 after:bg-border focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&i.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:i.jsx(f4,{className:"h-2.5 w-2.5"})})});var fx="Tabs",[ZK,Gee]=Ir(fx,[fg]),WN=fg(),[QK,px]=ZK(fx),GN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:s,defaultValue:o,orientation:a="horizontal",dir:l,activationMode:c="automatic",...u}=e,d=Zu(l),[f,p]=Bo({prop:r,onChange:s,defaultProp:o});return i.jsx(QK,{scope:n,baseId:Vr(),value:f,onValueChange:p,orientation:a,dir:d,activationMode:c,children:i.jsx(Ie.div,{dir:d,"data-orientation":a,...u,ref:t})})});GN.displayName=fx;var qN="TabsList",KN=m.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...s}=e,o=px(qN,n),a=WN(n);return i.jsx(ij,{asChild:!0,...a,orientation:o.orientation,dir:o.dir,loop:r,children:i.jsx(Ie.div,{role:"tablist","aria-orientation":o.orientation,...s,ref:t})})});KN.displayName=qN;var JN="TabsTrigger",ZN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:s=!1,...o}=e,a=px(JN,n),l=WN(n),c=XN(a.baseId,r),u=eP(a.baseId,r),d=r===a.value;return i.jsx(lj,{asChild:!0,...l,focusable:!s,active:d,children:i.jsx(Ie.button,{type:"button",role:"tab","aria-selected":d,"aria-controls":u,"data-state":d?"active":"inactive","data-disabled":s?"":void 0,disabled:s,id:c,...o,ref:t,onMouseDown:xe(e.onMouseDown,f=>{!s&&f.button===0&&f.ctrlKey===!1?a.onValueChange(r):f.preventDefault()}),onKeyDown:xe(e.onKeyDown,f=>{[" ","Enter"].includes(f.key)&&a.onValueChange(r)}),onFocus:xe(e.onFocus,()=>{const f=a.activationMode!=="manual";!d&&!s&&f&&a.onValueChange(r)})})})});ZN.displayName=JN;var QN="TabsContent",YN=m.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:s,children:o,...a}=e,l=px(QN,n),c=XN(l.baseId,r),u=eP(l.baseId,r),d=r===l.value,f=m.useRef(d);return m.useEffect(()=>{const p=requestAnimationFrame(()=>f.current=!1);return()=>cancelAnimationFrame(p)},[]),i.jsx(Hn,{present:s||d,children:({present:p})=>i.jsx(Ie.div,{"data-state":d?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:u,tabIndex:0,...a,ref:t,style:{...e.style,animationDuration:f.current?"0s":void 0},children:p&&o})})});YN.displayName=QN;function XN(e,t){return`${e}-trigger-${t}`}function eP(e,t){return`${e}-content-${t}`}var YK=GN,tP=KN,nP=ZN,rP=YN;const XK=YK,sP=m.forwardRef(({className:e,...t},n)=>i.jsx(tP,{ref:n,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",e),...t}));sP.displayName=tP.displayName;const Xv=m.forwardRef(({className:e,...t},n)=>i.jsx(nP,{ref:n,className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",e),...t}));Xv.displayName=nP.displayName;const ey=m.forwardRef(({className:e,...t},n)=>i.jsx(rP,{ref:n,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),...t}));ey.displayName=rP.displayName;const gx=new ur,eJ=async e=>(await gx.getInstance().post(`/chat/findChats/${e}`,{where:{}})).data,tJ=async(e,t)=>(await gx.getInstance().post(`/chat/findChats/${e}`,{where:{remoteJid:t}},{headers:{"Content-Type":"application/json"}})).data,nJ=async(e,t)=>(await gx.getInstance().post(`/chat/findMessages/${e}`,{where:{key:{remoteJid:t}}})).data;function Fl(e){const t=o=>typeof window<"u"?window.matchMedia(o).matches:!1,[n,r]=m.useState(t(e));function s(){r(t(e))}return m.useEffect(()=>{const o=window.matchMedia(e);return s(),o.addListener?o.addListener(s):o.addEventListener("change",s),()=>{o.removeListener?o.removeListener(s):o.removeEventListener("change",s)}},[e]),n}const zs=m.forwardRef(({className:e,...t},n)=>i.jsx("textarea",{className:me("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));zs.displayName="Textarea";function rJ({textareaRef:e,handleTextareaChange:t,textareaHeight:n,lastMessageRef:r,scrollToBottom:s}){const{instance:o}=st(),[a,l]=m.useState(null),[c,u]=m.useState([]),{remoteJid:d}=Ys();m.useEffect(()=>{const h=async(g,b)=>{try{const y=await tJ(g,b);l(y[0])}catch(y){console.error("Erro ao buscar dados:",y)}},v=async(g,b)=>{try{const y=await nJ(g,b);u(y.messages.records),s()}catch(y){console.error("Erro ao buscar dados:",y)}};o&&d&&(h(o.name,d),v(o.name,d))},[d,o,s]);const f=h=>i.jsx("div",{className:"bubble-right",children:i.jsx("div",{className:"flex items-start gap-4 self-end",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"prose text-muted-foreground",children:i.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})}),p=h=>i.jsx("div",{className:"bubble-left",children:i.jsx("div",{className:"flex items-start gap-4",children:i.jsx("div",{className:"grid gap-1",children:i.jsx("div",{className:"prose text-muted-foreground",children:i.jsx("div",{className:"bubble",children:JSON.stringify(h.message)})})})})});return i.jsxs("div",{className:"flex min-h-screen flex-col",children:[i.jsx("div",{className:"sticky top-0 p-2",children:i.jsxs(Pb,{children:[i.jsx(Ob,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-10 gap-1 rounded-xl px-3 text-lg data-[state=open]:bg-muted",children:[(a==null?void 0:a.pushName)||(a==null?void 0:a.remoteJid.split("@")[0]),i.jsx(rg,{className:"h-4 w-4 text-muted-foreground"})]})}),i.jsxs(Qr,{align:"start",className:"max-w-[300px]",children:[i.jsxs(at,{className:"items-start gap-2",children:[i.jsx(x4,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-4"}),i.jsx("div",{className:"text-muted-foreground/80",children:"With DALL-E, browsing and analysis. Limit 40 messages / 3 hours"})]})]}),i.jsx(ra,{}),i.jsxs(at,{className:"items-start gap-2",children:[i.jsx(ET,{className:"mr-2 h-4 w-4 shrink-0 translate-y-1"}),i.jsxs("div",{children:[i.jsx("div",{className:"font-medium",children:"GPT-3"}),i.jsx("div",{className:"text-muted-foreground/80",children:"Great for everyday tasks"})]})]})]})]})}),i.jsxs("div",{className:"message-container mx-auto flex max-w-4xl flex-1 flex-col gap-8 overflow-y-auto px-4",children:[c.map(h=>h.key.fromMe?f(h):p(h)),i.jsx("div",{ref:r})]}),i.jsx("div",{className:"sticky bottom-0 mx-auto flex w-full max-w-2xl flex-col gap-1.5 bg-background px-4 py-2",children:i.jsxs("div",{className:"input-message relative",children:[i.jsxs(J,{type:"button",size:"icon",className:"absolute bottom-3 left-3 h-8 w-8 rounded-full bg-transparent text-white hover:bg-transparent",children:[i.jsx(b4,{className:"h-4 w-4 text-white"}),i.jsx("span",{className:"sr-only",children:"Anexar"})]}),i.jsx(zs,{placeholder:"Enviar mensagem...",name:"message",id:"message",rows:1,ref:e,onChange:t,style:{height:n},className:"max-h-[240px] min-h-[48px] resize-none rounded-3xl border border-none p-4 pl-12 pr-16 shadow-sm"}),i.jsxs(J,{type:"submit",size:"icon",className:"absolute bottom-3 right-3 h-8 w-8 rounded-full",children:[i.jsx(t4,{className:"h-4 w-4"}),i.jsx("span",{className:"sr-only",children:"Enviar"})]})]})})]})}function x1(){const e=Fl("(min-width: 768px)"),t=m.useRef(null),[n]=m.useState("auto"),r=m.useRef(null),[s,o]=m.useState([]),{instance:a}=st(),{instanceId:l,remoteJid:c}=Ys(),u=En(),d=()=>{t.current&&t.current.scrollIntoView({})},f=()=>{if(r.current){r.current.style.height="auto";const h=r.current.scrollHeight,g=parseInt(getComputedStyle(r.current).lineHeight)*10;r.current.style.height=`${Math.min(h,g)}px`}};m.useEffect(()=>{a&&(async v=>{try{const g=await eJ(v);o(g)}catch(g){console.error("Erro ao buscar dados:",g)}})(a.name),d()},[a]);const p=h=>{u(`/manager/instance/${l}/chat/${h}`)};return i.jsxs(Dl,{direction:e?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:20,children:i.jsxs("div",{className:"hidden flex-col gap-2 bg-background text-foreground md:flex",children:[i.jsx("div",{className:"sticky top-0 p-2",children:i.jsxs(J,{variant:"ghost",className:"w-full justify-start gap-2 px-2 text-left",children:[i.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full",children:i.jsx(sg,{className:"h-4 w-4"})}),i.jsx("div",{className:"grow overflow-hidden text-ellipsis whitespace-nowrap text-sm",children:"Chat"}),i.jsx(Qa,{className:"h-4 w-4"})]})}),i.jsxs(XK,{defaultValue:"contacts",children:[i.jsxs(sP,{className:"tabs-chat",children:[i.jsx(Xv,{value:"contacts",children:"Contatos"}),i.jsx(Xv,{value:"groups",children:"Grupos"})]}),i.jsx(ey,{value:"contacts",children:i.jsx("div",{className:"flex-1 overflow-auto",children:i.jsxs("div",{className:"grid gap-1 p-2 text-foreground",children:[i.jsx("div",{className:"px-2 text-xs font-medium text-muted-foreground",children:"Contatos"}),s.map(h=>h.remoteJid.includes("@s.whatsapp.net")&&i.jsxs(lu,{to:"#",onClick:()=>p(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid.split("@")[0]})]})]},h.id))]})})}),i.jsx(ey,{value:"groups",children:i.jsx("div",{className:"flex-1 overflow-auto",children:i.jsx("div",{className:"grid gap-1 p-2 text-foreground",children:s.map(h=>h.remoteJid.includes("@g.us")&&i.jsxs(lu,{to:"#",onClick:()=>p(h.remoteJid),className:`chat-item flex items-center overflow-hidden truncate whitespace-nowrap rounded-md border-b border-gray-600/50 p-2 text-sm transition-colors hover:bg-muted/50 ${c===h.remoteJid?"active":""}`,children:[i.jsx("span",{className:"chat-avatar mr-2",children:i.jsx("img",{src:h.profilePicUrl||"https://via.placeholder.com/150",alt:"Avatar",className:"h-8 w-8 rounded-full"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"chat-title block font-medium",children:h.pushName}),i.jsx("span",{className:"chat-description block text-xs text-gray-500",children:h.remoteJid})]})]},h.id))})})})]})]})}),i.jsx(Al,{withHandle:!0,className:"border border-black"}),i.jsx(_r,{children:c&&i.jsx(rJ,{textareaRef:r,handleTextareaChange:f,textareaHeight:n,lastMessageRef:t,scrollToBottom:d})})]})}const oP=new ur,sJ=async(e,t)=>(await oP.getInstance().get(`/chatwoot/find/${e}`,{headers:{apikey:t}})).data,oJ=async(e,t,n)=>(await oP.getInstance().post(`/chatwoot/set/${e}`,n,{headers:{apikey:t}})).data,aJ=k.object({enabled:k.boolean(),accountId:k.string(),token:k.string(),url:k.string(),signMsg:k.boolean(),signDelimiter:k.string(),nameInbox:k.string(),organization:k.string(),logo:k.string(),reopenConversation:k.boolean(),conversationPending:k.boolean(),mergeBrazilContacts:k.boolean(),importContacts:k.boolean(),importMessages:k.boolean(),daysLimitImportMessages:k.coerce.number(),autoCreate:k.boolean(),ignoreJids:k.array(k.string()).default([])});function iJ(){const{t:e}=Le(),{instance:t}=st(),[,n]=m.useState(!1),r=kt({resolver:Et(aJ),defaultValues:{enabled:!0,accountId:"",token:"",url:"",signMsg:!0,signDelimiter:"\\n",nameInbox:"",organization:"",logo:"",reopenConversation:!0,conversationPending:!1,mergeBrazilContacts:!0,importContacts:!1,importMessages:!1,daysLimitImportMessages:7,autoCreate:!0,ignoreJids:[]}});m.useEffect(()=>{(async()=>{if(t){n(!0);try{const a=await sJ(t.name,t.token);r.setValue("ignoreJids",a.ignoreJids||[]),r.reset(a)}catch(a){console.error("Error:",a)}finally{n(!1)}}})()},[t,r]);const s=async o=>{var a,l,c;if(t){n(!0);try{const u={enabled:o.enabled,accountId:o.accountId,token:o.token,url:o.url,signMsg:o.signMsg,signDelimiter:o.signDelimiter,nameInbox:o.nameInbox,organization:o.organization,logo:o.logo,reopenConversation:o.reopenConversation,conversationPending:o.conversationPending,mergeBrazilContacts:o.mergeBrazilContacts,importContacts:o.importContacts,importMessages:o.importMessages,daysLimitImportMessages:o.daysLimitImportMessages,autoCreate:o.autoCreate,ignoreJids:o.ignoreJids};await oJ(t.name,t.token,u),X.success(e("chatwoot.toast.success"))}catch(u){console.error(e("chatwoot.toast.error"),u),X.error(`Error: ${(c=(l=(a=u==null?void 0:u.response)==null?void 0:a.data)==null?void 0:l.response)==null?void 0:c.message}`)}finally{n(!1)}}};return i.jsx(i.Fragment,{children:i.jsx(fr,{...r,children:i.jsxs("form",{onSubmit:r.handleSubmit(s),className:"w-full space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("chatwoot.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:px-4 [&>*]:py-2",children:[i.jsx(he,{name:"enabled",label:e("chatwoot.form.enabled.label"),className:"w-full justify-between",helper:e("chatwoot.form.enabled.description")}),i.jsx(D,{name:"url",label:e("chatwoot.form.url.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"accountId",label:e("chatwoot.form.accountId.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"token",label:e("chatwoot.form.token.label"),children:i.jsx(A,{type:"password"})}),i.jsx(he,{name:"signMsg",label:e("chatwoot.form.signMsg.label"),className:"w-full justify-between",helper:e("chatwoot.form.signMsg.description")}),i.jsx(D,{name:"signDelimiter",label:e("chatwoot.form.signDelimiter.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"nameInbox",label:e("chatwoot.form.nameInbox.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"organization",label:e("chatwoot.form.organization.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"logo",label:e("chatwoot.form.logo.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"conversationPending",label:e("chatwoot.form.conversationPending.label"),className:"w-full justify-between",helper:e("chatwoot.form.conversationPending.description")}),i.jsx(he,{name:"reopenConversation",label:e("chatwoot.form.reopenConversation.label"),className:"w-full justify-between",helper:e("chatwoot.form.reopenConversation.description")}),i.jsx(he,{name:"importContacts",label:e("chatwoot.form.importContacts.label"),className:"w-full justify-between",helper:e("chatwoot.form.importContacts.description")}),i.jsx(he,{name:"importMessages",label:e("chatwoot.form.importMessages.label"),className:"w-full justify-between",helper:e("chatwoot.form.importMessages.description")}),i.jsx(D,{name:"daysLimitImportMessages",label:e("chatwoot.form.daysLimitImportMessages.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("chatwoot.form.ignoreJids.label"),placeholder:e("chatwoot.form.ignoreJids.placeholder")}),i.jsx(he,{name:"autoCreate",label:e("chatwoot.form.autoCreate.label"),className:"w-full justify-between",helper:e("chatwoot.form.autoCreate.description")})]})]}),i.jsx("div",{className:"mx-4 flex justify-end",children:i.jsx(J,{type:"submit",children:e("chatwoot.button.save")})})]})})})}var Ug={},aP={exports:{}},lJ="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",cJ=lJ,uJ=cJ;function iP(){}function lP(){}lP.resetWarningCache=iP;var dJ=function(){function e(r,s,o,a,l,c){if(c!==uJ){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:lP,resetWarningCache:iP};return n.PropTypes=n,n};aP.exports=dJ();var cP=aP.exports,uP={L:1,M:0,Q:3,H:2},dP={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},fJ=dP;function fP(e){this.mode=fJ.MODE_8BIT_BYTE,this.data=e}fP.prototype={getLength:function(e){return this.data.length},write:function(e){for(var t=0;t>>7-e%8&1)==1},put:function(e,t){for(var n=0;n>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){var t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var hJ=pP,Lr={glog:function(e){if(e<1)throw new Error("glog("+e+")");return Lr.LOG_TABLE[e]},gexp:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return Lr.EXP_TABLE[e]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var pn=0;pn<8;pn++)Lr.EXP_TABLE[pn]=1<=0;)t^=dn.G15<=0;)t^=dn.G18<>>=1;return t},getPatternPosition:function(e){return dn.PATTERN_POSITION_TABLE[e-1]},getMask:function(e,t,n){switch(e){case vo.PATTERN000:return(t+n)%2==0;case vo.PATTERN001:return t%2==0;case vo.PATTERN010:return n%3==0;case vo.PATTERN011:return(t+n)%3==0;case vo.PATTERN100:return(Math.floor(t/2)+Math.floor(n/3))%2==0;case vo.PATTERN101:return t*n%2+t*n%3==0;case vo.PATTERN110:return(t*n%2+t*n%3)%2==0;case vo.PATTERN111:return(t*n%3+(t+n)%2)%2==0;default:throw new Error("bad maskPattern:"+e)}},getErrorCorrectPolynomial:function(e){for(var t=new w1([1],0),n=0;n5&&(n+=3+o-5)}for(var r=0;r=7&&this.setupTypeNumber(e),this.dataCache==null&&(this.dataCache=ps.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,t)};pr.setupPositionProbePattern=function(e,t){for(var n=-1;n<=7;n++)if(!(e+n<=-1||this.moduleCount<=e+n))for(var r=-1;r<=7;r++)t+r<=-1||this.moduleCount<=t+r||(0<=n&&n<=6&&(r==0||r==6)||0<=r&&r<=6&&(n==0||n==6)||2<=n&&n<=4&&2<=r&&r<=4?this.modules[e+n][t+r]=!0:this.modules[e+n][t+r]=!1)};pr.getBestMaskPattern=function(){for(var e=0,t=0,n=0;n<8;n++){this.makeImpl(!0,n);var r=ia.getLostPoint(this);(n==0||e>r)&&(e=r,t=n)}return t};pr.createMovieClip=function(e,t,n){var r=e.createEmptyMovieClip(t,n),s=1;this.make();for(var o=0;o>n&1)==1;this.modules[Math.floor(n/3)][n%3+this.moduleCount-8-3]=r}for(var n=0;n<18;n++){var r=!e&&(t>>n&1)==1;this.modules[n%3+this.moduleCount-8-3][Math.floor(n/3)]=r}};pr.setupTypeInfo=function(e,t){for(var n=this.errorCorrectLevel<<3|t,r=ia.getBCHTypeInfo(n),s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<6?this.modules[s][8]=o:s<8?this.modules[s+1][8]=o:this.modules[this.moduleCount-15+s][8]=o}for(var s=0;s<15;s++){var o=!e&&(r>>s&1)==1;s<8?this.modules[8][this.moduleCount-s-1]=o:s<9?this.modules[8][15-s-1+1]=o:this.modules[8][15-s-1]=o}this.modules[this.moduleCount-8][8]=!e};pr.mapData=function(e,t){for(var n=-1,r=this.moduleCount-1,s=7,o=0,a=this.moduleCount-1;a>0;a-=2)for(a==6&&a--;;){for(var l=0;l<2;l++)if(this.modules[r][a-l]==null){var c=!1;o>>s&1)==1);var u=ia.getMask(t,r,a-l);u&&(c=!c),this.modules[r][a-l]=c,s--,s==-1&&(o++,s=7)}if(r+=n,r<0||this.moduleCount<=r){r-=n,n=-n;break}}};ps.PAD0=236;ps.PAD1=17;ps.createData=function(e,t,n){for(var r=mP.getRSBlocks(e,t),s=new vP,o=0;ol*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+l*8+")");for(s.getLengthInBits()+4<=l*8&&s.put(0,4);s.getLengthInBits()%8!=0;)s.putBit(!1);for(;!(s.getLengthInBits()>=l*8||(s.put(ps.PAD0,8),s.getLengthInBits()>=l*8));)s.put(ps.PAD1,8);return ps.createBytes(s,r)};ps.createBytes=function(e,t){for(var n=0,r=0,s=0,o=new Array(t.length),a=new Array(t.length),l=0;l=0?h.get(v):0}}for(var g=0,d=0;d=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var kJ={bgColor:yr.default.oneOfType([yr.default.object,yr.default.string]).isRequired,bgD:yr.default.string.isRequired,fgColor:yr.default.oneOfType([yr.default.object,yr.default.string]).isRequired,fgD:yr.default.string.isRequired,size:yr.default.number.isRequired,title:yr.default.string,viewBoxSize:yr.default.number.isRequired,xmlns:yr.default.string},mx=(0,yP.forwardRef)(function(e,t){var n=e.bgColor,r=e.bgD,s=e.fgD,o=e.fgColor,a=e.size,l=e.title,c=e.viewBoxSize,u=e.xmlns,d=u===void 0?"http://www.w3.org/2000/svg":u,f=CJ(e,["bgColor","bgD","fgD","fgColor","size","title","viewBoxSize","xmlns"]);return Vd.default.createElement("svg",wJ({},f,{height:a,ref:t,viewBox:"0 0 "+c+" "+c,width:a,xmlns:d}),l?Vd.default.createElement("title",null,l):null,Vd.default.createElement("path",{d:r,fill:n}),Vd.default.createElement("path",{d:s,fill:o}))});mx.displayName="QRCodeSvg";mx.propTypes=kJ;hx.default=mx;Object.defineProperty(Ug,"__esModule",{value:!0});Ug.QRCode=void 0;var EJ=Object.assign||function(e){for(var t=1;t=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var DJ={bgColor:js.default.oneOfType([js.default.object,js.default.string]),fgColor:js.default.oneOfType([js.default.object,js.default.string]),level:js.default.string,size:js.default.number,value:js.default.string.isRequired},Vg=(0,xP.forwardRef)(function(e,t){var n=e.bgColor,r=n===void 0?"#FFFFFF":n,s=e.fgColor,o=s===void 0?"#000000":s,a=e.level,l=a===void 0?"L":a,c=e.size,u=c===void 0?256:c,d=e.value,f=MJ(e,["bgColor","fgColor","level","size","value"]),p=new IJ.default(-1,_J.default[l]);p.addData(d),p.make();var h=p.modules;return NJ.default.createElement(OJ.default,EJ({},f,{bgColor:r,bgD:h.map(function(v,g){return v.map(function(b,y){return b?"":"M "+y+" "+g+" l 1 0 0 1 -1 0 Z"}).join(" ")}).join(" "),fgColor:o,fgD:h.map(function(v,g){return v.map(function(b,y){return b?"M "+y+" "+g+" l 1 0 0 1 -1 0 Z":""}).join(" ")}).join(" "),ref:t,size:u,viewBoxSize:h.length}))});Ug.QRCode=Vg;Vg.displayName="QRCode";Vg.propTypes=DJ;var AJ=Ug.default=Vg;const FJ=ng("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7 space-y-1 [&_strong]:text-foreground",{variants:{variant:{default:"border-zinc-500/20 bg-zinc-50/50 dark:border-zinc-500/30 dark:bg-zinc-500/10 text-zinc-900 dark:text-zinc-300 [&>svg]:text-zinc-400 dark:[&>svg]:text-zinc-300",destructive:"border-red-500/20 bg-red-50/50 dark:border-red-500/30 dark:bg-red-500/10 text-red-900 dark:text-red-200 [&>svg]:text-red-600 dark:[&>svg]:text-red-400/80",warning:"border-amber-500/20 bg-amber-50/50 dark:border-amber-500/30 dark:bg-amber-500/10 text-amber-900 dark:text-amber-200 [&>svg]:text-amber-500",info:"border-sky-500/20 bg-sky-50/50 dark:border-sky-500/30 dark:bg-sky-500/10 text-sky-900 dark:text-sky-200 [&>svg]:text-sky-500",success:"border-emerald-500/20 bg-emerald-50/50 dark:border-emerald-500/30 dark:bg-emerald-500/10 text-emerald-900 dark:text-emerald-200 [&>svg]:text-emerald-600 dark:[&>svg]:text-emerald-400/80"}},defaultVariants:{variant:"default"}}),wP=m.forwardRef(({className:e,variant:t,...n},r)=>i.jsx("div",{ref:r,role:"alert",className:me(FJ({variant:t}),e),...n}));wP.displayName="Alert";const SP=m.forwardRef(({className:e,...t},n)=>i.jsx("h5",{ref:n,className:me("font-medium leading-none tracking-tight",e),...t}));SP.displayName="AlertTitle";const LJ=m.forwardRef(({className:e,...t},n)=>i.jsx("div",{ref:n,className:me("text-sm [&_p]:leading-relaxed",e),...t}));LJ.displayName="AlertDescription";const or=({size:e=45,className:t,...n})=>i.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,...n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:me("animate-spin",t),children:i.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}),om=new Intl.NumberFormat("pt-BR");function $J(){const{t:e}=Le(),[t,n]=m.useState(null),[r,s]=m.useState(""),o=localStorage.getItem("token"),{theme:a}=VE(),{instance:l}=st(),c=()=>{window.location.reload()},u=async g=>{try{await T4(g),window.location.reload()}catch(b){console.error("Error:",b)}},d=async g=>{try{await jT(g),window.location.reload()}catch(b){console.error("Error:",b)}},f=async(g,b)=>{try{if(n(null),!o){console.error("Token not found.");return}if(b){const y=await CS(g,o,l==null?void 0:l.number);s(y.pairingCode)}else{const y=await CS(g,o);n(y.code)}}catch(y){console.error("Error:",y)}},p=()=>{n(null),s(""),window.location.reload()},h=m.useMemo(()=>{var g,b,y;return l?{contacts:((g=l._count)==null?void 0:g.Contact)||0,chats:((b=l._count)==null?void 0:b.Chat)||0,messages:((y=l._count)==null?void 0:y.Message)||0}:{contacts:0,chats:0,messages:0}},[l]),v=m.useMemo(()=>a==="dark"?"#fff":a==="light"?"#000":"#189d68",[a]);return l?i.jsxs("main",{className:"flex flex-col gap-8",children:[i.jsx("section",{children:i.jsxs(wa,{children:[i.jsx(Sa,{children:i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsx("h2",{className:"break-all text-lg font-semibold",children:l.name}),i.jsx(aR,{status:l.connectionStatus})]})}),i.jsxs(Ca,{className:"flex flex-col items-start space-y-6",children:[i.jsx("div",{className:"flex w-full flex-1",children:i.jsx(iR,{token:l.token})}),l.profileName&&i.jsxs("div",{className:"flex flex-1 gap-2",children:[i.jsx(vg,{children:i.jsx(yg,{src:l.profilePicUrl,alt:""})}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("strong",{children:l.profileName}),i.jsx("p",{className:"break-all text-sm text-muted-foreground",children:l.ownerJid})]})]}),l.connectionStatus!=="open"&&i.jsxs(wP,{variant:"warning",className:"flex flex-wrap items-center justify-between gap-3",children:[i.jsx(SP,{className:"text-lg font-bold tracking-wide",children:e("instance.dashboard.alert")}),i.jsxs(yt,{children:[i.jsx(Rt,{onClick:()=>f(l.name,!1),asChild:!0,children:i.jsx(J,{variant:"warning",children:e("instance.dashboard.button.qrcode.label")})}),i.jsxs(pt,{onCloseAutoFocus:p,children:[i.jsx(gt,{children:e("instance.dashboard.button.qrcode.title")}),i.jsx("div",{className:"flex items-center justify-center",children:t&&i.jsx(AJ,{value:t,size:256,bgColor:"transparent",fgColor:v,className:"rounded-sm"})})]})]}),l.number&&i.jsxs(yt,{children:[i.jsx(Rt,{className:"connect-code-button",onClick:()=>f(l.name,!0),children:e("instance.dashboard.button.pairingCode.label")}),i.jsx(pt,{onCloseAutoFocus:p,children:i.jsx(gt,{children:i.jsx(ti,{children:r?i.jsxs("div",{className:"py-3",children:[i.jsx("p",{className:"text-center",children:i.jsx("strong",{children:e("instance.dashboard.button.pairingCode.title")})}),i.jsxs("p",{className:"pairing-code text-center",children:[r.substring(0,4),"-",r.substring(4,8)]})]}):i.jsx(or,{})})})})]})]})]}),i.jsxs(wg,{className:"flex flex-wrap items-center justify-end gap-3",children:[i.jsx(J,{variant:"outline",className:"refresh-button",size:"icon",onClick:c,children:i.jsx(kT,{size:"20"})}),i.jsx(J,{className:"action-button",variant:"secondary",onClick:()=>u(l.name),children:e("instance.dashboard.button.restart").toUpperCase()}),i.jsx(J,{variant:"destructive",onClick:()=>d(l.name),disabled:l.connectionStatus==="close",children:e("instance.dashboard.button.disconnect").toUpperCase()})]})]})}),i.jsxs("section",{className:"grid grid-cols-[repeat(auto-fit,_minmax(15rem,_1fr))] gap-6",children:[i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(CT,{size:"20"}),e("instance.dashboard.contacts")]})}),i.jsx(Ca,{children:om.format(h.contacts)})]}),i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(S4,{size:"20"}),e("instance.dashboard.chats")]})}),i.jsx(Ca,{children:om.format(h.chats)})]}),i.jsxs(wa,{className:"instance-card",children:[i.jsx(Sa,{children:i.jsxs(Dc,{className:"flex items-center gap-2",children:[i.jsx(sg,{size:"20"}),e("instance.dashboard.messages")]})}),i.jsx(Ca,{children:om.format(h.messages)})]})]})]}):i.jsx(or,{})}var BJ="Separator",S1="horizontal",zJ=["horizontal","vertical"],CP=m.forwardRef((e,t)=>{const{decorative:n,orientation:r=S1,...s}=e,o=UJ(r)?r:S1,l=n?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return i.jsx(Ie.div,{"data-orientation":o,...l,...s,ref:t})});CP.displayName=BJ;function UJ(e){return zJ.includes(e)}var kP=CP;const Ze=m.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},s)=>i.jsx(kP,{ref:s,decorative:n,orientation:t,className:me("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Ze.displayName=kP.displayName;const oo=new ur,EP=async(e,t)=>(await oo.getInstance().get(`/dify/find/${e}`,{headers:{apikey:t}})).data,VJ=async(e,t,n)=>(await oo.getInstance().get(`/dify/fetch/${n}/${e}`,{headers:{apikey:t}})).data,HJ=async(e,t,n)=>(await oo.getInstance().post(`/dify/create/${e}`,n,{headers:{apikey:t}})).data,WJ=async(e,t,n,r)=>(await oo.getInstance().put(`/dify/update/${n}/${e}`,r,{headers:{apikey:t}})).data,GJ=async(e,t,n)=>(await oo.getInstance().delete(`/dify/delete/${n}/${e}`,{headers:{apikey:t}})).data,qJ=async(e,t)=>(await oo.getInstance().get(`/dify/fetchSettings/${e}`,{headers:{apikey:t}})).data,KJ=async(e,t,n)=>(await oo.getInstance().post(`/dify/settings/${e}`,n,{headers:{apikey:t}})).data,JJ=async(e,t,n)=>(await oo.getInstance().get(`/dify/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,ZJ=async(e,t,n,r)=>(await oo.getInstance().post(`/dify/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,QJ=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),difyIdFallback:k.union([k.null(),k.string()]).optional()}),C1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await qJ(e.name,r);t(s);const o=await EP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function YJ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(QJ),defaultValues:{expire:"0",keywordFinish:e("dify.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("dify.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],difyIdFallback:void 0}});m.useEffect(()=>{n&&C1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,difyIdFallback:s.difyIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),difyIdFallback:f.difyIdFallback||void 0,ignoreJids:f.ignoreJids};await KJ(t.name,t.token,g),X.success(e("dify.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){C1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("dify.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("dify.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"difyIdFallback",label:e("dify.form.difyIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("dify.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("dify.form.ignoreJids.label"),placeholder:e("dify.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("dify.button.save")})})]})})]})]})}const XJ=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function eZ({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(XJ),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,botType:f.botType,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await HJ(n.name,n.token,g),X.success(t("dify.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("dify.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("dify.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("dify.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.difySettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:t("dify.form.botType.label"),options:[{label:t("dify.form.botType.chatBot"),value:"chatBot"},{label:t("dify.form.botType.textGenerator"),value:"textGenerator"},{label:t("dify.form.botType.agent"),value:"agent"},{label:t("dify.form.botType.workflow"),value:"workflow"}]}),i.jsx(D,{name:"apiUrl",label:t("dify.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("dify.form.apiKey.label"),required:!0,children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("dify.form.triggerType.label"),options:[{label:t("dify.form.triggerType.keyword"),value:"keyword"},{label:t("dify.form.triggerType.all"),value:"all"},{label:t("dify.form.triggerType.advanced"),value:"advanced"},{label:t("dify.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("dify.form.triggerOperator.label"),options:[{label:t("dify.form.triggerOperator.contains"),value:"contains"},{label:t("dify.form.triggerOperator.equals"),value:"equals"},{label:t("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("dify.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("dify.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("dify.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("dify.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("dify.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("dify.button.save")})})]})})]})]})}/** * table-core * * Copyright (c) TanStack @@ -378,4 +378,4 @@ lodash-es/lodash.js: * LICENSE.md file in the root directory of this source tree. * * @license MIT - */function Rr(e,t){return e?VZ(e)?m.createElement(e,t):e:null}function VZ(e){return HZ(e)||typeof e=="function"||WZ(e)}function HZ(e){return typeof e=="function"&&(()=>{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function WZ(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Ul(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=m.useState(()=>({current:LZ(t)})),[r,s]=m.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const ri=m.forwardRef(({className:e,...t},n)=>i.jsx("div",{className:"relative w-full overflow-auto",children:i.jsx("table",{ref:n,className:me("w-full caption-bottom text-sm",e),...t})}));ri.displayName="Table";const si=m.forwardRef(({className:e,...t},n)=>i.jsx("thead",{ref:n,className:me("[&_tr]:border-b",e),...t}));si.displayName="TableHeader";const oi=m.forwardRef(({className:e,...t},n)=>i.jsx("tbody",{ref:n,className:me("[&_tr:last-child]:border-0",e),...t}));oi.displayName="TableBody";const GZ=m.forwardRef(({className:e,...t},n)=>i.jsx("tfoot",{ref:n,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));GZ.displayName="TableFooter";const en=m.forwardRef(({className:e,...t},n)=>i.jsx("tr",{ref:n,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));en.displayName="TableRow";const ai=m.forwardRef(({className:e,...t},n)=>i.jsx("th",{ref:n,className:me("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));ai.displayName="TableHead";const ir=m.forwardRef(({className:e,...t},n)=>i.jsx("td",{ref:n,className:me("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));ir.displayName="TableCell";const qZ=m.forwardRef(({className:e,...t},n)=>i.jsx("caption",{ref:n,className:me("mt-4 text-sm text-muted-foreground",e),...t}));qZ.displayName="TableCaption";const T1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await JJ(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function DP({difyId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&T1(n,a,e)},[n,e,l]);function u(){T1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await ZJ(n.name,n.token,g,b),X.success(t("dify.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("dify.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("dify.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("dify.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("dify.sessions.table.none")})})})]})]})]})]})}const KZ=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function JZ({difyId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(KZ),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await VJ(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,botType:y.botType,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await WJ(t.name,w,e,S),X.success(r("dify.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await GJ(t.name,g,e),X.success(r("dify.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/dify`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Dify: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("dify.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.difySettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:r("dify.form.botType.label"),required:!0,options:[{label:r("dify.form.botType.chatBot"),value:"chatBot"},{label:r("dify.form.botType.textGenerator"),value:"textGenerator"},{label:r("dify.form.botType.agent"),value:"agent"},{label:r("dify.form.botType.workflow"),value:"workflow"}]}),i.jsx(D,{name:"apiUrl",label:r("dify.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("dify.form.apiKey.label"),required:!0,children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("dify.form.triggerType.label"),options:[{label:r("dify.form.triggerType.keyword"),value:"keyword"},{label:r("dify.form.triggerType.all"),value:"all"},{label:r("dify.form.triggerType.advanced"),value:"advanced"},{label:r("dify.form.triggerType.none"),value:"none"}],required:!0}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("dify.form.triggerOperator.label"),options:[{label:r("dify.form.triggerOperator.contains"),value:"contains"},{label:r("dify.form.triggerOperator.equals"),value:"equals"},{label:r("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("dify.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:r("dify.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("dify.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("dify.form.keywordFinish.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(DP,{difyId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("dify.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("dify.button.update")})]})]})]})})]})}const j1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await EP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function _1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{difyId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&j1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/dify/${f}`)},d=()=>{j1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(DP,{}),i.jsx(YJ,{}),i.jsx(eZ,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsxs(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:f.description||f.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:f.botType})]},f.id)):i.jsx(J,{variant:"link",children:e("dify.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(JZ,{difyId:r,instance:n,resetTable:d})})]})]})]})}const gr=new ur,Wg=async(e,t)=>(await gr.getInstance().get(`/openai/creds/${e}`,{headers:{apikey:t}})).data,ZZ=async(e,t,n)=>(await gr.getInstance().post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,QZ=async(e,t)=>(await gr.getInstance().delete(`/openai/creds/${e}/${t}`)).data,AP=async(e,t)=>(await gr.getInstance().get(`/openai/find/${e}`,{headers:{apikey:t}})).data,YZ=async(e,t,n)=>(await gr.getInstance().get(`/openai/fetch/${n}/${e}`,{headers:{apikey:t}})).data,XZ=async(e,t,n)=>(await gr.getInstance().post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,eQ=async(e,t,n,r)=>(await gr.getInstance().put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,tQ=async(e,t,n)=>(await gr.getInstance().delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,nQ=async(e,t)=>(await gr.getInstance().get(`/openai/fetchSettings/${e}`,{headers:{apikey:t}})).data,rQ=async(e,t,n)=>(await gr.getInstance().post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,sQ=async(e,t,n)=>(await gr.getInstance().get(`/openai/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,oQ=async(e,t,n,r)=>(await gr.getInstance().post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,FP=async(e,t)=>(await gr.getInstance().get(`/openai/getModels/${e}`,{headers:{apikey:t}})).data,aQ=k.object({name:k.string(),apiKey:k.string()}),pm=async(e,t)=>{try{const n=localStorage.getItem("token");if(n&&e&&e.name){const r=await Wg(e.name,n);t(r)}else console.error("Token not found.")}catch(n){console.error("Error:",n)}};function iQ(){var v;const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState([]),[a,l]=m.useState([]),c=kt({resolver:Et(aQ),defaultValues:{name:"",apiKey:""}});m.useEffect(()=>{n&&pm(t,l)},[t,n]);const u=async g=>{var b,y,x;try{if(!t||!t.name)throw new Error("instance not found.");const w={name:g.name,apiKey:g.apiKey};await ZZ(t.name,t.token,w),X.success(e("openai.toast.success.credentialsCreate")),d()}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}};function d(){c.reset(),pm(t,l)}const f=async g=>{var b,y,x;try{await QZ(g,t==null?void 0:t.name),X.success(e("openai.toast.success.credentialsDelete")),pm(t,l)}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=[{accessorKey:"name",header:({column:g})=>i.jsxs(J,{variant:"ghost",onClick:()=>g.toggleSorting(g.getIsSorted()==="asc"),children:[e("openai.credentials.table.name"),i.jsx(e4,{className:"ml-2 h-4 w-4"})]}),cell:({row:g})=>i.jsx("div",{children:g.getValue("name")})},{accessorKey:"apiKey",header:()=>i.jsx("div",{className:"text-right",children:e("openai.credentials.table.apiKey")}),cell:({row:g})=>i.jsxs("div",{children:[`${g.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:e("openai.credentials.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:e("openai.credentials.table.actions.title")}),i.jsx(ra,{}),i.jsx(at,{onClick:()=>f(b.id),children:e("openai.credentials.table.actions.delete")})]})]})}}],h=Ul({data:a,columns:p,onSortingChange:o,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:s}});return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(v4,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:e("openai.credentials.title")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("openai.credentials.title")})}),i.jsx(dr,{...c,children:i.jsxs("form",{onSubmit:c.handleSubmit(u),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[i.jsx(D,{name:"name",label:e("openai.credentials.table.name"),children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:e("openai.credentials.table.apiKey"),children:i.jsx(A,{type:"password"})})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("openai.button.save")})})]})}),i.jsx(Ze,{}),i.jsx("div",{children:i.jsxs(ri,{children:[i.jsx(si,{children:h.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=h.getRowModel().rows)!=null&&v.length?h.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:p.length,className:"h-24 text-center",children:e("openai.credentials.table.none")})})})]})})]})]})}const lQ=k.object({openaiCredsId:k.string(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number().default(0),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),speechToText:k.boolean(),ignoreJids:k.array(k.string()).default([]),openaiIdFallback:k.union([k.null(),k.string()]).optional()}),R1=async(e,t,n,r)=>{try{const s=localStorage.getItem("token");if(s&&e&&e.name){const o=await nQ(e.name,s);t(o);const a=await AP(e.name,s);n(a);const l=await Wg(e.name,s);r(l)}else console.error("Token not found")}catch(s){console.error("Error:",s)}};function cQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),[c,u]=m.useState(),d=kt({resolver:Et(lQ),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0}});m.useEffect(()=>{n&&R1(t,o,l,u)},[t,n]),m.useEffect(()=>{s&&d.reset({openaiCredsId:s.openaiCredsId,expire:(s==null?void 0:s.expire)??0,keywordFinish:s.keywordFinish,delayMessage:s.delayMessage??0,unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime??0,speechToText:s.speechToText,ignoreJids:s.ignoreJids,openaiIdFallback:s.openaiIdFallback})},[s]);const f=async h=>{var v,g,b;try{if(!t||!t.name)throw new Error("instance not found.");const y={openaiCredsId:h.openaiCredsId,expire:h.expire,keywordFinish:h.keywordFinish,delayMessage:h.delayMessage,unknownMessage:h.unknownMessage,listeningFromMe:h.listeningFromMe,stopBotFromMe:h.stopBotFromMe,keepOpen:h.keepOpen,debounceTime:h.debounceTime,speechToText:h.speechToText,openaiIdFallback:h.openaiIdFallback||void 0,ignoreJids:h.ignoreJids};await rQ(t.name,t.token,y),X.success(e("openai.toast.defaultSettings.success"))}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(g=(v=y==null?void 0:y.response)==null?void 0:v.data)==null?void 0:g.response)==null?void 0:b.message}`)}};function p(){R1(t,o,l,u)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[i.jsx(gt,{children:i.jsx(At,{children:e("openai.defaultSettings")})}),i.jsx(dr,{...d,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(f),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(c==null?void 0:c.filter(h=>!!h.id).map(h=>({label:h.name?h.name:h.apiKey.substring(0,15)+"...",value:h.id})))||[]}),i.jsx(et,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(a==null?void 0:a.filter(h=>!!h.id).map(h=>({label:h.description,value:h.id})))??[]}),i.jsx(D,{name:"expire",label:e("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),i.jsx(he,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const uQ=k.object({enabled:k.boolean(),description:k.string(),openaiCredsId:k.string(),botType:k.string(),assistantId:k.string(),functionUrl:k.string(),model:k.string(),systemMessages:k.string(),assistantMessages:k.string(),userMessages:k.string(),maxTokens:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function dQ({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),[l,c]=m.useState([]),[u,d]=m.useState([]),f=kt({resolver:Et(uQ),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"gpt-4o-mini",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:"300",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}});m.useEffect(()=>{o&&(async()=>{try{if(!n)return;const y=await FP(n.name,n.token);c(y);const x=await Wg(n.name,n.token);d(x)}catch(y){console.error("Error:",y)}})()},[n,o]);const p=async b=>{var y,x,w;try{if(!n||!n.name)throw new Error("instance not found.");s(!0);const S={enabled:b.enabled,description:b.description,openaiCredsId:b.openaiCredsId,botType:b.botType,assistantId:b.assistantId,functionUrl:b.functionUrl,model:b.model,systemMessages:[b.systemMessages],assistantMessages:[b.assistantMessages],userMessages:[b.userMessages],maxTokens:parseInt(b.maxTokens,10),triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:parseInt(b.expire,10),keywordFinish:b.keywordFinish,delayMessage:parseInt(b.delayMessage,10),unknownMessage:b.unknownMessage,listeningFromMe:b.listeningFromMe,stopBotFromMe:b.stopBotFromMe,keepOpen:b.keepOpen,debounceTime:parseInt(b.debounceTime,10)};await XZ(n.name,n.token,S),X.success(t("openai.toast.success.create")),a(!1),h(),e()}catch(S){console.error("Error:",S),X.error(`Error: ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}finally{s(!1)}};function h(){f.reset()}const v=f.watch("botType"),g=f.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),i.jsxs(pt,{className:"max-w-xl",onCloseAutoFocus:h,children:[i.jsx(gt,{children:i.jsx(At,{children:t("openai.form.title")})}),i.jsx(dr,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(p),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("openai.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("openai.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsx(et,{name:"openaiCredsId",label:t("openai.form.openaiCredsId.label"),required:!0,options:u.filter(b=>!!b.id).map(b=>({label:b.name?b.name:b.apiKey.substring(0,15)+"...",value:b.id}))}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.openaiSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:t("openai.form.botType.label"),required:!0,options:[{label:t("openai.form.botType.assistant"),value:"assistant"},{label:t("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),v==="assistant"&&i.jsxs(i.Fragment,{children:[i.jsx(D,{name:"assistantId",label:t("openai.form.assistantId.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"functionUrl",label:t("openai.form.functionUrl.label"),required:!0,children:i.jsx(A,{})})]}),v==="chatCompletion"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"model",label:t("openai.form.model.label"),required:!0,options:l.map(b=>({label:b.id,value:b.id}))}),i.jsx(D,{name:"systemMessages",label:t("openai.form.systemMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"assistantMessages",label:t("openai.form.assistantMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"userMessages",label:t("openai.form.userMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"maxTokens",label:t("openai.form.maxTokens.label"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("openai.form.triggerType.label"),required:!0,options:[{label:t("openai.form.triggerType.keyword"),value:"keyword"},{label:t("openai.form.triggerType.all"),value:"all"},{label:t("openai.form.triggerType.advanced"),value:"advanced"},{label:t("openai.form.triggerType.none"),value:"none"}]}),g==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("openai.form.triggerOperator.label"),required:!0,options:[{label:t("openai.form.triggerOperator.contains"),value:"contains"},{label:t("openai.form.triggerOperator.equals"),value:"equals"},{label:t("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("openai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:t("openai.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),g==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("openai.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("openai.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t(r?"openai.button.saving":"openai.button.save")})})]})})]})]})}const I1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await sQ(e.name,r,n);t(s)}else console.error("Token not found")}catch(r){console.error("Error:",r)}};function LP({botId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&I1(n,a,e)},[n,e,l]);function u(){I1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await oQ(n.name,n.token,g,b),X.success(t("openai.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",size:"icon",children:[i.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("openai.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("openai.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("openai.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{size:16})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("openai.sessions.table.none")})})})]})]})]})]})}const fQ=k.object({enabled:k.boolean(),description:k.string(),openaiCredsId:k.string(),botType:k.string(),assistantId:k.string(),functionUrl:k.string().optional(),model:k.string(),systemMessages:k.string(),assistantMessages:k.string(),userMessages:k.string(),maxTokens:k.coerce.number(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([])});function pQ({botId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),[u,d]=m.useState([]),[f,p]=m.useState([]),h=En(),v=kt({resolver:Et(fQ),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"gpt-3.5-turbo",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:300,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{const S=async()=>{try{const C=localStorage.getItem("token");if(C&&t&&t.name&&e){s(C);const T=await YZ(t.name,C,e);v.reset({enabled:T.enabled,description:T.description,openaiCredsId:T.openaiCredsId,botType:T.botType,assistantId:T.assistantId,functionUrl:T.functionUrl,model:T.model,systemMessages:T.systemMessages.toString(),assistantMessages:T.assistantMessages.toString(),userMessages:T.userMessages.toString(),maxTokens:T.maxTokens,triggerType:T.triggerType,triggerOperator:T.triggerOperator,triggerValue:T.triggerValue,expire:T.expire,keywordFinish:T.keywordFinish,delayMessage:T.delayMessage,unknownMessage:T.unknownMessage,listeningFromMe:T.listeningFromMe,stopBotFromMe:T.stopBotFromMe,keepOpen:T.keepOpen,debounceTime:T.debounceTime})}else console.error("Token not found.");a(!1)}catch(C){console.error("Error:",C),a(!1)}},E=async()=>{try{if(!t)return;const C=await FP(t.name,t.token);d(C);const T=await Wg(t.name,t.token);p(T)}catch(C){console.error("Error:",C)}};S(),E()},[v,t,e]);const g=async S=>{var E,C,T;try{const j=localStorage.getItem("token");if(j&&t&&t.name&&e){const I={enabled:S.enabled,description:S.description,openaiCredsId:S.openaiCredsId,botType:S.botType,assistantId:S.assistantId,functionUrl:S.functionUrl||"",model:S.model,systemMessages:[S.systemMessages],assistantMessages:[S.assistantMessages],userMessages:[S.userMessages],maxTokens:S.maxTokens,triggerType:S.triggerType,triggerOperator:S.triggerOperator||"",triggerValue:S.triggerValue||"",expire:S.expire,keywordFinish:S.keywordFinish,delayMessage:S.delayMessage,unknownMessage:S.unknownMessage,listeningFromMe:S.listeningFromMe,stopBotFromMe:S.stopBotFromMe,keepOpen:S.keepOpen,debounceTime:S.debounceTime};await eQ(t.name,j,e,I),X.success(r("openai.toast.success.update"))}else console.error("Instance not found")}catch(j){console.error("Error:",j),X.error(`Error: ${(T=(C=(E=j==null?void 0:j.response)==null?void 0:E.data)==null?void 0:C.response)==null?void 0:T.message}`)}},b=async()=>{try{const S=localStorage.getItem("token");S&&t&&t.name&&e?(await tQ(t.name,S,e),X.success(r("openai.toast.success.delete")),c(!1),n(),h(`/manager/instance/${t.id}/openai`)):console.error("Instance not found.")}catch(S){console.error("Error:",S)}},y=v.watch("description"),x=v.watch("botType"),w=v.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...v,children:i.jsxs("form",{onSubmit:v.handleSubmit(g),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["OpenAI: ",y]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("openai.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsx(et,{name:"openaiCredsId",label:r("openai.form.openaiCredsId.label"),required:!0,options:f.filter(S=>!!S.id).map(S=>({label:S.name?S.name:S.apiKey.substring(0,15)+"...",value:S.id}))}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.openaiSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:r("openai.form.botType.label"),required:!0,options:[{label:r("openai.form.botType.assistant"),value:"assistant"},{label:r("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),x==="assistant"&&i.jsxs(i.Fragment,{children:[i.jsx(D,{name:"assistantId",label:r("openai.form.assistantId.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"functionUrl",label:r("openai.form.functionUrl.label"),required:!0,children:i.jsx(A,{})})]}),x==="chatCompletion"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"model",label:r("openai.form.model.label"),required:!0,options:u.map(S=>({label:S.id,value:S.id}))}),i.jsx(D,{name:"systemMessages",label:r("openai.form.systemMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"assistantMessages",label:r("openai.form.assistantMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"userMessages",label:r("openai.form.userMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"maxTokens",label:r("openai.form.maxTokens"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("openai.form.triggerType.label"),required:!0,options:[{label:r("openai.form.triggerType.keyword"),value:"keyword"},{label:r("openai.form.triggerType.all"),value:"all"},{label:r("openai.form.triggerType.advanced"),value:"advanced"},{label:r("openai.form.triggerType.none"),value:"none"}]}),w==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("openai.form.triggerOperator.label"),required:!0,options:[{label:r("openai.form.triggerOperator.contains"),value:"contains"},{label:r("openai.form.triggerOperator.equals"),value:"equals"},{label:r("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("openai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("openai.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),w==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("openai.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("openai.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(LP,{botId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("openai.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:b,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("openai.button.update")})]})]})]})})]})}const N1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await AP(e.name,r);t(s)}else console.error("Token ou nome da instância não encontrados.");n(!1)}catch(r){console.error("Erro ao carregar configurações:",r),n(!1)}};function P1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{botId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&N1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/openai/${f}`)},d=()=>{N1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(LP,{}),i.jsx(cQ,{}),i.jsx(iQ,{}),i.jsx(dQ,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsxs(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:f.description||f.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:f.botType})]},f.id)):i.jsx(J,{variant:"link",children:e("openai.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(pQ,{botId:r,instance:n,resetTable:d})})]})]})]})}const $P=new ur,gQ=async(e,t)=>(await $P.getInstance().get(`/proxy/find/${e}`,{headers:{apikey:t}})).data,hQ=async(e,t,n)=>(await $P.getInstance().post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data,mQ=k.object({enabled:k.boolean(),host:k.string(),port:k.string(),protocol:k.string(),username:k.string(),password:k.string()});function vQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(mQ),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const l=await gQ(t.name,t.token);s.reset(l)}catch(l){console.error("Error:",l)}finally{r(!1)}}})()},[t,s]);const o=async a=>{var l,c,u;if(t){r(!0);try{const d={enabled:a.enabled,host:a.host,port:a.port,protocol:a.protocol,username:a.username,password:a.password};await hQ(t.name,t.token,d),X.success(e("proxy.toast.success"))}catch(d){console.error(e("proxy.toast.error"),d),X.error(`Error : ${(u=(c=(l=d==null?void 0:d.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{r(!1)}}};return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[i.jsx(D,{name:"protocol",label:e("proxy.form.protocol.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"host",label:e("proxy.form.host.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"port",label:e("proxy.form.port.label"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[i.jsx(D,{name:"username",label:e("proxy.form.username.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"password",label:e("proxy.form.password.label"),children:i.jsx(A,{type:"password"})})]}),i.jsx("div",{className:"flex justify-end px-4 pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const BP=new ur,yQ=async(e,t)=>(await BP.getInstance().get(`/rabbitmq/find/${e}`,{headers:{apikey:t}})).data,bQ=async(e,t,n)=>(await BP.getInstance().post(`/rabbitmq/set/${e}`,n,{headers:{apikey:t}})).data,xQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function wQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(xQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await yQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await bQ(t.name,t.token,f),X.success(e("rabbitmq.toast.success"))}catch(f){console.error(e("rabbitmq.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const SQ=k.object({rejectCall:k.boolean(),msgCall:k.string().optional(),groupsIgnore:k.boolean(),alwaysOnline:k.boolean(),readMessages:k.boolean(),syncFullHistory:k.boolean(),readStatus:k.boolean()});function CQ(){const{t:e}=Le(),[t,n]=m.useState(!0),[r,s]=m.useState(!1),[o,a]=m.useState(""),{instance:l}=st(),c=kt({resolver:Et(SQ),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});m.useEffect(()=>{(async()=>{try{if(l&&l.name&&l.token){a(l.token);const h=await _4(l.name,l.token);c.reset({rejectCall:h.rejectCall,msgCall:h.msgCall||"",groupsIgnore:h.groupsIgnore,alwaysOnline:h.alwaysOnline,readMessages:h.readMessages,syncFullHistory:h.syncFullHistory,readStatus:h.readStatus})}else console.error("token not found");n(!1)}catch(h){console.error("Error:",h),n(!1)}})()},[c,l]);const u=async p=>{try{if(!l||!l.name)throw new Error("instance not found");s(!0);const h={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await R4(l.name,o,h),X.success(e("settings.toast.success"))}catch(h){console.error(e("settings.toast.success"),h),X.error(e("settings.toast.error"))}finally{s(!1)}},d=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],f=c.watch("rejectCall");return t?i.jsx(or,{}):i.jsx(i.Fragment,{children:i.jsx(fr,{...c,children:i.jsx("form",{onSubmit:c.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),i.jsx(Ze,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[i.jsxs("div",{className:"flex flex-col p-4",children:[i.jsx(he,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),f&&i.jsx("div",{className:"mr-16 mt-2",children:i.jsx(D,{name:"msgCall",children:i.jsx(zs,{placeholder:e("settings.form.msgCall.description")})})})]}),d.map(p=>i.jsx("div",{className:"flex p-4",children:i.jsx(he,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),i.jsx("div",{className:"flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:r,children:e(r?"settings.button.saving":"settings.button.save")})})]})]})})})})}const zP=new ur,kQ=async(e,t)=>(await zP.getInstance().get(`/sqs/find/${e}`,{headers:{apikey:t}})).data,EQ=async(e,t,n)=>(await zP.getInstance().post(`/sqs/set/${e}`,n,{headers:{apikey:t}})).data,TQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function jQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(TQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await kQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await EQ(t.name,t.token,f),X.success(e("sqs.toast.success"))}catch(f){console.error(e("sqs.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const ao=new ur,UP=async(e,t)=>(await ao.getInstance().get(`/typebot/find/${e}`,{headers:{apikey:t}})).data,_Q=async(e,t,n)=>(await ao.getInstance().get(`/typebot/fetch/${n}/${e}`,{headers:{apikey:t}})).data,RQ=async(e,t,n)=>(await ao.getInstance().post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,IQ=async(e,t,n,r)=>(await ao.getInstance().put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,NQ=async(e,t,n)=>(await ao.getInstance().delete(`/typebot/delete/${n}/${e}`,{headers:{apikey:t}})).data,PQ=async(e,t)=>(await ao.getInstance().get(`/typebot/fetchSettings/${e}`,{headers:{apikey:t}})).data,OQ=async(e,t,n)=>(await ao.getInstance().post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,MQ=async(e,t,n)=>(await ao.getInstance().get(`/typebot/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,DQ=async(e,t,n,r)=>(await ao.getInstance().post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,AQ=k.object({expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([]),typebotIdFallback:k.union([k.null(),k.string()]).optional()}),O1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await PQ(e.name,r);t(s);const o=await UP(e.name,r);n(o)}else console.error("token not found.")}catch(r){console.error("Error:",r)}};function FQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(),[s,o]=m.useState([]),[a,l]=m.useState(!1),c=kt({resolver:Et(AQ),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,ignoreJids:[],typebotIdFallback:void 0}});m.useEffect(()=>{a&&O1(t,r,o)},[t,a]),m.useEffect(()=>{n&&c.reset({expire:(n==null?void 0:n.expire)??0,keywordFinish:n.keywordFinish,delayMessage:n.delayMessage??0,unknownMessage:n.unknownMessage,listeningFromMe:n.listeningFromMe,stopBotFromMe:n.stopBotFromMe,keepOpen:n.keepOpen,debounceTime:n.debounceTime??0,ignoreJids:n.ignoreJids,typebotIdFallback:n.typebotIdFallback})},[n]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime,typebotIdFallback:f.typebotIdFallback||void 0,ignoreJids:f.ignoreJids};await OQ(t.name,t.token,g),X.success(e("typebot.toast.defaultSettings.success"))}catch(g){console.error(e("typebot.toast.defaultSettings.error"),g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){O1(t,r,o)}return i.jsxs(yt,{open:a,onOpenChange:l,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("typebot.modal.defaultSettings.title")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(s==null?void 0:s.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),i.jsx(D,{name:"expire",label:e("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const LQ=k.object({enabled:k.boolean(),description:k.string(),url:k.string().url(),typebot:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([])});function $Q({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(LQ),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[]}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("Nome da instância não encontrado.");s(!0);const g={enabled:f.enabled,description:f.description,url:f.url,typebot:f.typebot,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await RQ(n.name,n.token,g),X.success(t("typebot.toast.success.create")),a(!1),u(),e()}catch(g){console.error(t("typebot.toast.error"),g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"default",className:"mr-5 text-white",children:[i.jsx(Qa,{}),i.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("typebot.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("typebot.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("typebot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.typebotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"url",label:t("typebot.form.url.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"typebot",label:t("typebot.form.typebot.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("typebot.form.triggerType.label"),required:!0,options:[{label:t("typebot.form.triggerType.keyword"),value:"keyword"},{label:t("typebot.form.triggerType.all"),value:"all"},{label:t("typebot.form.triggerType.advanced"),value:"advanced"},{label:t("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("typebot.form.triggerOperator.label"),required:!0,options:[{label:t("typebot.form.triggerOperator.contains"),value:"contains"},{label:t("typebot.form.triggerOperator.equals"),value:"equals"},{label:t("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("typebot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:t("typebot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("typebot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("typebot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("typebot.button.save")})})]})})]})]})}const M1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await MQ(e.name,r,n);t(s)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar sessões:",r)}};function VP({typebotId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&M1(n,a,e)},[n,e,l]);function u(){M1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await DQ(n.name,n.token,g,b),X.success(t("typebot.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:"Actions"}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"})," ",i.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("typebot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("typebot.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{size:16})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("typebot.sessions.table.none")})})})]})]})]})]})}const BQ=k.object({enabled:k.boolean(),description:k.string(),url:k.string().url(),typebot:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([])});function zQ({typebotId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(BQ),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,ignoreJids:[]}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await _Q(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,url:y.url,typebot:y.typebot,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await IQ(t.name,w,e,S),X.success(r("typebot.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await NQ(t.name,g,e),X.success(r("typebot.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/typebot`)):console.error("Token not found")}catch(g){console.error("Error:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Typebot: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("typebot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.typebotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"url",label:r("typebot.form.url.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"typebot",label:r("typebot.form.typebot.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("typebot.form.triggerType.label"),required:!0,options:[{label:r("typebot.form.triggerType.keyword"),value:"keyword"},{label:r("typebot.form.triggerType.all"),value:"all"},{label:r("typebot.form.triggerType.advanced"),value:"advanced"},{label:r("typebot.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("typebot.form.triggerOperator.label"),required:!0,options:[{label:r("typebot.form.triggerOperator.contains"),value:"contains"},{label:r("typebot.form.triggerOperator.equals"),value:"equals"},{label:r("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("typebot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("typebot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("typebot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("typebot.form.delay.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(VP,{typebotId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("typebot.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("typebot.button.update")})]})]})]})})]})}const D1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await UP(e.name,r);t(s)}else console.error("token not found.");n(!1)}catch(r){console.error("Error",r),n(!1)}};function A1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{typebotId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&D1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/typebot/${f}`)},d=()=>{D1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),i.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[i.jsx(VP,{}),i.jsx(FQ,{}),i.jsx($Q,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:f.description?i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:f.description}),i.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[f.url," - ",f.typebot]})]}):i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:f.url}),i.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:f.typebot})]})},f.id)):i.jsx(J,{variant:"link",children:e("typebot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-black"}),i.jsx(_r,{className:"",children:i.jsx(zQ,{typebotId:r,instance:n,resetTable:d})})]})]})]})}const HP=new ur,UQ=async(e,t)=>(await HP.getInstance().get(`/webhook/find/${e}`,{headers:{apikey:t}})).data,VQ=async(e,t,n)=>(await HP.getInstance().post(`/webhook/set/${e}`,n,{headers:{apikey:t}})).data,HQ=k.object({enabled:k.boolean(),url:k.string().url("Invalid URL format"),events:k.array(k.string()),webhookBase64:k.boolean(),webhookByEvents:k.boolean()});function WQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(HQ),defaultValues:{enabled:!1,url:"",events:[],webhookBase64:!1,webhookByEvents:!1}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await UQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,url:l.url,events:l.events,webhookBase64:l.webhookBase64,webhookByEvents:l.webhookByEvents};await VQ(t.name,t.token,f),X.success(e("webhook.toast.success"))}catch(f){console.error(e("webhook.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),i.jsx(D,{name:"url",label:"URL",children:i.jsx(A,{})}),i.jsx(he,{name:"webhookByEvents",label:e("webhook.form.webhookByEvents.label"),className:"w-full justify-between",helper:e("webhook.form.webhookByEvents.description")}),i.jsx(he,{name:"webhookBase64",label:e("webhook.form.webhookBase64.label"),className:"w-full justify-between",helper:e("webhook.form.webhookBase64.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const WP=new ur,GQ=async(e,t)=>(await WP.getInstance().get(`/websocket/find/${e}`,{headers:{apikey:t}})).data,qQ=async(e,t,n)=>(await WP.getInstance().post(`/websocket/set/${e}`,n,{headers:{apikey:t}})).data,KQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function JQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(KQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await GQ(t.name,t.token);s.reset(c)}catch(c){console.error("Erro ao buscar dados do websocket:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await qQ(t.name,t.token,f),X.success(e("websocket.toast.success"))}catch(f){console.error(e("websocket.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const ZQ=k.object({serverUrl:k.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:k.string({required_error:"ApiKey is required"})});function QQ(){const{t:e}=Le(),t=En(),n=kt({resolver:Et(ZQ),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await pT(s.serverUrl);if(!o||!o.version){gT(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await dL(s.serverUrl,s.apiKey)){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}if(!await uL(s.serverUrl,s.apiKey)){X.error(e("login.message.invalidCredentials"));return}localStorage.setItem("version",o.version),localStorage.setItem("clientName",o.clientName),t("/manager/")};return i.jsxs("div",{className:"flex min-h-screen flex-col",children:[i.jsx("div",{className:"flex items-center justify-center pt-2",children:i.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),i.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:i.jsxs(wa,{className:"b-none w-[350px] shadow-none",children:[i.jsxs(Sa,{children:[i.jsx(Dc,{className:"text-center",children:e("login.title")}),i.jsx(lR,{className:"text-center",children:e("login.description")})]}),i.jsx(fr,{...n,children:i.jsxs("form",{onSubmit:n.handleSubmit(r),children:[i.jsx(Ca,{children:i.jsxs("div",{className:"grid w-full items-center gap-4",children:[i.jsx(D,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:i.jsx(A,{})}),i.jsx(D,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:i.jsx(A,{type:"password"})})]})}),i.jsx(wg,{className:"flex justify-center",children:i.jsx(J,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),i.jsx(fb,{})]})}const io=new ur,GP=async(e,t)=>(await io.getInstance().get(`/generic/find/${e}`,{headers:{apikey:t}})).data,YQ=async(e,t,n)=>(await io.getInstance().get(`/generic/fetch/${n}/${e}`,{headers:{apikey:t}})).data,XQ=async(e,t,n)=>(await io.getInstance().post(`/generic/create/${e}`,n,{headers:{apikey:t}})).data,eY=async(e,t,n,r)=>(await io.getInstance().put(`/generic/update/${n}/${e}`,r,{headers:{apikey:t}})).data,tY=async(e,t,n)=>(await io.getInstance().delete(`/generic/delete/${n}/${e}`,{headers:{apikey:t}})).data,nY=async(e,t)=>(await io.getInstance().get(`/generic/fetchSettings/${e}`,{headers:{apikey:t}})).data,rY=async(e,t,n)=>(await io.getInstance().post(`/generic/settings/${e}`,n,{headers:{apikey:t}})).data,sY=async(e,t,n)=>(await io.getInstance().get(`/generic/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,oY=async(e,t,n,r)=>(await io.getInstance().post(`/generic/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,aY=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),botIdFallback:k.union([k.null(),k.string()]).optional()}),F1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await nY(e.name,r);t(s);const o=await GP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function iY(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(aY),defaultValues:{expire:"0",keywordFinish:e("genericBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("genericBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0}});m.useEffect(()=>{n&&F1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids};await rY(t.name,t.token,g),X.success(e("genericBot.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){F1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("genericBot.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("genericBot.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"botIdFallback",label:e("genericBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("genericBot.form.ignoreJids.label"),placeholder:e("genericBot.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("genericBot.button.save")})})]})})]})]})}const lY=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function cY({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(lY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await XQ(n.name,n.token,g),X.success(t("genericBot.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("genericBot.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("genericBot.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("genericBot.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("genericBot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.genericBotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:t("genericBot.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("genericBot.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("genericBot.form.triggerType.label"),options:[{label:t("genericBot.form.triggerType.keyword"),value:"keyword"},{label:t("genericBot.form.triggerType.all"),value:"all"},{label:t("genericBot.form.triggerType.advanced"),value:"advanced"},{label:t("genericBot.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("genericBot.form.triggerOperator.label"),options:[{label:t("genericBot.form.triggerOperator.contains"),value:"contains"},{label:t("genericBot.form.triggerOperator.equals"),value:"equals"},{label:t("genericBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("genericBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("genericBot.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("genericBot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("genericBot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("genericBot.button.save")})})]})})]})]})}const L1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await sY(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function qP({genericBotId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&L1(n,a,e)},[n,e,l]);function u(){L1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await oY(n.name,n.token,g,b),X.success(t("genericBot.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("genericBot.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("genericBot.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("genericBot.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("genericBot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("genericBot.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("genericBot.sessions.table.none")})})})]})]})]})]})}const uY=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function dY({genericBotId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(uY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await YQ(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await eY(t.name,w,e,S),X.success(r("genericBot.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await tY(t.name,g,e),X.success(r("genericBot.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/generic`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir genericBot:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["GenericBot: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("genericBot.form.description.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.genericBotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:r("genericBot.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("genericBot.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("genericBot.form.triggerType.label"),options:[{label:r("genericBot.form.triggerType.keyword"),value:"keyword"},{label:r("genericBot.form.triggerType.all"),value:"all"},{label:r("genericBot.form.triggerType.advanced"),value:"advanced"},{label:r("genericBot.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("genericBot.form.triggerOperator.label"),options:[{label:r("genericBot.form.triggerOperator.contains"),value:"contains"},{label:r("genericBot.form.triggerOperator.equals"),value:"equals"},{label:r("genericBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("genericBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("genericBot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("genericBot.form.triggerValue.label"),children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("genericBot.form.triggerConditions.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(qP,{genericBotId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("genericBot.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("genericBot.button.update")})]})]})]})})]})}const $1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await GP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function B1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{genericBotId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&$1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/generic/${f}`)},d=()=>{$1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("genericBot.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(qP,{}),i.jsx(iY,{}),i.jsx(cY,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:f.description||f.id})},f.id)):i.jsx(J,{variant:"link",children:e("genericBot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(dY,{genericBotId:r,instance:n,resetTable:d})})]})]})]})}const lo=new ur,KP=async(e,t)=>(await lo.getInstance().get(`/flowise/find/${e}`,{headers:{apikey:t}})).data,fY=async(e,t,n)=>(await lo.getInstance().get(`/flowise/fetch/${n}/${e}`,{headers:{apikey:t}})).data,pY=async(e,t,n)=>(await lo.getInstance().post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,gY=async(e,t,n,r)=>(await lo.getInstance().put(`/flowise/update/${n}/${e}`,r,{headers:{apikey:t}})).data,hY=async(e,t,n)=>(await lo.getInstance().delete(`/flowise/delete/${n}/${e}`,{headers:{apikey:t}})).data,mY=async(e,t)=>(await lo.getInstance().get(`/flowise/fetchSettings/${e}`,{headers:{apikey:t}})).data,vY=async(e,t,n)=>(await lo.getInstance().post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data,yY=async(e,t,n)=>(await lo.getInstance().get(`/flowise/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,bY=async(e,t,n,r)=>(await lo.getInstance().post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,xY=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),flowiseIdFallback:k.union([k.null(),k.string()]).optional()}),z1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await mY(e.name,r);t(s);const o=await KP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function wY(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(xY),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0}});m.useEffect(()=>{n&&z1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,flowiseIdFallback:s.flowiseIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids};await vY(t.name,t.token,g),X.success(e("flowise.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){z1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("flowise.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const SY=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function CY({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(SY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await pY(n.name,n.token,g),X.success(t("flowise.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("flowise.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("flowise.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("flowise.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.flowiseSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:t("flowise.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("flowise.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("flowise.form.triggerType.label"),options:[{label:t("flowise.form.triggerType.keyword"),value:"keyword"},{label:t("flowise.form.triggerType.all"),value:"all"},{label:t("flowise.form.triggerType.advanced"),value:"advanced"},{label:t("flowise.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("flowise.form.triggerOperator.label"),options:[{label:t("flowise.form.triggerOperator.contains"),value:"contains"},{label:t("flowise.form.triggerOperator.equals"),value:"equals"},{label:t("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("flowise.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("flowise.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("flowise.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("flowise.button.save")})})]})})]})]})}const U1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await yY(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function JP({flowiseId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&U1(n,a,e)},[n,e,l]);function u(){U1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await bY(n.name,n.token,g,b),X.success(t("flowise.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("flowise.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("flowise.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("flowise.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("flowise.sessions.table.none")})})})]})]})]})]})}const kY=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function EY({flowiseId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(kY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await fY(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await gY(t.name,w,e,S),X.success(r("flowise.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await hY(t.name,g,e),X.success(r("flowise.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/flowise`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir flowise:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Flowise: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("flowise.form.description.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.flowiseSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:r("flowise.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("flowise.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("flowise.form.triggerType.label"),options:[{label:r("flowise.form.triggerType.keyword"),value:"keyword"},{label:r("flowise.form.triggerType.all"),value:"all"},{label:r("flowise.form.triggerType.advanced"),value:"advanced"},{label:r("flowise.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("flowise.form.triggerOperator.label"),options:[{label:r("flowise.form.triggerOperator.contains"),value:"contains"},{label:r("flowise.form.triggerOperator.equals"),value:"equals"},{label:r("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("flowise.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("flowise.form.triggerValue.label"),children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("flowise.form.triggerConditions.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(JP,{flowiseId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("flowise.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("flowise.button.update")})]})]})]})})]})}const V1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await KP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function H1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{flowiseId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&V1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/flowise/${f}`)},d=()=>{V1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(JP,{}),i.jsx(wY,{}),i.jsx(CY,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:f.description||f.id})},f.id)):i.jsx(J,{variant:"link",children:e("flowise.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(EY,{flowiseId:r,instance:n,resetTable:d})})]})]})]})}const TY=lF([{path:"/manager/login",element:i.jsx(FF,{children:i.jsx(QQ,{})})},{path:"/manager/",element:i.jsx(zt,{children:i.jsx(Xz,{children:i.jsx(xK,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx($J,{})})})},{path:"/manager/instance/:instanceId/chat",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(x1,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(x1,{})})})},{path:"/manager/instance/:instanceId/settings",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(CQ,{})})})},{path:"/manager/instance/:instanceId/openai",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(P1,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(P1,{})})})},{path:"/manager/instance/:instanceId/webhook",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(WQ,{})})})},{path:"/manager/instance/:instanceId/websocket",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(JQ,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(wQ,{})})})},{path:"/manager/instance/:instanceId/sqs",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(jQ,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(iJ,{})})})},{path:"/manager/instance/:instanceId/typebot",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(A1,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(A1,{})})})},{path:"/manager/instance/:instanceId/dify",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(_1,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(_1,{})})})},{path:"/manager/instance/:instanceId/generic",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(B1,{})})})},{path:"/manager/instance/:instanceId/generic/:genericBotId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(B1,{})})})},{path:"/manager/instance/:instanceId/flowise",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(H1,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(H1,{})})})},{path:"/manager/instance/:instanceId/proxy",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(vQ,{})})})}]),jY={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class Cp{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||jY,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[l,c]=a;for(let u=0;u{let[l,c]=a;for(let u=0;u{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},W1=e=>e==null?"":""+e,_Y=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},RY=/###/g,G1=e=>e&&e.indexOf("###")>-1?e.replace(RY,"."):e,q1=e=>!e||typeof e=="string",zc=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=zc(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),l=zc(e,a,Object);for(;l.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),l=zc(e,a,Object),l&&l.obj&&typeof l.obj[`${l.k}.${o}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${o}`]=n},IY=(e,t,n,r)=>{const{obj:s,k:o}=zc(e,t,Object);s[o]=s[o]||[],s[o].push(n)},kp=(e,t)=>{const{obj:n,k:r}=zc(e,t);if(n)return n[r]},NY=(e,t,n)=>{const r=kp(e,n);return r!==void 0?r:kp(t,n)},ZP=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):ZP(e[r],t[r],n):e[r]=t[r]);return e},wi=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var PY={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const OY=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>PY[t]):e;class MY{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const DY=[" ",",","?","!",";"],AY=new MY(20),FY=(e,t,n)=>{t=t||"",n=n||"";const r=DY.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=AY.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},ay=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ce&&e.indexOf("_")>0?e.replace("_","-"):e;class J1 extends Gg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;t.indexOf(".")>-1?l=t.split("."):(l=[t,n],r&&(Array.isArray(r)?l.push(...r):typeof r=="string"&&o?l.push(...r.split(o)):l.push(r)));const c=kp(this.data,l);return!c&&!n&&!r&&t.indexOf(".")>-1&&(t=l[0],n=l[1],r=l.slice(2).join(".")),c||!a||typeof r!="string"?c:ay(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let l=[t,n];r&&(l=l.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(l=t.split("."),s=n,n=l[1]),this.addNamespaces(n),K1(this.data,l,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},l=[t,n];t.indexOf(".")>-1&&(l=t.split("."),s=r,r=n,n=l[1]),this.addNamespaces(n);let c=kp(this.data,l)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?ZP(c,r,o):c={...c,...r},K1(this.data,l,c),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var QP={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const Z1={};class Tp extends Gg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),_Y(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=gs.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!FY(t,r,s);if(a&&!l){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:o};const u=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(u[0])>-1)&&(o=u.shift()),t=u.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(t[t.length-1],n),c=l[l.length-1],u=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u&&u.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${c}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:`${c}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:a}const f=this.resolve(t,n);let p=f&&f.res;const h=f&&f.usedKey||a,v=f&&f.exactUsedKey||a,g=Object.prototype.toString.apply(p),b=["[object Number]","[object Function]","[object RegExp]"],y=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject;if(x&&p&&(typeof p!="string"&&typeof p!="boolean"&&typeof p!="number")&&b.indexOf(g)<0&&!(typeof y=="string"&&Array.isArray(p))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,p,{...n,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(f.res=S,f.usedParams=this.getUsedParamsDetails(n),f):S}if(o){const S=Array.isArray(p),E=S?[]:{},C=S?v:h;for(const T in p)if(Object.prototype.hasOwnProperty.call(p,T)){const j=`${C}${o}${T}`;E[T]=this.translate(j,{...n,joinArrays:!1,ns:l}),E[T]===j&&(E[T]=p[T])}p=E}}else if(x&&typeof y=="string"&&Array.isArray(p))p=p.join(y),p&&(p=this.extendTranslation(p,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",T=Tp.hasDefaultValue(n),j=C?this.pluralResolver.getSuffix(u,n.count,n):"",I=n.ordinal&&C?this.pluralResolver.getSuffix(u,n.count,{ordinal:!1}):"",P=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),V=P&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${j}`]||n[`defaultValue${I}`]||n.defaultValue;!this.isValidLookup(p)&&T&&(S=!0,p=V),this.isValidLookup(p)||(E=!0,p=a);const Z=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:p,H=T&&V!==p&&this.options.updateMissing;if(E||S||H){if(this.logger.log(H?"updateKey":"missingKey",u,c,a,H?V:p),o){const L=this.resolve(a,{...n,keySeparator:!1});L&&L.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let K=[];const Y=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Y&&Y[0])for(let L=0;L{const ue=T&&Q!==p?Q:Z;this.options.missingKeyHandler?this.options.missingKeyHandler(L,c,F,ue,H,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(L,c,F,ue,H,n),this.emit("missingKey",L,c,F,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?K.forEach(L=>{const F=this.pluralResolver.getSuffixes(L,n);P&&n[`defaultValue${this.options.pluralSeparator}zero`]&&F.indexOf(`${this.options.pluralSeparator}zero`)<0&&F.push(`${this.options.pluralSeparator}zero`),F.forEach(Q=>{G([L],a+Q,n[`defaultValue${Q}`]||V)})}):G(K,a,V))}p=this.extendTranslation(p,t,n,f,r),E&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${c}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}:${a}`:a,S?p:void 0):p=this.options.parseMissingKeyHandler(p))}return s?(f.res=p,f.usedParams=this.getUsedParamsDetails(n),f):p}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(u){const p=t.match(this.interpolator.nestingRegexp);d=p&&p.length}let f=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(f={...this.options.interpolation.defaultVariables,...f}),t=this.interpolator.interpolate(t,f,r.lng||this.language||s.usedLng,r),u){const p=t.match(this.interpolator.nestingRegexp),h=p&&p.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,l;return typeof t=="string"&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(c,n),d=u.key;s=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&typeof n.count!="string",h=p&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),v=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(b=>{this.isValidLookup(r)||(l=b,!Z1[`${g[0]}-${b}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(l)&&(Z1[`${g[0]}-${b}`]=!0,this.logger.warn(`key "${s}" for languages "${g.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(y=>{if(this.isValidLookup(r))return;a=y;const x=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(x,d,y,b,n);else{let S;p&&(S=this.pluralResolver.getSuffix(y,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(x.push(d+S),n.ordinal&&S.indexOf(C)===0&&x.push(d+S.replace(C,this.options.pluralSeparator)),h&&x.push(d+E)),v){const T=`${d}${this.options.contextSeparator}${n.context}`;x.push(T),p&&(x.push(T+S),n.ordinal&&S.indexOf(C)===0&&x.push(T+S.replace(C,this.options.pluralSeparator)),h&&x.push(T+E))}}let w;for(;w=x.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(y,b,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:l}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const gm=e=>e.charAt(0).toUpperCase()+e.slice(1);class Q1{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=gs.create("languageUtils")}getScriptPartFromCode(t){if(t=Ep(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ep(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=gm(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=gm(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=gm(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let LY=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],$Y={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const BY=["v1","v2","v3"],zY=["v4"],Y1={zero:0,one:1,two:2,few:3,many:4,other:5},UY=()=>{const e={};return LY.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:$Y[t.fc]}})}),e};class VY{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=gs.create("pluralResolver"),(!this.options.compatibilityJSON||zY.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=UY(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Ep(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>Y1[s]-Y1[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!BY.includes(this.options.compatibilityJSON)}}const X1=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=NY(e,t,n);return!o&&s&&typeof n=="string"&&(o=ay(e,n,r),o===void 0&&(o=ay(t,n,r))),o},hm=e=>e.replace(/\$/g,"$$$$");class HY{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=gs.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:l,suffixEscaped:c,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:v,nestingSuffixEscaped:g,nestingOptionsSeparator:b,maxReplaces:y,alwaysFormat:x}=t.interpolation;this.escape=n!==void 0?n:OY,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?wi(o):a||"{{",this.suffix=l?wi(l):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?wi(p):h||wi("$t("),this.nestingSuffix=v?wi(v):g||wi(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=y||1e3,this.alwaysFormat=x!==void 0?x:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const y=X1(n,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,r,{...s,...n,interpolationkey:h}):y}const v=h.split(this.formatSeparator),g=v.shift().trim(),b=v.join(this.formatSeparator).trim();return this.format(X1(n,c,g,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...s,...n,interpolationkey:g})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,f=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>hm(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?hm(this.escape(h)):hm(h)}].forEach(h=>{for(l=0;o=h.regex.exec(t);){const v=o[1].trim();if(a=u(v),a===void 0)if(typeof d=="function"){const b=d(t,o,s);a=typeof b=="string"?b:""}else if(s&&Object.prototype.hasOwnProperty.call(s,v))a="";else if(f){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${v} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=W1(a));const g=h.safeValue(a);if(t=t.replace(o[0],g),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=o[0].length):h.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const l=(c,u)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const f=c.split(new RegExp(`${d}[ ]*{`));let p=`{${f[1]}`;c=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),v=p.match(/"/g);(h&&h.length%2===0&&!v||v.length%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,g),`${c}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,c};for(;s=this.nestingRegexp.exec(t);){let c=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let u=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(f=>f.trim());s[1]=d.shift(),c=d,u=!0}if(o=n(l.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=W1(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),u&&(o=c.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const WY=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[l,...c]=a.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),d=l.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},Si=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let l=t[a];return l||(l=e(Ep(r),s),t[a]=l),l(n)}};class GY{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=gs.create("formatter"),this.options=t,this.formats={number:Si((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:Si((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:Si((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:Si((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:Si((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=Si(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(l=>l.indexOf(")")>-1)){const l=o.findIndex(c=>c.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,l)].join(this.formatSeparator)}return o.reduce((l,c)=>{const{formatName:u,formatOptions:d}=WY(c);if(this.formats[u]){let f=l;try{const p=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},h=p.locale||p.lng||s.locale||s.lng||r;f=this.formats[u](l,h,{...d,...s,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return l},t)}}const qY=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class KY extends Gg{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=gs.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},l={},c={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),o[p]===void 0&&(o[p]=!0),c[f]===void 0&&(c[f]=!0)))}),d||(l[u]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const l={};this.queue.forEach(c=>{IY(c.loaded,[o],a),qY(c,t),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{l[u]||(l[u]={});const d=c.loaded[u];d.length&&d.forEach(f=>{l[u][f]===void 0&&(l[u][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const l=(u,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(u&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(u,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const u=c(t,n);u&&typeof u.then=="function"?u.then(d=>l(null,d)).catch(l):l(null,u)}catch(u){l(u)}return}return c(t,n,l)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,l)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&l&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,l),this.loaded(t,a,l)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const c={...a,isUpdate:o},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,s,c):d=u(t,n,r,s),d&&typeof d.then=="function"?d.then(f=>l(null,f)).catch(l):l(null,d)}catch(d){l(d)}else u(t,n,r,s,l,c)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const eC=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),tC=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),qd=()=>{},JY=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Au extends Gg{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=tC(t),this.services={},this.logger=gs,this.modules={external:[]},JY(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=eC();this.options={...s,...this.options,...tC(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?gs.init(o(this.modules.logger),this.options):gs.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=GY);const f=new Q1(this.options);this.store=new J1(this.options.resources,this.options);const p=this.services;p.logger=gs,p.resourceStore=this.store,p.languageUtils=f,p.pluralResolver=new VY(f,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(p.formatter=o(d),p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new HY(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new KY(o(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",function(h){for(var v=arguments.length,g=new Array(v>1?v-1:0),b=1;b1?v-1:0),b=1;b{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=qd),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const c=pc(),u=()=>{const d=(f,p)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(p),r(f,p)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?u():setTimeout(u,0),c}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:qd;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(u=>{u!=="cimode"&&o.indexOf(u)<0&&o.push(u)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>a(c)),this.options.preload&&this.options.preload.forEach(l=>a(l)),this.services.backendConnector.load(o,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(t,n,r){const s=pc();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=qd),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&QP.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=pc();this.emit("languageChanging",t);const o=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},a=(c,u)=>{u?(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(c,function(){return r.t(...arguments)})},l=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const u=typeof c=="string"?c:this.services.languageUtils.getBestMatchFromCodes(c);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(u)),this.loadResources(u,d=>{a(d,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?l(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(l):this.services.languageDetector.detect(l):l(t),s}getFixedT(t,n,r){var s=this;const o=function(a,l){let c;if(typeof l!="object"){for(var u=arguments.length,d=new Array(u>2?u-2:0),f=2;f`${c.keyPrefix}${p}${v}`):h=c.keyPrefix?`${c.keyPrefix}${p}${a}`:a,s.t(h,c)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(l,c)=>{const u=this.services.backendConnector.state[`${l}|${c}`];return u===-1||u===0||u===2};if(n.precheck){const l=n.precheck(this,a);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=pc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=pc();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new Q1(eC());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Au(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:qd;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Au(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(l=>{o[l]=this[l]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new J1(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Tp(o.services,s),o.translator.on("*",function(l){for(var c=arguments.length,u=new Array(c>1?c-1:0),d=1;d{const t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function WZ(e){return typeof e=="object"&&typeof e.$$typeof=="symbol"&&["react.memo","react.forward_ref"].includes(e.$$typeof.description)}function Ul(e){const t={state:{},onStateChange:()=>{},renderFallbackValue:null,...e},[n]=m.useState(()=>({current:LZ(t)})),[r,s]=m.useState(()=>n.current.initialState);return n.current.setOptions(o=>({...o,...e,state:{...r,...e.state},onStateChange:a=>{s(a),e.onStateChange==null||e.onStateChange(a)}})),n.current}const ri=m.forwardRef(({className:e,...t},n)=>i.jsx("div",{className:"relative w-full overflow-auto",children:i.jsx("table",{ref:n,className:me("w-full caption-bottom text-sm",e),...t})}));ri.displayName="Table";const si=m.forwardRef(({className:e,...t},n)=>i.jsx("thead",{ref:n,className:me("[&_tr]:border-b",e),...t}));si.displayName="TableHeader";const oi=m.forwardRef(({className:e,...t},n)=>i.jsx("tbody",{ref:n,className:me("[&_tr:last-child]:border-0",e),...t}));oi.displayName="TableBody";const GZ=m.forwardRef(({className:e,...t},n)=>i.jsx("tfoot",{ref:n,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));GZ.displayName="TableFooter";const en=m.forwardRef(({className:e,...t},n)=>i.jsx("tr",{ref:n,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));en.displayName="TableRow";const ai=m.forwardRef(({className:e,...t},n)=>i.jsx("th",{ref:n,className:me("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",e),...t}));ai.displayName="TableHead";const ir=m.forwardRef(({className:e,...t},n)=>i.jsx("td",{ref:n,className:me("p-4 align-middle [&:has([role=checkbox])]:pr-0",e),...t}));ir.displayName="TableCell";const qZ=m.forwardRef(({className:e,...t},n)=>i.jsx("caption",{ref:n,className:me("mt-4 text-sm text-muted-foreground",e),...t}));qZ.displayName="TableCaption";const T1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await JJ(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function DP({difyId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&T1(n,a,e)},[n,e,l]);function u(){T1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await ZJ(n.name,n.token,g,b),X.success(t("dify.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("dify.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("dify.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("dify.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("dify.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("dify.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("dify.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("dify.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("dify.sessions.table.none")})})})]})]})]})]})}const KZ=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function JZ({difyId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(KZ),defaultValues:{enabled:!0,description:"",botType:"chatBot",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await VJ(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,botType:y.botType,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,botType:g.botType,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await WJ(t.name,w,e,S),X.success(r("dify.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await GJ(t.name,g,e),X.success(r("dify.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/dify`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir dify:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Dify: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("dify.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.difySettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:r("dify.form.botType.label"),required:!0,options:[{label:r("dify.form.botType.chatBot"),value:"chatBot"},{label:r("dify.form.botType.textGenerator"),value:"textGenerator"},{label:r("dify.form.botType.agent"),value:"agent"},{label:r("dify.form.botType.workflow"),value:"workflow"}]}),i.jsx(D,{name:"apiUrl",label:r("dify.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("dify.form.apiKey.label"),required:!0,children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("dify.form.triggerType.label"),options:[{label:r("dify.form.triggerType.keyword"),value:"keyword"},{label:r("dify.form.triggerType.all"),value:"all"},{label:r("dify.form.triggerType.advanced"),value:"advanced"},{label:r("dify.form.triggerType.none"),value:"none"}],required:!0}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("dify.form.triggerOperator.label"),options:[{label:r("dify.form.triggerOperator.contains"),value:"contains"},{label:r("dify.form.triggerOperator.equals"),value:"equals"},{label:r("dify.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("dify.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("dify.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:r("dify.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("dify.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("dify.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("dify.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("dify.form.keywordFinish.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("dify.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("dify.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("dify.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("dify.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("dify.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("dify.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(DP,{difyId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("dify.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("dify.button.update")})]})]})]})})]})}const j1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await EP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function _1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{difyId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&j1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/dify/${f}`)},d=()=>{j1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("dify.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(DP,{}),i.jsx(YJ,{}),i.jsx(eZ,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsxs(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:f.description||f.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:f.botType})]},f.id)):i.jsx(J,{variant:"link",children:e("dify.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(JZ,{difyId:r,instance:n,resetTable:d})})]})]})]})}const gr=new ur,Wg=async(e,t)=>(await gr.getInstance().get(`/openai/creds/${e}`,{headers:{apikey:t}})).data,ZZ=async(e,t,n)=>(await gr.getInstance().post(`/openai/creds/${e}`,n,{headers:{apikey:t}})).data,QZ=async(e,t)=>(await gr.getInstance().delete(`/openai/creds/${e}/${t}`)).data,AP=async(e,t)=>(await gr.getInstance().get(`/openai/find/${e}`,{headers:{apikey:t}})).data,YZ=async(e,t,n)=>(await gr.getInstance().get(`/openai/fetch/${n}/${e}`,{headers:{apikey:t}})).data,XZ=async(e,t,n)=>(await gr.getInstance().post(`/openai/create/${e}`,n,{headers:{apikey:t}})).data,eQ=async(e,t,n,r)=>(await gr.getInstance().put(`/openai/update/${n}/${e}`,r,{headers:{apikey:t}})).data,tQ=async(e,t,n)=>(await gr.getInstance().delete(`/openai/delete/${n}/${e}`,{headers:{apikey:t}})).data,nQ=async(e,t)=>(await gr.getInstance().get(`/openai/fetchSettings/${e}`,{headers:{apikey:t}})).data,rQ=async(e,t,n)=>(await gr.getInstance().post(`/openai/settings/${e}`,n,{headers:{apikey:t}})).data,sQ=async(e,t,n)=>(await gr.getInstance().get(`/openai/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,oQ=async(e,t,n,r)=>(await gr.getInstance().post(`/openai/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,FP=async(e,t)=>(await gr.getInstance().get(`/openai/getModels/${e}`,{headers:{apikey:t}})).data,aQ=k.object({name:k.string(),apiKey:k.string()}),pm=async(e,t)=>{try{const n=localStorage.getItem("token");if(n&&e&&e.name){const r=await Wg(e.name,n);t(r)}else console.error("Token not found.")}catch(n){console.error("Error:",n)}};function iQ(){var v;const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState([]),[a,l]=m.useState([]),c=kt({resolver:Et(aQ),defaultValues:{name:"",apiKey:""}});m.useEffect(()=>{n&&pm(t,l)},[t,n]);const u=async g=>{var b,y,x;try{if(!t||!t.name)throw new Error("instance not found.");const w={name:g.name,apiKey:g.apiKey};await ZZ(t.name,t.token,w),X.success(e("openai.toast.success.credentialsCreate")),d()}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}};function d(){c.reset(),pm(t,l)}const f=async g=>{var b,y,x;try{await QZ(g,t==null?void 0:t.name),X.success(e("openai.toast.success.credentialsDelete")),pm(t,l)}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=[{accessorKey:"name",header:({column:g})=>i.jsxs(J,{variant:"ghost",onClick:()=>g.toggleSorting(g.getIsSorted()==="asc"),children:[e("openai.credentials.table.name"),i.jsx(e4,{className:"ml-2 h-4 w-4"})]}),cell:({row:g})=>i.jsx("div",{children:g.getValue("name")})},{accessorKey:"apiKey",header:()=>i.jsx("div",{className:"text-right",children:e("openai.credentials.table.apiKey")}),cell:({row:g})=>i.jsxs("div",{children:[`${g.getValue("apiKey")}`.slice(0,20),"..."]})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:e("openai.credentials.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:e("openai.credentials.table.actions.title")}),i.jsx(ra,{}),i.jsx(at,{onClick:()=>f(b.id),children:e("openai.credentials.table.actions.delete")})]})]})}}],h=Ul({data:a,columns:p,onSortingChange:o,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:s}});return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(v4,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:e("openai.credentials.title")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("openai.credentials.title")})}),i.jsx(dr,{...c,children:i.jsxs("form",{onSubmit:c.handleSubmit(u),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[i.jsx(D,{name:"name",label:e("openai.credentials.table.name"),children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:e("openai.credentials.table.apiKey"),children:i.jsx(A,{type:"password"})})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("openai.button.save")})})]})}),i.jsx(Ze,{}),i.jsx("div",{children:i.jsxs(ri,{children:[i.jsx(si,{children:h.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=h.getRowModel().rows)!=null&&v.length?h.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:p.length,className:"h-24 text-center",children:e("openai.credentials.table.none")})})})]})})]})]})}const lQ=k.object({openaiCredsId:k.string(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number().default(0),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),speechToText:k.boolean(),ignoreJids:k.array(k.string()).default([]),openaiIdFallback:k.union([k.null(),k.string()]).optional()}),R1=async(e,t,n,r)=>{try{const s=localStorage.getItem("token");if(s&&e&&e.name){const o=await nQ(e.name,s);t(o);const a=await AP(e.name,s);n(a);const l=await Wg(e.name,s);r(l)}else console.error("Token not found")}catch(s){console.error("Error:",s)}};function cQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),[c,u]=m.useState(),d=kt({resolver:Et(lQ),defaultValues:{openaiCredsId:"",expire:0,keywordFinish:e("openai.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("openai.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,speechToText:!1,ignoreJids:[],openaiIdFallback:void 0}});m.useEffect(()=>{n&&R1(t,o,l,u)},[t,n]),m.useEffect(()=>{s&&d.reset({openaiCredsId:s.openaiCredsId,expire:(s==null?void 0:s.expire)??0,keywordFinish:s.keywordFinish,delayMessage:s.delayMessage??0,unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime??0,speechToText:s.speechToText,ignoreJids:s.ignoreJids,openaiIdFallback:s.openaiIdFallback})},[s]);const f=async h=>{var v,g,b;try{if(!t||!t.name)throw new Error("instance not found.");const y={openaiCredsId:h.openaiCredsId,expire:h.expire,keywordFinish:h.keywordFinish,delayMessage:h.delayMessage,unknownMessage:h.unknownMessage,listeningFromMe:h.listeningFromMe,stopBotFromMe:h.stopBotFromMe,keepOpen:h.keepOpen,debounceTime:h.debounceTime,speechToText:h.speechToText,openaiIdFallback:h.openaiIdFallback||void 0,ignoreJids:h.ignoreJids};await rQ(t.name,t.token,y),X.success(e("openai.toast.defaultSettings.success"))}catch(y){console.error("Error:",y),X.error(`Error: ${(b=(g=(v=y==null?void 0:y.response)==null?void 0:v.data)==null?void 0:g.response)==null?void 0:b.message}`)}};function p(){R1(t,o,l,u)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:e("openai.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:p,children:[i.jsx(gt,{children:i.jsx(At,{children:e("openai.defaultSettings")})}),i.jsx(dr,{...d,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:d.handleSubmit(f),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"openaiCredsId",label:e("openai.form.openaiCredsId.label"),options:(c==null?void 0:c.filter(h=>!!h.id).map(h=>({label:h.name?h.name:h.apiKey.substring(0,15)+"...",value:h.id})))||[]}),i.jsx(et,{name:"openaiIdFallback",label:e("openai.form.openaiIdFallback.label"),options:(a==null?void 0:a.filter(h=>!!h.id).map(h=>({label:h.description,value:h.id})))??[]}),i.jsx(D,{name:"expire",label:e("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("openai.form.keepOpen.label"),reverse:!0}),i.jsx(he,{name:"speechToText",label:e("openai.form.speechToText.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("openai.form.ignoreJids.label"),placeholder:e("openai.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("openai.button.save")})})]})})]})]})}const uQ=k.object({enabled:k.boolean(),description:k.string(),openaiCredsId:k.string(),botType:k.string(),assistantId:k.string(),functionUrl:k.string(),model:k.string(),systemMessages:k.string(),assistantMessages:k.string(),userMessages:k.string(),maxTokens:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function dQ({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),[l,c]=m.useState([]),[u,d]=m.useState([]),f=kt({resolver:Et(uQ),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"gpt-4o-mini",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:"300",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}});m.useEffect(()=>{o&&(async()=>{try{if(!n)return;const y=await FP(n.name,n.token);c(y);const x=await Wg(n.name,n.token);d(x)}catch(y){console.error("Error:",y)}})()},[n,o]);const p=async b=>{var y,x,w;try{if(!n||!n.name)throw new Error("instance not found.");s(!0);const S={enabled:b.enabled,description:b.description,openaiCredsId:b.openaiCredsId,botType:b.botType,assistantId:b.assistantId,functionUrl:b.functionUrl,model:b.model,systemMessages:[b.systemMessages],assistantMessages:[b.assistantMessages],userMessages:[b.userMessages],maxTokens:parseInt(b.maxTokens,10),triggerType:b.triggerType,triggerOperator:b.triggerOperator||"",triggerValue:b.triggerValue||"",expire:parseInt(b.expire,10),keywordFinish:b.keywordFinish,delayMessage:parseInt(b.delayMessage,10),unknownMessage:b.unknownMessage,listeningFromMe:b.listeningFromMe,stopBotFromMe:b.stopBotFromMe,keepOpen:b.keepOpen,debounceTime:parseInt(b.debounceTime,10)};await XZ(n.name,n.token,S),X.success(t("openai.toast.success.create")),a(!1),h(),e()}catch(S){console.error("Error:",S),X.error(`Error: ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}finally{s(!1)}};function h(){f.reset()}const v=f.watch("botType"),g=f.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("openai.button.create")})]})}),i.jsxs(pt,{className:"max-w-xl",onCloseAutoFocus:h,children:[i.jsx(gt,{children:i.jsx(At,{children:t("openai.form.title")})}),i.jsx(dr,{...f,children:i.jsxs("form",{onSubmit:f.handleSubmit(p),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("openai.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("openai.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsx(et,{name:"openaiCredsId",label:t("openai.form.openaiCredsId.label"),required:!0,options:u.filter(b=>!!b.id).map(b=>({label:b.name?b.name:b.apiKey.substring(0,15)+"...",value:b.id}))}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.openaiSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:t("openai.form.botType.label"),required:!0,options:[{label:t("openai.form.botType.assistant"),value:"assistant"},{label:t("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),v==="assistant"&&i.jsxs(i.Fragment,{children:[i.jsx(D,{name:"assistantId",label:t("openai.form.assistantId.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"functionUrl",label:t("openai.form.functionUrl.label"),required:!0,children:i.jsx(A,{})})]}),v==="chatCompletion"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"model",label:t("openai.form.model.label"),required:!0,options:l.map(b=>({label:b.id,value:b.id}))}),i.jsx(D,{name:"systemMessages",label:t("openai.form.systemMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"assistantMessages",label:t("openai.form.assistantMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"userMessages",label:t("openai.form.userMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"maxTokens",label:t("openai.form.maxTokens.label"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("openai.form.triggerType.label"),required:!0,options:[{label:t("openai.form.triggerType.keyword"),value:"keyword"},{label:t("openai.form.triggerType.all"),value:"all"},{label:t("openai.form.triggerType.advanced"),value:"advanced"},{label:t("openai.form.triggerType.none"),value:"none"}]}),g==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("openai.form.triggerOperator.label"),required:!0,options:[{label:t("openai.form.triggerOperator.contains"),value:"contains"},{label:t("openai.form.triggerOperator.equals"),value:"equals"},{label:t("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("openai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:t("openai.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),g==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("openai.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("openai.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("openai.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t(r?"openai.button.saving":"openai.button.save")})})]})})]})]})}const I1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await sQ(e.name,r,n);t(s)}else console.error("Token not found")}catch(r){console.error("Error:",r)}};function LP({botId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&I1(n,a,e)},[n,e,l]);function u(){I1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await oQ(n.name,n.token,g,b),X.success(t("openai.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("openai.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",size:"icon",children:[i.jsx("span",{className:"sr-only",children:t("openai.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("openai.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("openai.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden md:inline",children:t("openai.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("openai.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("openai.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{size:16})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("openai.sessions.table.none")})})})]})]})]})]})}const fQ=k.object({enabled:k.boolean(),description:k.string(),openaiCredsId:k.string(),botType:k.string(),assistantId:k.string(),functionUrl:k.string().optional(),model:k.string(),systemMessages:k.string(),assistantMessages:k.string(),userMessages:k.string(),maxTokens:k.coerce.number(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([])});function pQ({botId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),[u,d]=m.useState([]),[f,p]=m.useState([]),h=En(),v=kt({resolver:Et(fQ),defaultValues:{enabled:!0,description:"",openaiCredsId:"",botType:"assistant",assistantId:"",functionUrl:"",model:"gpt-3.5-turbo",systemMessages:"",assistantMessages:"",userMessages:"",maxTokens:300,triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{const S=async()=>{try{const C=localStorage.getItem("token");if(C&&t&&t.name&&e){s(C);const T=await YZ(t.name,C,e);v.reset({enabled:T.enabled,description:T.description,openaiCredsId:T.openaiCredsId,botType:T.botType,assistantId:T.assistantId,functionUrl:T.functionUrl,model:T.model,systemMessages:T.systemMessages.toString(),assistantMessages:T.assistantMessages.toString(),userMessages:T.userMessages.toString(),maxTokens:T.maxTokens,triggerType:T.triggerType,triggerOperator:T.triggerOperator,triggerValue:T.triggerValue,expire:T.expire,keywordFinish:T.keywordFinish,delayMessage:T.delayMessage,unknownMessage:T.unknownMessage,listeningFromMe:T.listeningFromMe,stopBotFromMe:T.stopBotFromMe,keepOpen:T.keepOpen,debounceTime:T.debounceTime})}else console.error("Token not found.");a(!1)}catch(C){console.error("Error:",C),a(!1)}},E=async()=>{try{if(!t)return;const C=await FP(t.name,t.token);d(C);const T=await Wg(t.name,t.token);p(T)}catch(C){console.error("Error:",C)}};S(),E()},[v,t,e]);const g=async S=>{var E,C,T;try{const j=localStorage.getItem("token");if(j&&t&&t.name&&e){const I={enabled:S.enabled,description:S.description,openaiCredsId:S.openaiCredsId,botType:S.botType,assistantId:S.assistantId,functionUrl:S.functionUrl||"",model:S.model,systemMessages:[S.systemMessages],assistantMessages:[S.assistantMessages],userMessages:[S.userMessages],maxTokens:S.maxTokens,triggerType:S.triggerType,triggerOperator:S.triggerOperator||"",triggerValue:S.triggerValue||"",expire:S.expire,keywordFinish:S.keywordFinish,delayMessage:S.delayMessage,unknownMessage:S.unknownMessage,listeningFromMe:S.listeningFromMe,stopBotFromMe:S.stopBotFromMe,keepOpen:S.keepOpen,debounceTime:S.debounceTime};await eQ(t.name,j,e,I),X.success(r("openai.toast.success.update"))}else console.error("Instance not found")}catch(j){console.error("Error:",j),X.error(`Error: ${(T=(C=(E=j==null?void 0:j.response)==null?void 0:E.data)==null?void 0:C.response)==null?void 0:T.message}`)}},b=async()=>{try{const S=localStorage.getItem("token");S&&t&&t.name&&e?(await tQ(t.name,S,e),X.success(r("openai.toast.success.delete")),c(!1),n(),h(`/manager/instance/${t.id}/openai`)):console.error("Instance not found.")}catch(S){console.error("Error:",S)}},y=v.watch("description"),x=v.watch("botType"),w=v.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...v,children:i.jsxs("form",{onSubmit:v.handleSubmit(g),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["OpenAI: ",y]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("openai.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsx(et,{name:"openaiCredsId",label:r("openai.form.openaiCredsId.label"),required:!0,options:f.filter(S=>!!S.id).map(S=>({label:S.name?S.name:S.apiKey.substring(0,15)+"...",value:S.id}))}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.openaiSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"botType",label:r("openai.form.botType.label"),required:!0,options:[{label:r("openai.form.botType.assistant"),value:"assistant"},{label:r("openai.form.botType.chatCompletion"),value:"chatCompletion"}]}),x==="assistant"&&i.jsxs(i.Fragment,{children:[i.jsx(D,{name:"assistantId",label:r("openai.form.assistantId.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"functionUrl",label:r("openai.form.functionUrl.label"),required:!0,children:i.jsx(A,{})})]}),x==="chatCompletion"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"model",label:r("openai.form.model.label"),required:!0,options:u.map(S=>({label:S.id,value:S.id}))}),i.jsx(D,{name:"systemMessages",label:r("openai.form.systemMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"assistantMessages",label:r("openai.form.assistantMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"userMessages",label:r("openai.form.userMessages.label"),children:i.jsx(zs,{})}),i.jsx(D,{name:"maxTokens",label:r("openai.form.maxTokens"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("openai.form.triggerType.label"),required:!0,options:[{label:r("openai.form.triggerType.keyword"),value:"keyword"},{label:r("openai.form.triggerType.all"),value:"all"},{label:r("openai.form.triggerType.advanced"),value:"advanced"},{label:r("openai.form.triggerType.none"),value:"none"}]}),w==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("openai.form.triggerOperator.label"),required:!0,options:[{label:r("openai.form.triggerOperator.contains"),value:"contains"},{label:r("openai.form.triggerOperator.equals"),value:"equals"},{label:r("openai.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("openai.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("openai.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("openai.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),w==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("openai.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("openai.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("openai.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("openai.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("openai.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("openai.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("openai.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("openai.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("openai.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("openai.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(LP,{botId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("openai.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:b,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("openai.button.update")})]})]})]})})]})}const N1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await AP(e.name,r);t(s)}else console.error("Token ou nome da instância não encontrados.");n(!1)}catch(r){console.error("Erro ao carregar configurações:",r),n(!1)}};function P1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{botId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&N1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/openai/${f}`)},d=()=>{N1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("openai.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(LP,{}),i.jsx(cQ,{}),i.jsx(iQ,{}),i.jsx(dQ,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsxs(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:[i.jsx("h4",{className:"text-base",children:f.description||f.id}),i.jsx("p",{className:"text-sm font-normal text-muted-foreground",children:f.botType})]},f.id)):i.jsx(J,{variant:"link",children:e("openai.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(pQ,{botId:r,instance:n,resetTable:d})})]})]})]})}const $P=new ur,gQ=async(e,t)=>(await $P.getInstance().get(`/proxy/find/${e}`,{headers:{apikey:t}})).data,hQ=async(e,t,n)=>(await $P.getInstance().post(`/proxy/set/${e}`,n,{headers:{apikey:t}})).data,mQ=k.object({enabled:k.boolean(),host:k.string(),port:k.string(),protocol:k.string(),username:k.string(),password:k.string()});function vQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(mQ),defaultValues:{enabled:!1,host:"",port:"",protocol:"http",username:"",password:""}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const l=await gQ(t.name,t.token);s.reset(l)}catch(l){console.error("Error:",l)}finally{r(!1)}}})()},[t,s]);const o=async a=>{var l,c,u;if(t){r(!0);try{const d={enabled:a.enabled,host:a.host,port:a.port,protocol:a.protocol,username:a.username,password:a.password};await hQ(t.name,t.token,d),X.success(e("proxy.toast.success"))}catch(d){console.error(e("proxy.toast.error"),d),X.error(`Error : ${(u=(c=(l=d==null?void 0:d.response)==null?void 0:l.data)==null?void 0:c.response)==null?void 0:u.message}`)}finally{r(!1)}}};return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("proxy.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("proxy.form.enabled.label"),className:"w-full justify-between",helper:e("proxy.form.enabled.description")}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-[10rem_1fr_10rem] md:gap-8",children:[i.jsx(D,{name:"protocol",label:e("proxy.form.protocol.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"host",label:e("proxy.form.host.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"port",label:e("proxy.form.port.label"),children:i.jsx(A,{type:"number"})})]}),i.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 md:gap-8",children:[i.jsx(D,{name:"username",label:e("proxy.form.username.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"password",label:e("proxy.form.password.label"),children:i.jsx(A,{type:"password"})})]}),i.jsx("div",{className:"flex justify-end px-4 pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"proxy.button.saving":"proxy.button.save")})})]})]})})})})}const BP=new ur,yQ=async(e,t)=>(await BP.getInstance().get(`/rabbitmq/find/${e}`,{headers:{apikey:t}})).data,bQ=async(e,t,n)=>(await BP.getInstance().post(`/rabbitmq/set/${e}`,n,{headers:{apikey:t}})).data,xQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function wQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(xQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await yQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await bQ(t.name,t.token,f),X.success(e("rabbitmq.toast.success"))}catch(f){console.error(e("rabbitmq.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("rabbitmq.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("rabbitmq.form.enabled.label"),className:"w-full justify-between",helper:e("rabbitmq.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("rabbitmq.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"rabbitmq.button.saving":"rabbitmq.button.save")})})]})})})})}const SQ=k.object({rejectCall:k.boolean(),msgCall:k.string().optional(),groupsIgnore:k.boolean(),alwaysOnline:k.boolean(),readMessages:k.boolean(),syncFullHistory:k.boolean(),readStatus:k.boolean()});function CQ(){const{t:e}=Le(),[t,n]=m.useState(!0),[r,s]=m.useState(!1),[o,a]=m.useState(""),{instance:l}=st(),c=kt({resolver:Et(SQ),defaultValues:{rejectCall:!1,msgCall:"",groupsIgnore:!1,alwaysOnline:!1,readMessages:!1,syncFullHistory:!1,readStatus:!1}});m.useEffect(()=>{(async()=>{try{if(l&&l.name&&l.token){a(l.token);const h=await _4(l.name,l.token);c.reset({rejectCall:h.rejectCall,msgCall:h.msgCall||"",groupsIgnore:h.groupsIgnore,alwaysOnline:h.alwaysOnline,readMessages:h.readMessages,syncFullHistory:h.syncFullHistory,readStatus:h.readStatus})}else console.error("token not found");n(!1)}catch(h){console.error("Error:",h),n(!1)}})()},[c,l]);const u=async p=>{try{if(!l||!l.name)throw new Error("instance not found");s(!0);const h={rejectCall:p.rejectCall,msgCall:p.msgCall,groupsIgnore:p.groupsIgnore,alwaysOnline:p.alwaysOnline,readMessages:p.readMessages,syncFullHistory:p.syncFullHistory,readStatus:p.readStatus};await R4(l.name,o,h),X.success(e("settings.toast.success"))}catch(h){console.error(e("settings.toast.success"),h),X.error(e("settings.toast.error"))}finally{s(!1)}},d=[{name:"groupsIgnore",label:e("settings.form.groupsIgnore.label"),description:e("settings.form.groupsIgnore.description")},{name:"alwaysOnline",label:e("settings.form.alwaysOnline.label"),description:e("settings.form.alwaysOnline.description")},{name:"readMessages",label:e("settings.form.readMessages.label"),description:e("settings.form.readMessages.description")},{name:"syncFullHistory",label:e("settings.form.syncFullHistory.label"),description:e("settings.form.syncFullHistory.description")},{name:"readStatus",label:e("settings.form.readStatus.label"),description:e("settings.form.readStatus.description")}],f=c.watch("rejectCall");return t?i.jsx(or,{}):i.jsx(i.Fragment,{children:i.jsx(fr,{...c,children:i.jsx("form",{onSubmit:c.handleSubmit(u),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("settings.title")}),i.jsx(Ze,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y",children:[i.jsxs("div",{className:"flex flex-col p-4",children:[i.jsx(he,{name:"rejectCall",label:e("settings.form.rejectCall.label"),className:"w-full justify-between",helper:e("settings.form.rejectCall.description")}),f&&i.jsx("div",{className:"mr-16 mt-2",children:i.jsx(D,{name:"msgCall",children:i.jsx(zs,{placeholder:e("settings.form.msgCall.description")})})})]}),d.map(p=>i.jsx("div",{className:"flex p-4",children:i.jsx(he,{name:p.name,label:p.label,className:"w-full justify-between",helper:p.description})},p.name)),i.jsx("div",{className:"flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:r,children:e(r?"settings.button.saving":"settings.button.save")})})]})]})})})})}const zP=new ur,kQ=async(e,t)=>(await zP.getInstance().get(`/sqs/find/${e}`,{headers:{apikey:t}})).data,EQ=async(e,t,n)=>(await zP.getInstance().post(`/sqs/set/${e}`,n,{headers:{apikey:t}})).data,TQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function jQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(TQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await kQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await EQ(t.name,t.token,f),X.success(e("sqs.toast.success"))}catch(f){console.error(e("sqs.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("sqs.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("sqs.form.enabled.label"),className:"w-full justify-between",helper:e("sqs.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("sqs.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"sqs.button.saving":"sqs.button.save")})})]})})})})}const ao=new ur,UP=async(e,t)=>(await ao.getInstance().get(`/typebot/find/${e}`,{headers:{apikey:t}})).data,_Q=async(e,t,n)=>(await ao.getInstance().get(`/typebot/fetch/${n}/${e}`,{headers:{apikey:t}})).data,RQ=async(e,t,n)=>(await ao.getInstance().post(`/typebot/create/${e}`,n,{headers:{apikey:t}})).data,IQ=async(e,t,n,r)=>(await ao.getInstance().put(`/typebot/update/${n}/${e}`,r,{headers:{apikey:t}})).data,NQ=async(e,t,n)=>(await ao.getInstance().delete(`/typebot/delete/${n}/${e}`,{headers:{apikey:t}})).data,PQ=async(e,t)=>(await ao.getInstance().get(`/typebot/fetchSettings/${e}`,{headers:{apikey:t}})).data,OQ=async(e,t,n)=>(await ao.getInstance().post(`/typebot/settings/${e}`,n,{headers:{apikey:t}})).data,MQ=async(e,t,n)=>(await ao.getInstance().get(`/typebot/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,DQ=async(e,t,n,r)=>(await ao.getInstance().post(`/typebot/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,AQ=k.object({expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([]),typebotIdFallback:k.union([k.null(),k.string()]).optional()}),O1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await PQ(e.name,r);t(s);const o=await UP(e.name,r);n(o)}else console.error("token not found.")}catch(r){console.error("Error:",r)}};function FQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(),[s,o]=m.useState([]),[a,l]=m.useState(!1),c=kt({resolver:Et(AQ),defaultValues:{expire:0,keywordFinish:e("typebot.form.examples.keywordFinish"),delayMessage:1e3,unknownMessage:e("typebot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,ignoreJids:[],typebotIdFallback:void 0}});m.useEffect(()=>{a&&O1(t,r,o)},[t,a]),m.useEffect(()=>{n&&c.reset({expire:(n==null?void 0:n.expire)??0,keywordFinish:n.keywordFinish,delayMessage:n.delayMessage??0,unknownMessage:n.unknownMessage,listeningFromMe:n.listeningFromMe,stopBotFromMe:n.stopBotFromMe,keepOpen:n.keepOpen,debounceTime:n.debounceTime??0,ignoreJids:n.ignoreJids,typebotIdFallback:n.typebotIdFallback})},[n]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:f.expire,keywordFinish:f.keywordFinish,delayMessage:f.delayMessage,unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:f.debounceTime,typebotIdFallback:f.typebotIdFallback||void 0,ignoreJids:f.ignoreJids};await OQ(t.name,t.token,g),X.success(e("typebot.toast.defaultSettings.success"))}catch(g){console.error(e("typebot.toast.defaultSettings.error"),g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){O1(t,r,o)}return i.jsxs(yt,{open:a,onOpenChange:l,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("typebot.button.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("typebot.modal.defaultSettings.title")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"typebotIdFallback",label:e("typebot.form.typebotIdFallback.label"),options:(s==null?void 0:s.filter(f=>!!f.id).map(f=>({label:f.typebot,value:f.description})))??[]}),i.jsx(D,{name:"expire",label:e("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("typebot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("typebot.form.ignoreJids.label"),placeholder:e("typebot.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("typebot.button.save")})})]})})]})]})}const LQ=k.object({enabled:k.boolean(),description:k.string(),url:k.string().url(),typebot:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([])});function $Q({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(LQ),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[]}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("Nome da instância não encontrado.");s(!0);const g={enabled:f.enabled,description:f.description,url:f.url,typebot:f.typebot,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await RQ(n.name,n.token,g),X.success(t("typebot.toast.success.create")),a(!1),u(),e()}catch(g){console.error(t("typebot.toast.error"),g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"default",className:"mr-5 text-white",children:[i.jsx(Qa,{}),i.jsx("span",{className:"hidden sm:inline",children:t("typebot.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("typebot.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("typebot.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("typebot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.typebotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"url",label:t("typebot.form.url.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"typebot",label:t("typebot.form.typebot.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("typebot.form.triggerType.label"),required:!0,options:[{label:t("typebot.form.triggerType.keyword"),value:"keyword"},{label:t("typebot.form.triggerType.all"),value:"all"},{label:t("typebot.form.triggerType.advanced"),value:"advanced"},{label:t("typebot.form.triggerType.none"),value:"none"}]}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("typebot.form.triggerOperator.label"),required:!0,options:[{label:t("typebot.form.triggerOperator.contains"),value:"contains"},{label:t("typebot.form.triggerOperator.equals"),value:"equals"},{label:t("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("typebot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:t("typebot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("typebot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("typebot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("typebot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("typebot.button.save")})})]})})]})]})}const M1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await MQ(e.name,r,n);t(s)}else console.error("Token ou nome da instância não encontrados.")}catch(r){console.error("Erro ao carregar sessões:",r)}};function VP({typebotId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&M1(n,a,e)},[n,e,l]);function u(){M1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await DQ(n.name,n.token,g,b),X.success(t("typebot.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("typebot.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("typebot.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:"Actions"}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("typebot.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"})," ",i.jsx("span",{className:"hidden sm:inline",children:t("typebot.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("typebot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("typebot.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{size:16})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("typebot.sessions.table.none")})})})]})]})]})]})}const BQ=k.object({enabled:k.boolean(),description:k.string(),url:k.string().url(),typebot:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number(),ignoreJids:k.array(k.string()).default([])});function zQ({typebotId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(BQ),defaultValues:{enabled:!0,description:"",url:"",typebot:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0,ignoreJids:[]}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await _Q(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,url:y.url,typebot:y.typebot,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,url:g.url,typebot:g.typebot,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await IQ(t.name,w,e,S),X.success(r("typebot.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await NQ(t.name,g,e),X.success(r("typebot.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/typebot`)):console.error("Token not found")}catch(g){console.error("Error:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Typebot: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("typebot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.typebotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"url",label:r("typebot.form.url.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"typebot",label:r("typebot.form.typebot.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("typebot.form.triggerType.label"),required:!0,options:[{label:r("typebot.form.triggerType.keyword"),value:"keyword"},{label:r("typebot.form.triggerType.all"),value:"all"},{label:r("typebot.form.triggerType.advanced"),value:"advanced"},{label:r("typebot.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("typebot.form.triggerOperator.label"),required:!0,options:[{label:r("typebot.form.triggerOperator.contains"),value:"contains"},{label:r("typebot.form.triggerOperator.equals"),value:"equals"},{label:r("typebot.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("typebot.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("typebot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("typebot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("typebot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("typebot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("typebot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("typebot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("typebot.form.delay.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("typebot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("typebot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("typebot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("typebot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("typebot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(VP,{typebotId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("typebot.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("typebot.button.update")})]})]})]})})]})}const D1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await UP(e.name,r);t(s)}else console.error("token not found.");n(!1)}catch(r){console.error("Error",r),n(!1)}};function A1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{typebotId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&D1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/typebot/${f}`)},d=()=>{D1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("typebot.title")}),i.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[i.jsx(VP,{}),i.jsx(FQ,{}),i.jsx($Q,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:f.description?i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:f.description}),i.jsxs("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:[f.url," - ",f.typebot]})]}):i.jsxs(i.Fragment,{children:[i.jsx("h4",{className:"text-base",children:f.url}),i.jsx("p",{className:"text-wrap text-sm font-normal text-muted-foreground",children:f.typebot})]})},f.id)):i.jsx(J,{variant:"link",children:e("typebot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-black"}),i.jsx(_r,{className:"",children:i.jsx(zQ,{typebotId:r,instance:n,resetTable:d})})]})]})]})}const HP=new ur,UQ=async(e,t)=>(await HP.getInstance().get(`/webhook/find/${e}`,{headers:{apikey:t}})).data,VQ=async(e,t,n)=>(await HP.getInstance().post(`/webhook/set/${e}`,n,{headers:{apikey:t}})).data,HQ=k.object({enabled:k.boolean(),url:k.string().url("Invalid URL format"),events:k.array(k.string()),webhookBase64:k.boolean(),webhookByEvents:k.boolean()});function WQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(HQ),defaultValues:{enabled:!1,url:"",events:[],webhookBase64:!1,webhookByEvents:!1}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await UQ(t.name,t.token);s.reset(c)}catch(c){console.error("Error:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,url:l.url,events:l.events,webhookBase64:l.webhookBase64,webhookByEvents:l.webhookByEvents};await VQ(t.name,t.token,f),X.success(e("webhook.toast.success"))}catch(f){console.error(e("webhook.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("webhook.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("webhook.form.enabled.label"),className:"w-full justify-between",helper:e("webhook.form.enabled.description")}),i.jsx(D,{name:"url",label:"URL",children:i.jsx(A,{})}),i.jsx(he,{name:"webhookByEvents",label:e("webhook.form.webhookByEvents.label"),className:"w-full justify-between",helper:e("webhook.form.webhookByEvents.description")}),i.jsx(he,{name:"webhookBase64",label:e("webhook.form.webhookBase64.label"),className:"w-full justify-between",helper:e("webhook.form.webhookBase64.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("webhook.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"webhook.button.saving":"webhook.button.save")})})]})})})})}const WP=new ur,GQ=async(e,t)=>(await WP.getInstance().get(`/websocket/find/${e}`,{headers:{apikey:t}})).data,qQ=async(e,t,n)=>(await WP.getInstance().post(`/websocket/set/${e}`,n,{headers:{apikey:t}})).data,KQ=k.object({enabled:k.boolean(),events:k.array(k.string())});function JQ(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),s=kt({resolver:Et(KQ),defaultValues:{enabled:!1,events:[]}});m.useEffect(()=>{(async()=>{if(t){r(!0);try{const c=await GQ(t.name,t.token);s.reset(c)}catch(c){console.error("Erro ao buscar dados do websocket:",c)}finally{r(!1)}}})()},[t,s]);const o=async l=>{var c,u,d;if(t){r(!0);try{const f={enabled:l.enabled,events:l.events};await qQ(t.name,t.token,f),X.success(e("websocket.toast.success"))}catch(f){console.error(e("websocket.toast.error"),f),X.error(`Error: ${(d=(u=(c=f==null?void 0:f.response)==null?void 0:c.data)==null?void 0:u.response)==null?void 0:d.message}`)}finally{r(!1)}}},a=["APPLICATION_STARTUP","QRCODE_UPDATED","MESSAGES_SET","MESSAGES_UPSERT","MESSAGES_UPDATE","MESSAGES_DELETE","SEND_MESSAGE","CONTACTS_SET","CONTACTS_UPSERT","CONTACTS_UPDATE","PRESENCE_UPDATE","CHATS_SET","CHATS_UPSERT","CHATS_UPDATE","CHATS_DELETE","GROUPS_UPSERT","GROUP_UPDATE","GROUP_PARTICIPANTS_UPDATE","CONNECTION_UPDATE","REMOVE_INSTANCE","LOGOUT_INSTANCE","LABELS_EDIT","LABELS_ASSOCIATION","CALL","TYPEBOT_START","TYPEBOT_CHANGE_STATUS"];return i.jsx(i.Fragment,{children:i.jsx(fr,{...s,children:i.jsx("form",{onSubmit:s.handleSubmit(o),className:"w-full space-y-6",children:i.jsxs("div",{children:[i.jsx("h3",{className:"mb-1 text-lg font-medium",children:e("websocket.title")}),i.jsx(na,{className:"my-4"}),i.jsxs("div",{className:"mx-4 space-y-2 divide-y [&>*]:p-4",children:[i.jsx(he,{name:"enabled",label:e("websocket.form.enabled.label"),className:"w-full justify-between",helper:e("websocket.form.enabled.description")}),i.jsx(aa,{control:s.control,name:"events",render:({field:l})=>i.jsxs(so,{className:"flex flex-col",children:[i.jsx(sr,{className:"my-2 text-lg",children:e("websocket.form.events.label")}),i.jsx(Ss,{children:i.jsx("div",{className:"flex flex-col gap-2 space-y-1 divide-y",children:a.sort((c,u)=>c.localeCompare(u)).map(c=>i.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3",children:[i.jsx(sr,{className:me("break-all",l.value.includes(c)?"text-foreground":"text-muted-foreground"),children:c}),i.jsx(Ol,{checked:l.value.includes(c),onCheckedChange:u=>{u?l.onChange([...l.value,c]):l.onChange(l.value.filter(d=>d!==c))}})]},c))})})]})})]}),i.jsx("div",{className:"mx-4 flex justify-end pt-6",children:i.jsx(J,{type:"submit",disabled:n,children:e(n?"websocket.button.saving":"websocket.button.save")})})]})})})})}const ZQ=k.object({serverUrl:k.string({required_error:"serverUrl is required"}).url("URL inválida"),apiKey:k.string({required_error:"ApiKey is required"})});function QQ(){const{t:e}=Le(),t=En(),n=kt({resolver:Et(ZQ),defaultValues:{serverUrl:window.location.protocol+"//"+window.location.host,apiKey:""}}),r=async s=>{const o=await pT(s.serverUrl);if(!o||!o.version){gT(),n.setError("serverUrl",{type:"manual",message:e("login.message.invalidServer")});return}if(!await dL(s.serverUrl,s.apiKey)){n.setError("apiKey",{type:"manual",message:e("login.message.invalidCredentials")});return}if(!await uL(s.serverUrl,s.apiKey)){X.error(e("login.message.invalidCredentials"));return}localStorage.setItem("version",o.version),localStorage.setItem("clientName",o.clientName),t("/manager/")};return i.jsxs("div",{className:"flex min-h-screen flex-col",children:[i.jsx("div",{className:"flex items-center justify-center pt-2",children:i.jsx("img",{className:"h-10",src:"/assets/images/evolution-logo.png",alt:"logo"})}),i.jsx("div",{className:"flex flex-1 items-center justify-center p-8",children:i.jsxs(wa,{className:"b-none w-[350px] shadow-none",children:[i.jsxs(Sa,{children:[i.jsx(Dc,{className:"text-center",children:e("login.title")}),i.jsx(lR,{className:"text-center",children:e("login.description")})]}),i.jsx(fr,{...n,children:i.jsxs("form",{onSubmit:n.handleSubmit(r),children:[i.jsx(Ca,{children:i.jsxs("div",{className:"grid w-full items-center gap-4",children:[i.jsx(D,{required:!0,name:"serverUrl",label:e("login.form.serverUrl"),children:i.jsx(A,{})}),i.jsx(D,{required:!0,name:"apiKey",label:e("login.form.apiKey"),children:i.jsx(A,{type:"password"})})]})}),i.jsx(wg,{className:"flex justify-center",children:i.jsx(J,{className:"w-full",type:"submit",children:e("login.button.login")})})]})})]})}),i.jsx(fb,{})]})}const io=new ur,GP=async(e,t)=>(await io.getInstance().get(`/generic/find/${e}`,{headers:{apikey:t}})).data,YQ=async(e,t,n)=>(await io.getInstance().get(`/generic/fetch/${n}/${e}`,{headers:{apikey:t}})).data,XQ=async(e,t,n)=>(await io.getInstance().post(`/generic/create/${e}`,n,{headers:{apikey:t}})).data,eY=async(e,t,n,r)=>(await io.getInstance().put(`/generic/update/${n}/${e}`,r,{headers:{apikey:t}})).data,tY=async(e,t,n)=>(await io.getInstance().delete(`/generic/delete/${n}/${e}`,{headers:{apikey:t}})).data,nY=async(e,t)=>(await io.getInstance().get(`/generic/fetchSettings/${e}`,{headers:{apikey:t}})).data,rY=async(e,t,n)=>(await io.getInstance().post(`/generic/settings/${e}`,n,{headers:{apikey:t}})).data,sY=async(e,t,n)=>(await io.getInstance().get(`/generic/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,oY=async(e,t,n,r)=>(await io.getInstance().post(`/generic/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,aY=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),botIdFallback:k.union([k.null(),k.string()]).optional()}),F1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await nY(e.name,r);t(s);const o=await GP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function iY(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(aY),defaultValues:{expire:"0",keywordFinish:e("genericBot.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("genericBot.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],botIdFallback:void 0}});m.useEffect(()=>{n&&F1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,botIdFallback:s.botIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),botIdFallback:f.botIdFallback||void 0,ignoreJids:f.ignoreJids};await rY(t.name,t.token,g),X.success(e("genericBot.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){F1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("genericBot.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("genericBot.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"botIdFallback",label:e("genericBot.form.botIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("genericBot.form.ignoreJids.label"),placeholder:e("genericBot.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("genericBot.button.save")})})]})})]})]})}const lY=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function cY({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(lY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await XQ(n.name,n.token,g),X.success(t("genericBot.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("genericBot.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("genericBot.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("genericBot.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("genericBot.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.genericBotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:t("genericBot.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("genericBot.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("genericBot.form.triggerType.label"),options:[{label:t("genericBot.form.triggerType.keyword"),value:"keyword"},{label:t("genericBot.form.triggerType.all"),value:"all"},{label:t("genericBot.form.triggerType.advanced"),value:"advanced"},{label:t("genericBot.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("genericBot.form.triggerOperator.label"),options:[{label:t("genericBot.form.triggerOperator.contains"),value:"contains"},{label:t("genericBot.form.triggerOperator.equals"),value:"equals"},{label:t("genericBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("genericBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("genericBot.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("genericBot.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("genericBot.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("genericBot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("genericBot.button.save")})})]})})]})]})}const L1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await sY(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function qP({genericBotId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&L1(n,a,e)},[n,e,l]);function u(){L1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await oY(n.name,n.token,g,b),X.success(t("genericBot.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("genericBot.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("genericBot.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("genericBot.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("genericBot.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("genericBot.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("genericBot.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("genericBot.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("genericBot.sessions.table.none")})})})]})]})]})]})}const uY=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function dY({genericBotId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(uY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await YQ(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await eY(t.name,w,e,S),X.success(r("genericBot.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await tY(t.name,g,e),X.success(r("genericBot.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/generic`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir genericBot:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["GenericBot: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("genericBot.form.description.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.genericBotSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:r("genericBot.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("genericBot.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("genericBot.form.triggerType.label"),options:[{label:r("genericBot.form.triggerType.keyword"),value:"keyword"},{label:r("genericBot.form.triggerType.all"),value:"all"},{label:r("genericBot.form.triggerType.advanced"),value:"advanced"},{label:r("genericBot.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("genericBot.form.triggerOperator.label"),options:[{label:r("genericBot.form.triggerOperator.contains"),value:"contains"},{label:r("genericBot.form.triggerOperator.equals"),value:"equals"},{label:r("genericBot.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("genericBot.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("genericBot.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("genericBot.form.triggerValue.label"),children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("genericBot.form.triggerConditions.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("genericBot.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("genericBot.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("genericBot.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("genericBot.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("genericBot.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("genericBot.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("genericBot.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("genericBot.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("genericBot.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(qP,{genericBotId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("genericBot.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("genericBot.button.update")})]})]})]})})]})}const $1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await GP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function B1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{genericBotId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&$1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/generic/${f}`)},d=()=>{$1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("genericBot.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(qP,{}),i.jsx(iY,{}),i.jsx(cY,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:f.description||f.id})},f.id)):i.jsx(J,{variant:"link",children:e("genericBot.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(dY,{genericBotId:r,instance:n,resetTable:d})})]})]})]})}const lo=new ur,KP=async(e,t)=>(await lo.getInstance().get(`/flowise/find/${e}`,{headers:{apikey:t}})).data,fY=async(e,t,n)=>(await lo.getInstance().get(`/flowise/fetch/${n}/${e}`,{headers:{apikey:t}})).data,pY=async(e,t,n)=>(await lo.getInstance().post(`/flowise/create/${e}`,n,{headers:{apikey:t}})).data,gY=async(e,t,n,r)=>(await lo.getInstance().put(`/flowise/update/${n}/${e}`,r,{headers:{apikey:t}})).data,hY=async(e,t,n)=>(await lo.getInstance().delete(`/flowise/delete/${n}/${e}`,{headers:{apikey:t}})).data,mY=async(e,t)=>(await lo.getInstance().get(`/flowise/fetchSettings/${e}`,{headers:{apikey:t}})).data,vY=async(e,t,n)=>(await lo.getInstance().post(`/flowise/settings/${e}`,n,{headers:{apikey:t}})).data,yY=async(e,t,n)=>(await lo.getInstance().get(`/flowise/fetchSessions/${n}/${e}`,{headers:{apikey:t}})).data,bY=async(e,t,n,r)=>(await lo.getInstance().post(`/flowise/changeStatus/${e}`,{remoteJid:n,status:r},{headers:{apikey:t}})).data,xY=k.object({expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string(),ignoreJids:k.array(k.string()).default([]),flowiseIdFallback:k.union([k.null(),k.string()]).optional()}),z1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await mY(e.name,r);t(s);const o=await KP(e.name,r);n(o)}else console.error("Token not found.")}catch(r){console.error("Error:",r)}};function wY(){const{t:e}=Le(),{instance:t}=st(),[n,r]=m.useState(!1),[s,o]=m.useState(),[a,l]=m.useState([]),c=kt({resolver:Et(xY),defaultValues:{expire:"0",keywordFinish:e("flowise.form.examples.keywordFinish"),delayMessage:"1000",unknownMessage:e("flowise.form.examples.unknownMessage"),listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0",ignoreJids:[],flowiseIdFallback:void 0}});m.useEffect(()=>{n&&z1(t,o,l)},[t,n]),m.useEffect(()=>{s&&c.reset({expire:s!=null&&s.expire?s.expire.toString():"0",keywordFinish:s.keywordFinish,delayMessage:s.delayMessage?s.delayMessage.toString():"0",unknownMessage:s.unknownMessage,listeningFromMe:s.listeningFromMe,stopBotFromMe:s.stopBotFromMe,keepOpen:s.keepOpen,debounceTime:s.debounceTime?s.debounceTime.toString():"0",ignoreJids:s.ignoreJids,flowiseIdFallback:s.flowiseIdFallback})},[s]);const u=async f=>{var p,h,v;try{if(!t||!t.name)throw new Error("instance not found.");const g={expire:parseInt(f.expire),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime),flowiseIdFallback:f.flowiseIdFallback||void 0,ignoreJids:f.ignoreJids};await vY(t.name,t.token,g),X.success(e("flowise.toast.defaultSettings.success"))}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}};function d(){z1(t,o,l)}return i.jsxs(yt,{open:n,onOpenChange:r,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Za,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:e("flowise.defaultSettings")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:d,children:[i.jsx(gt,{children:i.jsx(At,{children:e("flowise.defaultSettings")})}),i.jsx(dr,{...c,children:i.jsxs("form",{className:"w-full space-y-6",onSubmit:c.handleSubmit(u),children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(et,{name:"flowiseIdFallback",label:e("flowise.form.flowiseIdFallback.label"),options:(a==null?void 0:a.filter(f=>!!f.id).map(f=>({label:f.description,value:f.id})))??[]}),i.jsx(D,{name:"expire",label:e("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:e("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:e("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:e("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:e("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:e("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:e("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:e("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})}),i.jsx(Ml,{name:"ignoreJids",label:e("flowise.form.ignoreJids.label"),placeholder:e("flowise.form.ignoreJids.placeholder")})]})}),i.jsx(Jt,{children:i.jsx(J,{type:"submit",children:e("flowise.button.save")})})]})})]})]})}const SY=k.object({enabled:k.boolean(),description:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.string(),keywordFinish:k.string(),delayMessage:k.string(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.string()});function CY({resetTable:e}){const{t}=Le(),{instance:n}=st(),[r,s]=m.useState(!1),[o,a]=m.useState(!1),l=kt({resolver:Et(SY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:"0",keywordFinish:"",delayMessage:"0",unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:"0"}}),c=async f=>{var p,h,v;try{if(!n||!n.name)throw new Error("instance not found");s(!0);const g={enabled:f.enabled,description:f.description,apiUrl:f.apiUrl,apiKey:f.apiKey,triggerType:f.triggerType,triggerOperator:f.triggerOperator||"",triggerValue:f.triggerValue||"",expire:parseInt(f.expire,10),keywordFinish:f.keywordFinish,delayMessage:parseInt(f.delayMessage,10),unknownMessage:f.unknownMessage,listeningFromMe:f.listeningFromMe,stopBotFromMe:f.stopBotFromMe,keepOpen:f.keepOpen,debounceTime:parseInt(f.debounceTime,10)};await pY(n.name,n.token,g),X.success(t("flowise.toast.success.create")),a(!1),u(),e()}catch(g){console.error("Error:",g),X.error(`Error: ${(v=(h=(p=g==null?void 0:g.response)==null?void 0:p.data)==null?void 0:h.response)==null?void 0:v.message}`)}finally{s(!1)}};function u(){l.reset()}const d=l.watch("triggerType");return i.jsxs(yt,{open:o,onOpenChange:a,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{size:"sm",children:[i.jsx(Qa,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.button.create")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-h-[600px] sm:max-w-[740px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("flowise.form.title")})}),i.jsx(dr,{...l,children:i.jsxs("form",{onSubmit:l.handleSubmit(c),className:"w-full space-y-6",children:[i.jsx("div",{children:i.jsxs("div",{className:"space-y-4",children:[i.jsx(he,{name:"enabled",label:t("flowise.form.enabled.label"),reverse:!0}),i.jsx(D,{name:"description",label:t("flowise.form.description.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.flowiseSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:t("flowise.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:t("flowise.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:t("flowise.form.triggerType.label"),options:[{label:t("flowise.form.triggerType.keyword"),value:"keyword"},{label:t("flowise.form.triggerType.all"),value:"all"},{label:t("flowise.form.triggerType.advanced"),value:"advanced"},{label:t("flowise.form.triggerType.none"),value:"none"}],required:!0}),d==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:t("flowise.form.triggerOperator.label"),options:[{label:t("flowise.form.triggerOperator.contains"),value:"contains"},{label:t("flowise.form.triggerOperator.equals"),value:"equals"},{label:t("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:t("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:t("flowise.form.triggerOperator.regex"),value:"regex"}],required:!0}),i.jsx(D,{name:"triggerValue",label:t("flowise.form.triggerValue.label"),required:!0,children:i.jsx(A,{})})]}),d==="advanced"&&i.jsx(D,{name:"triggerValue",label:t("flowise.form.triggerConditions.label"),required:!0,children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:t("flowise.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:t("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:t("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:t("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:t("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:t("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:t("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:t("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:t("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})}),i.jsx(Jt,{children:i.jsx(J,{disabled:r,type:"submit",children:t("flowise.button.save")})})]})})]})]})}const U1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await yY(e.name,r,n);t(s)}else console.error("Token not found.")}catch(r){console.error("Errors:",r)}};function JP({flowiseId:e}){var h,v;const{t}=Le(),{instance:n}=st(),[r,s]=m.useState([]),[o,a]=m.useState([]),[l,c]=m.useState(!1);m.useEffect(()=>{l&&U1(n,a,e)},[n,e,l]);function u(){U1(n,a,e)}const d=async(g,b)=>{var y,x,w;try{if(!n)return;await bY(n.name,n.token,g,b),X.success(t("flowise.toast.success.status")),u()}catch(S){console.error("Error:",S),X.error(`Error : ${(w=(x=(y=S==null?void 0:S.response)==null?void 0:y.data)==null?void 0:x.response)==null?void 0:w.message}`)}},f=[{accessorKey:"remoteJid",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.remoteJid")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("remoteJid")})},{accessorKey:"pushName",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.pushName")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("pushName")})},{accessorKey:"sessionId",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.sessionId")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("sessionId")})},{accessorKey:"status",header:()=>i.jsx("div",{className:"text-center",children:t("flowise.sessions.table.status")}),cell:({row:g})=>i.jsx("div",{children:g.getValue("status")})},{id:"actions",enableHiding:!1,cell:({row:g})=>{const b=g.original;return i.jsxs(to,{children:[i.jsx(no,{asChild:!0,children:i.jsxs(J,{variant:"ghost",className:"h-8 w-8 p-0",children:[i.jsx("span",{className:"sr-only",children:t("flowise.sessions.table.actions.title")}),i.jsx(Sl,{className:"h-4 w-4"})]})}),i.jsxs(Qr,{align:"end",children:[i.jsx(ei,{children:t("flowise.sessions.table.actions.title")}),i.jsx(ra,{}),b.status!=="opened"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"opened"),children:[i.jsx(Ku,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.open")]}),b.status!=="paused"&&b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"paused"),children:[i.jsx(qu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.pause")]}),b.status!=="closed"&&i.jsxs(at,{onClick:()=>d(b.remoteJid,"closed"),children:[i.jsx(Hu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.close")]}),i.jsxs(at,{onClick:()=>d(b.remoteJid,"delete"),children:[i.jsx(Wu,{className:"mr-2 h-4 w-4"}),t("flowise.sessions.table.actions.delete")]})]})]})}}],p=Ul({data:o,columns:f,onSortingChange:s,getCoreRowModel:Ll(),getPaginationRowModel:Bl(),getSortedRowModel:zl(),getFilteredRowModel:$l(),state:{sorting:r}});return i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsxs(J,{variant:"secondary",size:"sm",children:[i.jsx(Gu,{size:16,className:"mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("flowise.sessions.label")})]})}),i.jsxs(pt,{className:"overflow-y-auto sm:max-w-[950px]",onCloseAutoFocus:u,children:[i.jsx(gt,{children:i.jsx(At,{children:t("flowise.sessions.label")})}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between gap-6 p-5",children:[i.jsx(A,{placeholder:t("flowise.sessions.search"),value:((h=p.getColumn("remoteJid"))==null?void 0:h.getFilterValue())??"",onChange:g=>{var b;return(b=p.getColumn("remoteJid"))==null?void 0:b.setFilterValue(g.target.value)}}),i.jsx(J,{variant:"outline",onClick:u,size:"icon",children:i.jsx(Ju,{})})]}),i.jsxs(ri,{children:[i.jsx(si,{children:p.getHeaderGroups().map(g=>i.jsx(en,{children:g.headers.map(b=>i.jsx(ai,{children:b.isPlaceholder?null:Rr(b.column.columnDef.header,b.getContext())},b.id))},g.id))}),i.jsx(oi,{children:(v=p.getRowModel().rows)!=null&&v.length?p.getRowModel().rows.map(g=>i.jsx(en,{"data-state":g.getIsSelected()&&"selected",children:g.getVisibleCells().map(b=>i.jsx(ir,{children:Rr(b.column.columnDef.cell,b.getContext())},b.id))},g.id)):i.jsx(en,{children:i.jsx(ir,{colSpan:f.length,className:"h-24 text-center",children:t("flowise.sessions.table.none")})})})]})]})]})]})}const kY=k.object({enabled:k.boolean(),description:k.string(),botType:k.string(),apiUrl:k.string(),apiKey:k.string(),triggerType:k.string(),triggerOperator:k.string().optional(),triggerValue:k.string().optional(),expire:k.coerce.number(),keywordFinish:k.string(),delayMessage:k.coerce.number(),unknownMessage:k.string(),listeningFromMe:k.boolean(),stopBotFromMe:k.boolean(),keepOpen:k.boolean(),debounceTime:k.coerce.number()});function EY({flowiseId:e,instance:t,resetTable:n}){const{t:r}=Le(),[,s]=m.useState(""),[o,a]=m.useState(!0),[l,c]=m.useState(!1),u=En(),d=kt({resolver:Et(kY),defaultValues:{enabled:!0,description:"",apiUrl:"",apiKey:"",triggerType:"keyword",triggerOperator:"contains",triggerValue:"",expire:0,keywordFinish:"",delayMessage:0,unknownMessage:"",listeningFromMe:!1,stopBotFromMe:!1,keepOpen:!1,debounceTime:0}});m.useEffect(()=>{(async()=>{try{const b=localStorage.getItem("token");if(b&&t&&t.name&&e){s(b);const y=await fY(t.name,b,e);d.reset({enabled:y.enabled,description:y.description,apiUrl:y.apiUrl,apiKey:y.apiKey,triggerType:y.triggerType,triggerOperator:y.triggerOperator,triggerValue:y.triggerValue,expire:y.expire,keywordFinish:y.keywordFinish,delayMessage:y.delayMessage,unknownMessage:y.unknownMessage,listeningFromMe:y.listeningFromMe,stopBotFromMe:y.stopBotFromMe,keepOpen:y.keepOpen,debounceTime:y.debounceTime})}else console.error("Token not found.");a(!1)}catch(b){console.error("Error:",b),a(!1)}})()},[d,t,e]);const f=async g=>{var b,y,x;try{const w=localStorage.getItem("token");if(w&&t&&t.name&&e){const S={enabled:g.enabled,description:g.description,apiUrl:g.apiUrl,apiKey:g.apiKey,triggerType:g.triggerType,triggerOperator:g.triggerOperator||"",triggerValue:g.triggerValue||"",expire:g.expire,keywordFinish:g.keywordFinish,delayMessage:g.delayMessage,unknownMessage:g.unknownMessage,listeningFromMe:g.listeningFromMe,stopBotFromMe:g.stopBotFromMe,keepOpen:g.keepOpen,debounceTime:g.debounceTime};await gY(t.name,w,e,S),X.success(r("flowise.toast.success.update"))}else console.error("Token not found")}catch(w){console.error("Error:",w),X.error(`Error: ${(x=(y=(b=w==null?void 0:w.response)==null?void 0:b.data)==null?void 0:y.response)==null?void 0:x.message}`)}},p=async()=>{try{const g=localStorage.getItem("token");g&&t&&t.name&&e?(await hY(t.name,g,e),X.success(r("flowise.toast.success.delete")),c(!1),n(),u(`/manager/instance/${t.id}/flowise`)):console.error("instance not found")}catch(g){console.error("Erro ao excluir flowise:",g)}},h=d.watch("description"),v=d.watch("triggerType");return i.jsxs(i.Fragment,{children:[o&&i.jsx(or,{}),!o&&i.jsx(fr,{...d,children:i.jsxs("form",{onSubmit:d.handleSubmit(f),className:"w-full space-y-6 pl-4 pr-2",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[i.jsxs("h3",{className:"mb-4 text-lg font-medium",children:["Flowise: ",h]}),i.jsx(he,{name:"enabled",className:"flex items-center gap-3"})]}),i.jsxs("div",{className:"space-y-4",children:[i.jsx(D,{name:"description",label:r("flowise.form.description.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.flowiseSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"apiUrl",label:r("flowise.form.apiUrl.label"),required:!0,children:i.jsx(A,{})}),i.jsx(D,{name:"apiKey",label:r("flowise.form.apiKey.label"),children:i.jsx(A,{type:"password"})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.triggerSettings.label")}),i.jsx(Ze,{})]}),i.jsx(et,{name:"triggerType",label:r("flowise.form.triggerType.label"),options:[{label:r("flowise.form.triggerType.keyword"),value:"keyword"},{label:r("flowise.form.triggerType.all"),value:"all"},{label:r("flowise.form.triggerType.advanced"),value:"advanced"},{label:r("flowise.form.triggerType.none"),value:"none"}]}),v==="keyword"&&i.jsxs(i.Fragment,{children:[i.jsx(et,{name:"triggerOperator",label:r("flowise.form.triggerOperator.label"),options:[{label:r("flowise.form.triggerOperator.contains"),value:"contains"},{label:r("flowise.form.triggerOperator.equals"),value:"equals"},{label:r("flowise.form.triggerOperator.startsWith"),value:"startsWith"},{label:r("flowise.form.triggerOperator.endsWith"),value:"endsWith"},{label:r("flowise.form.triggerOperator.regex"),value:"regex"}]}),i.jsx(D,{name:"triggerValue",label:r("flowise.form.triggerValue.label"),children:i.jsx(A,{})})]}),v==="advanced"&&i.jsx(D,{name:"triggerValue",label:r("flowise.form.triggerConditions.label"),children:i.jsx(A,{})}),i.jsxs("div",{className:"flex flex-col",children:[i.jsx("h3",{className:"my-4 text-lg font-medium",children:r("flowise.form.generalSettings.label")}),i.jsx(Ze,{})]}),i.jsx(D,{name:"expire",label:r("flowise.form.expire.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"keywordFinish",label:r("flowise.form.keywordFinish.label"),children:i.jsx(A,{})}),i.jsx(D,{name:"delayMessage",label:r("flowise.form.delayMessage.label"),children:i.jsx(A,{type:"number"})}),i.jsx(D,{name:"unknownMessage",label:r("flowise.form.unknownMessage.label"),children:i.jsx(A,{})}),i.jsx(he,{name:"listeningFromMe",label:r("flowise.form.listeningFromMe.label"),reverse:!0}),i.jsx(he,{name:"stopBotFromMe",label:r("flowise.form.stopBotFromMe.label"),reverse:!0}),i.jsx(he,{name:"keepOpen",label:r("flowise.form.keepOpen.label"),reverse:!0}),i.jsx(D,{name:"debounceTime",label:r("flowise.form.debounceTime.label"),children:i.jsx(A,{type:"number"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx(JP,{flowiseId:e}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs(yt,{open:l,onOpenChange:c,children:[i.jsx(Rt,{asChild:!0,children:i.jsx(J,{variant:"destructive",size:"sm",children:r("flowise.button.delete")})}),i.jsx(pt,{children:i.jsxs(gt,{children:[i.jsx(At,{children:r("modal.delete.title")}),i.jsx(ti,{children:r("modal.delete.messageSingle")}),i.jsxs(Jt,{children:[i.jsx(J,{size:"sm",variant:"outline",onClick:()=>c(!1),children:r("button.cancel")}),i.jsx(J,{variant:"destructive",onClick:p,children:r("button.delete")})]})]})})]}),i.jsx(J,{type:"submit",children:r("flowise.button.update")})]})]})]})})]})}const V1=async(e,t,n)=>{try{const r=localStorage.getItem("token");if(r&&e&&e.name){const s=await KP(e.name,r);t(s)}else console.error("Token not found");n(!1)}catch(r){console.error("Error:",r),n(!1)}};function H1(){const{t:e}=Le(),t=Fl("(min-width: 768px)"),{instance:n}=st(),{flowiseId:r}=Ys(),[s,o]=m.useState(!0),[a,l]=m.useState([]),c=En();m.useEffect(()=>{n&&V1(n,l,o)},[n]);const u=f=>{n&&c(`/manager/instance/${n.id}/flowise/${f}`)},d=()=>{V1(n,l,o)};return i.jsxs("main",{className:"pt-5",children:[i.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[i.jsx("h3",{className:"text-lg font-medium",children:e("flowise.title")}),i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsx(JP,{}),i.jsx(wY,{}),i.jsx(CY,{resetTable:d})]})]}),i.jsx(Ze,{className:"my-4"}),i.jsxs(Dl,{direction:t?"horizontal":"vertical",children:[i.jsx(_r,{defaultSize:35,className:"pr-4",children:i.jsx("div",{className:"flex flex-col gap-3",children:s?i.jsx(or,{}):i.jsx(i.Fragment,{children:a&&a.length>0&&Array.isArray(a)?a.map(f=>i.jsx(J,{className:"flex h-auto flex-col items-start justify-start",onClick:()=>u(`${f.id}`),variant:r===f.id?"secondary":"outline",children:i.jsx("h4",{className:"text-base",children:f.description||f.id})},f.id)):i.jsx(J,{variant:"link",children:e("flowise.table.none")})})})}),r&&i.jsxs(i.Fragment,{children:[i.jsx(Al,{withHandle:!0,className:"border border-border"}),i.jsx(_r,{className:"",children:i.jsx(EY,{flowiseId:r,instance:n,resetTable:d})})]})]})]})}const TY=lF([{path:"/manager/login",element:i.jsx(FF,{children:i.jsx(QQ,{})})},{path:"/manager/",element:i.jsx(zt,{children:i.jsx(Xz,{children:i.jsx(xK,{})})})},{path:"/manager/instance/:instanceId/dashboard",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx($J,{})})})},{path:"/manager/instance/:instanceId/chat",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(x1,{})})})},{path:"/manager/instance/:instanceId/chat/:remoteJid",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(x1,{})})})},{path:"/manager/instance/:instanceId/settings",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(CQ,{})})})},{path:"/manager/instance/:instanceId/openai",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(P1,{})})})},{path:"/manager/instance/:instanceId/openai/:botId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(P1,{})})})},{path:"/manager/instance/:instanceId/webhook",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(WQ,{})})})},{path:"/manager/instance/:instanceId/websocket",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(JQ,{})})})},{path:"/manager/instance/:instanceId/rabbitmq",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(wQ,{})})})},{path:"/manager/instance/:instanceId/sqs",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(jQ,{})})})},{path:"/manager/instance/:instanceId/chatwoot",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(iJ,{})})})},{path:"/manager/instance/:instanceId/typebot",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(A1,{})})})},{path:"/manager/instance/:instanceId/typebot/:typebotId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(A1,{})})})},{path:"/manager/instance/:instanceId/dify",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(_1,{})})})},{path:"/manager/instance/:instanceId/dify/:difyId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(_1,{})})})},{path:"/manager/instance/:instanceId/generic",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(B1,{})})})},{path:"/manager/instance/:instanceId/generic/:genericBotId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(B1,{})})})},{path:"/manager/instance/:instanceId/flowise",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(H1,{})})})},{path:"/manager/instance/:instanceId/flowise/:flowiseId",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(H1,{})})})},{path:"/manager/instance/:instanceId/proxy",element:i.jsx(zt,{children:i.jsx(Wt,{children:i.jsx(vQ,{})})})}]),jY={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console&&console[e]&&console[e].apply(console,t)}};class Cp{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.init(t,n)}init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=t||jY,this.options=n,this.debug=n.debug}log(){for(var t=arguments.length,n=new Array(t),r=0;r{this.observers[r]||(this.observers[r]=new Map);const s=this.observers[r].get(n)||0;this.observers[r].set(n,s+1)}),this}off(t,n){if(this.observers[t]){if(!n){delete this.observers[t];return}this.observers[t].delete(n)}}emit(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s{let[l,c]=a;for(let u=0;u{let[l,c]=a;for(let u=0;u{let e,t;const n=new Promise((r,s)=>{e=r,t=s});return n.resolve=e,n.reject=t,n},W1=e=>e==null?"":""+e,_Y=(e,t,n)=>{e.forEach(r=>{t[r]&&(n[r]=t[r])})},RY=/###/g,G1=e=>e&&e.indexOf("###")>-1?e.replace(RY,"."):e,q1=e=>!e||typeof e=="string",zc=(e,t,n)=>{const r=typeof t!="string"?t:t.split(".");let s=0;for(;s{const{obj:r,k:s}=zc(e,t,Object);if(r!==void 0||t.length===1){r[s]=n;return}let o=t[t.length-1],a=t.slice(0,t.length-1),l=zc(e,a,Object);for(;l.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),l=zc(e,a,Object),l&&l.obj&&typeof l.obj[`${l.k}.${o}`]<"u"&&(l.obj=void 0);l.obj[`${l.k}.${o}`]=n},IY=(e,t,n,r)=>{const{obj:s,k:o}=zc(e,t,Object);s[o]=s[o]||[],s[o].push(n)},kp=(e,t)=>{const{obj:n,k:r}=zc(e,t);if(n)return n[r]},NY=(e,t,n)=>{const r=kp(e,n);return r!==void 0?r:kp(t,n)},ZP=(e,t,n)=>{for(const r in t)r!=="__proto__"&&r!=="constructor"&&(r in e?typeof e[r]=="string"||e[r]instanceof String||typeof t[r]=="string"||t[r]instanceof String?n&&(e[r]=t[r]):ZP(e[r],t[r],n):e[r]=t[r]);return e},wi=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var PY={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};const OY=e=>typeof e=="string"?e.replace(/[&<>"'\/]/g,t=>PY[t]):e;class MY{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const n=this.regExpMap.get(t);if(n!==void 0)return n;const r=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,r),this.regExpQueue.push(t),r}}const DY=[" ",",","?","!",";"],AY=new MY(20),FY=(e,t,n)=>{t=t||"",n=n||"";const r=DY.filter(a=>t.indexOf(a)<0&&n.indexOf(a)<0);if(r.length===0)return!0;const s=AY.getRegExp(`(${r.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!s.test(e);if(!o){const a=e.indexOf(n);a>0&&!s.test(e.substring(0,a))&&(o=!0)}return o},ay=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:".";if(!e)return;if(e[t])return e[t];const r=t.split(n);let s=e;for(let o=0;o-1&&ce&&e.indexOf("_")>0?e.replace("_","-"):e;class J1 extends Gg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const n=this.options.ns.indexOf(t);n>-1&&this.options.ns.splice(n,1)}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=s.keySeparator!==void 0?s.keySeparator:this.options.keySeparator,a=s.ignoreJSONStructure!==void 0?s.ignoreJSONStructure:this.options.ignoreJSONStructure;let l;t.indexOf(".")>-1?l=t.split("."):(l=[t,n],r&&(Array.isArray(r)?l.push(...r):typeof r=="string"&&o?l.push(...r.split(o)):l.push(r)));const c=kp(this.data,l);return!c&&!n&&!r&&t.indexOf(".")>-1&&(t=l[0],n=l[1],r=l.slice(2).join(".")),c||!a||typeof r!="string"?c:ay(this.data&&this.data[t]&&this.data[t][n],r,o)}addResource(t,n,r,s){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{silent:!1};const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let l=[t,n];r&&(l=l.concat(a?r.split(a):r)),t.indexOf(".")>-1&&(l=t.split("."),s=n,n=l[1]),this.addNamespaces(n),K1(this.data,l,s),o.silent||this.emit("added",t,n,r,s)}addResources(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{silent:!1};for(const o in r)(typeof r[o]=="string"||Array.isArray(r[o]))&&this.addResource(t,n,o,r[o],{silent:!0});s.silent||this.emit("added",t,n,r)}addResourceBundle(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{silent:!1,skipCopy:!1},l=[t,n];t.indexOf(".")>-1&&(l=t.split("."),s=r,r=n,n=l[1]),this.addNamespaces(n);let c=kp(this.data,l)||{};a.skipCopy||(r=JSON.parse(JSON.stringify(r))),s?ZP(c,r,o):c={...c,...r},K1(this.data,l,c),a.silent||this.emit("added",t,n,r)}removeResourceBundle(t,n){this.hasResourceBundle(t,n)&&delete this.data[t][n],this.removeNamespaces(n),this.emit("removed",t,n)}hasResourceBundle(t,n){return this.getResource(t,n)!==void 0}getResourceBundle(t,n){return n||(n=this.options.defaultNS),this.options.compatibilityAPI==="v1"?{...this.getResource(t,n)}:this.getResource(t,n)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const n=this.getDataByLanguage(t);return!!(n&&Object.keys(n)||[]).find(s=>n[s]&&Object.keys(n[s]).length>0)}toJSON(){return this.data}}var QP={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,n,r,s){return e.forEach(o=>{this.processors[o]&&(t=this.processors[o].process(t,n,r,s))}),t}};const Z1={};class Tp extends Gg{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),_Y(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],t,this),this.options=n,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=gs.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}};if(t==null)return!1;const r=this.resolve(t,n);return r&&r.res!==void 0}extractFromKey(t,n){let r=n.nsSeparator!==void 0?n.nsSeparator:this.options.nsSeparator;r===void 0&&(r=":");const s=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator;let o=n.ns||this.options.defaultNS||[];const a=r&&t.indexOf(r)>-1,l=!this.options.userDefinedKeySeparator&&!n.keySeparator&&!this.options.userDefinedNsSeparator&&!n.nsSeparator&&!FY(t,r,s);if(a&&!l){const c=t.match(this.interpolator.nestingRegexp);if(c&&c.length>0)return{key:t,namespaces:o};const u=t.split(r);(r!==s||r===s&&this.options.ns.indexOf(u[0])>-1)&&(o=u.shift()),t=u.join(s)}return typeof o=="string"&&(o=[o]),{key:t,namespaces:o}}translate(t,n,r){if(typeof n!="object"&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),typeof n=="object"&&(n={...n}),n||(n={}),t==null)return"";Array.isArray(t)||(t=[String(t)]);const s=n.returnDetails!==void 0?n.returnDetails:this.options.returnDetails,o=n.keySeparator!==void 0?n.keySeparator:this.options.keySeparator,{key:a,namespaces:l}=this.extractFromKey(t[t.length-1],n),c=l[l.length-1],u=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(u&&u.toLowerCase()==="cimode"){if(d){const S=n.nsSeparator||this.options.nsSeparator;return s?{res:`${c}${S}${a}`,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:`${c}${S}${a}`}return s?{res:a,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:c,usedParams:this.getUsedParamsDetails(n)}:a}const f=this.resolve(t,n);let p=f&&f.res;const h=f&&f.usedKey||a,v=f&&f.exactUsedKey||a,g=Object.prototype.toString.apply(p),b=["[object Number]","[object Function]","[object RegExp]"],y=n.joinArrays!==void 0?n.joinArrays:this.options.joinArrays,x=!this.i18nFormat||this.i18nFormat.handleAsObject;if(x&&p&&(typeof p!="string"&&typeof p!="boolean"&&typeof p!="number")&&b.indexOf(g)<0&&!(typeof y=="string"&&Array.isArray(p))){if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(h,p,{...n,ns:l}):`key '${a} (${this.language})' returned an object instead of string.`;return s?(f.res=S,f.usedParams=this.getUsedParamsDetails(n),f):S}if(o){const S=Array.isArray(p),E=S?[]:{},C=S?v:h;for(const T in p)if(Object.prototype.hasOwnProperty.call(p,T)){const j=`${C}${o}${T}`;E[T]=this.translate(j,{...n,joinArrays:!1,ns:l}),E[T]===j&&(E[T]=p[T])}p=E}}else if(x&&typeof y=="string"&&Array.isArray(p))p=p.join(y),p&&(p=this.extendTranslation(p,t,n,r));else{let S=!1,E=!1;const C=n.count!==void 0&&typeof n.count!="string",T=Tp.hasDefaultValue(n),j=C?this.pluralResolver.getSuffix(u,n.count,n):"",I=n.ordinal&&C?this.pluralResolver.getSuffix(u,n.count,{ordinal:!1}):"",P=C&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),V=P&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${j}`]||n[`defaultValue${I}`]||n.defaultValue;!this.isValidLookup(p)&&T&&(S=!0,p=V),this.isValidLookup(p)||(E=!0,p=a);const Z=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&E?void 0:p,H=T&&V!==p&&this.options.updateMissing;if(E||S||H){if(this.logger.log(H?"updateKey":"missingKey",u,c,a,H?V:p),o){const L=this.resolve(a,{...n,keySeparator:!1});L&&L.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let K=[];const Y=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if(this.options.saveMissingTo==="fallback"&&Y&&Y[0])for(let L=0;L{const ue=T&&Q!==p?Q:Z;this.options.missingKeyHandler?this.options.missingKeyHandler(L,c,F,ue,H,n):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(L,c,F,ue,H,n),this.emit("missingKey",L,c,F,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&C?K.forEach(L=>{const F=this.pluralResolver.getSuffixes(L,n);P&&n[`defaultValue${this.options.pluralSeparator}zero`]&&F.indexOf(`${this.options.pluralSeparator}zero`)<0&&F.push(`${this.options.pluralSeparator}zero`),F.forEach(Q=>{G([L],a+Q,n[`defaultValue${Q}`]||V)})}):G(K,a,V))}p=this.extendTranslation(p,t,n,f,r),E&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${c}:${a}`),(E||S)&&this.options.parseMissingKeyHandler&&(this.options.compatibilityAPI!=="v1"?p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}:${a}`:a,S?p:void 0):p=this.options.parseMissingKeyHandler(p))}return s?(f.res=p,f.usedParams=this.getUsedParamsDetails(n),f):p}extendTranslation(t,n,r,s,o){var a=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...r},r.lng||this.language||s.usedLng,s.usedNS,s.usedKey,{resolved:s});else if(!r.skipInterpolation){r.interpolation&&this.interpolator.init({...r,interpolation:{...this.options.interpolation,...r.interpolation}});const u=typeof t=="string"&&(r&&r.interpolation&&r.interpolation.skipOnVariables!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let d;if(u){const p=t.match(this.interpolator.nestingRegexp);d=p&&p.length}let f=r.replace&&typeof r.replace!="string"?r.replace:r;if(this.options.interpolation.defaultVariables&&(f={...this.options.interpolation.defaultVariables,...f}),t=this.interpolator.interpolate(t,f,r.lng||this.language||s.usedLng,r),u){const p=t.match(this.interpolator.nestingRegexp),h=p&&p.length;d1&&arguments[1]!==void 0?arguments[1]:{},r,s,o,a,l;return typeof t=="string"&&(t=[t]),t.forEach(c=>{if(this.isValidLookup(r))return;const u=this.extractFromKey(c,n),d=u.key;s=d;let f=u.namespaces;this.options.fallbackNS&&(f=f.concat(this.options.fallbackNS));const p=n.count!==void 0&&typeof n.count!="string",h=p&&!n.ordinal&&n.count===0&&this.pluralResolver.shouldUseIntlApi(),v=n.context!==void 0&&(typeof n.context=="string"||typeof n.context=="number")&&n.context!=="",g=n.lngs?n.lngs:this.languageUtils.toResolveHierarchy(n.lng||this.language,n.fallbackLng);f.forEach(b=>{this.isValidLookup(r)||(l=b,!Z1[`${g[0]}-${b}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(l)&&(Z1[`${g[0]}-${b}`]=!0,this.logger.warn(`key "${s}" for languages "${g.join(", ")}" won't get resolved as namespace "${l}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(y=>{if(this.isValidLookup(r))return;a=y;const x=[d];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(x,d,y,b,n);else{let S;p&&(S=this.pluralResolver.getSuffix(y,n.count,n));const E=`${this.options.pluralSeparator}zero`,C=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(p&&(x.push(d+S),n.ordinal&&S.indexOf(C)===0&&x.push(d+S.replace(C,this.options.pluralSeparator)),h&&x.push(d+E)),v){const T=`${d}${this.options.contextSeparator}${n.context}`;x.push(T),p&&(x.push(T+S),n.ordinal&&S.indexOf(C)===0&&x.push(T+S.replace(C,this.options.pluralSeparator)),h&&x.push(T+E))}}let w;for(;w=x.pop();)this.isValidLookup(r)||(o=w,r=this.getResource(y,b,w,n))}))})}),{res:r,usedKey:s,exactUsedKey:o,usedLng:a,usedNS:l}}isValidLookup(t){return t!==void 0&&!(!this.options.returnNull&&t===null)&&!(!this.options.returnEmptyString&&t==="")}getResource(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,n,r,s):this.resourceStore.getResource(t,n,r,s)}getUsedParamsDetails(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const n=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],r=t.replace&&typeof t.replace!="string";let s=r?t.replace:t;if(r&&typeof t.count<"u"&&(s.count=t.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!r){s={...s};for(const o of n)delete s[o]}return s}static hasDefaultValue(t){const n="defaultValue";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&n===r.substring(0,n.length)&&t[r]!==void 0)return!0;return!1}}const gm=e=>e.charAt(0).toUpperCase()+e.slice(1);class Q1{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=gs.create("languageUtils")}getScriptPartFromCode(t){if(t=Ep(t),!t||t.indexOf("-")<0)return null;const n=t.split("-");return n.length===2||(n.pop(),n[n.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(n.join("-"))}getLanguagePartFromCode(t){if(t=Ep(t),!t||t.indexOf("-")<0)return t;const n=t.split("-");return this.formatLanguageCode(n[0])}formatLanguageCode(t){if(typeof t=="string"&&t.indexOf("-")>-1){const n=["hans","hant","latn","cyrl","cans","mong","arab"];let r=t.split("-");return this.options.lowerCaseLng?r=r.map(s=>s.toLowerCase()):r.length===2?(r[0]=r[0].toLowerCase(),r[1]=r[1].toUpperCase(),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=gm(r[1].toLowerCase()))):r.length===3&&(r[0]=r[0].toLowerCase(),r[1].length===2&&(r[1]=r[1].toUpperCase()),r[0]!=="sgn"&&r[2].length===2&&(r[2]=r[2].toUpperCase()),n.indexOf(r[1].toLowerCase())>-1&&(r[1]=gm(r[1].toLowerCase())),n.indexOf(r[2].toLowerCase())>-1&&(r[2]=gm(r[2].toLowerCase()))),r.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let n;return t.forEach(r=>{if(n)return;const s=this.formatLanguageCode(r);(!this.options.supportedLngs||this.isSupportedCode(s))&&(n=s)}),!n&&this.options.supportedLngs&&t.forEach(r=>{if(n)return;const s=this.getLanguagePartFromCode(r);if(this.isSupportedCode(s))return n=s;n=this.options.supportedLngs.find(o=>{if(o===s)return o;if(!(o.indexOf("-")<0&&s.indexOf("-")<0)&&(o.indexOf("-")>0&&s.indexOf("-")<0&&o.substring(0,o.indexOf("-"))===s||o.indexOf(s)===0&&s.length>1))return o})}),n||(n=this.getFallbackCodes(this.options.fallbackLng)[0]),n}getFallbackCodes(t,n){if(!t)return[];if(typeof t=="function"&&(t=t(n)),typeof t=="string"&&(t=[t]),Array.isArray(t))return t;if(!n)return t.default||[];let r=t[n];return r||(r=t[this.getScriptPartFromCode(n)]),r||(r=t[this.formatLanguageCode(n)]),r||(r=t[this.getLanguagePartFromCode(n)]),r||(r=t.default),r||[]}toResolveHierarchy(t,n){const r=this.getFallbackCodes(n||this.options.fallbackLng||[],t),s=[],o=a=>{a&&(this.isSupportedCode(a)?s.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return typeof t=="string"&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(t)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(t)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(t))):typeof t=="string"&&o(this.formatLanguageCode(t)),r.forEach(a=>{s.indexOf(a)<0&&o(this.formatLanguageCode(a))}),s}}let LY=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],$Y={1:e=>+(e>1),2:e=>+(e!=1),3:e=>0,4:e=>e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,5:e=>e==0?0:e==1?1:e==2?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5,6:e=>e==1?0:e>=2&&e<=4?1:2,7:e=>e==1?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2,8:e=>e==1?0:e==2?1:e!=8&&e!=11?2:3,9:e=>+(e>=2),10:e=>e==1?0:e==2?1:e<7?2:e<11?3:4,11:e=>e==1||e==11?0:e==2||e==12?1:e>2&&e<20?2:3,12:e=>+(e%10!=1||e%100==11),13:e=>+(e!==0),14:e=>e==1?0:e==2?1:e==3?2:3,15:e=>e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2,16:e=>e%10==1&&e%100!=11?0:e!==0?1:2,17:e=>e==1||e%10==1&&e%100!=11?0:1,18:e=>e==0?0:e==1?1:2,19:e=>e==1?0:e==0||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3,20:e=>e==1?0:e==0||e%100>0&&e%100<20?1:2,21:e=>e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0,22:e=>e==1?0:e==2?1:(e<0||e>10)&&e%10==0?2:3};const BY=["v1","v2","v3"],zY=["v4"],Y1={zero:0,one:1,two:2,few:3,many:4,other:5},UY=()=>{const e={};return LY.forEach(t=>{t.lngs.forEach(n=>{e[n]={numbers:t.nr,plurals:$Y[t.fc]}})}),e};class VY{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.languageUtils=t,this.options=n,this.logger=gs.create("pluralResolver"),(!this.options.compatibilityJSON||zY.includes(this.options.compatibilityJSON))&&(typeof Intl>"u"||!Intl.PluralRules)&&(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=UY(),this.pluralRulesCache={}}addRule(t,n){this.rules[t]=n}clearCache(){this.pluralRulesCache={}}getRule(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.shouldUseIntlApi())try{const r=Ep(t==="dev"?"en":t),s=n.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:r,type:s});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];const a=new Intl.PluralRules(r,{type:s});return this.pluralRulesCache[o]=a,a}catch{return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return this.shouldUseIntlApi()?r&&r.resolvedOptions().pluralCategories.length>1:r&&r.numbers.length>1}getPluralFormsOfKey(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return this.getSuffixes(t,r).map(s=>`${n}${s}`)}getSuffixes(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=this.getRule(t,n);return r?this.shouldUseIntlApi()?r.resolvedOptions().pluralCategories.sort((s,o)=>Y1[s]-Y1[o]).map(s=>`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${s}`):r.numbers.map(s=>this.getSuffix(t,s,n)):[]}getSuffix(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const s=this.getRule(t,r);return s?this.shouldUseIntlApi()?`${this.options.prepend}${r.ordinal?`ordinal${this.options.prepend}`:""}${s.select(n)}`:this.getSuffixRetroCompatible(s,n):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,n){const r=t.noAbs?t.plurals(n):t.plurals(Math.abs(n));let s=t.numbers[r];this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1&&(s===2?s="plural":s===1&&(s=""));const o=()=>this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString();return this.options.compatibilityJSON==="v1"?s===1?"":typeof s=="number"?`_plural_${s.toString()}`:o():this.options.compatibilityJSON==="v2"||this.options.simplifyPluralSuffix&&t.numbers.length===2&&t.numbers[0]===1?o():this.options.prepend&&r.toString()?this.options.prepend+r.toString():r.toString()}shouldUseIntlApi(){return!BY.includes(this.options.compatibilityJSON)}}const X1=function(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:".",s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,o=NY(e,t,n);return!o&&s&&typeof n=="string"&&(o=ay(e,n,r),o===void 0&&(o=ay(t,n,r))),o},hm=e=>e.replace(/\$/g,"$$$$");class HY{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=gs.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(n=>n),this.init(t)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const{escape:n,escapeValue:r,useRawValueToEscape:s,prefix:o,prefixEscaped:a,suffix:l,suffixEscaped:c,formatSeparator:u,unescapeSuffix:d,unescapePrefix:f,nestingPrefix:p,nestingPrefixEscaped:h,nestingSuffix:v,nestingSuffixEscaped:g,nestingOptionsSeparator:b,maxReplaces:y,alwaysFormat:x}=t.interpolation;this.escape=n!==void 0?n:OY,this.escapeValue=r!==void 0?r:!0,this.useRawValueToEscape=s!==void 0?s:!1,this.prefix=o?wi(o):a||"{{",this.suffix=l?wi(l):c||"}}",this.formatSeparator=u||",",this.unescapePrefix=d?"":f||"-",this.unescapeSuffix=this.unescapePrefix?"":d||"",this.nestingPrefix=p?wi(p):h||wi("$t("),this.nestingSuffix=v?wi(v):g||wi(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=y||1e3,this.alwaysFormat=x!==void 0?x:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(n,r)=>n&&n.source===r?(n.lastIndex=0,n):new RegExp(r,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}(.+?)${this.nestingSuffix}`)}interpolate(t,n,r,s){let o,a,l;const c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},u=h=>{if(h.indexOf(this.formatSeparator)<0){const y=X1(n,c,h,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(y,void 0,r,{...s,...n,interpolationkey:h}):y}const v=h.split(this.formatSeparator),g=v.shift().trim(),b=v.join(this.formatSeparator).trim();return this.format(X1(n,c,g,this.options.keySeparator,this.options.ignoreJSONStructure),b,r,{...s,...n,interpolationkey:g})};this.resetRegExp();const d=s&&s.missingInterpolationHandler||this.options.missingInterpolationHandler,f=s&&s.interpolation&&s.interpolation.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:h=>hm(h)},{regex:this.regexp,safeValue:h=>this.escapeValue?hm(this.escape(h)):hm(h)}].forEach(h=>{for(l=0;o=h.regex.exec(t);){const v=o[1].trim();if(a=u(v),a===void 0)if(typeof d=="function"){const b=d(t,o,s);a=typeof b=="string"?b:""}else if(s&&Object.prototype.hasOwnProperty.call(s,v))a="";else if(f){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${v} for interpolating ${t}`),a="";else typeof a!="string"&&!this.useRawValueToEscape&&(a=W1(a));const g=h.safeValue(a);if(t=t.replace(o[0],g),f?(h.regex.lastIndex+=a.length,h.regex.lastIndex-=o[0].length):h.regex.lastIndex=0,l++,l>=this.maxReplaces)break}}),t}nest(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s,o,a;const l=(c,u)=>{const d=this.nestingOptionsSeparator;if(c.indexOf(d)<0)return c;const f=c.split(new RegExp(`${d}[ ]*{`));let p=`{${f[1]}`;c=f[0],p=this.interpolate(p,a);const h=p.match(/'/g),v=p.match(/"/g);(h&&h.length%2===0&&!v||v.length%2!==0)&&(p=p.replace(/'/g,'"'));try{a=JSON.parse(p),u&&(a={...u,...a})}catch(g){return this.logger.warn(`failed parsing options string in nesting for key ${c}`,g),`${c}${d}${p}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,c};for(;s=this.nestingRegexp.exec(t);){let c=[];a={...r},a=a.replace&&typeof a.replace!="string"?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;let u=!1;if(s[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(s[1])){const d=s[1].split(this.formatSeparator).map(f=>f.trim());s[1]=d.shift(),c=d,u=!0}if(o=n(l.call(this,s[1].trim(),a),a),o&&s[0]===t&&typeof o!="string")return o;typeof o!="string"&&(o=W1(o)),o||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),o=""),u&&(o=c.reduce((d,f)=>this.format(d,f,r.lng,{...r,interpolationkey:s[1].trim()}),o.trim())),t=t.replace(s[0],o),this.regexp.lastIndex=0}return t}}const WY=e=>{let t=e.toLowerCase().trim();const n={};if(e.indexOf("(")>-1){const r=e.split("(");t=r[0].toLowerCase().trim();const s=r[1].substring(0,r[1].length-1);t==="currency"&&s.indexOf(":")<0?n.currency||(n.currency=s.trim()):t==="relativetime"&&s.indexOf(":")<0?n.range||(n.range=s.trim()):s.split(";").forEach(a=>{if(a){const[l,...c]=a.split(":"),u=c.join(":").trim().replace(/^'+|'+$/g,""),d=l.trim();n[d]||(n[d]=u),u==="false"&&(n[d]=!1),u==="true"&&(n[d]=!0),isNaN(u)||(n[d]=parseInt(u,10))}})}return{formatName:t,formatOptions:n}},Si=e=>{const t={};return(n,r,s)=>{let o=s;s&&s.interpolationkey&&s.formatParams&&s.formatParams[s.interpolationkey]&&s[s.interpolationkey]&&(o={...o,[s.interpolationkey]:void 0});const a=r+JSON.stringify(o);let l=t[a];return l||(l=e(Ep(r),s),t[a]=l),l(n)}};class GY{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.logger=gs.create("formatter"),this.options=t,this.formats={number:Si((n,r)=>{const s=new Intl.NumberFormat(n,{...r});return o=>s.format(o)}),currency:Si((n,r)=>{const s=new Intl.NumberFormat(n,{...r,style:"currency"});return o=>s.format(o)}),datetime:Si((n,r)=>{const s=new Intl.DateTimeFormat(n,{...r});return o=>s.format(o)}),relativetime:Si((n,r)=>{const s=new Intl.RelativeTimeFormat(n,{...r});return o=>s.format(o,r.range||"day")}),list:Si((n,r)=>{const s=new Intl.ListFormat(n,{...r});return o=>s.format(o)})},this.init(t)}init(t){const r=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=r.formatSeparator?r.formatSeparator:r.formatSeparator||","}add(t,n){this.formats[t.toLowerCase().trim()]=n}addCached(t,n){this.formats[t.toLowerCase().trim()]=Si(n)}format(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};const o=n.split(this.formatSeparator);if(o.length>1&&o[0].indexOf("(")>1&&o[0].indexOf(")")<0&&o.find(l=>l.indexOf(")")>-1)){const l=o.findIndex(c=>c.indexOf(")")>-1);o[0]=[o[0],...o.splice(1,l)].join(this.formatSeparator)}return o.reduce((l,c)=>{const{formatName:u,formatOptions:d}=WY(c);if(this.formats[u]){let f=l;try{const p=s&&s.formatParams&&s.formatParams[s.interpolationkey]||{},h=p.locale||p.lng||s.locale||s.lng||r;f=this.formats[u](l,h,{...d,...s,...p})}catch(p){this.logger.warn(p)}return f}else this.logger.warn(`there was no format function for ${u}`);return l},t)}}const qY=(e,t)=>{e.pending[t]!==void 0&&(delete e.pending[t],e.pendingCount--)};class KY extends Gg{constructor(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};super(),this.backend=t,this.store=n,this.services=r,this.languageUtils=r.languageUtils,this.options=s,this.logger=gs.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(r,s.backend,s)}queueLoad(t,n,r,s){const o={},a={},l={},c={};return t.forEach(u=>{let d=!0;n.forEach(f=>{const p=`${u}|${f}`;!r.reload&&this.store.hasResourceBundle(u,f)?this.state[p]=2:this.state[p]<0||(this.state[p]===1?a[p]===void 0&&(a[p]=!0):(this.state[p]=1,d=!1,a[p]===void 0&&(a[p]=!0),o[p]===void 0&&(o[p]=!0),c[f]===void 0&&(c[f]=!0)))}),d||(l[u]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(l),toLoadNamespaces:Object.keys(c)}}loaded(t,n,r){const s=t.split("|"),o=s[0],a=s[1];n&&this.emit("failedLoading",o,a,n),!n&&r&&this.store.addResourceBundle(o,a,r,void 0,void 0,{skipCopy:!0}),this.state[t]=n?-1:2,n&&r&&(this.state[t]=0);const l={};this.queue.forEach(c=>{IY(c.loaded,[o],a),qY(c,t),n&&c.errors.push(n),c.pendingCount===0&&!c.done&&(Object.keys(c.loaded).forEach(u=>{l[u]||(l[u]={});const d=c.loaded[u];d.length&&d.forEach(f=>{l[u][f]===void 0&&(l[u][f]=!0)})}),c.done=!0,c.errors.length?c.callback(c.errors):c.callback())}),this.emit("loaded",l),this.queue=this.queue.filter(c=>!c.done)}read(t,n,r){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!t.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:t,ns:n,fcName:r,tried:s,wait:o,callback:a});return}this.readingCalls++;const l=(u,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const f=this.waitingReads.shift();this.read(f.lng,f.ns,f.fcName,f.tried,f.wait,f.callback)}if(u&&d&&s{this.read.call(this,t,n,r,s+1,o*2,a)},o);return}a(u,d)},c=this.backend[r].bind(this.backend);if(c.length===2){try{const u=c(t,n);u&&typeof u.then=="function"?u.then(d=>l(null,d)).catch(l):l(null,u)}catch(u){l(u)}return}return c(t,n,l)}prepareLoading(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),s&&s();typeof t=="string"&&(t=this.languageUtils.toResolveHierarchy(t)),typeof n=="string"&&(n=[n]);const o=this.queueLoad(t,n,r,s);if(!o.toLoad.length)return o.pending.length||s(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(t,n,r){this.prepareLoading(t,n,{},r)}reload(t,n,r){this.prepareLoading(t,n,{reload:!0},r)}loadOne(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const r=t.split("|"),s=r[0],o=r[1];this.read(s,o,"read",void 0,void 0,(a,l)=>{a&&this.logger.warn(`${n}loading namespace ${o} for language ${s} failed`,a),!a&&l&&this.logger.log(`${n}loaded namespace ${o} for language ${s}`,l),this.loaded(t,a,l)})}saveMissing(t,n,r,s,o){let a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{},l=arguments.length>6&&arguments[6]!==void 0?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(n)){this.logger.warn(`did not save key "${r}" as the namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(r==null||r==="")){if(this.backend&&this.backend.create){const c={...a,isUpdate:o},u=this.backend.create.bind(this.backend);if(u.length<6)try{let d;u.length===5?d=u(t,n,r,s,c):d=u(t,n,r,s),d&&typeof d.then=="function"?d.then(f=>l(null,f)).catch(l):l(null,d)}catch(d){l(d)}else u(t,n,r,s,l,c)}!t||!t[0]||this.store.addResource(t[0],n,r,s)}}}const eC=()=>({debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if(typeof e[1]=="object"&&(t=e[1]),typeof e[1]=="string"&&(t.defaultValue=e[1]),typeof e[2]=="string"&&(t.tDescription=e[2]),typeof e[2]=="object"||typeof e[3]=="object"){const n=e[3]||e[2];Object.keys(n).forEach(r=>{t[r]=n[r]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}),tC=e=>(typeof e.ns=="string"&&(e.ns=[e.ns]),typeof e.fallbackLng=="string"&&(e.fallbackLng=[e.fallbackLng]),typeof e.fallbackNS=="string"&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e),qd=()=>{},JY=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(n=>{typeof e[n]=="function"&&(e[n]=e[n].bind(e))})};class Au extends Gg{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(super(),this.options=tC(t),this.services={},this.logger=gs,this.modules={external:[]},JY(this),n&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,n),this;setTimeout(()=>{this.init(t,n)},0)}}init(){var t=this;let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;this.isInitializing=!0,typeof n=="function"&&(r=n,n={}),!n.defaultNS&&n.defaultNS!==!1&&n.ns&&(typeof n.ns=="string"?n.defaultNS=n.ns:n.ns.indexOf("translation")<0&&(n.defaultNS=n.ns[0]));const s=eC();this.options={...s,...this.options,...tC(n)},this.options.compatibilityAPI!=="v1"&&(this.options.interpolation={...s.interpolation,...this.options.interpolation}),n.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=n.keySeparator),n.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=n.nsSeparator);const o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?gs.init(o(this.modules.logger),this.options):gs.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:typeof Intl<"u"&&(d=GY);const f=new Q1(this.options);this.store=new J1(this.options.resources,this.options);const p=this.services;p.logger=gs,p.resourceStore=this.store,p.languageUtils=f,p.pluralResolver=new VY(f,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),d&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(p.formatter=o(d),p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new HY(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new KY(o(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",function(h){for(var v=arguments.length,g=new Array(v>1?v-1:0),b=1;b1?v-1:0),b=1;b{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,r||(r=qd),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(d=>{this[d]=function(){return t.store[d](...arguments)}}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=function(){return t.store[d](...arguments),t}});const c=pc(),u=()=>{const d=(f,p)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),c.resolve(p),r(f,p)};if(this.languages&&this.options.compatibilityAPI!=="v1"&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initImmediate?u():setTimeout(u,0),c}loadResources(t){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:qd;const s=typeof t=="string"?t:this.language;if(typeof t=="function"&&(r=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&s.toLowerCase()==="cimode"&&(!this.options.preload||this.options.preload.length===0))return r();const o=[],a=l=>{if(!l||l==="cimode")return;this.services.languageUtils.toResolveHierarchy(l).forEach(u=>{u!=="cimode"&&o.indexOf(u)<0&&o.push(u)})};s?a(s):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(c=>a(c)),this.options.preload&&this.options.preload.forEach(l=>a(l)),this.services.backendConnector.load(o,this.options.ns,l=>{!l&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),r(l)})}else r(null)}reloadResources(t,n,r){const s=pc();return typeof t=="function"&&(r=t,t=void 0),typeof n=="function"&&(r=n,n=void 0),t||(t=this.languages),n||(n=this.options.ns),r||(r=qd),this.services.backendConnector.reload(t,n,o=>{s.resolve(),r(o)}),s}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return t.type==="backend"&&(this.modules.backend=t),(t.type==="logger"||t.log&&t.warn&&t.error)&&(this.modules.logger=t),t.type==="languageDetector"&&(this.modules.languageDetector=t),t.type==="i18nFormat"&&(this.modules.i18nFormat=t),t.type==="postProcessor"&&QP.addPostProcessor(t),t.type==="formatter"&&(this.modules.formatter=t),t.type==="3rdParty"&&this.modules.external.push(t),this}setResolvedLanguage(t){if(!(!t||!this.languages)&&!(["cimode","dev"].indexOf(t)>-1))for(let n=0;n-1)&&this.store.hasLanguageSomeTranslations(r)){this.resolvedLanguage=r;break}}}changeLanguage(t,n){var r=this;this.isLanguageChangingTo=t;const s=pc();this.emit("languageChanging",t);const o=c=>{this.language=c,this.languages=this.services.languageUtils.toResolveHierarchy(c),this.resolvedLanguage=void 0,this.setResolvedLanguage(c)},a=(c,u)=>{u?(o(u),this.translator.changeLanguage(u),this.isLanguageChangingTo=void 0,this.emit("languageChanged",u),this.logger.log("languageChanged",u)):this.isLanguageChangingTo=void 0,s.resolve(function(){return r.t(...arguments)}),n&&n(c,function(){return r.t(...arguments)})},l=c=>{!t&&!c&&this.services.languageDetector&&(c=[]);const u=typeof c=="string"?c:this.services.languageUtils.getBestMatchFromCodes(c);u&&(this.language||o(u),this.translator.language||this.translator.changeLanguage(u),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(u)),this.loadResources(u,d=>{a(d,u)})};return!t&&this.services.languageDetector&&!this.services.languageDetector.async?l(this.services.languageDetector.detect()):!t&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(l):this.services.languageDetector.detect(l):l(t),s}getFixedT(t,n,r){var s=this;const o=function(a,l){let c;if(typeof l!="object"){for(var u=arguments.length,d=new Array(u>2?u-2:0),f=2;f`${c.keyPrefix}${p}${v}`):h=c.keyPrefix?`${c.keyPrefix}${p}${a}`:a,s.t(h,c)};return typeof t=="string"?o.lng=t:o.lngs=t,o.ns=n,o.keyPrefix=r,o}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const r=n.lng||this.resolvedLanguage||this.languages[0],s=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(r.toLowerCase()==="cimode")return!0;const a=(l,c)=>{const u=this.services.backendConnector.state[`${l}|${c}`];return u===-1||u===0||u===2};if(n.precheck){const l=n.precheck(this,a);if(l!==void 0)return l}return!!(this.hasResourceBundle(r,t)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(r,t)&&(!s||a(o,t)))}loadNamespaces(t,n){const r=pc();return this.options.ns?(typeof t=="string"&&(t=[t]),t.forEach(s=>{this.options.ns.indexOf(s)<0&&this.options.ns.push(s)}),this.loadResources(s=>{r.resolve(),n&&n(s)}),r):(n&&n(),Promise.resolve())}loadLanguages(t,n){const r=pc();typeof t=="string"&&(t=[t]);const s=this.options.preload||[],o=t.filter(a=>s.indexOf(a)<0&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=s.concat(o),this.loadResources(a=>{r.resolve(),n&&n(a)}),r):(n&&n(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const n=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],r=this.services&&this.services.languageUtils||new Q1(eC());return n.indexOf(r.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return new Au(t,n)}cloneInstance(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:qd;const r=t.forkResourceStore;r&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},o=new Au(s);return(t.debug!==void 0||t.prefix!==void 0)&&(o.logger=o.logger.clone(t)),["store","services","language"].forEach(l=>{o[l]=this[l]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},r&&(o.store=new J1(this.store.data,s),o.services.resourceStore=o.store),o.translator=new Tp(o.services,s),o.translator.on("*",function(l){for(var c=arguments.length,u=new Array(c>1?c-1:0),d=1;d