PageSourceSearch

https://pragmaz.ai/assets/Chat-DFBnXqr6.js

js pragmaz.ai collected 2026-09-24 14:07:58 UTC 449,370 bytes, 9 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/meta-3f0h279n.js","assets/app-BEDoDvHI.js","assets/app-BDiLeu3I.css"])))=>i.map(i=>d[i]);
2import{j as e,bE as ne,r,bb as bs,bj as It,bD as lt,e as M,a7 as bt,bF as ba,bG as _s,bH as W,c as ds,b as mi,aN as hi,$ as nn,T as ya,aZ as go,ax as xo,q as vo,a2 as jo,bI as bo,as as yo,bo as Rn,p as fi,ap as wo,M as No,bf as Sr,y as ko,z as Ks,aj as So,u as Co,a as Eo,au as Io,bJ as Ao,av as Ro,bK as wn,ab as Mo,bC as Xs,bL as $o,bM as To,aJ as Fo,aK as Cr,bN as _o}from"./app-BEDoDvHI.js";import{g as Ds,a as Ht,C as Do,l as Lo,e as Po,u as zo,f as Wo,b as Er,t as qo,L as gi,m as Bo,c as Uo,d as Oo,h as Go,i as Vo,j as Ho,k as xi}from"./chat-v2-BNrMhjCo.js";import{g as vi,P as Jo,a as ji,b as Yo,c as bi,d as Jt}from"./sessionCaps-BVTI-NVQ.js";import{t as Qo}from"./locale-BJ7r9eqn.js";import{i as yi,g as Ko}from"./forwardable-u6lLpteR.js";import{listSessionTemplates as Xo}from"./meta-3f0h279n.js";import{C as Zo}from"./CvDeviceOptionsModal-CI0uZfK2.js";import{P as ec}from"./PzEmpty-xdnU4l46.js";import"./TemplatePreview-D2yU3xgs.js";import"./useTplPreviewMedia-DjoTBYPq.js";import"./emoji-picker-react.esm-CBzfsOpW.js";import"./mediaLimits-CvHWOfh2.js";function tc({syncing:t,locale:n="pt"}){if(!t)return null;const{messages:o=0,chats:i=0,contacts:s=0,progress:f=0,paused:l=!1,indeterminate:c=!1,kind:d}=t,v=d==="coex",k=!l&&!c&&f>0,x=!l&&(c||f===0),P=l?n==="en"?"Sync paused":n==="es"?"Sincronización en pausa":"Sincronização pausada":v?n==="en"?"Syncing WhatsApp history":n==="es"?"Sincronizando historial":"Sincronizando histórico do WhatsApp":n==="en"?"Syncing history":n==="es"?"Sincronizando historial":"Sincronizando histórico";return e.jsxs("div",{className:"cs-sync",children:[e.jsxs("div",{className:"cs-sync-head",children:[l?e.jsx(ne,{content:n==="en"?"Paused":n==="es"?"En pausa":"Pausado",position:"top",children:e.jsx("span",{className:"warn-dot"})}):e.jsx("span",{className:"spin",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsx("span",{className:"cs-sync-ttl",children:P}),k&&e.jsxs("span",{className:"cs-sync-pct",children:[Math.min(99,Math.floor(f)),"%"]})]}),e.jsx("div",{className:`bar${x?" indet":""}`,children:e.jsx("div",{className:"fill",style:x?void 0:{width:`${Math.min(99,Math.floor(f))}%`}})}),e.jsxs("div",{className:"cs-sync-meta",children:[o>0&&e.jsxs("span",{children:[o.toLocaleString()," msgs"]}),i>0&&e.jsxs("span",{children:["· ",i.toLocaleString()," ",n==="en"?"chats":n==="es"?"conversaciones":"conversas"]}),s>0&&e.jsxs("span",{children:["· ",s.toLocaleString()," ",n==="en"?"contacts":n==="es"?"contactos":"contatos"]}),v&&o===0&&e.jsx("span",{className:"cs-sync-hint",children:n==="en"?"importing up to 180 days…":n==="es"?"importando hasta 180 días…":"importando até 180 dias…"})]})]})}const Ir={pt:{all:"Todas",unread:"Não lidas",groups:"Grupos",archived:"Arquivadas",muted:"Silenciadas",channels:"Canais"},en:{all:"All",unread:"Unread",groups:"Groups",archived:"Archived",muted:"Muted",channels:"Channels"},es:{all:"Todas",unread:"No leídas",groups:"Grupos",archived:"Archivadas",muted:"Silenciadas",channels:"Canales"}},Rs=(t,n)=>(Ir[n]||Ir.pt)[t]||t,an=t=>t?t.trim().split(/\s+/).slice(0,2).map(o=>o[0]).join("").toUpperCase():"?",wi=(t,n="pt")=>{if(!t)return"";const o=new Date(t*1e3),i=new Date;if(o.toDateString()===i.toDateString())return o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});const f=new Date(i);return f.setDate(f.getDate()-1),o.toDateString()===f.toDateString()?n==="en"?"Yesterday":n==="es"?"Ayer":"Ontem":Math.floor((i-o)/(1e3*60*60*24))<7?o.toLocaleDateString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{weekday:"short"}):o.toLocaleDateString([],{day:"2-digit",month:"2-digit"})},Ar={web:{cls:"web",icon:"ci-iphone"},web_business:{cls:"web",icon:"ci-iphone"},coex:{cls:"coex",icon:"ci-link"},cloud:{cls:"",icon:"ci-cloud"}},Rr={flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:6,background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:7,color:"var(--text-2)",fontSize:12,padding:"7px 6px",cursor:"pointer",fontFamily:"inherit"},ia={width:"100%",background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-1)",padding:"8px 10px",fontSize:13,fontFamily:"inherit"},Mr=t=>{if(!t)return null;const n=vi(t),o=Ar[n]||Ar.web;return{label:Jo[n],cls:o.cls,icon:o.icon}},tn=(t,n="pt")=>t?ji(t)||bt(t.phone)||(n==="en"?"Device":"Dispositivo"):n==="en"?"No session":n==="es"?"Sin sesión":"Sem sessão",Nn=t=>{if(!(t!=null&&t.phone))return"";const n=bt(t.phone);return n&&n!==tn(t)?n:""},$r=(t,n)=>{const o=new Set;return(t||[]).filter(i=>{const s=n(i);return o.has(s)?!1:(o.add(s),!0)})};function sc({sessions:t,activeSession:n,onChangeSession:o,chats:i,chatsLoading:s,selectedJid:f,onSelectChat:l,onLoadMore:c,chatsLoadingMore:d=!1,chatsTotal:v=0,chatsLoaded:k,onConvAction:x,onConfirmAsk:P,onNewChat:A,chatFilter:y,onChangeFilter:w,chatSearch:m,onChangeSearch:I,searchContacts:U=[],searchMessages:u=[],onOpenContact:p,onOpenMessage:b,labels:se=[],archivedCount:C=0,channelsCount:H=0,syncing:Q,typingMap:O={},presenceMap:oe={},onDeviceOptions:ke,onMarkAllRead:Ae,onAddDevice:ve,onBulkDelete:_,pinnedSessionId:$,onTogglePinDevice:X,canAddDevice:ce=!1,onChannelAction:Z,aiEnabled:D=!1,onOpenRadar:ae,radarCount:K=null,onOpenQa:Re=null,adKanban:_e=null,locale:Y="pt"}){const[Oe,Je]=r.useState(!1),[Be,Qe]=r.useState(!1),[Me,De]=r.useState(!1),[xt,ut]=r.useState(!1),mt=Number.isFinite(k)?k:i.length,[st,kt]=r.useState(null),At=r.useMemo(()=>new Map(((_e==null?void 0:_e.colunas)||[]).map((J,We)=>[Number(J.id),{...J,entrada:We===0}])),[_e]);r.useEffect(()=>{kt(null)},[m,n==null?void 0:n.session_id]);const dt=async()=>{var We,it;const J=(m||"").trim();if(!(!J||!(n!=null&&n.session_id))){kt({q:J,loading:!0});try{const{data:ot}=await M.post("/wa/chat-ai/search",{sessionId:n.session_id,query:J});kt({q:J,hits:ot.hits||[],plan:ot.plan})}catch(ot){kt({q:J,error:((it=(We=ot==null?void 0:ot.response)==null?void 0:We.data)==null?void 0:it.error)||de("IA indisponível agora","AI unavailable","IA no disponible")})}}},jt=r.useRef(null),[G,me]=r.useState(null),[Se,Fe]=r.useState(!1),[le,Xe]=r.useState(!1),[z,Ce]=r.useState(()=>new Set),[ye,at]=r.useState(null),[L,Ze]=r.useState(null),[rt,_t]=r.useState(!1),[Yt,Qt]=r.useState(!1),{settings:Rt}=bs(),de=(J,We,it)=>Y==="en"?We:Y==="es"?it:J;r.useEffect(()=>{const J=We=>{jt.current&&!jt.current.contains(We.target)&&(Je(!1),ut(!1))};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[]);const[$t,Ut]=r.useState(()=>{try{return JSON.parse(localStorage.getItem("chat_sessionOrder")||"[]")}catch{return[]}}),[q,he]=r.useState(null),[et,re]=r.useState(null),tt=r.useMemo(()=>{const J=[...t||[]];return $t.length&&J.sort((We,it)=>{const ot=$t.indexOf(We.session_id),ft=$t.indexOf(it.session_id);return(ot===-1?1e9:ot)-(ft===-1?1e9:ft)}),$&&J.sort((We,it)=>(We.session_id===$?-1:0)-(it.session_id===$?-1:0)),J},[t,$,$t]),pt=(J,We)=>{if(!J||J===We)return;const it=tt.map(Xt=>Xt.session_id),ot=it.indexOf(J),ft=it.indexOf(We);if(!(ot===-1||ft===-1)){it.splice(ot,1),it.splice(ft,0,J),Ut(it);try{localStorage.setItem("chat_sessionOrder",JSON.stringify(it))}catch{}}},Et=()=>{Xe(!1),Ce(new Set)},wt=J=>{Ce(We=>{const it=new Set(We);return it.has(J)?it.delete(J):it.add(J),it})},He=i.length>0&&i.every(J=>z.has(J.jid)),Ls=()=>{Ce(He?new Set:new Set(i.map(J=>J.jid)))},rn=()=>{z.size&&(Qt(!1),at({jids:[...z]}))},Kt=async()=>{const J=(ye==null?void 0:ye.jids)||[];at(null),await(_==null?void 0:_(J,Yt)),Et()},us=Mr(n),Ps=r.useMemo(()=>{const J=[{key:"all",label:Rs("all",Y)},{key:"unread",label:Rs("unread",Y)},{key:"groups",label:Rs("groups",Y)},{key:"archived",label:Rs("archived",Y)+(C?` (${C})`:"")},{key:"muted",label:Rs("muted",Y)}],it=(n==null?void 0:n.provider_type)==="web"&&(!!(n!=null&&n.is_business)||(n==null?void 0:n.platform)==="smba"||(n==null?void 0:n.platform)==="smbi")?(se||[]).map(ft=>({key:`label:${ft.id!=null?ft.id:ft.name||ft}`,label:Ht(ft,Y),dotColor:Ds(ft.color)})):[],ot=H>0?[{key:"channels",label:Rs("channels",Y)+` (${H})`}]:[];return[...J,...it,...ot]},[se,C,H,Y,n]),Ot=r.useMemo(()=>({unread:(i||[]).filter(J=>(J.unreadCount||0)>0).length||null,groups:(i||[]).filter(J=>J.isGroup).length||null}),[i]);return r.useEffect(()=>{if(!Be&&!Me)return;const J=ot=>{ot.target.closest(".cs-filter-menu")||ot.target.closest(".cs-filter-btn")||ot.target.closest(".cs-ai-menu")||ot.target.closest(".cs-ai-btn")||(Qe(!1),De(!1))},We=ot=>{ot.key==="Escape"&&(Qe(!1),De(!1))},it=setTimeout(()=>document.addEventListener("mousedown",J),0);return document.addEventListener("keydown",We),()=>{clearTimeout(it),document.removeEventListener("mousedown",J),document.removeEventListener("keydown",We)}},[Be,Me]),r.useEffect(()=>{if(!G)return;const J=it=>{it.target.closest(".conv-actions-menu")||me(null)},We=setTimeout(()=>document.addEventListener("mousedown",J),0);return()=>{clearTimeout(We),document.removeEventListener("mousedown",J)}},[G]),e.jsxs("aside",{className:"chat-sidebar",children:[e.jsxs("div",{className:"cs-device",ref:jt,onClick:J=>{J.target.closest(".more")||(ut(!1),Je(We=>!We))},children:[e.jsxs("div",{className:`av ${It("blurAvatars",Rt)}`,children:[n!=null&&n.img_url?e.jsx("img",{src:n.img_url,alt:""}):an(tn(n,Y)),n&&e.jsx("span",{className:"status-dot",style:n.status==="connected"?void 0:{background:"var(--text-4)"}})]}),e.jsxs("div",{className:"t",children:[e.jsxs("div",{className:"nm",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{className:It("blurNames",Rt),style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:tn(n,Y)}),us&&e.jsxs("span",{className:`prv-chip ${us.cls}`,children:[e.jsx("svg",{children:e.jsx("use",{href:`#${us.icon}`})}),us.label]}),$&&$===(n==null?void 0:n.session_id)&&e.jsx(ne,{content:de("Dispositivo fixado","Pinned device","Dispositivo fijado"),position:"bottom",children:e.jsx("span",{className:"dev-pinned",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-fill"})})})})]}),e.jsx("div",{className:"ph",children:Nn(n)?e.jsx("span",{className:It("blurNames",Rt),children:Nn(n)}):(n==null?void 0:n.status)==="connected"?de("Conectado","Connected","Conectado"):(n==null?void 0:n.status)==="connecting"?de("Reconectando…","Reconnecting…","Reconectando…"):de("Desconectado","Disconnected","Desconectado")})]}),e.jsx("span",{className:"chev",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev"})})}),e.jsx(ne,{content:de("Mais opções","More options","Más opciones"),position:"bottom",children:e.jsx("button",{className:"more",onClick:J=>{J.stopPropagation(),Je(!1),ut(We=>!We)},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-dots"})})})}),xt&&e.jsxs("div",{className:"dropdown-menu cs-device-more-menu",onClick:J=>J.stopPropagation(),children:[e.jsxs("button",{className:"item",onClick:()=>{ut(!1),Xe(!0),Ce(new Set)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})}),de("Selecionar chats","Select chats","Seleccionar chats")]}),e.jsxs("button",{className:"item",onClick:()=>{ut(!1),X==null||X(n==null?void 0:n.session_id)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-stick"})}),$&&$===(n==null?void 0:n.session_id)?de("Desafixar dispositivo","Unpin device","Desfijar dispositivo"):de("Fixar dispositivo","Pin device","Fijar dispositivo")]}),e.jsxs("button",{className:"item",onClick:()=>{ut(!1),ke==null||ke()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-info"})}),de("Opções do dispositivo","Device options","Opciones del dispositivo")]}),e.jsx("div",{className:"sep"}),e.jsxs("button",{className:"item",onClick:()=>{ut(!1),Ae==null||Ae()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-mark-read"})}),de("Marcar todos como lidos","Mark all as read","Marcar todo como leído")]}),e.jsxs("button",{className:"item",onClick:()=>{ut(!1),w("archived")},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-archive"})}),de("Mostrar arquivados","Show archived","Mostrar archivados")]})]}),Oe&&t.length>0&&e.jsxs("div",{className:"dropdown-menu cs-device-menu",onClick:J=>J.stopPropagation(),children:[e.jsx("div",{className:"group-lbl",children:Y==="en"?"Switch device":Y==="es"?"Cambiar dispositivo":"Trocar dispositivo"}),tt.map(J=>{const We=Mr(J),it=J.session_id===(n==null?void 0:n.session_id),ot=J.status==="connected";return e.jsxs("button",{className:`dev-item${it?" active":""}${et===J.session_id?" drag-over":""}`,draggable:!0,onDragStart:ft=>{he(J.session_id),ft.dataTransfer.effectAllowed="move";try{ft.dataTransfer.setData("text/plain",J.session_id)}catch{}},onDragOver:ft=>{q&&q!==J.session_id&&(ft.preventDefault(),ft.dataTransfer.dropEffect="move",re(J.session_id))},onDrop:ft=>{ft.preventDefault(),pt(q,J.session_id),he(null),re(null)},onDragEnd:()=>{he(null),re(null)},onClick:()=>{o(J.session_id),Je(!1)},children:[e.jsxs("div",{className:`av ${It("blurAvatars",Rt)}`,children:[J.img_url?e.jsx("img",{src:J.img_url,alt:""}):an(tn(J,Y)),e.jsx("span",{className:`dot${ot?"":" warn"}`})]}),e.jsxs("div",{className:"t",children:[e.jsxs("div",{className:"nm",children:[e.jsx("span",{className:It("blurNames",Rt),style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:tn(J,Y)}),We&&e.jsxs("span",{className:`prv-chip ${We.cls}`,children:[e.jsx("svg",{children:e.jsx("use",{href:`#${We.icon}`})}),We.label]})]}),e.jsx("div",{className:"ph",children:Nn(J)?e.jsx("span",{className:It("blurNames",Rt),children:Nn(J)}):ot?de("Conectado","Connected","Conectado"):de("Desconectado","Disconnected","Desconectado")})]}),$===J.session_id&&e.jsx("span",{className:"pin-ic",style:{color:"var(--indigo-light)",display:"inline-flex"},children:e.jsx("svg",{width:"14",height:"14",children:e.jsx("use",{href:"#ci-pin-fill"})})}),e.jsx("span",{className:"check",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})})]},J.session_id)}),ce&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sep"}),e.jsxs("button",{className:"item",onClick:()=>{Je(!1),ve==null||ve()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-add"})}),de("Adicionar dispositivo","Add device","Agregar dispositivo")]})]})]})]}),le?e.jsxs("div",{className:"cs-select-bar",children:[e.jsx(ne,{content:de("Cancelar","Cancel","Cancelar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:Et,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})}),e.jsxs("span",{className:"count",children:[z.size," ",de("selecionado(s)","selected","seleccionado(s)")]}),e.jsx("button",{className:"sel-all",onClick:Ls,children:He?de("Limpar","Clear","Limpiar"):de("Todos","All","Todos")}),e.jsx(ne,{content:de("Apagar","Delete","Borrar"),position:"bottom",children:e.jsx("button",{className:"del",onClick:rn,disabled:!z.size,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})})})})]}):e.jsxs("div",{className:"cs-search",style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsxs("div",{className:"cs-search-input",style:{flex:1},children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",value:m,onChange:J=>I(J.target.value),placeholder:Y==="en"?"Search conversations":Y==="es"?"Buscar conversaciones":"Buscar conversas"}),m&&e.jsx(ne,{content:de("Limpar busca","Clear search","Limpiar búsqueda"),position:"bottom",children:e.jsx("button",{className:"clear",onClick:()=>I(""),"aria-label":de("Limpar","Clear","Limpiar"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})}),e.jsxs("button",{className:`cs-filter-btn${y!=="all"?" on":""}`,onClick:()=>{Qe(J=>!J),De(!1)},title:de("Filtrar conversas","Filter chats","Filtrar chats"),children:[e.jsx("span",{className:"lb",children:(Ps.find(J=>J.key===y)||Ps[0]).label}),e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev"})})]})]}
2),D&&e.jsx(ne,{content:de("IA do chat: Radar, Qualidade, atalhos","Chat AI: Radar, Quality, shortcuts","IA del chat"),position:"bottom",children:e.jsxs("button",{className:"cs-ai-btn",onClick:()=>{De(J=>!J),Qe(!1)},children:[e.jsx("span",{className:"gl",children:"✦"}),K?e.jsx("span",{className:"bdg",children:K>99?"99+":K}):null]})}),e.jsx(ne,{content:Y==="en"?"New chat":Y==="es"?"Nuevo chat":"Nova conversa",position:"left",children:e.jsx("button",{className:"cs-newchat",onClick:A,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-add"})})})})]}),Be&&e.jsx("div",{className:"cs-filter-menu",style:{top:131},children:Ps.map(J=>e.jsxs("button",{className:`fm-i${y===J.key?" on":""}`,onClick:()=>{w(J.key),Qe(!1)},children:[e.jsx("span",{className:"fm-c",children:y===J.key&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),J.dotColor&&e.jsx("span",{className:"lbl-dot",style:{background:J.dotColor}}),e.jsx("span",{children:J.label}),(J.count??Ot[J.key])!=null&&e.jsx("span",{className:"fm-n",children:J.count??Ot[J.key]})]},J.key))}),Me&&e.jsxs("div",{className:"cs-ai-menu",style:{top:131},children:[e.jsx("div",{className:"ai-h",children:de("IA do chat","Chat AI","IA del chat")}),e.jsxs("button",{className:"ai-i",onClick:()=>{De(!1),ae==null||ae()},children:["✦ ",de("Radar","Radar","Radar"),K?e.jsx("span",{className:"b",children:K}):null]}),Re&&e.jsxs("button",{className:"ai-i",onClick:()=>{De(!1),Re()},children:["📊 ",de("Qualidade","Quality","Calidad")]}),e.jsxs("button",{className:"ai-i",onClick:()=>{De(!1);try{window.dispatchEvent(new CustomEvent("pragmaz:cv2-ai-settings"))}catch{}},children:["⚙ ",de("Atalhos e tom","Shortcuts & tone","Atajos y tono")]})]}),y==="channels"&&e.jsxs("div",{style:{display:"flex",gap:6,padding:"0 12px 8px"},children:[e.jsxs("button",{onClick:()=>Ze({mode:"create",name:"",desc:""}),style:Rr,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-plus"})}),de("Criar canal","Create channel","Crear canal")]}),e.jsxs("button",{onClick:()=>Ze({mode:"join",invite:""}),style:Rr,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-link"})}),de("Entrar por link","Join by link","Entrar por enlace")]})]}),e.jsx(tc,{syncing:Q,locale:Y}),e.jsxs("div",{className:"cs-list",onScroll:J=>{if(!c)return;const We=J.currentTarget;We.scrollHeight-We.scrollTop-We.clientHeight<600&&c()},children:[s&&i.length===0&&e.jsxs("div",{className:"cs-loading",children:[e.jsx("span",{className:"cs-spinner"}),e.jsx("span",{children:de("Carregando conversas…","Loading chats…","Cargando chats…")})]}),(()=>{const J=Ee=>e.jsx(oc,{chat:Ee,selected:Ee.jid===f,typing:O[Ee.jid],presence:oe[Ee.jid],locale:Y,selectMode:le,checked:z.has(Ee.jid),markArchived:y!=="archived",kanban:(()=>{var Lt,ps;const ht=(Lt=_e==null?void 0:_e.contatos)==null?void 0:Lt[Ee.jid];return ht?{coluna:ht[0]!=null&&At.get(Number(ht[0]))||null,anuncio:ht[1]&&((ps=_e.anuncios)==null?void 0:ps[ht[1]])||null}:null})(),onQuick:x,onClick:()=>le?wt(Ee.jid):l(Ee),onContextMenu:ht=>{if(le){ht.preventDefault(),wt(Ee.jid);return}ht.preventDefault(),me({chat:Ee,x:ht.clientX,y:ht.clientY})}},Ee.jid);if(!!!(m&&m.trim())){if(!s&&i.length===0)return e.jsx("div",{style:{padding:30,color:"var(--text-4)",fontSize:13,textAlign:"center"},children:de("Nenhuma conversa.","No chats.","Sin chats.")});const Ee=new Date;Ee.setHours(0,0,0,0);const ht=Ee.getTime()/1e3-86400,Lt=Pt=>{var zs;if(Pt.isPinned)return"pin";const Gt=(zs=Pt.lastMessage)==null?void 0:zs.timestamp;return Gt?Gt>=Ee.getTime()/1e3?"hoje":Gt>=ht?"ontem":"antes":"antes"},ps={pin:de("Fixadas","Pinned","Fijadas"),hoje:de("Hoje","Today","Hoy"),ontem:de("Ontem","Yesterday","Ayer"),antes:de("Anteriores","Earlier","Anteriores")},ss=[];let Zt=null;for(const Pt of i){const Gt=Lt(Pt);Gt!==Zt&&(Zt=Gt,ss.push(e.jsx("div",{className:"cs-sec-h",children:ps[Gt]},`sec-${Gt}-${Pt.jid}`))),ss.push(J(Pt))}return ss}const it=new Set(i.map(Ee=>Ee.jid)),ot=$r((U||[]).filter(Ee=>!it.has(Ee.jid)&&!(Ee.lid&&it.has(Ee.lid))),Ee=>Ee.jid),ft=$r(u||[],Ee=>`${Ee.msg_id||""}|${Ee.jid||""}|${Ee.timestamp}`),Xt={};
2return i.forEach(Ee=>{Xt[Ee.jid]=Ee.name}),!s&&i.length===0&&ot.length===0&&ft.length===0?e.jsx("div",{style:{padding:30,color:"var(--text-4)",fontSize:13,textAlign:"center"},children:de("Nenhum resultado encontrado.","No results found.","Sin resultados.")}):e.jsxs(e.Fragment,{children:[i.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cs-sec-h",children:de("Conversas","Chats","Chats")}),i.map(J)]}),ot.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cs-sec-h",children:de("Contatos","Contacts","Contactos")}),ot.map(Ee=>e.jsx(rc,{contact:Ee,onClick:()=>p&&p(Ee)},Ee.jid))]}),ft.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cs-sec-h",children:de("Mensagens","Messages","Mensajes")}),ft.map(Ee=>e.jsx(ic,{msg:Ee,chatName:Xt[Ee.jid],query:m.trim(),locale:Y,onClick:()=>b&&b(Ee)},`${Ee.msg_id||""}|${Ee.jid||""}|${Ee.timestamp}`))]}),D&&m.trim().length>=4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cs-sec-h",style:{color:"var(--indigo-light)"},children:["✦ ",de("Perguntar à IA","Ask AI","Preguntar a la IA")]}),!st&&e.jsx("button",{onClick:dt,style:{display:"block",width:"calc(100% - 16px)",margin:"2px 8px 8px",textAlign:"left",cursor:"pointer",padding:"9px 11px",borderRadius:10,fontFamily:"inherit",fontSize:12.5,color:"var(--indigo-light)",background:"color-mix(in srgb, var(--indigo) 8%, transparent)",border:"1px dashed color-mix(in srgb, var(--indigo) 35%, transparent)"},children:de(`Buscar em português: "${m.trim().slice(0,44)}"`,`Ask in plain words: "${m.trim().slice(0,44)}"`,`Preguntar: "${m.trim().slice(0,44)}"`)}),(st==null?void 0:st.loading)&&e.jsxs("div",{style:{padding:"6px 14px 10px",fontSize:12,color:"var(--indigo-light)"},children:["✦ ",de("procurando…","searching…","buscando…")]}),(st==null?void 0:st.error)&&e.jsx("div",{style:{padding:"6px 14px 10px",fontSize:12,color:"var(--rose)"},children:st.error}),(st==null?void 0:st.hits)&&st.hits.length===0&&e.jsx("div",{style:{padding:"6px 14px 10px",fontSize:12,color:"var(--text-4)"},children:de("Nada encontrado com essa pergunta.","Nothing found.","Nada encontrado.")}),(st==null?void 0:st.hits)&&st.hits.map(Ee=>{const ht=i.find(Lt=>Lt.jid===Ee.jid);return e.jsxs("div",{className:"conv",onClick:()=>{b?b({jid:Ee.jid,msg_id:Ee.msgId,timestamp:Ee.ts,name:Ee.name||ht&&ht.name||null}):ht&&l(ht)},children:[e.jsx("div",{className:"av",children:String(Ee.name||Ee.jid).trim().charAt(0).toUpperCase()}),e.jsxs("div",{className:"col",children:[e.jsxs("div",{className:"row1",children:[e.jsx("span",{className:"nm",children:Ee.name||Ee.jid.split("@")[0]}),e.jsx("span",{className:"time",children:wi(Ee.ts,Y)})]}),e.jsx("div",{className:"row2",children:e.jsxs("span",{className:"last",children:[Ee.fromMe?Y==="en"?"You: ":Y==="es"?"Tú: ":"Você: ":"","“",Ee.text,"”"]})}),Ee.unanswered&&!Ee.fromMe&&e.jsx("div",{style:{marginTop:4},children:e.jsx("span",{style:{fontSize:10.5,fontWeight:600,padding:"1px 7px",borderRadius:999,color:"var(--text-3)",background:"var(--fill)",border:"1px solid var(--hairline)"},children:de("sem resposta","unanswered","sin respuesta")})})]})]},Ee.jid)})]})]})})(),d&&e.jsxs("div",{className:"cs-loading cs-loading-more",children:[e.jsx("span",{className:"cs-spinner"}),e.jsx("span",{children:de("Carregando mais conversas…","Loading more chats…","Cargando más chats…")})]}),!d&&v>mt&&e.jsx("button",{type:"button",className:"cs-load-more",onClick:()=>c==null?void 0:c(),children:de(`Carregar mais (${mt} de ${v})`,`Load more (${mt} of ${v})`,`Cargar más (${mt} de ${v})`)})]}),G&&e.jsxs("div",{className:"conv-actions-menu",style:{top:G.y,left:G.x},onClick:J=>J.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{x(G.chat,"pin",!G.chat.isPinned),me(null)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-fill"})}),G.chat.isPinned?de("Desafixar","Unpin","Desfijar"):de("Fixar","Pin","Fijar")]}),G.chat.isMuted?e.jsxs("button",{onClick:()=>{x(G.chat,"mute",null),me(null)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-bell"})}),de("Reativar","Unmute","Reactivar")]}):G.chat.isNewsletter?e.jsxs("button",{onClick:()=>{x(G.chat,"mute",Date.now()+10*365*864e5),me(null)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-mute"})}),de("Silenciar","Mute","Silenciar")]}):e.jsxs("div",{className:"mute-sub",style:{position:"relative"},onMouseEnter:()=>Fe(!0),onMouseLeave:()=>Fe(!1),children:[e.jsxs("button",{onClick:()=>Fe(J=>!J),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-mute"})}),de("Silenciar","Mute","Silenciar"),e.jsx("svg",{style:{marginLeft:"auto",width:14,height:14,opacity:.6},children:e.jsx("use",{href:"#ci-chev-r"})})]}),Se&&e.jsx("div",{className:"conv-actions-menu",style:{position:"absolute",left:"100%",top:0,minWidth:150},children:[{lbl:de("8 horas","8 hours","8 horas"),ms:8*36e5},{lbl:de("1 semana","1 week","1 semana"),ms:7*864e5},{lbl:de("Sempre","Always","Siempre"),ms:10*365*864e5}].map(J=>e.jsx("button",{onClick:()=>{x(G.chat,"mute",Date.now()+J.ms),me(null),Fe(!1)},children:J.lbl},J.lbl))})]}),e.jsxs("button",{onClick:()=>{x(G.chat,(G.chat.unreadCount||0)>0?"markRead":"markUnread"),me(null)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-mark-read"})}),(G.chat.unreadCount||0)>0?de("Marcar como lida","Mark as read","Marcar como leída"):de("Marcar como não lida","Mark as unread","Marcar como no leída")]}),!G.chat.isNewsletter&&e.jsxs("button",{onClick:()=>{x(G.chat,"archive",!G.chat.isArchived),me(null)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-archive"})}),G.chat.isArchived?de("Desarquivar","Unarchive","Desarchivar"):de("Arquivar","Archive","Archivar")]}),e.jsxs("button",{onClick:()=>{const J=G.chat;me(null),Xe(!0),Ce(new Set([J.jid]))},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})}),de("Selecionar","Select","Seleccionar")]}),!G.chat.isNewsletter&&e.jsx("div",{className:"sep"}),!G.chat.isNewsletter&&e.jsxs("button",{className:"danger",onClick:()=>{const J=G.chat;me(null),P==null||P({title:de("Apagar conversa?","Delete chat?","¿Borrar chat?"),message:de(`Toda a conversa com ${lt(J.name,{phone:J.phone,jid:J.jid,lidLabel:"este contato"})} será removida do dispositivo. Mensagens não serão apagadas pra outros.`,`The whole chat with ${lt(J.name,{phone:J.phone,jid:J.jid,lidLabel:"this contact"})} will be removed from this device. Messages won't be deleted for others.`,`Todo el chat con ${lt(J.name,{phone:J.phone,jid:J.jid,lidLabel:"este contacto"})} se eliminará de este dispositivo. Los mensajes no se borrarán para los demás.`),confirmLabel:de("Apagar","Delete","Borrar"),onConfirm:()=>x(J,"delete")})},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})}),de("Apagar conversa","Delete chat","Borrar chat")]})]}),L&&e.jsx("div",{className:"cv2-modal-overlay",onMouseDown:J=>J.target===J.currentTarget&&!rt&&Ze(null),children:e.jsxs("div",{className:"cv2-modal",style:{maxWidth:400},onMouseDown:J=>J.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("h3",{children:L.mode==="create"?de("Criar canal","Create channel","Crear canal"):de("Entrar em canal","Join channel","Entrar en canal")}),e.jsx("button",{className:"x",onClick:()=>!rt&&Ze(null),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})]}),e.jsxs("div",{style:{padding:"4px 16px 14px",display:"flex",flexDirection:"column",gap:10},children:[L.mode==="create"?e.jsxs(e.Fragment,{children:[e.jsx("input",{autoFocus:!0,maxLength:25,value:L.name,onChange:J=>Ze(We=>({...We,name:J.target.value})),placeholder:de("Nome do canal (máx. 25)","Channel name (max 25)","Nombre del canal (máx. 25)"),style:ia}),e.jsx("textarea",{rows:3,maxLength:2048,value:L.desc,onChange:J=>Ze(We=>({...We,desc:J.target.value})),placeholder:de("Descrição (opcional)","Description (optional)","Descripción (opcional)"),style:{...ia,resize:"vertical"}})]}):e.jsx("input",{autoFocus:!0,value:L.invite,onChange:J=>Ze(We=>({...We,invite:J.target.value})),placeholder:"whatsapp.com/channel/XXXXXXXX",style:ia}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:2},children:[e.jsx("button",{onClick:()=>!rt&&Ze(null),style:{background:"transparent",border:0,color:"var(--text-3)",fontSize:13,cursor:"pointer",fontFamily:"inherit"}
2,children:de("Cancelar","Cancel","Cancelar")}),e.jsx("button",{disabled:rt||(L.mode==="create"?!L.name.trim():!L.invite.trim()),onClick:async()=>{_t(!0);const J=L.mode==="create"?{action:"create",name:L.name.trim(),description:L.desc.trim()||null}:{action:"join",invite:L.invite.trim()},We=await(Z==null?void 0:Z(J));_t(!1),We&&Ze(null)},style:{background:"var(--indigo-light, #6366f1)",border:0,color:"#fff",fontSize:13,padding:"7px 16px",borderRadius:6,cursor:"pointer",fontFamily:"inherit",opacity:rt?.6:1},children:rt?"…":L.mode==="create"?de("Criar","Create","Crear"):de("Entrar","Join","Entrar")})]})]})]})}),ye&&e.jsx("div",{className:"cv2-modal-backdrop",onClick:()=>at(null),children:e.jsxs("div",{className:"cv2-modal",style:{maxWidth:380},onClick:J=>J.stopPropagation(),children:[e.jsx("div",{className:"cv2-modal-head",children:e.jsxs("div",{children:[e.jsx("div",{className:"ttl",children:de("Apagar conversas?","Delete chats?","¿Borrar chats?")}),e.jsxs("div",{className:"sub",style:{marginTop:4,lineHeight:1.5,color:"var(--text-2)"},children:[ye.jids.length," ",de("conversa(s) serão removidas deste dispositivo.","chat(s) will be removed from this device.","chat(s) serán eliminados de este dispositivo.")]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,marginTop:12,fontSize:13,color:"var(--text-2)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:Yt,onChange:J=>Qt(J.target.checked)}),de("Também apagar no celular","Also delete on phone","También borrar en el celular")]})]})}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:()=>at(null),children:de("Cancelar","Cancel","Cancelar")}
2),e.jsx("button",{className:"confirm",style:{background:"var(--rose)",color:"var(--on-accent)"},onClick:Kt,children:de("Apagar","Delete","Borrar")})]})]})})]})}function nc(t,n,o){const i=(n||"").trim();switch(t){case"image":return o("Foto","Photo","Foto");case"video":return o("Vídeo","Video","Video");case"audio":return o("Áudio","Audio","Audio");case"document":return i||o("Documento","Document","Documento");case"sticker":return o("Figurinha","Sticker","Figurita");case"contact":return"👤 "+(i||o("Contato","Contact","Contacto"));case"location":return o("Localização","Location","Ubicación");case"poll":return i||o("Enquete","Poll","Encuesta");default:return i}}function ac(t,n){const o=String(t||"");if(!n)return o;const i=d=>d.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,""),s=i(o),f=i(n);if(!f)return o;const l=s.indexOf(f);if(l<0)return o;const c=l+f.length;return e.jsxs(e.Fragment,{children:[o.slice(0,l),e.jsx("span",{className:"cs-hl",children:o.slice(l,c)}),o.slice(c)]})}function rc({contact:t,onClick:n}){const o=lt(t.name,{phone:t.phone,jid:t.jid});return e.jsxs("div",{className:"conv",onClick:n,children:[e.jsx("div",{className:"av",children:t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:""}):an(o)}),e.jsxs("div",{className:"col",children:[e.jsx("div",{className:"row1",children:e.jsx("span",{className:"nm",children:o})}),e.jsx("div",{className:"row2",children:e.jsx("span",{className:"last",children:bt(t.phone)||t.statusText||""})})]})]})}function ic({msg:t,chatName:n,query:o,locale:i="pt",onClick:s}){const f=n||lt(t.name,{phone:String(t.jid||"").replace("@s.whatsapp.net",""),jid:t.jid}),l=Number(t.timestamp)||0,c=l>0&&l<1e12?l*1e3:l,d=i==="en"?"en-US":i==="es"?"es-ES":"pt-BR",v=t.from_me?i==="en"?"You: ":i==="es"?"Tú: ":"Você: ":"";return e.jsxs("div",{className:"conv",onClick:s,children:[e.jsx("div",{className:"av",children:t.img_url?e.jsx("img",{src:t.img_url,alt:""}):an(f)}),e.jsxs("div",{className:"col",children:[e.jsxs("div",{className:"row1",children:[e.jsx("span",{className:"nm",children:f}),e.jsx("span",{className:"time",children:c?new Date(c).toLocaleDateString(d,{day:"2-digit",month:"2-digit",year:"2-digit"}):""})]}),e.jsx("div",{className:"row2",children:e.jsxs("span",{className:"last",children:[v,ac(t.text_content,o)]})})]})]})}function oc({chat:t,selected:n,typing:o,presence:i,locale:s="pt",selectMode:f=!1,checked:l=!1,markArchived:c=!1,kanban:d=null,onClick:v,onContextMenu:k,onQuick:x}){var b,se;const{settings:P}=bs(),A=(C,H,Q)=>s==="en"?H:s==="es"?Q:C,y=(t.unreadCount||0)>0,w=t.lastMessage||{},m=w.msgType,I=Array.isArray(t.labels)?t.labels.slice(0,3):[],U=i&&(i.type==="available"||i==="available"||i===!0),u=o||m==="reaction"||m==="revoked"||m==="revoke"?"":w.fromMe?s==="en"?"You: ":s==="es"?"Tú: ":"Você: ":t.isGroup&&w.pushName?`${w.pushName}: `:"";let p=null;return o?o.type==="recording"?p=e.jsxs("span",{className:"recording",children:[o.participant?`${o.participant} `:"",A("gravando áudio…","recording audio…","grabando audio…")]}):p=e.jsxs("span",{className:"typing",children:[o.participant?`${o.participant} `:"",A("digitando…","typing…","escribiendo…")]}):p=e.jsxs(e.Fragment,{children:[u&&e.jsx("span",{style:{color:"var(--text-3)"},children:u}),m==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-image"})})})," ",w.text||A("Foto","Photo","Foto")]}),m==="video"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-video"})})})," ",w.text||A("Vídeo","Video","Video")]}),m==="audio"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-mic-fill"})})})," ",A("Áudio","Audio","Audio")]}),m==="document"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-file"})})})," ",w.text||A("Documento","Document","Documento")]}),m==="poll"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-poll"})})})," ",A("Enquete","Poll","Encuesta")]}),m==="sticker"&&e.jsx("span",{style:{color:"var(--text-3)"},children:"Sticker"}),m==="location"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-loc"})})})," ",A("Localização","Location","Ubicación")]}),(m==="contact"||m==="contacts")&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-user"})})})," ",w.text||A("Contato","Contact","Contacto")]}),m==="reaction"&&(()=>{const C=w.reaction||{};if(!C.emoji)return null;const H=nc(C.targetType,C.targetText,A),Q=w.fromMe?A("Você reagiu com","You reacted with","Reaccionaste con"):`${C.actor?C.actor+" ":""}${A("reagiu com","reacted with","reaccionó con")}`;return e.jsxs("span",{style:{color:"var(--text-3)"},children:[Q," ",C.emoji,H?` ${A("a:","to:","a:")} "${H}"`:""]})})(),(m==="revoked"||m==="revoke")&&e.jsxs("span",{style:{color:"var(--text-3)",fontStyle:"italic",display:"inline-flex",alignItems:"center",gap:5},children:[e.jsx("span",{className:"ic",style:{display:"inline-flex"},children:e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-block"})})}),w.fromMe?A("Você apagou esta mensagem","You deleted this message","Eliminaste este mensaje"):A("Esta mensagem foi apagada","This message was deleted","Este mensaje fue eliminado")]}),m==="unsupported"&&e.jsxs("span",{style:{color:"var(--text-3)",fontStyle:"italic",display:"inline-flex",alignItems:"center",gap:5},children:[e.jsx("span",{className:"ic",style:{display:"inline-flex"},children:e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-alert"})})}),A("Mensagem não suportada","Unsupported message","Mensaje no compatible")]}),(!m||["text","system","template","button","buttons","list","interactive","order","product","payment","event","album","groupInvite","request_welcome"].includes(m))&&(w.text||"")]}),e.jsxs("div",{className:`conv${n?" active":""}${y?" unread":""}${f?" selecting":""}${l?" checked":""}`,onClick:v,onContextMenu:k,children:[f&&e.jsx("span",{className:"conv-check",children:l&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),e.jsxs("div",{className:`av ${It("blurAvatars",P)}`,children:[t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:""}):an(lt(t.name,{phone:t.phone,jid:t.jid})),t.isGroup&&e.jsx("span",{className:"group-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-users"})})}),t.isNewsletter&&e.jsx("span",{className:"group-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-megaphone"})})}),U&&!t.isGroup&&!t.isNewsletter&&e.jsx("span",{className:"online-dot"})]}),e.jsxs("div",{className:"col",children:[e.jsxs("div",{className:"row1",children:[!t.isGroup&&t.phone?e.jsx(ne,{content:bt(t.phone),position:"top",children:e.jsx("span",{className:`nm ${It("blurNames",P)}`,children:lt(t.name,{phone:t.phone,jid:t.jid})})}):e.jsx("span",{className:`nm ${It("blurNames",P)}`,children:lt(t.name,{phone:t.phone,jid:t.jid})}),I.map((C,H)=>e.jsx(ne,{content:Ht(C,s),position:"top",children:e.jsx("span",{className:"lbl-dot",style:{background:Ds(C.color)}})},H)),(d==null?void 0:d.coluna)&&!d.coluna.entrada&&e.jsx(ne,{content:`Kanban: ${d.coluna.nome}${(b=d.anuncio)!=null&&b.titulo?` · ${A("Anúncio","Ad","Anuncio")}: ${d.anuncio.titulo}`:""}`,position:"top",children:e.jsx("span",{className:"lbl-dot","data-kanban-dot":"1",style:{background:d.coluna.cor||"#667eea"}})}),e.jsx("span",{className:"time",children:wi(w.timestamp,s)})]}),e.jsxs("div",{className:"row2",children:[e.jsx("span",{className:`last ${It("blurPreviews",P)}`,children:p}),e.jsxs("div",{className:"ind",children:[c&&t.isArchived&&e.jsx(ne,{content:A("Conversa arquivada","Archived chat","Chat archivado"),position:"top",children:e.jsx("span",{className:"arch-chip",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-archive"})})})}),t.isMuted&&e.jsx("span",{className:"muted",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-mute"})})}),t.isPinned&&e.jsx("span",{className:"pin",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-fill"})})}),y&&e.jsx("span",{className:"unread-n",children:t.unreadCount>99?"99+":t.unreadCount})]})]}),((se=d==null?void 0:d.anuncio)==null?void 0:se.titulo)&&e.jsx("div",{className:"row3",children:e.jsx(ne,{content:`${A("Veio do anúncio","Came from the ad","Vino del anuncio")}: ${d.anuncio.titulo}`,position:"top",children:e.jsxs("span",{className:"ad-tag","data-ad-tag":"1",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-megaphone"})}),e.jsx("span",{className:"tx",children:d.anuncio.titulo})]})})})]}),!f&&x&&e.jsxs("div",{className:"hv-acts",children:[e.jsx(ne,{content:t.isPinned?A("Desafixar","Unpin","Desfijar"):A("Fixar","Pin","Fijar"),position:"top",children:e.jsx("button",{className:"hb",onClick:C=>{C.stopPropagation(),x(t,"pin",!t.isPinned)},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-fill"})})})}),e.jsx(ne,{content:t.isMuted?A("Reativar som","Unmute","Reactivar"):A("Silenciar","Mute","Silenciar"),position:"top",children:e.jsx("button",{className:"hb",onClick:C=>{C.stopPropagation(),x(t,"mute",t.isMuted?null:Date.now()+8*36e5)},children:e.jsx("svg",{children:e.jsx("use",{href:t.isMuted?"#ci-bell":"#ci-mute"})})})}),e.jsx(ne,{content:t.isArchived?A("Desarquivar","Unarchive","Desarchivar"):A("Arquivar","Archive","Archivar"),position:"top",children:e.jsx("button",{className:"hb",onClick:C=>{C.stopPropagation(),x(t,"archive",!t.isArchived)},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-archive"})})})}
2),e.jsx(ne,{content:y?A("Marcar como lida","Mark read","Marcar leída"):A("Marcar como não lida","Mark unread","Marcar no leída"),position:"top",children:e.jsx("button",{className:"hb",onClick:C=>{C.stopPropagation(),x(t,y?"markRead":"markUnread")},children:e.jsx("svg",{children:e.jsx("use",{href:y?"#ci-check":"#ci-mark-read"})})})})]})]})}const Tr={title:{pt:"Mensagens agendadas",en:"Scheduled messages",es:"Mensajes programados"},up:{pt:"Vão sair",en:"Upcoming",es:"Por salir"},failed:{pt:"Não saíram",en:"Failed",es:"No salieron"},done:{pt:"Já enviadas",en:"Sent",es:"Enviados"},emptyUp:{pt:"Nada agendado nesta conversa.",en:"Nothing scheduled here.",es:"Nada programado aquí."},emptyFail:{pt:"Nenhuma falha. 👌",en:"No failures.",es:"Sin fallos."},emptyDone:{pt:"Nada foi enviado por agendamento ainda.",en:"Nothing sent by schedule yet.",es:"Nada enviado aún."},edit:{pt:"Mudar horário",en:"Change time",es:"Cambiar hora"},now:{pt:"Enviar agora",en:"Send now",es:"Enviar ahora"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},retry:{pt:"Tentar de novo",en:"Retry",es:"Reintentar"},askCancel:{pt:"Cancelar este agendamento? A mensagem não será enviada.",en:"Cancel this schedule? The message will not be sent.",es:"¿Cancelar? El mensaje no se enviará."},askNow:{pt:"Enviar esta mensagem agora, sem esperar o horário?",en:"Send this message now?",es:"¿Enviar ahora?"},waiting:{pt:"Aguardando o dispositivo",en:"Waiting for the device",es:"Esperando el dispositivo"},nextTry:{pt:"nova tentativa",en:"retry at",es:"reintento"},sending:{pt:"Enviando agora…",en:"Sending…",es:"Enviando…"},sentAt:{pt:"enviada",en:"sent",es:"enviado"},by:{pt:"por",en:"by",es:"por"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},attempts:{pt:"tentativas",en:"attempts",es:"intentos"},keep:{pt:"Voltar",en:"Back",es:"Volver"},confirmCancel:{pt:"Sim, cancelar",en:"Yes, cancel",es:"Sí, cancelar"}},Ct=(t,n)=>(Tr[t]||{})[n]||(Tr[t]||{}).pt||t,Fr={text:"#ci-msg",image:"#ci-image",video:"#ci-video",audio:"#ci-mic-fill",document:"#ci-file",sticker:"#ci-smile",poll:"#ci-poll",location:"#ci-loc",contact:"#ci-user",template:"#ci-zap"},Ts={pt:{text:"Mensagem",image:"Foto",video:"Vídeo",audio:"Áudio",document:"Documento",sticker:"Figurinha",poll:"Enquete",location:"Localização",contact:"Contato",template:"Template"},en:{text:"Message",image:"Photo",video:"Video",audio:"Audio",document:"Document",sticker:"Sticker",poll:"Poll",location:"Location",contact:"Contact",template:"Template"},es:{text:"Mensaje",image:"Foto",video:"Vídeo",audio:"Audio",document:"Documento",sticker:"Sticker",poll:"Encuesta",location:"Ubicación",contact:"Contacto",template:"Plantilla"}},oa=(t,n,o=!1)=>new Date(t).toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{weekday:"short",day:"2-digit",month:"2-digit",...o?{year:"2-digit"}:{},hour:"2-digit",minute:"2-digit"});function cc({s:t}){var i;const n=(i=t.content)==null?void 0:i.url;return["image","sticker"].includes(t.type)&&n?e.jsx("img",{className:"cvsm-thumb",src:n,alt:"",onError:s=>{s.currentTarget.style.display="none"}}):e.jsx("span",{className:`cvsm-ic t-${t.type}`,children:e.jsx("svg",{children:e.jsx("use",{href:Fr[t.type]||Fr.text})})})}function lc({s:t,locale:n}){const o=t.content||{};return t.type==="text"?e.jsx("div",{className:"cvsm-txt",children:o.text||t.text}):t.type==="poll"?e.jsxs("div",{className:"cvsm-txt",children:[e.jsx("b",{children:o.name}),e.jsx("ul",{className:"cvsm-poll",children:(o.values||[]).map((i,s)=>e.jsx("li",{children:i},s))})]}):t.type==="contact"?e.jsxs("div",{className:"cvsm-txt",children:[o.displayName||o.name," · ",o.phone]}):t.type==="location"?e.jsx("div",{className:"cvsm-txt",children:o.name||`${o.latitude}, ${o.longitude}`}):t.type==="template"?e.jsxs("div",{className:"cvsm-txt",children:[(Ts[n]||Ts.pt).template," #",t.templateId]}):t.type==="audio"?e.jsxs("div",{className:"cvsm-txt",children:[o.ptt?"🎤":"🎵"," ",o.seconds?`${Math.round(o.seconds)}s`:""]}):e.jsxs("div",{className:"cvsm-txt",children:[o.fileName&&e.jsx("div",{className:"cvsm-file",children:o.fileName}),o.caption&&e.jsx("div",{children:o.caption}),!o.fileName&&!o.caption&&(Ts[n]||Ts.pt)[t.type]]})}
2function dc({open:t,onClose:n,schedules:o=[],locale:i="pt",onChanged:s,onConfirmAsk:f}){const l=ba(),[c,d]=r.useState(null),[v,k]=r.useState(null),[x,P]=r.useState(!1),[A,y]=r.useState(null),w=r.useMemo(()=>({up:o.filter(p=>["pending","retrying","sending"].includes(p.status)).sort((p,b)=>new Date(p.scheduledAt)-new Date(b.scheduledAt)),failed:o.filter(p=>p.status==="failed"),done:o.filter(p=>p.status==="sent").sort((p,b)=>new Date(b.sentAt||b.scheduledAt)-new Date(p.sentAt||p.scheduledAt))}),[o]),m=c||(w.failed.length?"failed":"up");if(!t)return null;const I=async(p,b)=>{var se,C;P(!0);try{await p(),b&&W.success(b),s==null||s()}catch(H){W.error(((C=(se=H==null?void 0:H.response)==null?void 0:se.data)==null?void 0:C.error)||(i==="en"?"Something went wrong":i==="es"?"Algo salió mal":"Não deu certo"))}finally{P(!1)}},U=w[m]||[],u={up:"emptyUp",failed:"emptyFail",done:"emptyDone"}[m];return _s.createPortal(e.jsxs("div",{className:"cv2-portal cvsm-ov","data-cv2-theme":l,onMouseDown:p=>{p.target===p.currentTarget&&(n==null||n())},children:[e.jsxs("div",{className:"cvsm",role:"dialog","aria-modal":"true",children:[e.jsxs("div",{className:"cvsm-head",children:[e.jsx("span",{className:"cvsm-hic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsx("h3",{children:Ct("title",i)}),e.jsx("button",{className:"cvsm-x",onClick:n,"aria-label":Ct("close",i),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})]}),e.jsx("div",{className:"cvsm-tabs",children:[{k:"up",n:w.up.length},{k:"failed",n:w.failed.length},{k:"done",n:w.done.length}].map(p=>e.jsxs("button",{className:`cvsm-tab${m===p.k?" on":""}${p.k==="failed"&&p.n?" bad":""}`,onClick:()=>d(p.k),children:[Ct(p.k,i),p.n>0&&e.jsx("span",{className:"cvsm-n",children:p.n})]},p.k))}),e.jsxs("div",{className:"cvsm-body",children:[!U.length&&e.jsx("div",{className:"cvsm-empty",children:Ct(u,i)}),U.map(p=>e.jsxs("div",{className:`cvsm-card ${m}`,children:[e.jsx(cc,{s:p}),e.jsxs("div",{className:"cvsm-mid",children:[e.jsxs("div",{className:"cvsm-top",children:[e.jsx("span",{className:"cvsm-tipo",children:(Ts[i]||Ts.pt)[p.type]||p.type}),e.jsx("span",{className:"cvsm-when",children:p.status==="sent"?`${Ct("sentAt",i)} ${oa(p.sentAt||p.scheduledAt,i)}`:oa(p.scheduledAt,i)})]}),e.jsx(lc,{s:p,locale:i}),p.status==="retrying"&&e.jsxs("div",{className:"cvsm-state warn",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-alert"})}),Ct("waiting",i)," — ",Ct("nextTry",i)," ",p.nextAttemptAt?oa(p.nextAttemptAt,i):"",p.attempts>1&&` · ${p.attempts} ${Ct("attempts",i)}`]}),p.status==="sending"&&e.jsx("div",{className:"cvsm-state warn",children:Ct("sending",i)}),p.status==="failed"&&p.error&&e.jsxs("div",{className:"cvsm-state bad",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-alert"})}),p.error]})]}),p.status!=="sent"&&p.status!=="sending"&&((A==null?void 0:A.id)===p.id?e.jsxs("div",{className:"cvsm-acts cvsm-conf",children:[e.jsx("span",{className:"cvsm-conf-q",children:A.acao==="cancel"?Ct("askCancel",i):Ct("askNow",i)}),e.jsxs("div",{className:"cvsm-conf-btns",children:[e.jsx("button",{className:"cvsm-act",disabled:x,onClick:()=>y(null),children:Ct("keep",i)}),e.jsx("button",{className:`cvsm-act ${A.acao==="cancel"?"bad":"go"}`,disabled:x,onClick:async()=>{const b=A;y(null),b.acao==="cancel"?await I(()=>M.delete(`/wa/chat/schedules/${p.id}`)):await I(()=>M.post(`/wa/chat/schedules/${p.id}/send-now`),i==="en"?"Sending now":i==="es"?"Enviando ahora":"Enviando agora")},children:A.acao==="cancel"?Ct("confirmCancel",i):Ct("now",i)})]})]}):e.jsxs("div",{className:"cvsm-acts",children:[e.jsxs("button",{className:"cvsm-act",disabled:x,onClick:()=>k(p),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})}),Ct("edit",i)]}),e.jsxs("button",{className:"cvsm-act",disabled:x,onClick:()=>y({id:p.id,acao:"now"}),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-send"})}),p.status==="failed"?Ct("retry",i):Ct("now",i)]}),e.jsxs("button",{className:"cvsm-act bad",disabled:x,onClick:()=>y({id:p.id,acao:"cancel"}),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})}),Ct("cancel",i)]})]}))]}
2,p.id))]})]}),e.jsx(Do,{open:!!v,editing:!0,locale:i,busy:x,initialAt:v==null?void 0:v.scheduledAt,onClose:()=>k(null),onConfirm:async p=>{const b=v;k(null),await I(()=>M.patch(`/wa/chat/schedules/${b.id}`,{scheduledAt:p}),i==="en"?"Rescheduled":i==="es"?"Reprogramado":"Reagendada")}})]}),document.body)}const _r={pt:{tip:"Atribuir / quem pode acessar",aria:"Atribuir / compartilhar conversa",title:"Atribuir conversa",close:"Fechar",loading:"Carregando…",none1:"Nenhum atendente com acesso a este dispositivo.",none2:"Libere o dispositivo para a equipe em",team:"Equipe",search:"Buscar atendente…",owner:"Responsável",ownerHint:"— recebe a conversa e a notificação",queue:"Fila (sem responsável)",queueSub:"Volta para a fila não-atribuída",others:"Quem mais pode acessar",othersHint:"— veem e respondem, sem ser o responsável",noOthers:"Nenhum outro atendente.",cancel:"Cancelar",saving:"Salvando…",save:"Salvar",loadErr:"Erro ao carregar atendentes",saved:"Acesso da conversa atualizado",saveErr:"Erro ao salvar",manager:"Gerente",agent:"Atendente"},es:{tip:"Asignar / quién puede acceder",aria:"Asignar / compartir conversación",title:"Asignar conversación",close:"Cerrar",loading:"Cargando…",none1:"Ningún agente tiene acceso a este dispositivo.",none2:"Habilita el dispositivo para el equipo en",team:"Equipo",search:"Buscar agente…",owner:"Responsable",ownerHint:"— recibe la conversación y la notificación",queue:"Cola (sin responsable)",queueSub:"Vuelve a la cola sin asignar",others:"Quién más puede acceder",othersHint:"— ven y responden, sin ser el responsable",noOthers:"Ningún otro agente.",cancel:"Cancelar",saving:"Guardando…",save:"Guardar",loadErr:"Error al cargar los agentes",saved:"Acceso a la conversación actualizado",saveErr:"Error al guardar",manager:"Gerente",agent:"Agente"},en:{tip:"Assign / who can access",aria:"Assign / share conversation",title:"Assign conversation",close:"Close",loading:"Loading…",none1:"No agent has access to this device.",none2:"Give the team access to the device in",team:"Team",search:"Search agent…",owner:"Owner",ownerHint:"— receives the conversation and the notification",queue:"Queue (no owner)",queueSub:"Goes back to the unassigned queue",others:"Who else can access",othersHint:"— they see and reply, without being the owner",noOthers:"No other agent.",cancel:"Cancel",saving:"Saving…",save:"Save",loadErr:"Could not load agents",saved:"Conversation access updated",saveErr:"Could not save",manager:"Manager",agent:"Agent"}};function Dr({name:t,active:n}){const o=(t||"?").trim().charAt(0).toUpperCase();return e.jsx("div",{style:{width:36,height:36,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:700,color:n?"#fff":"var(--accent,#8b8bf5)",background:n?"var(--accent,#6366f1)":"color-mix(in srgb, var(--accent,#6366f1) 16%, transparent)",transition:"all .15s"},children:o})}function Lr({on:t}){return e.jsx("div",{style:{width:20,height:20,borderRadius:"50%",flexShrink:0,border:`2px solid ${t?"var(--accent,#6366f1)":"var(--hairline-strong,rgba(255,255,255,.22))"}`,display:"flex",alignItems:"center",justifyContent:"center"},children:t&&e.jsx("div",{style:{width:10,height:10,borderRadius:"50%",background:"var(--accent,#6366f1)"}})})}function uc({on:t}){return e.jsx("div",{style:{width:20,height:20,borderRadius:6,flexShrink:0,border:`2px solid ${t?"var(--accent,#6366f1)":"var(--hairline-strong,rgba(255,255,255,.22))"}`,background:t?"var(--accent,#6366f1)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff"},children:t&&e.jsx(vo,{size:13,strokeWidth:3})})}function pc({sessionId:t,chat:n}){const{locale:o}=ds(),i=_r[o]||_r.pt,{user:s}=mi(),f=ba(),l=(s==null?void 0:s.team_role)==="manager"||(s==null?void 0:s.is_team_owner)===!0,[c,d]=r.useState(!1),[v,k]=r.useState(!1),[x,P]=r.useState(!1),[A,y]=r.useState([]),[w,m]=r.useState(""),[I,U]=r.useState(null),[u,p]=r.useState(()=>new Set),[b,se]=r.useState({assignee:null,access:new Set}),C=r.useCallback(async()=>{var _,$,X;k(!0),m("");try{const[ce,Z]=await Promise.all([M.get("/wa/chat/assignees",{params:{sessionId:t}}
2),M.get("/wa/chat/access",{params:{sessionId:t,jid:n.jid}})]);y(((_=ce.data)==null?void 0:_.assignees)||[]);const D=(($=Z.data)==null?void 0:$.assigned_user_id)??null,ae=new Set((((X=Z.data)==null?void 0:X.access_member_ids)||[]).map(Number));U(D==null?null:Number(D)),p(ae),se({assignee:D==null?null:Number(D),access:new Set(ae)})}catch{W.error(i.loadErr)}finally{k(!1)}},[t,n.jid]);r.useEffect(()=>{c&&C()},[c,C]);const H=r.useMemo(()=>{const _=w.trim().toLowerCase();return _?A.filter($=>($.name||"").toLowerCase().includes(_)):A},[A,w]),Q=_=>p($=>{const X=new Set($);return X.has(_)?X.delete(_):X.add(_),X}),O=_=>{U(_),_!=null&&p($=>{const X=new Set($);return X.delete(_),X})},oe=r.useMemo(()=>{if(I!==b.assignee||u.size!==b.access.size)return!0;for(const _ of u)if(!b.access.has(_))return!0;return!1},[I,u,b]),ke=async()=>{var _,$;P(!0);try{I!==b.assignee&&(I==null?await M.post("/wa/chat/unassign",{sessionId:t,jid:n.jid}):await M.post("/wa/chat/assign",{sessionId:t,jid:n.jid,assigneeUserId:I}));const X=[...u].filter(ce=>ce!==I);await M.put("/wa/chat/access",{sessionId:t,jid:n.jid,member_user_ids:X}),W.success(i.saved),d(!1)}catch(X){W.error((($=(_=X.response)==null?void 0:_.data)==null?void 0:$.error)||i.saveErr)}finally{P(!1)}};if(!l)return null;const Ae=_=>_==="manager"?i.manager:i.agent,ve=H.filter(_=>Number(_.member_user_id)!==I);return e.jsxs(e.Fragment,{children:[e.jsx(ne,{content:i.tip,position:"bottom",children:e.jsx("button",{className:"a-btn",onClick:()=>d(!0),"aria-label":i.aria,children:e.jsx(hi,{size:18})})}),c&&_s.createPortal(e.jsx("div",{className:"cv2-portal","data-cv2-theme":f,onClick:()=>!x&&d(!1),style:gt.backdrop,children:e.jsxs("div",{onClick:_=>_.stopPropagation(),style:gt.modal,children:[e.jsxs("div",{style:gt.head,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,minWidth:0},children:[e.jsx("div",{style:gt.headIcon,children:e.jsx(nn,{size:17})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:gt.title,children:i.title}),e.jsx("div",{style:gt.sub,children:n.name||n.jid})]})]}),e.jsx(ne,{content:i.close,position:"left",children:e.jsx("button",{onClick:()=>!x&&d(!1),style:gt.close,"aria-label":i.close,children:e.jsx(ya,{size:18})})})]}),v?e.jsx("div",{style:{padding:"40px 0",textAlign:"center",color:"var(--text-3,#71717a)"},children:i.loading}):A.length===0?e.jsxs("div",{style:{padding:"36px 18px",textAlign:"center",color:"var(--text-3,#71717a)",fontSize:14,lineHeight:1.5},children:[i.none1,e.jsx("br",{}),i.none2," ",e.jsx("b",{children:i.team}),"."]}):e.jsxs("div",{style:gt.body,children:[A.length>6&&e.jsxs("div",{style:{position:"relative",margin:"0 0 12px"},children:[e.jsx(go,{size:14,style:{position:"absolute",left:11,top:"50%",transform:"translateY(-50%)",color:"var(--text-3,#71717a)"}}),e.jsx("input",{value:w,onChange:_=>m(_.target.value),placeholder:i.search,style:gt.search})]}),e.jsxs("div",{style:gt.sectionLabel,children:[i.owner," ",e.jsx("span",{style:gt.hint,children:i.ownerHint})]}),e.jsxs("div",{style:gt.list,children:[e.jsxs("button",{onClick:()=>O(null),style:gt.row(I==null),children:[e.jsx("div",{style:{...gt.queueIcon,...I==null?{background:"var(--accent,#6366f1)",color:"#fff"}:{}},children:e.jsx(xo,{size:16})}),e.jsxs("div",{style:{flex:1,textAlign:"left",minWidth:0},children:[e.jsx("div",{style:gt.name,children:i.queue}),e.jsx("div",{style:gt.role,children:i.queueSub})]}),e.jsx(Lr,{on:I==null})]}),H.map(_=>e.jsxs("button",{onClick:()=>O(Number(_.member_user_id)),style:gt.row(I===Number(_.member_user_id)),children:[e.jsx(Dr,{name:_.n
2ame,active:I===Number(_.member_user_id)}),e.jsxs("div",{style:{flex:1,textAlign:"left",minWidth:0},children:[e.jsx("div",{style:gt.name,children:_.name}),e.jsx("div",{style:gt.role,children:Ae(_.team_role)})]}),e.jsx(Lr,{on:I===Number(_.member_user_id)})]},_.member_user_id))]}),e.jsxs("div",{style:{...gt.sectionLabel,marginTop:18},children:[i.others," ",e.jsx("span",{style:gt.hint,children:i.othersHint})]}),e.jsx("div",{style:gt.list,children:ve.length===0?e.jsx("div",{style:{padding:"10px 12px",fontSize:13,color:"var(--text-3,#71717a)"},children:i.noOthers}):ve.map(_=>{const $=u.has(Number(_.member_user_id));return e.jsxs("button",{onClick:()=>Q(Number(_.member_user_id)),style:gt.row($),children:[e.jsx(Dr,{name:_.name,active:$}),e.jsxs("div",{style:{flex:1,textAlign:"left",minWidth:0},children:[e.jsx("div",{style:gt.name,children:_.name}),e.jsx("div",{style:gt.role,children:Ae(_.team_role)})]}),e.jsx(uc,{on:$})]},_.member_user_id)})})]}),!v&&A.length>0&&e.jsxs("div",{style:gt.foot,children:[e.jsx("button",{onClick:()=>d(!1),style:gt.btnGhost,disabled:x,children:i.cancel}),e.jsx("button",{onClick:ke,style:{...gt.btnPrimary,opacity:!oe||x?.55:1,pointerEvents:!oe||x?"none":"auto"},children:x?i.saving:i.save})]})]})}),document.body)]})}const gt={backdrop:{position:"fixed",inset:0,background:"rgba(0,0,0,.55)",backdropFilter:"blur(3px)",zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center",padding:16},modal:{background:"var(--surface,#131316)",border:"1px solid var(--hairline-strong,rgba(255,255,255,.12))",borderRadius:16,width:420,maxWidth:"94vw",maxHeight:"88vh",display:"flex",flexDirection:"column",color:"var(--text,#fafafa)",boxShadow:"var(--shadow-modal,0 24px 70px -16px rgba(0,0,0,.6))",overflow:"hidden"},head:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"15px 16px",borderBottom:"1px solid var(--hairline,rgba(255,255,255,.07))"},headIcon:{width:34,height:34,borderRadius:10,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"color-mix(in srgb, var(--accent,#6366f1) 14%, transparent)",color:"var(--accent,#8b8bf5)"},title:{fontWeight:700,fontSize:15.5,lineHeight:1.2},sub:{fontSize:12.5,color:"var(--text-3,#71717a)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:300},close:{background:"transparent",border:"none",color:"var(--text-3,#71717a)",cursor:"pointer",padding:4,borderRadius:8,display:"flex"},body:{padding:"14px 16px",overflowY:"auto"},search:{width:"100%",background:"var(--surface-2,#1a1a1f)",border:"1px solid var(--hairline,rgba(255,255,255,.1))",borderRadius:10,padding:"9px 10px 9px 32px",fontSize:13.5,color:"var(--text,#fafafa)",outline:"none",boxSizing:"border-box"},sectionLabel:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:".04em",color:"var(--text-2,#a1a1aa)",marginBottom:8},hint:{fontWeight:500,textTransform:"none",letterSpacing:0,color:"var(--text-3,#71717a)"},list:{display:"flex",flexDirection:"column",gap:4},row:t=>({display:"flex",alignItems:"center",gap:11,width:"100%",padding:"8px 10px",borderRadius:11,cursor:"pointer",textAlign:"left",border:`1px solid ${t?"color-mix(in srgb, var(--accent,#6366f1) 45%, transparent)":"transparent"}`,background:t?"color-mix(in srgb, var(--accent,#6366f1) 10%, transparent)":"transparent",transition:"background .12s, border-color .12s"}),queueIcon:{width:36,height:36,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--surface-3,#1f1f24)",color:"var(--text-3,#71717a)"},name:{fontSize:14,fontWeight:600,color:"var(--text,#fafafa)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},role:{fontSize:12,color:"var(--text-3,#71717a)"},foot:{display:"flex",gap:10,padding:"12px 16px",borderTop:"1px solid var(--hairline,rgba(255,255,255,.07))"},btnGhost:{flex:1,padding:"10px",borderRadius:10,border:"1px solid var(--hairline-strong,rgba(255,255,255,.14))",background:"transparent",color:"var(--text,#fafafa)",fontSize:14,fontWeight:600,cursor:"pointer"},btnPrimary:{flex:1,padding:"10px",borderRadius:10,border:"none",background:"var(--accent,#6366f1)",color:"#fff",fontSize:14,fontWeight:700,cursor:"pointer"}},mc=t=>
2(t||"").trim().split(/\s+/).filter(Boolean).slice(0,2).map(n=>n[0]).join("").toUpperCase();function hc({chat:t,session:n,locale:o="pt",theme:i="dark",initialFirst:s="",initialLast:f="",onSave:l,onClose:c}){const d=(u,p,b)=>o==="en"?p:o==="es"?b:u,[v,k]=r.useState(s),[x,P]=r.useState(f),A=r.useRef(null);r.useEffect(()=>{var u,p;(u=A.current)==null||u.focus(),(p=A.current)==null||p.select()},[]);const y=[v.trim(),x.trim()].filter(Boolean).join(" "),w=!!v.trim(),m=r.useRef(null);m.current=()=>{w&&(l==null||l({fullName:y,firstName:v.trim(),lastName:x.trim()}))},r.useEffect(()=>{const u=p=>{var b,se;p.key==="Escape"?(p.stopPropagation(),c==null||c()):p.key==="Enter"&&((b=p.target)==null?void 0:b.tagName)!=="BUTTON"&&(p.preventDefault(),(se=m.current)==null||se.call(m))};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[c]);const I=bt(n==null?void 0:n.phone),U=bt(t==null?void 0:t.phone);return _s.createPortal(e.jsx("div",{className:"cvsave-backdrop cv2-portal","data-cv2-theme":i,onMouseDown:c,children:e.jsxs("div",{className:"cvsave",role:"dialog","aria-modal":"true","aria-label":d("Salvar contato","Save contact","Guardar contacto"),onMouseDown:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"cvsave-top",children:[e.jsxs("span",{className:"cvsave-chip",children:[e.jsx("span",{className:"dot"}),d("Novo contato","New contact","Nuevo contacto")]}),e.jsx("button",{className:"cvsave-x",onClick:c,"aria-label":d("Fechar","Close","Cerrar"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})]}),e.jsxs("div",{className:"cvsave-stage",children:[e.jsx("span",{className:"cvsave-halo"}),e.jsx("div",{className:"cvsave-av",children:t!=null&&t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:""}):mc(y)||"?"}),e.jsx("span",{className:"cvsave-badge",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-user-plus"})})})]}),e.jsx("div",{className:`cvsave-name${y?"":" empty"}`,children:y||d("Sem nome ainda","No name yet","Sin nombre aún")}),U&&e.jsx("div",{className:"cvsave-num",children:U}),e.jsxs("div",{className:"cvsave-note",children:[e.jsx("span",{className:"cvsave-note-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-iphone"})})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{className:"cvsave-note-ttl",children:d("Vai para os contatos do seu celular","Goes into your phone’s contacts","Va a los contactos de tu celular")}),e.jsx("div",{className:"cvsave-note-txt",children:d(e.jsxs(e.Fragment,{children:["Este contato é gravado na ",e.jsx("strong",{children:"agenda do celular"})," em que este WhatsApp está pareado — não fica só no Pragmaz. Depois de salvar, ele aparece nos Contatos do telefone e em todos os aparelhos que usam essa conta."]}),e.jsxs(e.Fragment,{children:["This contact is written to the ",e.jsx("strong",{children:"address book of the phone"})," this WhatsApp is paired with — it does not stay only in Pragmaz. Once saved, it shows up in the phone's Contacts and on every device using this account."]}),e.jsxs(e.Fragment,{children:["Este contacto se guarda en la ",e.jsx("strong",{children:"agenda del celular"})," donde este WhatsApp está vinculado — no queda solo en Pragmaz. Al guardarlo, aparece en los Contactos del teléfono y en todos los aparatos que usan esta cuenta."]}))}),I&&e.jsxs("div",{className:"cvsave-dev",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-iphone"})}),d("Agenda de","Address book of","Agenda de")," ",e.jsx("strong",{children:I})]})]})]}),e.jsxs("div",{className:"cvsave-fields",children:[e.jsxs("div",{className:"cvsave-field",children:[e.jsxs("label",{htmlFor:"cvsave-first",children:[d("Nome","First name","Nombre")," ",e.jsx("span",{className:"req",children:"*"})]}),e.jsx("input",{id:"cvsave-first",ref:A,className:"cvsave-input",type:"text",value:v,onChange:u=>k(u.target.value),placeholder:d("Ex.: Maria","e.g. Maria","Ej.: María"),autoComplete:"off",maxLength:60})]}),e.jsxs("div",{className:"cvsave-field",children:[e.jsx("label",{htmlFor:"cvsave-last",children:d("Sobrenome","Last name","Apellido")}),e.jsx("input",{id:"cvsave-last",className:"cvsave-input",type:"text",value:x,onChange:u=>P(u.target.value),placeholder:d("Ex.: Souza","e.g. Souza","Ej.: Souza"),autoComplete:"off",maxLength:60})]})]}),e.jsx("div",{className:"cvsave-hint",children:d("Só o nome é obrigatório. Enter salva, Esc fecha.","Only the first name is required. Enter saves, Esc closes.","Solo el nombre es obligatorio. Enter guarda, Esc cierra.")}),e.jsxs("div",{className:"cvsave-foot",children:[e.jsx("button",{className:"cvsave-btn ghost",onClick:c,children:d("Cancelar","Cancel","Cancelar")}
2),e.jsxs("button",{className:"cvsave-btn primary",disabled:!w,onClick:()=>{var u;return(u=m.current)==null?void 0:u.call(m)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-user-plus"})}),d("Salvar na agenda","Save to address book","Guardar en la agenda")]})]})]})}),document.body)}const fc=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase(),gc=(t,n)=>{if(!t)return"";const o=Date.now()/1e3-t;return o<60?n==="en"?"just now":n==="es"?"ahora":"agora":o<3600?n==="en"?`${Math.floor(o/60)}min ago`:n==="es"?`hace ${Math.floor(o/60)}min`:`há ${Math.floor(o/60)}min`:o<86400?n==="en"?`${Math.floor(o/3600)}h ago`:n==="es"?`hace ${Math.floor(o/3600)}h`:`há ${Math.floor(o/3600)}h`:new Date(t*1e3).toLocaleDateString()},xc=Yo,vc={iphone:{label:"iPhone",icon:"#ci-iphone",color:"var(--text-2)"},android:{label:"Android",icon:"#ci-android",color:"#3DDC84"},web:{label:"WhatsApp Web",icon:"#ci-globe",color:"var(--sky, #38bdf8)"},desktop:{label:"WhatsApp Desktop",icon:"#ci-monitor",color:"var(--indigo-light)"}},jc=(t,n,o,i)=>{var s;return o?o.type==="recording"?e.jsxs("span",{style:{color:"var(--indigo-light)",fontWeight:500},children:[o.participant?`${o.participant} `:"",i==="en"?"recording audio…":i==="es"?"grabando audio…":"gravando áudio…"]}):e.jsxs("span",{style:{color:"var(--green)",fontWeight:500},children:[o.participant?`${o.participant} `:"",i==="en"?"typing…":i==="es"?"escribiendo…":"digitando…"]}):t!=null&&t.isGroup?`${t.memberCount||t.participantsCount||"–"} ${i==="en"?"members":i==="es"?"miembros":"membros"}`:t!=null&&t.isNewsletter||(s=t==null?void 0:t.jid)!=null&&s.endsWith("@newsletter")?i==="en"?"Channel":"Canal":(n==null?void 0:n.lastKnownPresence)==="available"?e.jsx("span",{style:{color:"var(--green)"},children:i==="es"?"en línea":"online"}):n!=null&&n.lastSeen?(i==="en"?"last seen ":"visto ")+gc(n.lastSeen,i):bt(t==null?void 0:t.phone)||bt(t==null?void 0:t.jid)||""};function bc({chat:t,session:n,sessionId:o,presence:i,typing:s,lastRecvMsgId:f,onBack:l,onToggleInfo:c,onToggleSearch:d,onContactSaved:v,onConvAction:k,onConfirmAsk:x,onOpenStarred:P,labels:A=[],onLabelChange:y,onManageLabels:w,kanban:m=null,onKanbanColumnChange:I,infoOpen:U,searchOpen:u,locale:p="pt",theme:b="dark",onToggleTheme:se,hasAiAgent:C=!1,onAiPauseChange:H,hasChatbot:Q=!1,onChatbotPauseChange:O,aiEnabled:oe=!1,onOpenAi:ke,onOpenCrm:Ae,canCall:ve=!1,canVideoCall:_=!1,onStartCall:$,scheduleCount:X=0,scheduleFailed:ce=0,onOpenSchedules:Z}){var he,et;const D=n==null?void 0:n.provider_type,ae=D==="cloud_api"?"Cloud API":D==="coexistence"?p==="en"?"Coexistence":p==="es"?"Coexistencia":"Coexistência":null,K=D==="cloud_api"?"#ci-cloud":D==="coexistence"?"#ci-iphone":null,Re=D==="cloud_api"||D==="coexistence",_e=!!(t!=null&&t.isNewsletter||(he=t==null?void 0:t.jid)!=null&&he.endsWith("@newsletter")),Y=D==="web"&&(!!(n!=null&&n.is_business)||(n==null?void 0:n.platform)==="smba"||(n==null?void 0:n.platform)==="smbi"),{settings:Oe}=bs(),[Je,Be]=r.useState(!1),[Qe,Me]=r.useState(""),[De,xt]=r.useState(""),[ut,mt]=r.useState(!1),[st,kt]=r.useState(!1),[At,dt]=r.useState(null),[jt,G]=r.useState(!1),me=r.useRef(null),Se=r.useRef(null),Fe=r.useRef(null),le=(re,tt,pt)=>p==="en"?tt:p==="es"?pt:re,Xe=!!(m!=null&&m.enabled&&((et=m.columns)!=null&&et.length)&&!(t!=null&&t.isGroup)&&!_e&&(t!=null&&t.jid)),z=Xe?m.columns.find(re=>String(re.id)===String(m.columnId??"")):null,Ce=new Set(((t==null?void 0:t.labels)||[]).map(re=>String(re.id??re))),ye=Ce.size,[at,L]=r.useState(null),[Ze,rt]=r.useState(!1),[_t,Yt]=r.useState(!1);r.useEffect(()=>{const re=tt=>{me.current&&!me.current.contains(tt.target)&&mt(!1),Se.current&&!Se.current.contains(tt.target)&&kt(!1),Fe.current&&!Fe.current.contains(tt.target)&&G(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[]);const Qt=async re=>{if(at)return;const pt=Ce.has(String(re.id))?"remove":"add";L(re.id);try{await M.post("/wa/chat/label-assign",{sessionId:o,jid:t.jid,labelId:String(re.id),action:pt}),y==null||y(t.jid,re.id,pt,re)}catch{W.error(p==="en"?"Failed to update label":p==="es"?"Error al actualizar la etiqueta":"Falha ao atualizar etiqueta")}finally{L(null)}},Rt=(i==null?void 0:i.lastKnownPresence)==="available",de=!Re&&!(t!=null&&t.isGroup)&&!(t!=null&&t.isSavedContact)&&(t==null?void 0:t.jid),$t=re=>!re||/^[+\d\s().-]+$/.test(String(re).trim()),Ut=()=>{const re=t!=null&&t.pushName&&!$t(t.pushName)?String(t.pushName).trim():"",tt=re?re.split(/\s+/):[];Me(tt[0]||""),xt(tt.slice(1).join(" ")),Be(!0)},q=({fullName:re,firstName:tt})=>
2{if(!tt){W.error(le("Nome obrigatório","First name required","Nombre obligatorio"));return}const pt=t==null?void 0:t.name,Et=!!(t!=null&&t.isSavedContact);v==null||v(t.jid,re,!0),Be(!1),W.success(le("Salvando na agenda do celular…","Saving to the phone’s address book…","Guardando en la agenda del celular…")),M.post("/wa/chat/save-contact",{sessionId:o,jid:t.jid,fullName:re,firstName:tt}).catch(()=>{v==null||v(t.jid,pt,Et),W.error(le("Falha ao salvar contato","Save failed","Error al guardar el contacto"))})};return e.jsxs("header",{className:"ct-head",children:[e.jsx(ne,{content:le("Voltar","Back","Volver"),position:"bottom",children:e.jsx("button",{className:"ct-back",onClick:l,"aria-label":le("Voltar","Back","Volver"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-l"})})})}),e.jsxs("div",{className:`av ${It("blurAvatars",Oe)}`,children:[t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:""}):fc(lt(t.name,{phone:t.phone,jid:t.jid})),!t.isGroup&&Rt&&e.jsx("span",{className:"online"})]}),e.jsxs("div",{className:"t",onClick:c,children:[e.jsxs("div",{className:`nm ${It("blurNames",Oe)}`,children:[!t.isGroup&&t.phone?e.jsx(ne,{content:bt(t.phone),position:"bottom",children:e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"default"},children:lt(t.name,{phone:t.phone,jid:t.jid})})}):e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:lt(t.name,{phone:t.phone,jid:t.jid})}),K&&e.jsx(ne,{content:ae,position:"bottom",children:e.jsx("span",{className:"src-ic",children:e.jsx("svg",{children:e.jsx("use",{href:K})})})}),!t.isGroup&&!Re&&(()=>{const re=vc[xc(f)];return re?e.jsx(ne,{content:re.label,position:"bottom",children:e.jsx("span",{className:"src-ic",style:{color:re.color},children:e.jsx("svg",{children:e.jsx("use",{href:re.icon})})})}):null})()]}),e.jsx("div",{className:"sub",children:jc(t,i,s,p)})]}),e.jsxs("div",{className:"actions",children:[de&&e.jsx(ne,{className:"cv2-tip-rich",position:"bottom",content:e.jsxs("span",{className:"cv2-tip-rich-in",children:[e.jsx("strong",{children:le("Salvar contato","Save contact","Guardar contacto")}),e.jsx("span",{children:le("Grava o número nos contatos do celular pareado — não fica só aqui no Pragmaz.","Writes the number into the paired phone’s contacts — it does not stay only in Pragmaz.","Guarda el número en los contactos del celular vinculado — no queda solo en Pragmaz.")})]}),children:e.jsx("button",{className:`a-btn${Je?" active":""}`,onClick:re=>{re.stopPropagation(),mt(!1),G(!1),Je?Be(!1):Ut()},"aria-label":le("Salvar contato na agenda do celular","Save contact to the phone’s address book","Guardar contacto en la agenda del celular"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-user-plus"})})})}),Je&&e.jsx(hc,{chat:t,session:n,locale:p,theme:b,initialFirst:Qe,initialLast:De,onSave:q,onClose:()=>Be(!1)}),Y&&e.jsxs("div",{style:{position:"relative"},ref:me,children:[e.jsx(ne,{content:le("Etiquetas","Labels","Etiquetas"),position:"bottom",children:e.jsxs("button",{className:`a-btn collapse-mobile${ut?" active":""}`,onClick:re=>{re.stopPropagation(),G(!1),mt(tt=>!tt)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-tag"})}),ye>0&&e.jsx("span",{className:"n",children:ye})]})}),ut&&e.jsxs("div",{className:"dropdown-menu",style:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:220},onClick:re=>re.stopPropagation(),children:[e.jsx("div",{className:"group-lbl",children:le("Etiquetas","Labels","Etiquetas")}),A.length===0&&e.jsx("div",{style:{padding:"8px 10px",fontSize:13,color:"var(--text-4)"},children:le("Nenhuma etiqueta","No labels","Sin etiquetas")}),A.map(re=>{const tt=Ce.has(String(re.id));return e.jsxs("button",{className:"item",onClick:()=>Qt(re),disabled:at===re.id,children:[e.jsx("span",{className:"d",style:{width:10,height:10,borderRadius:"50%",background:Ds(re.color),flexShrink:0}}),e.jsx("span",{style:{flex:1},children:Ht(re,p)}),tt&&e.jsx("svg",{style:{color:"var(--indigo-light)"},children:e.jsx("use",{href:"#ci-check"})})]},re.id)}),e.jsx("div",{className:"sep"}),e.jsxs("button",{className:"item",onClick:()=>{mt(!1),w==null||w()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-edit"})}),le("Gerenciar etiquetas","Manage labels","Gestionar etiquetas")]})]})]}),Xe&&e.jsxs("div",{style:{position:"relative"},ref:Se,children:[e.jsx(ne,{content:z?`${le("Etapa","Stage","Etapa")}: ${z.name}`:le("Etapa do funil","Funnel stage","Etapa del embudo"),position:"bottom",children:e.jsxs("button",{className:`a-btn collapse-mobile${st?" active":""}`,onClick:re=>{re.stopPropagation(),G(!1),mt(!1),kt(tt=>!tt)},"aria-label":le("Etapa do funil","Funnel stage","Etapa del embudo"),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-columns"})}),z&&e.jsx("span",{className:"kb-dot",style:{background:z.color||"var(--indigo)"}})]})}),st&&e.jsxs("div",{className:"dropdown-menu",style:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:230},onClick:re=>re.stopPropagation(),children:[e.jsx("div",{className:"group-lbl",children:le("Etapa do funil","Funnel stage","Etapa del embudo")}),m.columns.length===0&&e.jsx("div",{style:{padding:"8px 10px",fontSize:13,color:"var(--text-4)"},children:le("Nenhuma etapa","No stages","Sin etapas")}),m.columns.map(re=>
2{const tt=String(re.id)===String(m.columnId??"");return e.jsxs("button",{className:"item",disabled:At!=null,onClick:async()=>{if(tt||At!=null){kt(!1);return}dt(re.id);try{await(I==null?void 0:I(re)),kt(!1)}finally{dt(null)}},children:[e.jsx("span",{className:"d",style:{width:10,height:10,borderRadius:"50%",background:re.color||"var(--indigo)",flexShrink:0}}),e.jsx("span",{style:{flex:1},children:re.name}),tt&&e.jsx("svg",{style:{color:"var(--indigo-light)"},children:e.jsx("use",{href:"#ci-check"})})]},re.id)})]})]}),se&&e.jsx(ne,{content:b==="dark"?p==="en"?"Light theme":"Tema claro":p==="en"?"Dark theme":p==="es"?"Tema oscuro":"Tema escuro",position:"bottom",children:e.jsx("button",{className:"a-btn collapse-mobile",onClick:se,"aria-label":p==="en"?"Toggle theme":p==="es"?"Cambiar tema":"Alternar tema",children:e.jsx("svg",{children:e.jsx("use",{href:b==="dark"?"#ci-sun":"#ci-moon"})})})}),oe&&!_e&&(t==null?void 0:t.jid)&&e.jsx(ne,{content:le("IA: resumo e pendências","AI: summary & pending","IA: resumen y pendientes"),position:"bottom",children:e.jsx("button",{className:"a-btn collapse-mobile",onClick:ke,"aria-label":le("IA do chat","Chat AI","IA del chat"),style:{color:"var(--indigo-light)"},children:e.jsx("span",{style:{fontSize:15,lineHeight:1},children:"✦"})})}),!_e&&e.jsx(ne,{content:p==="en"?"Search messages":p==="es"?"Buscar mensajes":"Buscar mensagens",position:"bottom",children:e.jsx("button",{className:`a-btn collapse-mobile${u?" active":""}`,onClick:d,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})})}),ve&&!(t!=null&&t.isGroup)&&!_e&&(t==null?void 0:t.jid)&&e.jsx(ne,{content:le("Ligar","Call","Llamar"),position:"bottom",children:e.jsx("button",{className:"a-btn collapse-mobile",onClick:()=>$==null?void 0:$(!1),"aria-label":le("Ligar","Call","Llamar"),children:e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M6.6 10.8a15.9 15.9 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25c1.1.37 2.3.57 3.6.57a1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.3.2 2.5.57 3.6a1 1 0 0 1-.25 1z"})})})}),_&&!(t!=null&&t.isGroup)&&!_e&&(t==null?void 0:t.jid)&&e.jsx(ne,{content:le("Chamada de vídeo","Video call","Videollamada"),position:"bottom",children:e.jsx("button",{className:"a-btn collapse-mobile",onClick:()=>$==null?void 0:$(!0),"aria-label":le("Chamada de vídeo","Video call","Videollamada"),children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"6",width:"12",height:"12",rx:"2"}),e.jsx("path",{d:"M21 8l-6 4 6 4V8z"})]})})}),!(t!=null&&t.isGroup)&&!_e&&(t==null?void 0:t.jid)&&e.jsx(ne,{content:le("Cadastro / CRM","Contact CRM","Ficha / CRM"),position:"bottom",children:e.jsx("button",{className:"a-btn collapse-mobile",onClick:Ae,"aria-label":"CRM",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),e.jsx("circle",{cx:"9",cy:"10",r:"2.2"}),e.jsx("path",{d:"M5.5 17c.6-1.9 2-2.7 3.5-2.7s2.9.8 3.5 2.7"}),e.jsx("path",{d:"M15 9.5h4M15 13.5h4"})]})})}),(t==null?void 0:t.jid)&&!_e&&e.jsx(pc,{sessionId:o,chat:t}),C&&(t==null?void 0:t.jid)&&!_e&&e.jsx(ne,{content:t!=null&&t.aiPaused?p==="en"?"Resume AI in this chat":p==="es"?"Reanudar la IA en este chat":"Retomar a I.A neste chat":p==="en"?"Pause AI in this chat":p==="es"?"Pausar la IA en este chat":"Pausar a I.A neste chat",position:"bottom",children:e.jsx("button",{className:`a-btn${t!=null&&t.aiPaused?" active":""}`,disabled:Ze,onClick:async()=>{if(Ze)return;const re=!(t!=null&&t.aiPaused);rt(!0);try{await M.post("/wa/chat/ai-pause",{sessionId:o,jid:t.jid,paused:re}),H==null||H(t.jid,re),W.success(re?p==="en"?"AI paused in this chat":p==="es"?"IA pausada en este chat":"I.A pausada neste chat":p==="en"?"AI resumed in this chat":p==="es"?"IA reanudada":"I.A retomada neste chat")}catch{W.error(p==="en"?"Action failed":p==="es"?"Acción falló":"Falha na ação")}finally{rt(!1)}},"aria-label":p==="en"?"Toggle AI":p==="es"?"Activar/pausar IA":"Ligar/pausar I.A",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"4.5",y:"8",width:"15",height:"11",rx:"2.5"}),e.jsx("path",{d:"M12 8V4.5M8.5 3.5h7"}
2),e.jsx("circle",{cx:"9.2",cy:"13.3",r:"1.2",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"14.8",cy:"13.3",r:"1.2",fill:"currentColor",stroke:"none"}),(t==null?void 0:t.aiPaused)&&e.jsx("path",{d:"M4 4l16 16"})]})})}),Q&&(t==null?void 0:t.jid)&&!_e&&!(t!=null&&t.isGroup)&&e.jsx(ne,{content:t!=null&&t.chatbotPaused?p==="en"?"Resume chatbot in this chat":p==="es"?"Reanudar el chatbot en este chat":"Retomar o chatbot neste chat":p==="en"?"Pause chatbot in this chat":p==="es"?"Pausar el chatbot en este chat":"Pausar o chatbot neste chat",position:"bottom",children:e.jsx("button",{className:`a-btn${t!=null&&t.chatbotPaused?" active":""}`,disabled:_t,"data-chatbot-pause":!0,onClick:async()=>{if(_t)return;const re=!(t!=null&&t.chatbotPaused);Yt(!0);try{await M.post("/wa/chat/chatbot-pause",{sessionId:o,jid:t.jid,paused:re}),O==null||O(t.jid,re),W.success(re?p==="en"?"Chatbot paused in this chat":p==="es"?"Chatbot pausado en este chat":"Chatbot pausado neste chat":p==="en"?"Chatbot resumed in this chat":p==="es"?"Chatbot reanudado en este chat":"Chatbot retomado neste chat")}catch{W.error(p==="en"?"Action failed":p==="es"?"Acción falló":"Falha na ação")}finally{Yt(!1)}},"aria-label":p==="en"?"Toggle chatbot":p==="es"?"Activar/pausar chatbot":"Ligar/pausar chatbot",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"7.5",height:"6",rx:"1.5"}),e.jsx("rect",{x:"13.5",y:"15",width:"7.5",height:"6",rx:"1.5"}),e.jsx("path",{d:"M6.75 9v4.5a2 2 0 0 0 2 2h4.75"}),(t==null?void 0:t.chatbotPaused)&&e.jsx("path",{d:"M4 4l16 16"})]})})}),(X>0||ce>0)&&e.jsx(ne,{content:ce>0?p==="en"?`${ce} scheduled message(s) failed`:p==="es"?`${ce} programado(s) fallaron`:`${ce} agendada(s) falharam`:p==="en"?`${X} scheduled message(s)`:p==="es"?`${X} programado(s)`:`${X} mensagem(ns) agendada(s)`,position:"bottom",children:e.jsxs("button",{className:`ct-sched-pill${ce>0?" bad":""}`,onClick:Z,children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})}),e.jsx("span",{children:ce>0?ce:X})]})}),e.jsx(ne,{content:p==="en"?"Contact info":p==="es"?"Info del contacto":"Info do contato",position:"bottom",children:e.jsx("button",{className:`a-btn collapse-mobile${U?" active":""}`,onClick:c,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-info"})})})}),e.jsxs("div",{style:{position:"relative"},ref:Fe,children:[e.jsx(ne,{content:le("Mais opções","More options","Más opciones"),position:"bottom",children:e.jsx("button",{className:`a-btn${jt?" active":""}`,onClick:re=>{re.stopPropagation(),mt(!1),G(tt=>!tt)},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-dots"})})})}),jt&&e.jsxs("div",{className:"dropdown-menu",style:{position:"absolute",top:"calc(100% + 6px)",right:0,minWidth:230},onClick:re=>re.stopPropagation(),children:[e.jsxs("button",{className:"item",onClick:()=>{G(!1),c==null||c()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-info"})}),_e?le("Info do canal","Channel info","Info del canal"):le("Info do contato","Contact info","Info del contacto")]}),!_e&&e.jsxs("button",{className:"item",onClick:()=>{G(!1),d==null||d()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})}),le("Buscar mensagens","Search messages","Buscar mensajes")]}),!(t!=null&&t.isGroup)&&!_e&&(t==null?void 0:t.jid)&&e.jsxs("button",{className:"item",onClick:()=>{G(!1),Ae==null||Ae()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-user-plus"})}),le("Cadastro / CRM","Contact CRM","Ficha / CRM")]}),!(t!=null&&t.isGroup)&&!_e&&(t==null?void 0:t.jid)&&e.jsxs("button",{className:"item",onClick:async()=>{G(!1);try{await M.post("/wa/kanban/cards",{sessionId:o,jid:t.jid}),W.success(le("Adicionado ao Kanban","Added to Kanban","Añadido al Kanban"))}catch{W.error(le("Falha ao adicionar","Failed to add","Error al añadir"))}},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-tag"})}),le("Adicionar ao Kanban","Add to Kanban","Añadir al Kanban")]}),!Re&&!_e&&e.jsxs("button",{className:"item",onClick:()=>{G(!1),P==null||P()},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-star"})}),le("Mensagens favoritas","Starred messages","Mensajes destacados")]}),!_e&&e.jsxs("button",{className:"item",onClick:async()=>{G(!1);try{const re=lt(t==null?void 0:t.name,{phone:t==null?void 0:t.phone,jid:t==null?void 0:t.jid,lidLabel:le("conversa","chat","conversación")}),tt=await M.get(`/wa/chat/export?${new URLSearchParams({sessionId:o,jid:t.jid,name:re})}`,{responseType:"blob"}),pt=URL.createObjectURL(tt.data),Et=document.createElement("a");Et.href=pt,Et.download=le(`Conversa - ${re}.txt`,`Chat - ${re}.txt`,`Conversación - ${re}.txt`),Et.click(),setTimeout(()=>URL.revokeObjectURL(pt),1e3)}catch{W.error(le("Falha ao exportar","Export failed","Error al exportar"))}},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-download"})}),le("Exportar conversa","Export chat","Exportar chat")]}),e.jsxs("button",{className:"item",onClick:()=>{G(!1),k==null||k(t,"pin",!(t!=null&&t.isPinned))},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-stick"})}),t!=null&&t.isPinned?le("Desafixar conversa","Unpin chat","Desfijar chat"):le("Fixar conversa","Pin chat","Fijar chat")]}),e.jsxs("button",{className:"item",onClick:()=>{G(!1),k==null||k(t,"mute",t!=null&&t.isMuted?null:Date.now()+365*864e5)},children:[e.jsx("svg",{children:e.jsx("use",{href:t!=null&&t.isMuted?"#ci-bell":"#ci-mute"})}),t!=null&&t.isMuted?le("Reativar notificações","Unmute","Reactivar"):le("Silenciar notificações","Mute notifications","Silenciar")]}),!_e&&e.jsxs("button",{className:"item",onClick:()=>{G(!1),k==null||k(t,"archive",!(t!=null&&t.isArchived))},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-archive"})}),t!=null&&t.isArchived?le("Desarquivar","Unarchive","Desarchivar"):le("Arquivar conversa","Archive chat","Archivar")]}),e.jsxs("button",{className:"item",onClick:()=>{G(!1),k==null||k(t,"markUnread")},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-mark-read"})}),le("Marcar como não lida","Mark as unread","Marcar como no leída")]}),Y&&!_e&&e.jsxs("button",{className:"item",onClick:()=>{G(!1),mt(!0)},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-tag"})}),le("Etiquetas","Labels","Etiquetas")]}),!_e&&e.jsx("div",{className:"sep"}),!_e&&e.jsxs("button",{className:"item danger",onClick:()=>{G(!1),x==null||x({title:le("Apagar conversa?","Delete chat?","¿Borrar chat?"),message:le("Toda a conversa será removida do dispositivo.","The whole chat will be removed from this device.","Todo el chat será eliminado de este dispositivo."),confirmLabel:le("Apagar","Delete","Borrar"),onConfirm:()=>k==null?void 0:k(t,"delete")})},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})}),le("Apagar conversa","Delete chat","Borrar chat")]})]})]})]})]})}const Pr={pt:{now:"agora",ago:t=>`há ${t}`,noCoords:"Sem coordenadas para esta localização.",loadFail:"Falha ao carregar a localização.",noKey:"Chave do Google Maps não configurada.",mapFail:"Falha ao iniciar o mapa.",location:"Localização",live:"AO VIVO",endsIn:t=>` · termina em ${t}`,ended:"Compartilhamento encerrado",updated:t=>`· atualizado ${t}`,close:"Fechar",loadingMap:"Carregando mapa…",follow:"Seguir",openMaps:"Abrir no Google Maps"},es:{now:"ahora",ago:t=>`hace ${t}`,noCoords:"Sin coordenadas para esta ubicación.",loadFail:"No se pudo cargar la ubicación.",noKey:"La clave de Google Maps no está configurada.",mapFail:"No se pudo iniciar el mapa.",location:"Ubicación",live:"EN VIVO",endsIn:t=>` · termina en ${t}`,ended:"Ubicación compartida finalizada",updated:t=>`· actualizada ${t}`,close:"Cerrar",loadingMap:"Cargando mapa…",follow:"Seguir",openMaps:"Abrir en Google Maps"},en:{now:"now",ago:t=>`${t}
2 ago`,noCoords:"No coordinates for this location.",loadFail:"Could not load the location.",noKey:"Google Maps key not configured.",mapFail:"Could not start the map.",location:"Location",live:"LIVE",endsIn:t=>` · ends in ${t}`,ended:"Sharing ended",updated:t=>`· updated ${t}`,close:"Close",loadingMap:"Loading map…",follow:"Follow",openMaps:"Open in Google Maps"}};function yc(t,n,o){if(!t)return"";const i=Math.max(0,Math.floor((n-t)/1e3));if(i<5)return o.now;if(i<60)return o.ago(`${i}s`);const s=Math.floor(i/60);if(s<60)return o.ago(`${s} min`);const f=Math.floor(s/60);return o.ago(`${f}h`)}function wc(t,n){if(t==null)return null;const o=Math.floor((t-n)/1e3);if(o<=0)return null;const i=Math.floor(o/3600),s=Math.floor(o%3600/60);return i>0?`${i}h${s>0?" "+s+"min":""}`:s>0?`${s} min`:`${o}s`}function Nc({open:t,onClose:n,sessionId:o,msgId:i,name:s}){const{locale:f}=ds(),l=Pr[f]||Pr.pt,[c,d]=r.useState(null),[v,k]=r.useState(!1),[x,P]=r.useState(null),[A,y]=r.useState(!0),[w,m]=r.useState(Date.now()),I=r.useRef(null),U=r.useRef(null),u=r.useRef(null),p=r.useRef(null),b=r.useRef(null),se=r.useRef([]),C=r.useRef(!0),H=r.useRef(null),Q=r.useRef(null);r.useEffect(()=>{C.current=A},[A]),r.useEffect(()=>{if(!t||!i||!o)return;let Z=!0;return k(!0),P(null),d(null),se.current=[],Q.current=null,M.get(`/wa/chat/live-location/${encodeURIComponent(i)}`,{params:{sessionId:o}}).then(D=>
2{if(!Z)return;const ae=D.data||{};if(ae.lat==null||ae.lng==null){P(l.noCoords),k(!1);return}se.current=(ae.trail||[]).map(K=>({lat:K.lat,lng:K.lng})),Q.current={lat:ae.lat,lng:ae.lng,seq:ae.seq??null},d(ae),k(!1)}).catch(D=>{var ae,K;Z&&(P(((K=(ae=D==null?void 0:D.response)==null?void 0:ae.data)==null?void 0:K.error)||l.loadFail),k(!1))}),()=>{Z=!1}},[t,i,o]),r.useEffect(()=>{if(!t||!c||x)return;let Z=!1;return Lo().then(D=>{if(Z||!I.current)return;H.current=D;const ae={lat:c.lat,lng:c.lng},K=new D.Map(I.current,{center:ae,zoom:16,disableDefaultUI:!0,zoomControl:!0,gestureHandling:"greedy",clickableIcons:!1,backgroundColor:"#0a0a0b",styles:kc});U.current=K,b.current=new D.Polyline({path:se.current,geodesic:!0,strokeColor:"#25d366",strokeOpacity:.9,strokeWeight:4,map:K}),p.current=new D.Circle({center:ae,radius:c.accuracy||0,map:K,strokeColor:"#25d366",strokeOpacity:.25,strokeWeight:1,fillColor:"#25d366",fillOpacity:.1}),u.current=new D.Marker({position:ae,map:K,icon:zr(D,c.heading),zIndex:5}),K.setCenter(ae),K.addListener("dragstart",()=>y(!1))}).catch(D=>{Z||P(D.message||l.mapFail)}),()=>{var D,ae,K;Z=!0;try{(D=u.current)==null||D.setMap(null)}catch{}try{(ae=p.current)==null||ae.setMap(null)}catch{}try{(K=b.current)==null||K.setMap(null)}catch{}u.current=null,p.current=null,b.current=null,U.current=null}},[t,c?"ready":"no",x]);const O=r.useCallback(Z=>{const D=Q.current;if(D&&(Z.seq!=null&&D.seq!=null&&Z.seq<=D.seq||Z.lat===D.lat&&Z.lng===D.lng))return;Q.current={lat:Z.lat,lng:Z.lng,seq:Z.seq??(D?D.seq:null)};const ae=H.current;if(d(Re=>Re&&{...Re,lat:Z.lat,lng:Z.lng,accuracy:Z.accuracy??Re.accuracy,speed:Z.speed??Re.speed,heading:Z.heading??Re.heading,updatedAt:Z.ts||Date.now(),seq:Z.seq??Re.seq}),!ae||!U.current)return;const K={lat:Z.lat,lng:Z.lng};u.current&&(u.current.setPosition(K),u.current.setIcon(zr(ae,Z.heading))),p.current&&(p.current.setCenter(K),Z.accuracy!=null&&p.current.setRadius(Z.accuracy)),se.current.push(K),b.current&&b.current.setPath(se.current),C.current&&U.current.panTo(K)},[]);if(r.useEffect(()=>{if(!t||!i)return;const Z=D=>{const ae=D.detail;!ae||ae.msgId!==i||o&&ae.sessionId&&ae.sessionId!==o||ae.lat==null||ae.lng==null||O(ae)};return window.addEventListener("pragmaz:live-location",Z),()=>window.removeEventListener("pragmaz:live-location",Z)},[t,i,o,O]),r.useEffect(()=>{if(!t||!i||!o)return;let Z=!1;const D=()=>{M.post("/wa/chat/live-location/refresh",{sessionId:o,msgId:i}).catch(()=>{})};D();const ae=setInterval(()=>{if(Z)return;const K=c==null?void 0:c.expiresAt;K!=null&&K<=Date.now()||D()},12e3);return()=>{Z=!0,clearInterval(ae)}},[t,i,o,c==null?void 0:c.expiresAt]),r.useEffect(()=>{if(!t)return;const Z=setInterval(()=>m(Date.now()),1e3);return()=>clearInterval(Z)},[t]),r.useEffect(()=>{if(!t)return;const Z=D=>{D.key==="Escape"&&(n==null||n())};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[t,n]),!t)return null;const oe=!!(c!=null&&c.isLive),ke=(c==null?void 0:c.expiresAt)??null,Ae=oe?wc(ke,w):null,ve=oe&&ke!=null&&ke<=w,_=oe&&!ve,$=(c==null?void 0:c.speed)!=null?Math.round(c.speed*3.6):null,X=c?Po(c.lat,c.lng):null,ce=()=>{y(!0),U.current&&c&&U.current.panTo({lat:c.lat,lng:c.lng})};return e.jsx("div",{className:"cv-llm-backdrop",onClick:n,children:e.jsxs("div",{className:"cv-llm",onClick:Z=>Z.stopPropagation(),children:[e.jsxs("header",{className:"cv-llm-head",children:[e.jsxs("div",{className:"cv-llm-title",children:[e.jsx("div",{className:"nm",children:s||l.location}),e.jsxs("div",{className:"sub",children:[_&&e.jsxs("span",{className:"live",children:[e.jsx("span",{className:"dot"}),l.live,Ae?l.endsIn(Ae):""]}),ve&&e.jsx("span",{className:"ended",children:l.ended}),oe&&!ve&&(c==null?void 0:c.updatedAt)&&e.jsx("span",{className:"ago",children:l.updated(yc(c.updatedAt,w,l))}),!oe&&c&&e.jsx("span",{className:"ago",children:l.location}),$!=null&&_&&$>0&&e.jsxs("span",{className:"ago",children:["· ",$," km/h"]})]})]}),e.jsx(ne,{content:l.close,position:"bottom",children:e.jsx("button",{className:"cv-llm-x",onClick:n,"aria-label":l.close,children:e.jsx(ya,{})})})]}),e.jsxs("div",{className:"cv-llm-map-wrap",children:[x?e.jsxs("div",{className:"cv-llm-msg",children:[e.jsx(jo,{size:22}),e.jsx("span",{children:x})]}):v?e.jsxs("div",{className:"cv-llm-msg",children:[e.jsx("span",{className:"cv-llm-spin"}),l.loadingMap]}):null,e.jsx("div",{ref:I,className:"cv-llm-map",style:{visibility:x||v?"hidden":"visible"}}),!x&&!v&&e.jsx(ne,{content:l.follow,position:"left",children:e.jsx("button",{className:`cv-llm-recenter ${A?"on":""}`,onClick:ce,children:e.jsx(bo,{})})})]}),e.jsxs("footer",{className:"cv-llm-foot",children:[c&&e.jsxs("div",{className:"coords",children:[Number(c.lat).toFixed(5),", ",Number(c.lng).toFixed(5),c.accuracy?` · ±${Math.round(c.accuracy)}m`:""]}),X&&e.jsxs("a",{className:"cv-llm-ext",href:X,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(yo,{size:14})," ",l.openMaps]})]})]})})}function zr(t,n){return n!=null&&!Number.isNaN(n)?{path:t.SymbolPath.FORWARD_CLOSED_ARROW,scale:5,rotation:Number(n),fillColor:"#25d366",fillOpacity:1,strokeColor:"#0a0a0b",strokeWeight:2}:{path:t.SymbolPath.CIRCLE,scale:8,fillColor:"#25d366",fillOpacity:1,strokeColor:"#fff",strokeWeight:2}}const kc=[{elementType:"geometry",stylers:[{color:"#212121"}]},{elementType:"labels.icon",stylers:[{visibility:"off"}]},{elementType:"labels.text.fill",stylers:[{color:"#757575"}]},{elementType:"labels.text.stroke",stylers:[{color:"#212121"}]},{featureType:"road",elementType:"geometry.fill",stylers:[{color:"#2c2c2c"}]},{featureType:"road",elementType:"labels.text.fill",stylers:[{color:"#8a8a8a"}]},{featureType:"road.highway",elementType:"geometry",stylers:[{color:"#3c3c3c"}]},{featureType:"water",elementType:"geometry",stylers:[{color:"#000000"}]},{featureType:"poi",elementType:"labels.text.fill",stylers:[{color:"#757575"}]},{featureType:"poi.park",elementType:"geometry",stylers:[{color:"#181818"}]},{featureType:"transit",elementType:"labels.text.fill",stylers:[{color:"#757575"}]}];function Sc({msg:t,sessionId:n,onOpen:o}){const i=t.msgType==="video",s=r.useRef(null),[f,l]=r.useState(!1);r.useEffect(()=>
2{const k=s.current;if(!k||f)return;const x=new IntersectionObserver(([P])=>{P.isIntersecting&&(l(!0),x.disconnect())},{rootMargin:"300px"});return x.observe(k),()=>x.disconnect()},[f]);const{src:c}=zo({msgId:t.msgId,sessionId:n,jid:t.jid,poster:i,lazy:!f,enabled:f}),d=t.thumbBase64||c,v=async k=>{k.stopPropagation();const x=await Wo(t.msgId,n,t.jid,null,!1,!1);x&&o({type:i?"video":"image",url:x})};return e.jsxs("div",{ref:s,onClick:v,className:"cv2-gal-thumb",style:{position:"relative",aspectRatio:"1",background:"var(--surface-3)",cursor:"pointer",overflow:"hidden",borderRadius:"var(--r-md)"},children:[d?e.jsx("img",{src:d,alt:"",loading:"lazy",style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}}):e.jsx("span",{className:"cv2-gal-skel",style:{position:"absolute",inset:0}}),i&&e.jsx("span",{style:{position:"absolute",right:6,bottom:6,width:22,height:22,borderRadius:"50%",background:"rgba(0,0,0,0.5)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:e.jsx("svg",{style:{width:14,height:14,color:"#fff"},children:e.jsx("use",{href:"#ci-play"})})})]})}function Cc({type:t,url:n,onClose:o}){return r.useEffect(()=>{const i=s=>s.key==="Escape"&&o();return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[o]),_s.createPortal(e.jsx("div",{onClick:o,style:{position:"fixed",inset:0,zIndex:100001,background:"rgba(0,0,0,0.92)",display:"flex",alignItems:"center",justifyContent:"center"},children:t==="video"?e.jsx("video",{src:n,controls:!0,autoPlay:!0,style:{maxWidth:"92%",maxHeight:"92%"},onClick:i=>i.stopPropagation()}):e.jsx("img",{src:n,alt:"",style:{maxWidth:"92%",maxHeight:"92%",objectFit:"contain"},onClick:i=>i.stopPropagation()})}),document.body)}function Ec({sessionId:t,jid:n,initialTab:o="media",locale:i="pt",onClose:s}){const[f,l]=r.useState(o),[c,d]=r.useState(null),[v,k]=r.useState(null),x=(y,w,m)=>i==="en"?w:i==="es"?m:y;r.useEffect(()=>{d(null),M.get(`/wa/chat/media-gallery?${new URLSearchParams({sessionId:t,jid:n,tab:f,limit:"100"})}`).then(({data:y})=>d(Array.isArray(y==null?void 0:y.items)?y.items:[])).catch(()=>d([]))},[t,n,f]);const P=[{k:"media",lbl:x("Mídia","Media","Multimedia")},{k:"docs",lbl:x("Docs","Docs","Docs")},{k:"links",lbl:x("Links","Links","Enlaces")}],A=y=>(String(y||"").match(/https?:\/\/[^\s]+/)||[""])[0];return e.jsxs("div",{className:"cv2-modal-backdrop",onClick:s,children:[e.jsxs("div",{className:"cv2-modal cv2-gal",style:{maxWidth:480,width:"94%",maxHeight:"84vh",display:"flex",flexDirection:"column"},onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{children:e.jsx("div",{className:"ttl",children:x("Mídia, links e docs","Media, links and docs","Multimedia, enlaces y docs")})}),e.jsx(ne,{content:x("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:s,"aria-label":"Fechar",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{className:"cv2-gal-tabs",children:P.map(y=>e.jsx("button",{onClick:()=>l(y.k),className:`cv2-gal-tab${f===y.k?" active":""}`,children:y.lbl},y.k))}),e.jsx("div",{className:"cv2-gal-body",children:c==null?e.jsx("div",{className:"cv2-gal-empty",children:"…"}):c.length===0?e.jsx("div",{className:"cv2-gal-empty",children:x("Nada aqui ainda","Nothing here yet","Nada aún")}):f==="media"?e.jsx("div",{className:"cv2-gal-grid",children:c.map(y=>e.jsx(Sc,{msg:y,sessionId:t,onOpen:k},y.msgId))}):f==="docs"?c.map(y=>e.jsxs("a",{href:`/api/wa/chat/media/${encodeURIComponent(y.msgId)}?sessionId=${encodeURIComponent(t)}`,target:"_blank",rel:"noopener noreferrer",className:"cv2-gal-row",children:[e.jsx("span",{className:"cv2-gal-doc-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-file"})})}),e.jsx("span",{className:"cv2-gal-doc-nm",children:y.fileName||"documento"})]},y.msgId)):c.map(y=>{const w=A(y.text);return e.jsx("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"cv2-gal-link",children:w},y.msgId)})})]}),v&&e.jsx(Cc,{...v,onClose:()=>k(null)})]})}const Wr={title:{pt:"Mensagens agendadas",en:"Scheduled messages",es:"Mensajes programados"},up:{pt:"vão sair",en:"upcoming",es:"por salir"},failed:{pt:"não saíram",en:"failed",es:"no salieron"},done:{pt:"enviadas",en:"sent",es:"enviados"},open:{pt:"Ver todas",en:"View all",es:"Ver todas"},next:{pt:"próxima",en:"next",es:"próxima"}},Ms=(t,n)=>(Wr[t]||{})[n]||(Wr[t]||{}).pt||t;function Ic({schedules:t=[],locale:n="pt",onOpen:o}){const{up:i,failed:s,done:f,proxima:l}=r.useMemo(()=>{const c=t.filter(d=>["pending","retrying","sending"].includes(d.status));return{up:c,failed:t.filter(d=>d.status==="failed"),done:t.filter(d=>d.status==="sent"),proxima:[...c].sort((d,v)=>new Date(d.scheduledAt)-new Date(v.scheduledAt))[0]||null}},[t]);return t.length?e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:Ms("title",n)}),e.jsxs("button",{className:`cvsl-entry${s.length?" bad":""}`,onClick:o,children:[e.jsx("span",{className:"cvsl-e-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsxs("span",{className:"cvsl-e-mid",children:[e.jsxs("span",{className:"cvsl-e-nums",children:[i.length>0&&e.jsxs("b",{children:[i.length," ",Ms("up",n)]}),s.length>0&&e.jsxs("b",{className:"bad",children:[s.length," ",Ms("failed",n)]}),f.length>
20&&e.jsxs("span",{children:[f.length," ",Ms("done",n)]})]}),l&&e.jsxs("span",{className:"cvsl-e-next",children:[Ms("next",n),": ",new Date(l.scheduledAt).toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{weekday:"short",day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})]})]}),e.jsxs("span",{className:"cvsl-e-go",children:[Ms("open",n),e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-r"})})]})]})]}):null}const ge={title:{pt:"Dados do canal",en:"Channel info",es:"Datos del canal"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},channel:{pt:"Canal",en:"Channel",es:"Canal"},subscribers:{pt:"inscritos",en:"followers",es:"suscriptores"},subscriber:{pt:"inscrito",en:"follower",es:"suscriptor"},admins:{pt:"Administradores",en:"Admins",es:"Administradores"},description:{pt:"Descrição",en:"Description",es:"Descripción"},addDescription:{pt:"Adicionar descrição",en:"Add description",es:"Añadir descripción"},noDescription:{pt:"Sem descrição",en:"No description",es:"Sin descripción"},link:{pt:"Link do canal",en:"Channel link",es:"Enlace del canal"},copy:{pt:"Copiar link",en:"Copy link",es:"Copiar enlace"},copied:{pt:"Link copiado",en:"Link copied",es:"Enlace copiado"},createdAt:{pt:"Criado em",en:"Created on",es:"Creado el"},yourRole:{pt:"Você neste canal",en:"You in this channel",es:"Tú en este canal"},roleOwner:{pt:"Dono",en:"Owner",es:"Dueño"},roleAdmin:{pt:"Administrador",en:"Admin",es:"Administrador"},roleSub:{pt:"Inscrito",en:"Follower",es:"Suscriptor"},roleGuest:{pt:"Visitante",en:"Guest",es:"Visitante"},reactions:{pt:"Quem pode reagir",en:"Who can react",es:"Quién puede reaccionar"},reactAll:{pt:"Todos os emojis",en:"All emojis",es:"Todos los emojis"},reactBasic:{pt:"Só os emojis básicos",en:"Basic emojis only",es:"Solo emojis básicos"},reactNone:{pt:"Ninguém",en:"No one",es:"Nadie"},readOnly:{pt:"Somente leitura — só quem administra o canal publica.",en:"Read-only — only channel admins can post.",es:"Solo lectura — solo quien administra publica."},editName:{pt:"Editar nome",en:"Edit name",es:"Editar nombre"},changePhoto:{pt:"Alterar foto",en:"Change photo",es:"Cambiar foto"},removePhoto:{pt:"Remover foto",en:"Remove photo",es:"Quitar foto"},save:{pt:"Salvar",en:"Save",es:"Guardar"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},saved:{pt:"Canal atualizado",en:"Channel updated",es:"Canal actualizado"},saveFail:{pt:"Não deu pra salvar",en:"Could not save",es:"No se pudo guardar"},verified:{pt:"Verificado",en:"Verified",es:"Verificado"},suspended:{pt:"Canal suspenso pelo WhatsApp",en:"Channel suspended by WhatsApp",es:"Canal suspendido por WhatsApp"},offline:{pt:"Dispositivo offline — mostrando o que está em cache.",en:"Device offline — showing cached data.",es:"Dispositivo sin conexión — mostrando caché."},followers:{pt:"Inscritos",en:"Followers",es:"Suscriptores"},noFollowers:{pt:"Nenhum inscrito ainda",en:"No followers yet",es:"Sin suscriptores aún"},nameMax:{pt:"Máx. 25 caracteres",en:"Max 25 characters",es:"Máx. 25 caracteres"},manage:{pt:"Gestão do canal",en:"Channel management",es:"Gestión del canal"},inviteAdmin:{pt:"Convidar administrador",en:"Invite admin",es:"Invitar administrador"},invitePlaceholder:{pt:"Telefone com DDI (ex.: 5561999999999)",en:"Phone with country code",es:"Teléfono con código de país"},invite:{pt:"Convidar",en:"Invite",es:"Invitar"},invited:{pt:"Convite de administrador enviado",en:"Admin invite sent",es:"Invitación enviada"},pending:{pt:"Convites pendentes",en:"Pending invites",es:"Invitaciones pendientes"},revoke:{pt:"Revogar",en:"Revoke",es:"Revocar"},revoked:{pt:"Convite revogado",en:"Invite revoked",es:"Invitación revocada"},demote:{pt:"Rebaixar",en:"Demote",es:"Degradar"},demoted:{pt:"Administrador rebaixado",en:"Admin demoted",es:"Administrador degradado"},transfer:{pt:"Transferir propriedade",en:"Transfer ownership",es:"Transferir propiedad"},transferred:{pt:"Propriedade transferida",en:"Ownership transferred",es:"Propiedad transferida"},transferAsk:{pt:"Transferir a propriedade do canal para {who}? Você deixa de ser o dono e não dá pra desfazer sozinho.",en:"Transfer channel ownership to {who}? You stop being the owner and cannot undo it alone.",es:"¿Transferir la propiedad del canal a {who}? Dejas de ser el dueño y no se puede deshacer solo."},leaveCh:{pt:"Deixar de seguir",en:"Unfollow",es:"Dejar de seguir"},leaveAsk:{pt:'Deixar de seguir "{name}"? As publicações já recebidas continuam no seu histórico.',en:'Unfollow "{name}"? Posts you already received stay in your history.',es:'¿Dejar de seguir "{name}"? Las publicaciones ya recibidas siguen en tu historial.'},left:{pt:"Você deixou de seguir o canal",en:"You unfollowed the channel",es:"Dejaste de seguir el canal"},del:{pt:"Apagar canal",en:"Delete channel",es:"Eliminar canal"},delAsk:{pt:'APAGAR o canal "{name}" de vez? Todos os inscritos perdem o acesso e isso não tem volta.',en:'DELETE the channel "{name}" for good? All followers lose access and this cannot be undone.',es:'¿ELIMINAR el canal "{name}" para siempre? Todos los suscriptores pierden el acceso y no tiene vuelta.'}
2,deleted:{pt:"Canal apagado",en:"Channel deleted",es:"Canal eliminado"},actionFail:{pt:"Não deu pra concluir",en:"Could not complete",es:"No se pudo completar"},expiresIn:{pt:"expira em",en:"expires",es:"expira"},tiposOk:{pt:"Neste canal você publica texto, imagem, vídeo, figurinha, enquete e áudio de voz. O WhatsApp não aceita documento nem arquivo de áudio em canal.",en:"In this channel you can post text, image, video, sticker, poll and voice note. WhatsApp does not accept documents or audio files in channels.",es:"En este canal publicas texto, imagen, video, sticker, encuesta y nota de voz. WhatsApp no acepta documentos ni archivos de audio en canales."}},be=(t,n)=>t[n]||t.pt,qr={OWNER:ge.roleOwner,ADMIN:ge.roleAdmin,SUBSCRIBER:ge.roleSub,GUEST:ge.roleGuest},Ac=[{v:"ALL",l:ge.reactAll},{v:"BASIC",l:ge.reactBasic},{v:"NONE",l:ge.reactNone}],Rc=t=>t?t.trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase():"#",ca=(t,n)=>t==null?"—":Number(t).toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR"),Mc=(t,n)=>t?new Date(Number(t)*1e3).toLocaleDateString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{day:"2-digit",month:"long",year:"numeric"}):null,os={display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"9px 14px",fontSize:13},vs={color:"var(--text-3)",flexShrink:0},cs={color:"var(--text-1)",fontWeight:500,textAlign:"right",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function $c({chat:t,sessionId:n,onClose:o,onConvAction:i,onToggleSearch:s,onConfirmAsk:f,onLeaveGroup:l,locale:c="pt"}){const{settings:d}=bs(),v=It("blurAvatars",d),k=It("blurNames",d),[x,P]=r.useState(null),[A,y]=r.useState(!0),[w,m]=r.useState(!1),[I,U]=r.useState(null),[u,p]=r.useState(null),[b,se]=r.useState(null),C=r.useRef(null),H=t==null?void 0:t.jid,Q=r.useCallback(async()=>{if(!(!n||!H))try{const{data:Y}=await M.get(`/wa/chat/contact?sessionId=${n}&jid=${encodeURIComponent(H)}`);P(Y||{})}catch{P({})}finally{y(!1)}},[n,H]);r.useEffect(()=>{y(!0),P(null),se(null),Q()},[Q]),r.useEffect(()=>{!(x!=null&&x.canEdit)||b!==null||M.get(`/wa/chat/newsletter-followers?sessionId=${n}&jid=${encodeURIComponent(H)}&limit=200`).then(({data:Y})=>se(Array.isArray(Y==null?void 0:Y.followers)?Y.followers:[])).catch(()=>se([]))},[x==null?void 0:x.canEdit,b,n,H]);const[O,oe]=r.useState(null),[ke,Ae]=r.useState(""),ve=async(Y,Oe={},Je)=>{var Be,Qe;m(!0);try{const{data:Me}=await M.post("/wa/chat/newsletter-action",{sessionId:n,jid:H,action:Y,...Oe});return Je&&W.success(Je),Me}catch(Me){return W.error(((Qe=(Be=Me==null?void 0:Me.response)==null?void 0:Be.data)==null?void 0:Qe.error)||be(ge.actionFail,c)),null}finally{m(!1)}},_=r.useCallback(async()=>{const Y=await ve("pendingInvites");Y&&oe(Array.isArray(Y.result)?Y.result:[])},[n,H]);r.useEffect(()=>{x!=null&&x.canEdit&&O===null&&_()},[x==null?void 0:x.canEdit,O,_]);const $=async(Y,Oe)=>{var Je,Be;m(!0);try{return await M.post("/wa/chat/newsletter-update",{sessionId:n,jid:H,...Y}),W.success(Oe||be(ge.saved,c)),await Q(),!0}catch(Qe){return W.error(((Be=(Je=Qe==null?void 0:Qe.response)==null?void 0:Je.data)==null?void 0:Be.error)||be(ge.saveFail,c)),!1}finally{m(!1)}},X=async Y=>{var Be;const Oe=(Be=Y.target.files)==null?void 0:Be[0];if(Y.target.value="",!Oe)return;const Je=await new Promise((Qe,Me)=>{const De=new FileReader;De.onload=()=>Qe(String(De.result)),De.onerror=Me,De.readAsDataURL(Oe)});await $({picture:Je})},ce=!!(x!=null&&x.canEdit),Z=(x==null?void 0:x.name)||(t==null?void 0:t.name)||be(ge.channel,c),D=(x==null?void 0:x.imgUrl)||(t==null?void 0:t.imgUrl),ae=x==null?void 0:x.subscribersCount,K=x!=null&&x.invite?`https://whatsapp.com/channel/${x.invite}`:null,Re=Mc(x==null?void 0:x.creationTime,c),_e=(x==null?void 0:x.reactionCodes)||null;return e.jsxs("aside",{className:"chat-info",children:[e.jsxs("div",{className:"ci-head",children:[e.jsx("div",{className:"title",children:be(ge.title,c)}),e.jsx(ne,{content:be(ge.close,c),position:"bottom",children:e.jsx("button",{className:"x",onClick:o,"aria-label":be(ge.close,c),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"ci-body",children:[e.jsxs("div",{className:"ci-hero",children:[e.jsxs("div",{className:`av ${v}`,children:[D?e.jsx("img",{src:D,alt:""}):Rc(Z),ce&&e.jsx(ne,{content:be(ge.changePhoto,c),position:"top",children:e.jsx("span",{className:"edit-cam",onClick:()=>{var Y;return(Y=C.current)==null?void 0:Y.click()},style:{cursor:"pointer"},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-camera"})})})})]}),ce&&e.jsx("input",{ref:C,type:"file",accept:"image/*",style:{display:"none"},onChange:X}),I!==null?e.jsxs("div",{style:{padding:"0 14px",width:"100%"}
2,children:[e.jsx("input",{autoFocus:!0,value:I,maxLength:25,onChange:Y=>U(Y.target.value),onKeyDown:Y=>{Y.key==="Escape"&&U(null),Y.key==="Enter"&&I.trim()&&$({name:I.trim()}).then(Oe=>Oe&&U(null))},style:{width:"100%",background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-1)",padding:"7px 10px",fontSize:14,fontFamily:"inherit"}}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:6},children:[e.jsxs("span",{style:{fontSize:11,color:"var(--text-4)"},children:[be(ge.nameMax,c)," · ",I.length,"/25"]}),e.jsxs("span",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>U(null),style:{background:"transparent",border:0,color:"var(--text-3)",fontSize:12,cursor:"pointer",fontFamily:"inherit"},children:be(ge.cancel,c)}),e.jsx("button",{disabled:w||!I.trim(),onClick:()=>$({name:I.trim()}).then(Y=>Y&&U(null)),style:{background:"var(--accent, #6366f1)",border:0,color:"#fff",fontSize:12,padding:"4px 12px",borderRadius:5,cursor:"pointer",fontFamily:"inherit",opacity:w?.6:1},children:be(ge.save,c)})]})]})]}):e.jsxs("div",{className:`nm ${k}${ce?" editable":""}`,onClick:()=>ce&&U(Z),children:[Z,(x==null?void 0:x.verified)&&e.jsx(ne,{content:be(ge.verified,c),position:"top",children:e.jsx("span",{style:{marginLeft:5,color:"var(--green)",display:"inline-flex",verticalAlign:"middle"},children:e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-check"})})})}),ce&&e.jsx(ne,{content:be(ge.editName,c),position:"top",children:e.jsx("span",{className:"edit",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-edit"})})})})]}),e.jsxs("div",{className:"sub",children:[e.jsx("svg",{style:{width:13,height:13,verticalAlign:-2,marginRight:4},children:e.jsx("use",{href:"#ci-megaphone"})}),be(ge.channel,c),ae!=null&&` · ${ca(ae,c)} ${Number(ae)===1?be(ge.subscriber,c):be(ge.subscribers,c)}`]}),ce&&D&&e.jsx("button",{disabled:w,onClick:()=>$({picture:null}),style:{marginTop:6,background:"transparent",border:0,color:"var(--text-4)",fontSize:11.5,cursor:"pointer",fontFamily:"inherit"},children:be(ge.removePhoto,c)})]}),(x==null?void 0:x.metaUnavailable)&&e.jsx("div",{style:{margin:"0 14px 8px",padding:"7px 10px",borderRadius:6,background:"var(--surface-2)",color:"var(--text-3)",fontSize:11.5},children:be(ge.offline,c)}),(x==null?void 0:x.state)==="SUSPENDED"&&e.jsx("div",{style:{margin:"0 14px 8px",padding:"7px 10px",borderRadius:6,background:"var(--danger-bg, rgba(239,68,68,.12))",color:"var(--danger, #ef4444)",fontSize:11.5},children:be(ge.suspended,c)}),e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:be(ge.description,c)}),u!==null?e.jsxs("div",{style:{padding:"0 14px"},children:[e.jsx("textarea",{autoFocus:!0,value:u,maxLength:2048,rows:4,onChange:Y=>p(Y.target.value),onKeyDown:Y=>{Y.key==="Escape"&&p(null)},style:{width:"100%",background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-1)",padding:"8px 10px",fontSize:13,fontFamily:"inherit",resize:"vertical"}}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:6,marginTop:6},children:[e.jsx("button",{onClick:()=>p(null),style:{background:"transparent",border:0,color:"var(--text-3)",fontSize:12,cursor:"pointer",fontFamily:"inherit"},children:be(ge.cancel,c)}),e.jsx("button",{disabled:w,onClick:()=>$({description:u}).then(Y=>Y&&p(null)),style:{background:"var(--accent, #6366f1)",border:0,color:"#fff",fontSize:12,padding:"4px 12px",borderRadius:5,cursor:"pointer",fontFamily:"inherit",opacity:w?.6:1},children:be(ge.save,c)})]})]}):e.jsx("div",{style:{padding:"8px 14px",fontSize:13,color:"var(--text-2)",lineHeight:1.5,whiteSpace:"pre-wrap",cursor:ce?"pointer":"default",borderRadius:6},onClick:()=>ce&&p((x==null?void 0:x.description)||""),children:(x==null?void 0:x.description)||e.jsx("span",{style:{color:"var(--text-4)",fontStyle:ce?"italic":"normal"},children:be(ce?ge.addDescription:ge.noDescription,c)})})]}),e.jsx("div",{className:"ci-section",children:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"center",padding:"2px 12px 4px"},children:[e.jsxs("button",{style:da,onClick:()=>s==null?void 0:s(),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-search"})}),c==="en"?"Search":"Buscar"]}),e.jsxs("button",{style:da,onClick:()=>i==null?void 0:i(t,"mute",t!=null&&t.isMuted?null:Date.now()+10*365*864e5),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:t!=null&&t.isMuted?"#ci-bell":"#ci-mute"})}),t!=null&&t.isMuted?c==="en"?"Unmute":c==="es"?"Reactivar":"Reativar":c==="en"?"Mute":"Silenciar"]}),e.jsxs("button",{style:da,onClick:()=>i==null?void 0:i(t,"pin",!(t!=null&&t.isPinned)),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-pin-stick"})}),t!=null&&t.isPinned?c==="en"?"Unpin":c==="es"?"Desfijar":"Desafixar":c==="en"?"Pin":c==="es"?"Fijar":"Fixar"]})]})}),e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:be(ge.title,c)}),e.jsxs("div",{style:os,children:[e.jsx("span",{style:vs,children:be(ge.subscribers,c).replace(/^./,Y=>Y.toUpperCase())}),e.jsx("span",{style:cs,children:ca(ae,c)})]}),(x==null?void 0:x.adminCount)!=null&&e.jsxs("div",{style:os,children:[e.jsx("span",{style:vs,children:be(ge.admins,c)}),e.jsx("span",{style:cs,children:ca(x.adminCount,c)})]}),e.jsxs("div",{style:os,children:[e.jsx("span",{style:vs,children:be(ge.yourRole,c)}),e.jsx("span",{style:cs,children:be(qr[x==null?void 0:x.role]||ge.roleGuest,c)})]}),Re&&e.jsxs("div",{style:os,children:[e.jsx("span",{style:vs,children:be(ge.createdAt,c)}),e.jsx("span",{style:cs,children:Re})]}),(x==null?void 0:x.handle)&&e.jsxs("div",{style:os,children:[e.jsx("span",{style:vs,children:"@"}),e.jsx("span",{style:cs,children:x.handle})]}),K&&e.jsxs("div",{style:{...os,alignItems:"flex-start"},children:[e.jsx("span",{style:vs,children:be(ge.link,c)}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[e.jsx("span",{style:{...cs,fontSize:12,color:"var(--text-2)"},children:K}),e.jsx(ne,{content:be(ge.copy,c),position:"left",children:e.jsx("button",{onClick:()=>{var Y;(Y=navigator.clipboard)==null||Y.writeText(K),W.success(be(ge.copied,c))},style:{background:"transparent",border:0,color:"var(--text-3)",cursor:"pointer",display:"flex",padding:2},children:e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-copy"})})})})]})]})]}),ce&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:be(ge.reactions,c)}),e.jsx("div",{style:{padding:"2px 14px 6px",display:"flex",flexDirection:"column",gap:2},children:Ac.map(Y=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 0",fontSize:13,color:"var(--text-2)",cursor:w?"default":"pointer"},children:[e.jsx("input",{type:"radio",name:"nl-react",value:Y.v,checked:_e===Y.v,disabled:w,onChange:()=>$({reactionCodes:Y.v})}),be(Y.l,c)]},Y.v))})]}),ce&&Array.isArray(b)&&e.jsxs("div",{className:"ci-section",children:[e.jsxs("div",{className:"lbl",children:[be(ge.followers,c)," ",b.length?`(${b.length})`:""]}),b.length===0?e.jsx("div",{style:{padding:"8px 14px",fontSize:12.5,color:"var(--text-4)"},children:be(ge.noFollowers,c)}):b.map(Y=>e.jsxs("div",{style:os,children:[e.jsx("span",{style:{...cs,textAlign:"left",fontWeight:400},className:k,children:Y.displayName||Rn(Y.phoneNumber)||be(ge.roleSub,c)}),e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,flexShrink:0},children:[(Y.role==="OWNER"||Y.role==="ADMIN")&&e.jsx("span",{style:{fontSize:11,color:"var(--green)"},children:be(qr[Y.role],c)}),Y.role==="ADMIN"&&e.jsx("button",{disabled:w,style:la,onClick:()=>ve("adminDemote",{userJid:Y.id}
2,be(ge.demoted,c)).then(Oe=>Oe&&(se(null),Q())),children:be(ge.demote,c)}),(x==null?void 0:x.role)==="OWNER"&&Y.role!=="OWNER"&&e.jsx("button",{disabled:w,style:la,onClick:()=>{const Oe=Y.displayName||Rn(Y.phoneNumber)||be(ge.roleSub,c);f==null||f({title:be(ge.transfer,c),message:be(ge.transferAsk,c).replace("{who}",Oe),confirmLabel:be(ge.transfer,c),onConfirm:()=>ve("changeOwner",{userJid:Y.id},be(ge.transferred,c)).then(Je=>Je&&(se(null),Q()))})},children:be(ge.transfer,c)})]})]},Y.id))]}),ce&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:be(ge.manage,c)}),e.jsxs("div",{style:{padding:"2px 14px 8px"},children:[e.jsx("div",{style:{fontSize:12,color:"var(--text-3)",marginBottom:5},children:be(ge.inviteAdmin,c)}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("input",{value:ke,onChange:Y=>Ae(Y.target.value),placeholder:be(ge.invitePlaceholder,c),style:{flex:1,minWidth:0,background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-1)",padding:"6px 9px",fontSize:12.5,fontFamily:"inherit"}}),e.jsx("button",{disabled:w||!ke.trim(),onClick:()=>{const Y=ke.replace(/\D/g,"");Y&&ve("adminInvite",{userJid:`${Y}@s.whatsapp.net`},be(ge.invited,c)).then(Oe=>{Oe&&(Ae(""),_())})},style:{background:"var(--accent, #6366f1)",border:0,color:"#fff",fontSize:12,padding:"0 12px",borderRadius:6,cursor:"pointer",fontFamily:"inherit",opacity:w?.6:1,flexShrink:0},children:be(ge.invite,c)})]})]}),Array.isArray(O)&&O.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{...vs,padding:"4px 14px",fontSize:12},children:be(ge.pending,c)}),O.map(Y=>e.jsxs("div",{style:os,children:[e.jsx("span",{style:{...cs,textAlign:"left",fontWeight:400},className:k,children:Rn(Y.phoneNumber)||be(ge.roleSub,c)}),e.jsx("button",{disabled:w,style:la,onClick:()=>ve("adminInviteRevoke",{userJid:Y.id||`${String(Y.phoneNumber).replace(/\D/g,"")}@s.whatsapp.net`},be(ge.revoked,c)).then(Oe=>Oe&&_()),children:be(ge.revoke,c)})]},Y.id||Y.phoneNumber))]})]}),e.jsxs("div",{className:"ci-section",children:[e.jsxs("button",{disabled:w,onClick:()=>f==null?void 0:f({title:be(ge.leaveCh,c),message:be(ge.leaveAsk,c).replace("{name}",Z),confirmLabel:be(ge.leaveCh,c),onConfirm:()=>ve("leave",{},be(ge.left,c)).then(Y=>Y&&(l==null||l(t),o==null?void 0:o()))}),style:Br,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-logout"})}),be(ge.leaveCh,c)]}),(x==null?void 0:x.role)==="OWNER"&&e.jsxs("button",{disabled:w,onClick:()=>f==null?void 0:f({title:be(ge.del,c),message:be(ge.delAsk,c).replace("{name}",Z),confirmLabel:be(ge.del,c),onConfirm:()=>ve("delete",{},be(ge.deleted,c)).then(Y=>Y&&(l==null||l(t),o==null?void 0:o()))}),style:Br,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-trash"})}),be(ge.del,c)]})]}),e.jsx("div",{style:{padding:"10px 14px 18px",fontSize:11.5,color:"var(--text-4)",lineHeight:1.5},children:ce?e.jsxs(e.Fragment,{children:[c==="en"?"You administer this channel — your posts go out to every follower.":c==="es"?"Administras este canal — tus publicaciones llegan a todos los suscriptores.":"Você administra este canal — o que você publica vai pra todos os inscritos.",e.jsx("br",{}),be(ge.tiposOk,c)]}):be(ge.readOnly,c)}),A&&e.jsx("div",{style:{padding:14,fontSize:12,color:"var(--text-4)"},children:"…"})]})]})}const la={background:"transparent",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-3)",fontSize:11,padding:"2px 8px",cursor:"pointer",fontFamily:"inherit"},Br={display:"flex",alignItems:"center",gap:9,width:"100%",background:"transparent",border:0,color:"var(--danger, #ef4444)",fontSize:13,padding:"10px 14px",cursor:"pointer",fontFamily:"inherit",textAlign:"left"},da={flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:4,background:"var(--surface-2)",border:"1px solid var(--border)",borderRadius:8,color:"var(--text-2)",fontSize:11.5,padding:"9px 4px",cursor:"pointer",fontFamily:"inherit"},T=(t,n)=>Qo(t,n),xa={pt:"pt-BR",en:"en-US",es:"es-ES"},R={groupInfo:{pt:"Info do grupo",en:"Group info",es:"Info del grupo"},contactInfo:{pt:"Info do contato",en:"Contact info",es:"Info del contacto"},close:{pt:"Fechar",en:"Close",es:"Cerrar"},changePhoto:{pt:"Alterar foto",en:"Change photo",es:"Cambiar foto"},name:{pt:"Nome",en:"Name",es:"Nombre"},firstName:{pt:"Nome",en:"First name",es:"Nombre"},lastName:{pt:"Sobrenome",en:"Last name",es:"Apellido"},editName:{pt:"Editar nome",en:"Edit name",es:"Editar nombre"},editContact:{pt:"Editar contato",en:"Edit contact",es:"Editar contacto"},members:{pt:"membros",en:"members",es:"miembros"},removePhoto:{pt:"Remover foto",en:"Remove photo",es:"Quitar foto"},description:{pt:"Descrição",en:"Description",es:"Descripción"},groupDescription:{pt:"Descrição do grupo",en:"Group description",es:"Descripción del grupo"}
2,thisChat:{pt:"esta conversa",en:"this chat",es:"este chat"},suspendedTitle:{pt:"Grupo suspenso pelo WhatsApp",en:"Group suspended by WhatsApp",es:"Grupo suspendido por WhatsApp"},suspendedDesc:{pt:"Não é possível enviar mensagens nem adicionar participantes enquanto durar a suspensão.",en:"You cannot send messages or add participants while the suspension lasts.",es:"No se pueden enviar mensajes ni añadir participantes mientras dure la suspensión."},growthLockedTitle:{pt:"Entradas travadas pelo WhatsApp",en:"Joins locked by WhatsApp",es:"Entradas bloqueadas por WhatsApp"},growthLockedDesc:{pt:"O link de convite não vai funcionar{quando}. É um limite do WhatsApp contra crescimento rápido demais, não uma configuração do grupo.",en:"The invite link will not work{quando}. This is a WhatsApp limit against growing too fast, not a group setting.",es:"El enlace de invitación no funcionará{quando}. Es un límite de WhatsApp contra el crecimiento rápido, no una configuración del grupo."},growthLockedUntil:{pt:" até {data}",en:" until {data}",es:" hasta {data}"},limitSharingTitle:{pt:"Privacidade Avançada ligada",en:"Advanced Privacy on",es:"Privacidad Avanzada activada"},limitSharingDesc:{pt:"O WhatsApp bloqueia exportar esta conversa. Exportar aqui também fica indisponível.",en:"WhatsApp blocks exporting this chat. Exporting here is unavailable too.",es:"WhatsApp bloquea exportar este chat. Exportar aquí tampoco está disponible."},addDescription:{pt:"Adicionar descrição",en:"Add description",es:"Agregar descripción"},search:{pt:"Buscar",en:"Search",es:"Buscar"},unmute:{pt:"Reativar",en:"Unmute",es:"Reactivar"},mute:{pt:"Silenciar",en:"Mute",es:"Silenciar"},mute8h:{pt:"8 horas",en:"8 hours",es:"8 horas"},mute1w:{pt:"1 semana",en:"1 week",es:"1 semana"},muteAlways:{pt:"Sempre",en:"Always",es:"Siempre"},unpin:{pt:"Desafixar",en:"Unpin",es:"Desfijar"},pin:{pt:"Fixar",en:"Pin",es:"Fijar"},labels:{pt:"Etiquetas",en:"Labels",es:"Etiquetas"},add:{pt:"Adicionar",en:"Add",es:"Agregar"},labelUpdateFail:{pt:"Falha ao atualizar etiqueta",en:"Failed to update label",es:"Error al actualizar la etiqueta"},mediaLinksDocs:{pt:"Mídia, links e docs",en:"Media, links and docs",es:"Multimedia, enlaces y docs"},photos:{pt:"Fotos",en:"Photos",es:"Fotos"},videos:{pt:"Vídeos",en:"Videos",es:"Videos"},audios:{pt:"Áudios",en:"Audio",es:"Audios"},docs:{pt:"Docs",en:"Docs",es:"Docs"},links:{pt:"Links",en:"Links",es:"Enlaces"},ephemeral:{pt:"Mensagens efêmeras",en:"Disappearing messages",es:"Mensajes temporales"},ephOff:{pt:"Desativado",en:"Off",es:"Desactivado"},eph24h:{pt:"24 horas",en:"24 hours",es:"24 horas"},eph7d:{pt:"7 dias",en:"7 days",es:"7 días"},eph90d:{pt:"90 dias",en:"90 days",es:"90 días"},ephUpdated:{pt:"Mensagens efêmeras atualizadas",en:"Disappearing messages updated",es:"Mensajes temporales actualizados"},groupSettings:{pt:"Configurações do grupo",en:"Group settings",es:"Configuración del grupo"},onlyAdminsSend:{pt:"Apenas admins enviam mensagens",en:"Only admins can send messages",es:"Solo los admins envían mensajes"},onlyAdminsEdit:{pt:"Apenas admins editam infos do grupo",en:"Only admins can edit group info",es:"Solo los admins editan la info del grupo"},onlyAdminsAdd:{pt:"Apenas admins adicionam membros",en:"Only admins can add members",es:"Solo los admins agregan miembros"},approveNewMembers:{pt:"Aprovar novos participantes",en:"Approve new participants",es:"Aprobar nuevos participantes"},settingUpdated:{pt:"Configuração atualizada",en:"Setting updated",es:"Configuración actualizada"},settingUpdateFail:{pt:"Falha ao atualizar",en:"Failed to update",es:"Error al actualizar"},commonGroups:{pt:"Grupos em comum",en:"Groups in common",es:"Grupos en común"},group:{pt:"Grupo",en:"Group",es:"Grupo"},inviteLink:{pt:"Link de convite",en:"Invite link",es:"Enlace de invitación"},publicLink:{pt:"Link público",en:"Public link",es:"Enlace público"},show:{pt:"Mostrar",en:"Show",es:"Mostrar"},copy:{pt:"Copiar",en:"Copy",es:"Copiar"},copied:{pt:"Copiado",en:"Copied",es:"Copiado"},share:{pt:"Compartilhar",en:"Share",es:"Compartir"},revoke:{pt:"Revogar",en:"Revoke",es:"Revocar"},revokeTitle:{pt:"Revogar link de convite?",en:"Revoke invite link?",es:"¿Revocar el enlace de invitación?"},revokeMsg:{pt:"Quem tiver o link antigo não conseguirá mais entrar. Um novo link será gerado.",en:"Anyone with the old link will no longer be able to join. A new link will be generated.",es:"Quien tenga el enlace anterior ya no podrá entrar. Se generará un enlace nuevo."},revoked:{pt:"Link revogado",en:"Link revoked",es:"Enlace revocado"},revokeFail:{pt:"Falha ao revogar",en:"Failed to revoke",es:"Error al revocar"},linkFail:{pt:"Falha ao obter link",en:"Failed to get link",es:"Error al obtener el enlace"},pendingRequests:{pt:"Solicitações pendentes",en:"Pending requests",es:"Solicitudes pendientes"},waitingApprovalOne:{pt:"{n} pessoa aguardando aprovação",en:"{n} person waiting for approval",es:"{n} persona esperando aprobación"},waitingApprovalMany:{pt:"{n} pessoas aguardando aprovação",en:"{n} people waiting for approval",es:"{n} personas esperando aprobación"},waitingApproval:{pt:"{n} aguardando aprovação",en:"{n} waiting for approval",es:"{n} esperando aprobación"},noRequests:{pt:"Nenhuma solicitação",en:"No requests",es:"Sin solicitudes"},decline:{pt:"Recusar",en:"Decline",es:"Rechazar"},approve:{pt:"Aprovar",en:"Approve",es:"Aprobar"},participants:{pt:"Participantes",en:"Participants",es:"Participantes"},searchParticipants:{pt:"Buscar participantes",en:"Search participants",es:"Buscar participantes"},addMembers:{pt:"Adicionar membros",en:"Add members",es:"Agregar miembros"},participant:{pt:"Participante",en:"Participant",es:"Participante"},contact:{pt:"Contato",en:"Contact",es:"Contacto"},selectContacts:{pt:"Selecione contatos",en:"Select contacts",es:"Selecciona contactos"},selectedOne:{pt:"{n} selecionado",en:"{n} selected",es:"{n} seleccionado"},selectedMany:{pt:"{n} selecionados",en:"{n} selected",es:"{n} seleccionados"},searchContact:{pt:"Buscar contato",en:"Search contact",es:"Buscar contacto"},noContacts:{pt:"Nenhum contato disponível",en:"No contacts available",es:"Ningún contacto disponible"},cancel:{pt:"Cancelar",en:"Cancel",es:"Cancelar"},adding:{pt:"Adicionando…",en:"Adding…",es:"Agregando…"},addedN:{pt:"{n} adicionado(s)",en:"{n} added",es:"{n} agregado(s)"},addFail:{pt:"Falha ao adicionar",en:"Failed to add",es:"Error al agregar"},participantOptions:{pt:"Opções do participante",en:"Participant options",es:"Opciones del participante"},sendMessage:{pt:"Enviar mensagem",en:"Send message",es:"Enviar mensaje"},addToContacts:{pt:"Adicionar aos contatos",en:"Add to contacts",es:"Agregar a contactos"},mentionWithAt:{pt:"Mencionar com @",en:"Mention with @",es:"Mencionar con @"},copyPhone:{pt:"Copiar telefone",en:"Copy phone number",es:"Copiar teléfono"},phoneCopied:{pt:"Telefone copiado",en:"Phone number copied",es:"Teléfono copiado"},mentionAdded:{pt:"Menção a {name} adicionada",en:"Mention of {name} added",es:"Mención a {name} agregada"},demoteAdmin:{pt:"Rebaixar admin",en:"Dismiss as admin",es:"Quitar admin"},makeAdmin:{pt:"Tornar admin",en:"Make admin",es:"Hacer admin"},remove:{pt:"Remover",en:"Remove",es:"Quitar"},removeParticipantTitle:{pt:"Remover participante?",en:"Remove participant?",es:"¿Quitar participante?"},removeParticipantMsg:{pt:"{name} será removido do grupo.",en:"{name} will be removed from the group.",es:"Se quitará a {name} del grupo."},removed:{pt:"Removido",en:"Removed",es:"Quitado"},promoted:{pt:"Promovido a admin",en:"Promoted to admin",es:"Promovido a admin"},demoted:{pt:"Rebaixado",en:"Dismissed as admin",es:"Degradado"},creator:{pt:"Criador",en:"Creator",es:"Creador"},admin:{pt:"Admin",en:"Admin",es:"Admin"},blockContact:{pt:"Bloquear contato",en:"Block contact",es:"Bloquear contacto"},blockContactMsg:{pt:"{name} não poderá te enviar mensagens ou ver seu status.",en:"{name} won't be able to message you or see your status.",es:"{name} no podrá enviarte mensajes ni ver tu estado."},block:{pt:"Bloquear",en:"Block",es:"Bloquear"}
2,contactBlocked:{pt:"Contato bloqueado",en:"Contact blocked",es:"Contacto bloqueado"},blockFail:{pt:"Falha ao bloquear",en:"Failed to block",es:"Error al bloquear"},report:{pt:"Denunciar",en:"Report",es:"Denunciar"},contactSaved:{pt:"Contato salvo",en:"Contact saved",es:"Contacto guardado"},saveContactFail:{pt:"Falha ao salvar contato",en:"Failed to save contact",es:"Error al guardar el contacto"},pastMembers:{pt:"Membros anteriores",en:"Past members",es:"Miembros anteriores"},none:{pt:"Nenhum",en:"None",es:"Ninguno"},left:{pt:"Saiu",en:"Left",es:"Salió"},e2eTitle:{pt:"Criptografia de ponta a ponta",en:"End-to-end encryption",es:"Cifrado de extremo a extremo"},e2eDesc:{pt:"As mensagens são protegidas com criptografia E2E.",en:"Messages are protected with end-to-end encryption.",es:"Los mensajes están protegidos con cifrado de extremo a extremo."},createdOn:{pt:"Criado em {date}",en:"Created on {date}",es:"Creado el {date}"},unblockContact:{pt:"Desbloquear contato",en:"Unblock contact",es:"Desbloquear contacto"},blockThisContact:{pt:"Bloquear este contato?",en:"Block this contact?",es:"¿Bloquear este contacto?"},blockThisContactMsg:{pt:"Você não receberá mais mensagens ou chamadas dele.",en:"You won't receive their messages or calls anymore.",es:"Ya no recibirás sus mensajes ni llamadas."},blocked:{pt:"Bloqueado",en:"Blocked",es:"Bloqueado"},unblocked:{pt:"Desbloqueado",en:"Unblocked",es:"Desbloqueado"},unblockFail:{pt:"Falha ao desbloquear",en:"Failed to unblock",es:"Error al desbloquear"},leaveGroup:{pt:"Sair do grupo",en:"Leave group",es:"Salir del grupo"},leaveCommunity:{pt:"Sair da comunidade",en:"Leave community",es:"Salir de la comunidad"},leaveCommunityTitle:{pt:"Sair desta comunidade?",en:"Leave this community?",es:"¿Salir de esta comunidad?"},leaveGroupTitle:{pt:"Sair deste grupo?",en:"Leave this group?",es:"¿Salir de este grupo?"},leaveMsg:{pt:"Você não receberá mais mensagens de {name}.",en:"You won't receive messages from {name} anymore.",es:"Ya no recibirás mensajes de {name}."},thisCommunity:{pt:"desta comunidade",en:"this community",es:"esta comunidad"},thisGroup:{pt:"deste grupo",en:"this group",es:"este grupo"},leave:{pt:"Sair",en:"Leave",es:"Salir"},leftCommunity:{pt:"Você saiu da comunidade",en:"You left the community",es:"Saliste de la comunidad"},leftGroup:{pt:"Você saiu do grupo",en:"You left the group",es:"Saliste del grupo"},leaveFail:{pt:"Falha ao sair",en:"Failed to leave",es:"Error al salir"},reportChat:{pt:"Reportar conversa",en:"Report chat",es:"Denunciar chat"},deviceOptions:{pt:"Opções do dispositivo",en:"Device options",es:"Opciones del dispositivo"},loading:{pt:"Carregando…",en:"Loading…",es:"Cargando…"},save:{pt:"Salvar",en:"Save",es:"Guardar"},descSaved:{pt:"Descrição salva",en:"Description saved",es:"Descripción guardada"},nameSaved:{pt:"Nome salvo",en:"Name saved",es:"Nombre guardado"},saveFail:{pt:"Falha ao salvar",en:"Failed to save",es:"Error al guardar"},imageTooBig:{pt:"Imagem muito grande (máx 5MB)",en:"Image too large (max 5MB)",es:"Imagen demasiado grande (máx 5MB)"},groupPhotoUpdated:{pt:"Foto do grupo atualizada",en:"Group photo updated",es:"Foto del grupo actualizada"},groupPhotoFail:{pt:"Falha ao atualizar foto",en:"Failed to update photo",es:"Error al actualizar la foto"},removeGroupPhotoTitle:{pt:"Remover foto do grupo?",en:"Remove group photo?",es:"¿Quitar la foto del grupo?"},photoRemoved:{pt:"Foto removida",en:"Photo removed",es:"Foto quitada"},fail:{pt:"Falha",en:"Failed",es:"Error"}},Fs=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase(),Vt=t=>bt(t),Ur=t=>!t||/^[+\d\s().\-–]+$/.test(String(t).trim()),Tc=t=>{const n=String(t||"").trim().split(/\s+/).filter(Boolean);return{first:n[0]||"",last:n.slice(1).join(" ")}};function Fc({chat:t,session:n,sessionId:o,labels:i=[],onClose:s,onContactSaved:f,onLabelChange:l,onLeaveGroup:c,onConfirmAsk:d,onDeviceOptions:v,onConvAction:k,onToggleSearch:x,onOpenChat:P,schedules:A=[],onOpenSchedules:y,anuncioKanban:w=null,locale:m="en"}){const{settings:I}=bs(),U=It("blurAvatars",I),u=It("blurNames",I),[p,b]=r.useState(null),[se,C]=r.useState(!0),[H,Q]=r.useState(null),[O,oe]=r.useState(""),[ke,Ae]=r.useState(!1),[ve,_]=r.useState(!1),[$,X]=r.useState(!1),[ce,Z]=r.useState(!1),[D,ae]=r.useState(null),[K,Re]=r.useState(0),[_e,Y]=r.useState(0),[Oe,Je]=r.useState(""),[Be,Qe]=r.useState(!1),Me=t==null?void 0:t.isGroup,De=t==null?void 0:t.jid,xt=!!(t!=null&&t.isNewsletter||String(De||"").endsWith("@newsletter")),ut=!!(p!=null&&p.isCommunity||p!=null&&p.isParent),mt=(n==null?void 0:n.provider_type)==="cloud_api"||(n==null?void 0:n.provider_type)==="coexistence",st=bi(n),kt=(n==null?void 0:n.provider_type)==="web"&&(!!(n!=null&&n.is_business)||(n==null?void 0:n.platform)==="smba"||(n==null?void 0:n.platform)==="smbi");r.useEffect(()=>{if(!o||!De)return;if(xt){C(!1);return}let q=!1;return C(!0),M.get(`/wa/chat/contact?sessionId=${o}&jid=${encodeURIComponent(De)}`).then(({data:he})=>{q||(b(he||{}),he!=null&&he.description&&Je(he.description),he!=null&&he.inviteCode&&ae(`https://chat.whatsapp.com/${he.inviteCode}`))}).catch(()=>!q&&b({})).finally(()=>!q&&C(!1)),()=>{q=!0}},[o,De,xt]),r.useEffect(()=>{if(!Me||!p||!st)return;let q=!1;return M.get(`/wa/chat/group-past-participants?sessionId=${o}&jid=${encodeURIComponent(De)}`).then(({data:he})=>!q&&Re(Array.isArray(he==null?void 0:he.participants)?he.participants.length:0)).catch(()=>{}),M.get(`/wa/chat/group-pending-requests?sessionId=${o}&jid=${encodeURIComponent(De)}`).then(({data:he})=>!q&&Y(Array.isArray(he==null?void 0:he.requests)?he.requests.length:0)).catch(()=>{}),()=>{q=!0}},[Me,p,o,De]);const At=r.useCallback(async()=>{try{const{data:q}=await M.get(`/wa/chat/contact?sessionId=${o}&jid=${encodeURIComponent(De)}`);b(q||{}),q!=null&&q.description&&Je(q.description)}catch{}},[o,De]);r.useEffect(()=>{if(!De)return;let q=null;const he=et=>{var re;(re=et.detail)!=null&&re.jid&&et.detail.jid!==De||(clearTimeout(q),q=setTimeout(()=>At(),600))};return window.addEventListener("pragmaz:group-update",he),window.addEventListener("pragmaz:group-participants",he),()=>{clearTimeout(q),window.removeEventListener("pragmaz:group-update",he),window.removeEventListener("pragmaz:group-participants",he)}},[De,At]);const dt=async(q,he={})=>
2{if(!st)throw W.error(Jt(m)),new Error("group_op_blocked_non_web_session");const{data:et}=await M.post("/wa/chat/group-action",{sessionId:o,groupJid:De,action:q,payload:he});return(et==null?void 0:et.result)??et},jt=async q=>{try{await dt("updateDescription",{description:q}),Je(q),W.success(T(R.descSaved,m)),Z(!1)}catch{W.error(T(R.saveFail,m))}},G=async q=>{try{Me?await dt("updateSubject",{subject:q}):await M.post("/wa/chat/save-contact",{sessionId:o,jid:De,fullName:q}),W.success(T(R.nameSaved,m)),X(!1)}catch{W.error(T(R.saveFail,m))}},me=({fullName:q,firstName:he})=>{const et=t==null?void 0:t.name,re=!!(t!=null&&t.isSavedContact);f==null||f(De,q,!0),X(!1),M.post("/wa/chat/save-contact",{sessionId:o,jid:De,fullName:q,firstName:he}).catch(()=>{f==null||f(De,et,re),W.error(T(R.saveContactFail,m))})},Se=async()=>{try{const q=await dt("inviteCode"),he=typeof q=="string"?`https://chat.whatsapp.com/${q}`:null;ae(he)}catch{W.error(T(R.linkFail,m))}},Fe=()=>{d==null||d({title:T(R.revokeTitle,m),message:T(R.revokeMsg,m),confirmLabel:T(R.revoke,m),onConfirm:async()=>{try{const q=await dt("revokeInvite"),he=typeof q=="string"?`https://chat.whatsapp.com/${q}`:null;ae(he),W.success(T(R.revoked,m))}catch{W.error(T(R.revokeFail,m))}}})},le=()=>{d==null||d({title:T(ut?R.leaveCommunityTitle:R.leaveGroupTitle,m),message:T(R.leaveMsg,m).replace("{name}",(t==null?void 0:t.name)||T(ut?R.thisCommunity:R.thisGroup,m)),confirmLabel:T(R.leave,m),onConfirm:async()=>{try{await dt("leave"),W.success(T(ut?R.leftCommunity:R.leftGroup,m)),c==null||c(De),s==null||s()}catch{W.error(T(R.leaveFail,m))}}})},Xe=()=>{d==null||d({title:m==="en"?"Deactivate community":m==="es"?"Desactivar comunidad":"Desativar comunidade",message:m==="en"?"This is IRREVERSIBLE. Subgroups become standalone groups.":m==="es"?"Acción IRREVERSIBLE. Los subgrupos se vuelven autónomos.":"Ação IRREVERSÍVEL. Os subgrupos viram grupos autônomos.",confirmLabel:m==="en"?"Deactivate":m==="es"?"Desactivar":"Desativar",onConfirm:async()=>{try{await dt("deactivateCommunity"),W.success(m==="en"?"Community deactivated":m==="es"?"Comunidad desactivada":"Comunidade desativada"),c==null||c(De),s==null||s()}catch{W.error(m==="en"?"Failed to deactivate":m==="es"?"Error al desactivar":"Falha ao desativar")}}})},z=()=>{const q=!!(p!=null&&p.isBlocked),he=q?"unblock":"block",et=async()=>{var re,tt;try{await M.post("/wa/chat/block",{sessionId:o,jid:De,action:he}),await M.post("/wa/chat/modify",{sessionId:o,jid:De,action:"setBlocked",value:!q}).catch(()=>{}),b(pt=>pt&&{...pt,isBlocked:!q}),window.dispatchEvent(new CustomEvent("pragmaz:block-changed",{detail:{jid:De,blocked:!q}})),W.success(T(q?R.unblocked:R.blocked,m))}catch(pt){W.error(((tt=(re=pt==null?void 0:pt.response)==null?void 0:re.data)==null?void 0:tt.error)||T(q?R.unblockFail:R.blockFail,m))}};if(q)return et();d==null||d({title:T(R.blockThisContact,m),message:T(R.blockThisContactMsg,m),confirmLabel:T(R.block,m),onConfirm:et})},Ce=async(q,he,et)=>{try{await dt(q,he),b(re=>re&&{...re,...et}),window.dispatchEvent(new CustomEvent("pragmaz:group-update",{detail:{jid:De}})),W.success(T(R.settingUpdated,m))}catch{W.error(T(R.settingUpdateFail,m))}},ye=r.useRef(null),at=()=>{var q;return(q=ye.current)==null?void 0:q.click()},L=async q=>{var et;const he=(et=q.target.files)==null?void 0:et[0];if(q.target.value="",!!he){if(!st){W.error(Jt(m));return}if(he.size>5*1024*1024){W.error(T(R.imageTooBig,m));return}try{const re=await new Promise((tt,pt)=>{const Et=new FileReader;Et.onload=()=>tt(Et.result),Et.onerror=pt,Et.readAsDataURL(he)});await M.post("/wa/chat/group-picture",{sessionId:o,jid:De,pictureBase64:re}),W.success(T(R.groupPhotoUpdated,m)),At()}catch{W.error(T(R.groupPhotoFail,m))}}},Ze=()=>{if(!st){W.error(Jt(m));return}d==null||d({title:T(R.removeGroupPhotoTitle,m),confirmLabel:T(R.remove,m),onConfirm:async()=>{try{await M.post("/wa/chat/group-picture",{sessionId:o,jid:De,remove:!0}),W.success(T(R.photoRemoved,m)),At()}catch{W.error(T(R.fail,m))}}})},rt=async q=>{try{Me?await dt("toggleEphemeral",{expiration:q}):await dt("setChatEphemeral",{expiration:q}),b(he=>he&&{...he,ephemeralDuration:q,ephemeralSeconds:q}),W.success(T(R.ephUpdated,m))}catch{W.error(T(R.fail,m))}},_t=async(q,he)=>{const et=q.lid||q.jid;try{await dt(he,{participants:[et]}),b(re=>{if(!re)return re;if(he==="remove")return{...re,participants:(re.participants||[]).filter(pt=>(pt.lid||pt.jid)!==et)};const tt=he==="promote"?"admin":"member";return{...re,participants:(re.participants||[]).map(pt=>(pt.lid||pt.jid)===et?{...pt,role:tt}:pt)}}),W.success(T(he==="remove"?R.removed:he==="promote"?R.promoted:R.demoted,m))}catch{W.error(T(R.fail,m))}};if(!t)return null;const Yt=T(Me?R.groupInfo:R.contactInfo,m),Qt=q=>q.role==="superadmin"?0:q.role==="admin"||q.admin?1:2,Rt=[...(p==null?void 0:p.participants)||[]].sort((q,he)=>{const et=Qt(q)-Qt(he);return et!==0?et:String(q.name||q.phone||"").localeCompare(String(he.n
2ame||he.phone||""))}),de=O.trim()?Rt.filter(q=>(q.name||"").toLowerCase().includes(O.toLowerCase())||(q.phone||"").includes(O)):Rt,$t=[{value:0,label:T(R.ephOff,m)},{value:86400,label:T(R.eph24h,m)},{value:604800,label:T(R.eph7d,m)},{value:7776e3,label:T(R.eph90d,m)}],Ut=$t.find(q=>q.value===((p==null?void 0:p.ephemeralDuration)??(p==null?void 0:p.ephemeralSeconds)??0))||$t[0];return xt?e.jsx($c,{chat:t,sessionId:o,onClose:s,onConvAction:k,onToggleSearch:x,onConfirmAsk:d,onLeaveGroup:c,locale:m}):e.jsxs("aside",{className:"chat-info",children:[e.jsxs("div",{className:"ci-head",children:[e.jsx("div",{className:"title",children:Yt}),e.jsx(ne,{content:T(R.close,m),position:"bottom",children:e.jsx("button",{className:"x",onClick:s,"aria-label":T(R.close,m),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"ci-body",children:[e.jsxs("div",{className:"ci-hero",children:[e.jsxs("div",{className:`av ${U}`,children:[t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:""}):Fs(lt(t.name,{phone:t.phone,jid:t.jid,lidLabel:T(R.contact,m)})),Me&&(p==null?void 0:p.amIAdmin)&&e.jsx(ne,{content:T(R.changePhoto,m),position:"top",children:e.jsx("span",{className:"edit-cam",onClick:at,style:{cursor:"pointer"},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-camera"})})})})]}),Me&&(p==null?void 0:p.amIAdmin)&&e.jsx("input",{ref:ye,type:"file",accept:"image/*",style:{display:"none"},onChange:L}),$?Me?e.jsx(Or,{initial:t.name||"",onSave:G,onCancel:()=>X(!1),placeholder:T(R.name,m),locale:m}):(()=>{const q=Ur(t==null?void 0:t.name)?Ur(t==null?void 0:t.pushName)?"":t==null?void 0:t.pushName:t==null?void 0:t.name,{first:he,last:et}=Tc(q);return e.jsx(zc,{firstInit:he,lastInit:et,phoneLabel:Vt(t.phone)||Vt(p==null?void 0:p.phone)||Vt(t.jid),onSave:me,onCancel:()=>X(!1),locale:m})})():e.jsxs("div",{className:`nm ${u}${!Me||p!=null&&p.amIAdmin?" editable":""}`,onClick:()=>{(!Me||p!=null&&p.amIAdmin)&&X(!0)},children:[lt(t.name,{phone:t.phone,jid:t.jid,lidLabel:T(R.contact,m)}),e.jsx(ne,{content:T(Me?R.editName:R.editContact,m),position:"top",children:e.jsx("span",{className:"edit",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-edit"})})})})]}),e.jsxs("div",{className:"sub",children:[Me?`${Rt.length||t.participantsCount||"–"} ${T(R.members,m)}`:Vt(t.phone)||Vt(p==null?void 0:p.phone)||Vt(t.jid),!Me&&!!(p!=null&&p.isBusiness)&&e.jsxs("span",{style:{marginLeft:8,display:"inline-flex",alignItems:"center",gap:3,color:"var(--green)",fontSize:11.5,fontWeight:600},children:[e.jsx("svg",{style:{width:13,height:13},children:e.jsx("use",{href:"#ci-shop"})}),"Business"]})]}),!Me&&((p==null?void 0:p.statusText)||(p==null?void 0:p.status))&&e.jsx("div",{className:"status",children:p.statusText||p.status}),Me&&(p==null?void 0:p.amIAdmin)&&t.imgUrl&&e.jsx("button",{onClick:Ze,style:{marginTop:6,background:"transparent",border:0,color:"var(--text-4)",fontSize:11.5,cursor:"pointer",fontFamily:"inherit"},children:T(R.removePhoto,m)})]}),Me&&((p==null?void 0:p.suspended)||(p==null?void 0:p.growthLocked)||(p==null?void 0:p.limitSharingEnabled))&&e.jsxs("div",{className:"ci-section",style:{display:"grid",gap:6,padding:"4px 12px 8px"},children:[p.suspended&&e.jsx(ua,{tom:"rose",icone:"#ci-alert",titulo:T(R.suspendedTitle,m),texto:T(R.suspendedDesc,m)}),p.growthLocked&&e.jsx(ua,{tom:"rose",icone:"#ci-lock",titulo:T(R.growthLockedTitle,m),texto:T(R.growthLockedDesc,m).replace("{quando}",Pc(p.growthLockExpiration,m))}),p.limitSharingEnabled&&e.jsx(ua,{tom:"indigo",icone:"#ci-shield",titulo:T(R.limitSharingTitle,m),texto:T(R.limitSharingDesc,m)})]}),Me&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.description,m)}),ce?e.jsx(Or,{initial:Oe,onSave:jt,onCancel:()=>Z(!1),multiline:!0,placeholder:T(R.groupDescription,m),locale:m}):e.jsx("div",{style:{padding:"8px 14px",fontSize:13,color:"var(--text-2)",lineHeight:1.5,cursor:p!=null&&p.amIAdmin?"pointer":"default",borderRadius:6,transition:"background 100ms"},onClick:()=>(p==null?void 0:p.amIAdmin)&&Z(!0),onMouseEnter:q=>(p==null?void 0:p.amIAdmin)&&(q.currentTarget.style.background="var(--surface-2)"),onMouseLeave:q=>q.currentTarget.style.background="transparent",children:Oe||(p!=null&&p.amIAdmin?e.jsx("span",{style:{color:"var(--text-4)",fontStyle:"italic"},children:T(R.addDescription,m)}):e.jsx("span",{style:{color:"var(--text-4)"},children:"—"}))})]}),e.jsx("div",{className:"ci-section",children:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"center",padding:"2px 12px 4px"},children:[e.jsxs("button",{style:pa,onClick:()=>x==null?void 0:x(),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-search"})}),T(R.search,m)]}),e.jsxs("div",{style:{position:"relative"},children:[e.jsxs("button",{style:pa,onClick:()=>t.isMuted?k==null?void 0:k(t,"mute",null):Qe(q=>!q),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:t.isMuted?"#ci-bell":"#ci-mute"})}),T(t.isMuted?R.unmute:R.mute,m)]}),Be&&!t.isMuted&&e.jsxs("div",{className:"dropdown-menu",style:{position:"absolute",top:"calc(100% + 4px)",left:"50%",transform:"translateX(-50%)",minWidth:130,zIndex:9e3},onMouseLeave:()=>Qe(!1),children:[e.jsx("button",{className:"item",onClick:()=>{Qe(!1),k==null||k(t,"mute",Date.now()+8*3600*1e3)},children:T(R.mute8h,m)}),e.jsx("button",{className:"item",onClick:()=>{Qe(!1),k==null||k(t,"mute",Date.now()+7*24*3600*1e3)},children:T(R.mute1w,m)}),e.jsx("button",{className:"item",onClick:()=>{Qe(!1),k==null||k(t,"mute",Date.now()+10*365*864e5)},children:T(R.muteAlways,m)})]})]}),e.jsxs("button",{style:pa,onClick:()=>k==null?void 0:k(t,"pin",!t.isPinned),children:[e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-pin-stick"})}),T(t.isPinned?R.unpin:R.pin,m)]})]})}),kt&&i.length>0&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.labels,m)}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,padding:"0 14px"},children:[(t.labels||[]).map((q,he)=>{const et=Ds(q.color);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,height:22,padding:"0 9px",borderRadius:5,background:`${et}1a`,color:et,fontSize:12,fontWeight:500},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:et}}),Ht(q,m)]},(typeof q=="object"?q.id??q.name:q)??he)}),e.jsx(Wc,{chat:t,labels:i,sessionId:o,onLabelChange:l,locale:m})]})]}),e.jsx(Ic,{schedules:A,locale:m,onOpen:y}),(p==null?void 0:p.mediaCounts)&&(p.mediaCounts.image>0||p.mediaCounts.video>0||p.mediaCounts.audio>0||p.mediaCounts.document>0||p.mediaCounts.link>0)&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.mediaLinksDocs,m)}),e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:6,padding:"0 14px"},children:[{k:"image",icon:"#ci-image",label:T(R.photos,m)},{k:"video",icon:"#ci-video",label:T(R.videos,m)},{k:"audio",icon:"#ci-mic-fill",label:T(R.audios,m)},{k:"document",icon:"#ci-file",label:T(R.docs,m)},{k:"link",icon:"#ci-link",label:T(R.links,m)}].filter(q=>p.mediaCounts[q.k]>0).map(q=>{const he=q.k==="document"?"docs":q.k==="link"?"links":q.k==="audio"?null:"media";return e.jsxs("div",{onClick:he?()=>Q(he):void 0,style:{background:"var(--surface-2)",borderRadius:7,padding:"8px 4px",textAlign:"center",border:"1px solid var(--hairline)",cursor:he?"pointer":"default"},children:[e.jsx("svg",{style:{width:17,height:17,color:"var(--text-3)"},children:e.jsx("use",{href:q.icon})}),e.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)",marginTop:3,fontVariantNumeric:"tabular-nums"},children:p.mediaCounts[q.k]}),e.jsx("div",{style:{fontSize:11,color:"var(--text-4)"},children:q.label})]},q.k)})})]}),!Me&&w&&(w.anuncio||w.card||w.chatbot)&&e.jsxs("div",{className:"ci-section","data-anuncio-kanban":"1",children:[e.jsx("div",{className:"lbl",children:T({pt:"Anúncio e Kanban",en:"Ad and Kanban",es:"Anuncio y Kanban"},m)}),e.jsxs("div",{style:{display:"grid",gap:6},children:[w.anuncio&&e.jsxs("div",{className:"ci-eph",onClick:()=>{const q=Er(w.anuncio.link);q&&window.open(q,"_blank","noopener,noreferrer")},children:[e.jsx("span",{className:"ic",children:w.anuncio.imagem?e.jsx("img",{src:w.anuncio.imagem,alt:"",style:{width:16,height:16,borderRadius:3,objectFit:"cover"}}):e.jsx("svg",{children:e.jsx("use",{href:"#ci-megaphone"})})}),e.jsxs("div",{className:"t",children:[e.jsxs("div",{className:"k",children:[T({pt:"Anúncio",en:"Ad",es:"Anuncio"},m),w.anuncio.plataforma?` · ${w.anuncio.plataforma}`:""]}),e.jsx("div",{className:"v",children:w.anuncio.titulo||w.anuncio.sourceId})]}),Er(w.anuncio.link)&&e.jsx("span",{className:"chev",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-r"})})})]}),w.card&&e.jsxs("div",{className:"ci-eph",style:{cursor:"default"},children:[e.jsx("span",{className:"ic",children:e.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:w.card.cor||"#667eea",display:"inline-block",margin:3}})}),e.jsxs("div",{className:"t",children:[e.jsx("div",{className:"k",children:T({pt:"Etapa",en:"Stage",es:"Etapa"},m)}),e.jsxs("div",{className:"v",children:[w.card.coluna,w.card.valor!=null?` · ${w.card.moeda?`${w.card.moeda} `:""}
2${Number(w.card.valor).toLocaleString(xa[m]||"pt-BR",{maximumFractionDigits:2})}`:"",w.card.meta==="aceito"?` · ${T({pt:"venda na Meta",en:"sale sent to Meta",es:"venta en Meta"},m)}`:"",w.card.venda_pendente?` · ${T({pt:"confirmar venda",en:"confirm sale",es:"confirmar venta"},m)}`:""]})]})]}),w.chatbot&&e.jsxs("div",{className:"ci-eph",style:{cursor:"default"},children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-zap"})})}),e.jsxs("div",{className:"t",children:[e.jsxs("div",{className:"k",children:["Chatbot",w.chatbot.chatbot?` · ${w.chatbot.chatbot}`:""]}),e.jsx("div",{className:"v",children:qo(w.chatbot.texto,w.chatbot.tipo,w.chatbot.gatilho)})]})]})]})]}),!mt&&e.jsx("div",{className:"ci-section",children:e.jsxs("div",{className:"ci-eph",onClick:()=>{const q=$t[($t.findIndex(he=>he.value===Ut.value)+1)%$t.length];rt(q.value)},children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsxs("div",{className:"t",children:[e.jsx("div",{className:"k",children:T(R.ephemeral,m)}),e.jsx("div",{className:"v",children:Ut.label})]}),e.jsx("span",{className:"chev",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-r"})})})]})}),Me&&p&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.groupSettings,m)}),e.jsxs("div",{style:{padding:"0 14px",display:"flex",flexDirection:"column",gap:11},children:[e.jsx(kn,{label:T(R.onlyAdminsSend,m),on:!!p.restrictSend,disabled:!p.amIAdmin,onToggle:q=>Ce("settings",{setting:q?"announcement":"not_announcement"},{restrictSend:q})}),e.jsx(kn,{label:T(R.onlyAdminsEdit,m),on:!!p.restrictEdit,disabled:!p.amIAdmin,onToggle:q=>Ce("settings",{setting:q?"locked":"unlocked"},{restrictEdit:q})}),e.jsx(kn,{label:T(R.onlyAdminsAdd,m),on:p.memberAddMode==="admin_add",disabled:!p.amIAdmin,onToggle:q=>Ce("memberAddMode",{mode:q?"admin_add":"all_member_add"},{memberAddMode:q?"admin_add":"all_member_add"})}),e.jsx(kn,{label:T(R.approveNewMembers,m),on:!!p.joinApprovalMode,disabled:!p.amIAdmin,onToggle:q=>Ce("joinApprovalMode",{mode:q?"on":"off"},{joinApprovalMode:q})})]})]}),!Me&&Array.isArray(p==null?void 0:p.commonGroups)&&p.commonGroups.length>0&&e.jsxs("div",{className:"ci-section",children:[e.jsxs("div",{className:"lbl",children:[T(R.commonGroups,m)," · ",p.commonGroups.length]}),e.jsx("div",{style:{padding:"2px 8px"},children:p.commonGroups.map(q=>e.jsxs("button",{className:"cv2-list-row",onClick:()=>P==null?void 0:P(q.jid,{jid:q.jid,name:q.subject,isGroup:!0,imgUrl:q.imgUrl}),children:[e.jsx("span",{className:"av",children:q.imgUrl?e.jsx("img",{src:q.imgUrl,alt:"",style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):Fs(q.subject)}),e.jsx("span",{className:"nm",children:q.subject||T(R.group,m)}),e.jsx("span",{style:{marginLeft:"auto",color:"var(--text-4)",fontSize:12},children:q.size||0})]},q.jid))})]}),Me&&(p==null?void 0:p.amIAdmin)&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.inviteLink,m)}),e.jsxs("div",{className:"ci-invite-link",style:{margin:"0 14px"},children:[e.jsxs("div",{className:"r1",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-link"})}),e.jsx("span",{className:"t",children:T(R.publicLink,m)}),!D&&e.jsx("button",{onClick:Se,style:{background:"transparent",border:0,color:"var(--indigo-light)",fontSize:12,fontWeight:600,cursor:"pointer"},children:T(R.show,m)})]}),D&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"url",children:D}),e.jsxs("div",{className:"actions",children:[e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(D),W.success(T(R.copied,m))},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-copy"})}),T(R.copy,m)]}),e.jsxs("button",{onClick:()=>{navigator.share?navigator.share({url:D}).catch(()=>{}):(navigator.clipboard.writeText(D),W.success(T(R.copied,m)))},children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-share"})}),T(R.share,m)]}),e.jsxs("button",{className:"revoke",onClick:Fe,children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})}),T(R.revoke,m)]})]})]})]})]}),Me&&(p==null?void 0:p.amIAdmin)&&_e>0&&e.jsxs("div",{className:"ci-section",children:[e.jsx("div",{className:"lbl",children:T(R.pendingRequests,m)}),e.jsxs("button",{style:{display:"flex",alignItems:"center",gap:9,width:"100%",padding:"10px 14px",background:"rgba(245,158,11,0.06)",border:"1px solid rgba(245,158,11,0.20)",borderRadius:8,color:"var(--amber)",fontFamily:"inherit",fontSize:13,fontWeight:600,cursor:"pointer",margin:"0 14px"},onClick:()=>_(!0),children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-alert"})}),T(_e>1?R.waitingApprovalMany:R.waitingApprovalOne,m).replace("{n}",_e),e.jsx("span",{style:{marginLeft:"auto",color:"var(--text-3)"},children:e.jsx("svg",{style:{width:13,height:13},children:e.jsx("use",{href:"#ci-chev-r"})})})]})]}),Me&&e.jsxs("div",{className:"ci-section",children:[e.jsxs("div",{className:"lbl",children:[T(R.participants,m)," · ",Rt.length]}),e.jsx("div",{style:{padding:"0 14px 6px"},children:e.jsx("input",{type:"text",value:O,onChange:q=>oe(q.target.value),placeholder:T(R.searchParticipants,m),style:{width:"100%",padding:"7px 11px",background:"var(--surface-2)",border:"1px solid var(--hairline)",borderRadius:6,color:"var(--text)",fontFamily:"inherit",fontSize:13,outline:"none"}})}),(p==null?void 0:p.amIAdmin)&&st&&e.jsxs("button",{onClick:()=>Ae(!0),style:{display:"flex",alignItems:"center",gap:9,width:"calc(100% - 28px)",margin:"4px 14px",padding:"8px 11px",background:"transparent",border:"1px dashed var(--hairline-strong)",borderRadius:7,color:"var(--indigo-light)",fontFamily:"inherit",fontSize:13,fontWeight:500,cursor:"pointer",transition:"background 100ms"},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-user-plus"})}),T(R.addMembers,m)]}),e.jsx("div",{style:{padding:"4px 4px 8px",maxHeight:360,overflowY:"auto"},children:de.map(q=>
2e.jsx(Lc,{p:q,amIAdmin:p==null?void 0:p.amIAdmin,sessionId:o,onAction:_t,onConfirmAsk:d,onOpenChat:P,locale:m},q.lid||q.jid||q.phone))})]}),Me&&st&&K>0&&e.jsx(qc,{sessionId:o,chatJid:De,count:K,locale:m}),Me&&st&&((p==null?void 0:p.isCommunity)||(p==null?void 0:p.isParent))&&e.jsx(_c,{sessionId:o,communityJid:De,onOpenChat:P,onConfirmAsk:d,amIAdmin:p==null?void 0:p.amIAdmin,locale:m}),e.jsxs("div",{className:"ci-section",children:[e.jsxs("div",{className:"ci-row",style:{display:"flex",alignItems:"flex-start",gap:10,padding:"8px 14px"},children:[e.jsx("svg",{style:{width:16,height:16,color:"var(--text-4)",flexShrink:0,marginTop:1},children:e.jsx("use",{href:"#ci-lock"})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:13,color:"var(--text-2)"},children:T(R.e2eTitle,m)}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-4)",marginTop:1,lineHeight:1.4},children:T(R.e2eDesc,m)})]})]}),Me&&(p==null?void 0:p.creation)&&e.jsxs("div",{className:"ci-row",style:{display:"flex",alignItems:"center",gap:10,padding:"4px 14px 8px"},children:[e.jsx("svg",{style:{width:16,height:16,color:"var(--text-4)",flexShrink:0},children:e.jsx("use",{href:"#ci-clock"})}),e.jsx("div",{style:{fontSize:12,color:"var(--text-3)"},children:T(R.createdOn,m).replace("{date}",new Date(Number(p.creation)*1e3).toLocaleDateString(xa[m]||"en-US",{day:"2-digit",month:"long",year:"numeric"}))})]})]}),e.jsxs("div",{className:"ci-section",style:{marginTop:18,paddingBottom:20},children:[!Me&&p&&e.jsxs("button",{onClick:z,style:Zs,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:p.isBlocked?"#ci-check":"#ci-block"})}),T(p.isBlocked?R.unblockContact:R.blockContact,m)]}),Me&&(p==null?void 0:p.amIMember)&&e.jsxs("button",{onClick:le,style:Zs,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-logout"})}),T(ut?R.leaveCommunity:R.leaveGroup,m)]}),Me&&ut&&(p==null?void 0:p.amIAdmin)&&e.jsxs("button",{onClick:Xe,style:Zs,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-trash"})}),m==="en"?"Deactivate community":m==="es"?"Desactivar comunidad":"Desativar comunidade"]}),!mt&&e.jsxs("button",{style:Zs,onClick:()=>Ni({onConfirmAsk:d,sessionId:o,jid:t.jid,origem:Me?"grupo":"contato",nome:t.name||T(R.thisChat,m),locale:m}),children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-flag"})}),T(R.reportChat,m)]}),v&&e.jsxs("button",{style:{...Zs,color:"var(--text-2)"},onClick:v,children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-lock"})}),T(R.deviceOptions,m)]})]}),se&&e.jsx("div",{style:{padding:20,textAlign:"center",color:"var(--text-4)",fontSize:13},children:T(R.loading,m)})]}),H&&e.jsx(Ec,{sessionId:o,jid:t.jid,initialTab:H,locale:m,onClose:()=>Q(null)}),ke&&e.jsx(Bc,{sessionId:o,groupJid:De,canGroup:st,existingJids:Rt.map(q=>q.jid||q.lid),onClose:()=>Ae(!1),onAdded:()=>{Ae(!1),At()},locale:m}),ve&&e.jsx(Uc,{sessionId:o,groupJid:De,canGroup:st,onClose:()=>_(!1),onChange:q=>Y(q),locale:m})]})}function _c({sessionId:t,communityJid:n,onOpenChat:o,onConfirmAsk:i,amIAdmin:s,locale:f="en"}){const[l,c]=r.useState(null),[d,v]=r.useState(!1),[k,x]=r.useState(!1),P=(w,m,I)=>f==="en"?m:f==="es"?I:w,A=(w=()=>!0)=>{v(!0),M.post("/wa/chat/group-action",{sessionId:t,groupJid:n,action:"getSubGroups",payload:{}}).then(({data:m})=>{w()&&c(m.result||[])}).catch(()=>{w()&&c([])}).finally(()=>{w()&&v(!1)})};r.useEffect(()=>{let w=!1;return A(()=>!w),()=>{w=!0}},[t,n]);const y=w=>{i==null||i({title:P("Remover grupo da comunidade?","Remove group from community?","¿Quitar grupo de la comunidad?"),message:P(`"${w.subject}" deixará de fazer parte da comunidade.`,`"${w.subject}" will no longer be part of the community.`,`"${w.subject}" dejará de pertenecer a la comunidad.`),confirmLabel:P("Remover","Remove","Quitar"),danger:!0,onConfirm:async()=>{var m,I;try{await M.post("/wa/chat/group-action",{sessionId:t,groupJid:n,action:"unlinkSubgroup",payload:{parentJid:n,childJid:w.jid}}),c(U=>(U||[]).filter(u=>u.jid!==w.jid)),W.success(P("Grupo removido da comunidade","Group removed from community","Grupo quitado de la comunidad"))}catch(U){W.error(((I=(m=U.response)==null?void 0:m.data)==null?void 0:I.error)||P("Falha ao remover","Failed to remove","Error al quitar"))}}})};return e.jsxs("div",{className:"ci-section",children:[e.jsxs("div",{className:"lbl",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-users"})}),P("Grupos da comunidade","Community groups","Grupos de la comunidad")," ",l&&`(${l.length})`]}
2),d?e.jsx("div",{style:{textAlign:"center",padding:10,color:"var(--text-4)",fontSize:13},children:P("Carregando…","Loading…","Cargando…")}):(l||[]).map(w=>e.jsxs("div",{className:"cv2-participant-row",style:{display:"flex",alignItems:"center",gap:10,padding:"8px 14px"},children:[e.jsxs("button",{onClick:()=>o==null?void 0:o(w.jid,{jid:w.jid,name:w.subject,isGroup:!0}),style:{display:"flex",alignItems:"center",gap:10,flex:1,minWidth:0,background:"transparent",border:0,cursor:"pointer",textAlign:"left"},children:[e.jsx("div",{style:{width:32,height:32,borderRadius:9,background:"rgba(99,102,241,0.15)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--indigo-light)",flexShrink:0},children:e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-users"})})}),e.jsx("div",{style:{flex:1,minWidth:0},children:e.jsxs("div",{style:{fontSize:13,color:"var(--text)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",display:"flex",alignItems:"center",gap:6},children:[w.subject,w.isDefaultSubGroup&&e.jsx("span",{style:{fontSize:11,background:"rgba(99,102,241,0.2)",color:"var(--indigo-light)",padding:"1px 5px",borderRadius:3},children:P("AVISOS","NEWS","AVISOS")})]})})]}),s&&!w.isDefaultSubGroup&&e.jsx(ne,{content:P("Remover da comunidade","Remove from community","Quitar de la comunidad"),position:"left",children:e.jsx("button",{onClick:m=>{m.stopPropagation(),y(w)},style:{background:"transparent",border:0,cursor:"pointer",color:"var(--text-4)",padding:4,flexShrink:0},children:e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-x"})})})})]},w.jid)),s&&!d&&e.jsxs("button",{onClick:()=>x(!0),style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"9px 14px",background:"transparent",border:0,cursor:"pointer",textAlign:"left",color:"var(--indigo-light)"},children:[e.jsx("div",{style:{width:32,height:32,borderRadius:9,background:"rgba(99,102,241,0.12)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-add"})})}),e.jsx("span",{style:{fontSize:13,fontWeight:600},children:P("Adicionar grupo","Add group","Agregar grupo")}
2)]}),k&&e.jsx(Dc,{sessionId:t,communityJid:n,existingSubJids:new Set((l||[]).map(w=>w.jid)),onClose:()=>x(!1),onChanged:A,locale:f})]})}function Dc({sessionId:t,communityJid:n,existingSubJids:o,onClose:i,onChanged:s,locale:f="en"}){const l=(C,H,Q)=>f==="en"?H:f==="es"?Q:C,[c,d]=r.useState("existing"),[v,k]=r.useState(null),[x,P]=r.useState(""),[A,y]=r.useState(null),[w,m]=r.useState(()=>new Set),[I,U]=r.useState("");r.useEffect(()=>{if(c!=="existing")return;let C=!0;return M.post("/wa/chat/group-action",{sessionId:t,groupJid:"@g.us",action:"fetchAll",payload:{}}).then(({data:H})=>{if(!C)return;const O=Object.values((H==null?void 0:H.result)||{}).filter(oe=>oe&&oe.id&&!oe.isCommunity&&!oe.isParent&&!oe.linkedParentJID&&!oe.linkedParent&&oe.id!==n&&!o.has(oe.id));k(O)}).catch(()=>{C&&k([])}),()=>{C=!1}},[c,t,n]);const u=C=>m(H=>{const Q=new Set(H);return Q.has(C)?Q.delete(C):Q.add(C),Q}),p=async()=>{var H,Q;const C=[...w];if(C.length){y("link");try{const{data:O}=await M.post("/wa/chat/group-action",{sessionId:t,groupJid:n,action:"linkSubgroup",payload:{parentJid:n,childJids:C}}),oe=(O==null?void 0:O.result)||{},ke=oe.linkedGroupJids||C,Ae=oe.failedGroups||[];if(ke.length&&W.success(ke.length===1?l("Grupo adicionado à comunidade","Group added to community","Grupo agregado a la comunidad"):l(`${ke.length} grupos adicionados à comunidade`,`${ke.length} groups added to community`,`${ke.length} grupos agregados a la comunidad`)),Ae.length){const _=Ae.some($=>$.error===406);W.error(_?l("Alguns grupos não entraram: comunidade cheia.","Some groups not added: community is full.","Algunos no se agregaron: la comunidad está llena."):l(`${Ae.length} grupo(s) não foram adicionados (precisa ser admin).`,`${Ae.length} group(s) were not linked (must be admin).`,`${Ae.length} grupo(s) no se agregaron (debes ser admin).`))}const ve=new Set(ke);k(_=>(_||[]).filter($=>!ve.has($.id))),m(_=>{const $=new Set(_);return ke.forEach(X=>$.delete(X)),$}),s==null||s()}catch(O){W.error(((Q=(H=O.response)==null?void 0:H.data)==null?void 0:Q.error)||l("Falha ao adicionar (você precisa ser admin do grupo)","Failed to add (you must be group admin)","Error al agregar (debes ser admin del grupo)"))}finally{y(null)}}},b=async()=>{var H,Q,O;const C=I.trim();if(C){y("create");try{const{data:oe}=await M.post("/wa/chat/group-action",{sessionId:t,groupJid:"@g.us",action:"create",payload:{subject:C,participants:[],linkedParent:n}});if((H=oe==null?void 0:oe.result)!=null&&H.id)W.success(l("Grupo criado na comunidade","Group created in community","Grupo creado en la comunidad")),s==null||s(),i==null||i();else throw new Error("no id")}catch(oe){W.error(((O=(Q=oe.response)==null?void 0:Q.data)==null?void 0:O.error)||l("Falha ao criar grupo","Failed to create group","Error al crear el grupo"))}finally{y(null)}}},se=(v||[]).filter(C=>!x.trim()||(C.subject||"").toLowerCase().includes(x.trim().toLowerCase()));return e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{className:"ttl",children:l("Adicionar grupo","Add group","Agregar grupo")}
2),e.jsx(ne,{content:l("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:i,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{display:"flex",gap:4,padding:"4px 16px 0"},children:[["existing",l("Grupo existente","Existing group","Grupo existente")],["new",l("Criar novo","Create new","Crear nuevo")]].map(([C,H])=>e.jsx("button",{onClick:()=>d(C),style:{flex:1,padding:"8px 0",background:"transparent",border:0,cursor:"pointer",fontSize:13,fontWeight:600,color:c===C?"var(--text)":"var(--text-4)",borderBottom:c===C?"2px solid var(--indigo-light)":"2px solid transparent"},children:H},C))}),c==="existing"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cv2-modal-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",value:x,onChange:C=>P(C.target.value),placeholder:l("Buscar grupo","Search group","Buscar grupo")})]}),e.jsxs("div",{className:"cv2-modal-list",children:[v===null&&e.jsx("div",{className:"empty",children:l("Carregando grupos…","Loading groups…","Cargando grupos…")}),v!==null&&se.length===0&&e.jsx("div",{className:"empty",children:l("Nenhum grupo elegível (grupos já em uma comunidade não aparecem).","No eligible groups (groups already in a community are hidden).","Ningún grupo elegible.")}),se.map(C=>{var Q;const H=w.has(C.id);return e.jsxs("button",{className:`cv2-target-row ${H?"selected":""}`,disabled:A==="link",onClick:()=>u(C.id),children:[e.jsx("span",{className:`sel-check ${H?"on":""}`,children:H&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),e.jsx("div",{className:"av",children:e.jsx("svg",{style:{width:17,height:17},children:e.jsx("use",{href:"#ci-users"})})}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:C.subject||l("(grupo sem nome)","(unnamed group)","(grupo sin nombre)")}),e.jsxs("div",{className:"ph",children:[((Q=C.participants)==null?void 0:Q.length)||C.size||0," ",l("membros","members","miembros")]})]})]},C.id)})]}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsxs("span",{className:"count",children:[w.size," ",l("selecionado(s)","selected","seleccionado(s)")]}),e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:i,children:l("Cancelar","Cancel","Cancelar")}
2),e.jsx("button",{className:"confirm",onClick:p,disabled:A==="link"||w.size===0,children:A==="link"?l("Adicionando…","Adding…","Agregando…"):l(`Adicionar${w.size?` (${w.size})`:""}`,`Add${w.size?` (${w.size})`:""}`,`Agregar${w.size?` (${w.size})`:""}`)})]})]}):e.jsxs("div",{style:{padding:"14px 16px"},children:[e.jsx("input",{type:"text",value:I,maxLength:100,autoFocus:!0,onChange:C=>U(C.target.value),onKeyDown:C=>{C.key==="Enter"&&b()},placeholder:l("Nome do novo grupo","New group name","Nombre del nuevo grupo"),style:{width:"100%",padding:"9px 12px",background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:8,color:"var(--text)",fontFamily:"inherit",fontSize:14,outline:"none"}}),e.jsx("p",{style:{fontSize:12,color:"var(--text-4)",margin:"8px 2px 0"},children:l("O grupo é criado já dentro desta comunidade.","The group is created already inside this community.","El grupo se crea ya dentro de esta comunidad.")}),e.jsxs("div",{className:"cv2-modal-foot",style:{paddingLeft:0,paddingRight:0},children:[e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:i,children:l("Cancelar","Cancel","Cancelar")}
2),e.jsx("button",{className:"confirm",onClick:b,disabled:A==="create"||!I.trim(),children:A==="create"?l("Criando…","Creating…","Creando…"):l("Criar grupo","Create group","Crear grupo")})]})]})]})})}function Lc({p:t,amIAdmin:n,sessionId:o,onAction:i,onConfirmAsk:s,onOpenChat:f,locale:l="en"}){const[c,d]=r.useState(!1),v=t.role==="admin"||t.role==="superadmin",k=t.role==="superadmin",x=Vt(t.phone||t.jid),P=lt(t.name,{phone:t.phone,jid:t.jid,lidLabel:T(R.participant,l)}),A=()=>{navigator.clipboard.writeText("+"+String(t.phone||t.jid||"").replace(/\D/g,"")),W.success(T(R.phoneCopied,l)),d(!1)},y=()=>{const p=t.pnJid&&t.pnJid.endsWith("@s.whatsapp.net")?t.pnJid:t.pnJid?`${String(t.pnJid).split("@")[0]}@s.whatsapp.net`:null,b=p||t.jid||t.lid;b&&(f==null||f(b,{jid:b,name:P,isGroup:!1,imgUrl:t.imgUrl,pnJid:p||void 0,lid:t.lid||void 0}),d(!1))},w=()=>{d(!1),window.dispatchEvent(new CustomEvent("pragmaz:insert-mention",{detail:{jid:t.lid||t.jid,name:P}})),W.success(T(R.mentionAdded,l).replace("{name}",P))},m=()=>{d(!1);const p=t.jid||t.lid;p&&(s==null||s({title:T(R.blockContact,l),message:T(R.blockContactMsg,l).replace("{name}",P),confirmLabel:T(R.block,l),onConfirm:async()=>{var b,se;try{await M.post("/wa/chat/block",{sessionId:o,jid:p,action:"block"}),W.success(T(R.contactBlocked,l))}catch(C){W.error(((se=(b=C.response)==null?void 0:b.data)==null?void 0:se.error)||T(R.blockFail,l))}}}))},I=()=>{d(!1);const p=t.jid||t.lid;p&&Ni({onConfirmAsk:s,sessionId:o,jid:p,origem:"contato",nome:P,locale:l})},U=async()=>{d(!1);try{await M.post("/wa/chat/save-contact",{sessionId:o,jid:t.jid||t.lid,fullName:t.name||"+"+String(x).replace(/\D/g,"")}),W.success(T(R.contactSaved,l))}catch{W.error(T(R.saveContactFail,l))}},u=()=>{d(!1),s==null||s({title:T(R.removeParticipantTitle,l),message:T(R.removeParticipantMsg,l).replace("{name}",P),confirmLabel:T(R.remove,l),onConfirm:()=>i(t,"remove")})};return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",borderRadius:6,cursor:"default",position:"relative"},className:"cv2-participant-row",children:[e.jsx("div",{style:{width:32,height:32,borderRadius:"50%",background:"linear-gradient(135deg, #2a2a30, #18181c)",border:"1px solid var(--hairline-strong)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:600,color:"var(--text-2)",flexShrink:0},children:t.imgUrl?e.jsx("img",{src:t.imgUrl,alt:"",style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):Fs(P)}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:"var(--text)",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:P}),e.jsx("div",{style:{fontSize:12,color:"var(--text-3)",fontVariantNumeric:"tabular-nums"},children:Vt(t.phone||t.jid)})]}),(v||k)&&e.jsx("span",{style:{padding:"1px 6px",borderRadius:3,background:k?"rgba(245,158,11,0.15)":"rgba(192,132,252,0.15)",color:k?"var(--amber)":"var(--purple-light)",fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em"},children:T(k?R.creator:R.admin,l)}),e.jsx(ne,{content:T(R.participantOptions,l),position:"left",children:e.jsx("button",{onClick:p=>{p.stopPropagation(),d(b=>!b)},style:{background:"transparent",border:0,padding:4,cursor:"pointer",color:"var(--text-4)",borderRadius:4},children:e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-dots"})})})}),c&&e.jsxs("div",{style:{position:"absolute",top:"100%",right:10,zIndex:9e3,background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:7,padding:4,minWidth:190,boxShadow:"var(--shadow-pop)"},onMouseLeave:()=>d(!1),children:[e.jsxs("button",{style:ls,onClick:y,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-msg"})}),T(R.sendMessage,l)]}),e.jsxs("button",{style:ls,onClick:U,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-user-plus"})}),T(R.addToContacts,l)]}),e.jsxs("button",{style:ls,onClick:w,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-tag"})}),T(R.mentionWithAt,l)]}),e.jsxs("button",{style:ls,onClick:A,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-copy"})}),T(R.copyPhone,l)]}),n&&!k&&e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{height:1,background:"var(--hairline)",margin:"4px 0"}}),e.jsxs("button",{style:ls,onClick:()=>{i(t,v?"demote":"promote"),d(!1)},children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-star"})}),T(v?R.demoteAdmin:R.makeAdmin,l)]}),e.jsxs("button",{style:{...ls,color:"var(--rose)"},onClick:u,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-logout"})}),T(R.remove,l)]})]}),e.jsx("div",{style:{height:1,background:"var(--hairline)",margin:"4px 0"}}),e.jsxs("button",{style:{...ls,color:"var(--rose)"},onClick:m,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-block"})}),T(R.blockContact,l)]}),e.jsxs("button",{style:{...ls,color:"var(--rose)"},onClick:I,children:[e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-alert"})}),T(R.report,l)]})]})]})}function kn({label:t,on:n,disabled:o,onToggle:i}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,opacity:o?.5:1},children:[e.jsx("span",{style:{flex:1,fontSize:13,color:"var(--text-2)",lineHeight:1.3},children:t}),e.jsx("div",{className:`sg-tg ${n?"on":""}`,role:"switch","aria-checked":n,onClick:()=>!o&&i(!n),style:{cursor:o?"not-allowed":"pointer",flexShrink:0}})]})}function ua({tom:t,icone:n,titulo:o,texto:i}){const s=t==="rose"?"var(--rose)":"var(--indigo-light)";return e.jsxs("div",{style:{display:"flex",gap:9,alignItems:"flex-start",padding:"9px 11px",borderRadius:8,background:t==="rose"?"rgba(244,63,94,0.08)":"rgba(99,102,241,0.08)",border:`1px solid ${t==="rose"?"rgba(244,63,94,0.28)":"rgba(99,102,241,0.28)"}`},children:[e.jsx("svg",{style:{width:15,height:15,color:s,flexShrink:0,marginTop:1},children:e.jsx("use",{href:n})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:s},children:o}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-2)",lineHeight:1.45,marginTop:2},children:i})]})]})}function Pc(t,n){if(!t)return"";const o=Number(t)*1e3;if(!Number.isFinite(o)||o<=Date.now())return"";
2const s=new Date(o).toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});return(n==="en"?" until ":n==="es"?" hasta ":" até ")+s}function Ni({onConfirmAsk:t,sessionId:n,jid:o,origem:i,nome:s,locale:f}){const l=(c,d,v)=>f==="en"?d:f==="es"?v:c;t==null||t({title:l(`Denunciar ${s}?`,`Report ${s}?`,`¿Denunciar ${s}?`),message:i==="grupo"?l("O grupo vai para revisão do WhatsApp. A denúncia não pode ser desfeita.","The group goes to WhatsApp for review. A report cannot be undone.","El grupo va a revisión de WhatsApp. La denuncia no se puede deshacer."):l('A conta vai para revisão do WhatsApp e pode ser banida. A denúncia não pode ser desfeita. Isto NÃO bloqueia o contato — use "Bloquear" para isso.','The account goes to WhatsApp for review and may be banned. A report cannot be undone. This does NOT block the contact — use "Block" for that.','La cuenta va a revisión de WhatsApp y puede ser baneada. La denuncia no se puede deshacer. Esto NO bloquea el contacto — usa "Bloquear".'),confirmLabel:l("Denunciar","Report","Denunciar"),onConfirm:async()=>{var c,d;try{await M.post("/wa/chat/report",{sessionId:n,jid:o,origem:i}),W.success(l("Denúncia enviada ao WhatsApp","Report sent to WhatsApp","Denuncia enviada a WhatsApp"))}catch(v){W.error(((d=(c=v.response)==null?void 0:c.data)==null?void 0:d.error)||l("Falha ao denunciar","Report failed","Error al denunciar"))}}})}function Or({initial:t,onSave:n,onCancel:o,multiline:i,placeholder:s,locale:f="en"}){const[l,c]=r.useState(t||""),d=r.useRef(null);r.useEffect(()=>{var k;(k=d.current)==null||k.focus()},[]);const v=k=>{k.key==="Escape"&&(o==null||o()),k.key==="Enter"&&!k.shiftKey&&!i&&(k.preventDefault(),n(l.trim()))};return e.jsxs("div",{className:"inline-edit",style:{padding:"8px 14px"},children:[i?e.jsx("textarea",{ref:d,value:l,onChange:k=>c(k.target.value),onKeyDown:v,placeholder:s}):e.jsx("input",{ref:d,value:l,onChange:k=>c(k.target.value),onKeyDown:v,placeholder:s}),e.jsx(ne,{content:T(R.save,f),position:"top",children:e.jsx("button",{className:"ok",onClick:()=>n(l.trim()),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})})}),e.jsx(ne,{content:T(R.cancel,f),position:"top",children:e.jsx("button",{className:"cancel",onClick:o,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]})}function zc({firstInit:t,lastInit:n,phoneLabel:o,onSave:i,onCancel:s,locale:f="en"}){const[l,c]=r.useState(t||""),[d,v]=r.useState(n||""),k=r.useRef(null);r.useEffect(()=>{var y;(y=k.current)==null||y.focus()},[]);const x=()=>{const y=l.trim();y&&i({fullName:[y,d.trim()].filter(Boolean).join(" ").trim(),firstName:y})},P=y=>{y.key==="Escape"&&(s==null||s()),y.key==="Enter"&&(y.preventDefault(),x())},A={width:"100%",padding:"7px 10px",background:"var(--surface-3)",border:"1px solid var(--hairline)",borderRadius:6,color:"var(--text)",fontFamily:"inherit",fontSize:13,outline:"none",marginBottom:6};return e.jsxs("div",{style:{padding:"8px 14px",width:"100%",maxWidth:300,margin:"0 auto"},children:[e.jsx("input",{ref:k,value:l,onChange:y=>c(y.target.value),onKeyDown:P,placeholder:T(R.firstName,f),style:A}),e.jsx("input",{value:d,onChange:y=>v(y.target.value),onKeyDown:P,placeholder:T(R.lastName,f),style:{...A,marginBottom:o?6:8}}),o&&e.jsx("div",{style:{fontSize:11,color:"var(--text-3)",marginBottom:8,fontVariantNumeric:"tabular-nums",textAlign:"center"},children:o}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:s,style:{flex:1,padding:"6px 10px",background:"var(--surface-3)",border:"1px solid var(--hairline)",borderRadius:5,color:"var(--text-2)",fontFamily:"inherit",fontSize:12,cursor:"pointer"},children:T(R.cancel,f)}),e.jsx("button",{onClick:x,disabled:!l.trim(),style:{flex:1,padding:"6px 10px",background:"var(--green)",border:0,borderRadius:5,color:"var(--on-accent)",fontFamily:"inherit",fontSize:12,fontWeight:600,cursor:l.trim()?"pointer":"not-allowed",opacity:l.trim()?1:.6},children:T(R.save,f)})]})]})}function Wc({chat:t,labels:n,sessionId:o,onLabelChange:i,locale:s="en"}){const[f,l]=r.useState(!1),c=new Set((t.labels||[]).map(v=>String(v.id??v.name??v))),d=async v=>{const k=c.has(String(v.id??v.name));try{await M.post("/wa/chat/label-assign",{sessionId:o,jid:t.jid,labelId:String(v.id??v.name),action:k?"remove":"add"}),i==null||i(t.jid,v.id??v.name,k?"remove":"add",v)}catch{W.error(T(R.labelUpdateFail,s))}};return e.jsxs("div",{style:{position:"relative"},children:[e.jsxs("button",{onClick:()=>l(v=>!v),style:{display:"inline-flex",alignItems:"center",gap:4,height:22,padding:"0 9px",borderRadius:5,background:"transparent",border:"1px dashed var(--hairline-strong)",color:"var(--text-3)",fontFamily:"inherit",fontSize:12,cursor:"pointer"},children:[e.jsx("svg",{style:{width:13,height:13},children:e.jsx("use",{href:"#ci-add"})}),T(R.add,s)]}),f&&e.jsx("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:9e3,background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:8,padding:6,minWidth:200,boxShadow:"var(--shadow-pop)"},onMouseLeave:()=>l(!1),children:n.map(v=>{const k=c.has(String(v.id??v.name));return e.jsxs("button",{onClick:()=>d(v),style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 9px",borderRadius:5,background:k?"var(--surface-3)":"transparent",border:0,color:"var(--text-2)",fontFamily:"inherit",fontSize:13,cursor:"pointer",textAlign:"left"},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:Ds(v.color)}}),e.jsx("span",{style:{flex:1},children:Ht(v,s)}),k&&e.jsx("svg",{style:{width:14,height:14,color:"var(--indigo-light)"},children:e.jsx("use",{href:"#ci-check"})})]},v.id||v.name)})})]})}function qc({sessionId:t,chatJid:n,count:o,locale:i="en"}){const[s,f]=r.useState(!1),[l,c]=r.useState([]),[d,v]=r.useState(!1),k=async()=>
2{if(!s){v(!0);try{const{data:x}=await M.get(`/wa/chat/group-past-participants?sessionId=${t}&jid=${encodeURIComponent(n)}`);c((x==null?void 0:x.participants)||[])}catch{}finally{v(!1)}}};return e.jsxs("div",{className:"ci-section",children:[e.jsxs("button",{onClick:()=>{f(x=>!x),!s&&k()},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"8px 14px",background:"transparent",border:0,color:"var(--text-3)",fontFamily:"inherit",fontSize:12,fontWeight:500,cursor:"pointer",textTransform:"uppercase",letterSpacing:"0.08em"},children:[T(R.pastMembers,i)," · ",o,e.jsx("span",{style:{marginLeft:"auto"},children:e.jsx("svg",{style:{width:13,height:13},children:e.jsx("use",{href:s?"#ci-chev-u":"#ci-chev-d"})})})]}),s&&e.jsxs("div",{style:{padding:"4px 4px 10px"},children:[d&&e.jsx("div",{style:{padding:8,color:"var(--text-4)",fontSize:12,textAlign:"center"},children:T(R.loading,i)}),!d&&l.length===0&&e.jsx("div",{style:{padding:8,color:"var(--text-4)",fontSize:12,textAlign:"center"},children:T(R.none,i)}),l.map((x,P)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 10px",opacity:.7},children:[e.jsx("div",{style:{width:30,height:30,borderRadius:"50%",background:"linear-gradient(135deg, #2a2a30, #18181c)",border:"1px solid var(--hairline-strong)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,color:"var(--text-2)",flexShrink:0},children:Fs(lt(x.name,{phone:x.phone,jid:x.jid,lidLabel:T(R.participant,i)}))}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:"var(--text-2)"},children:lt(x.name,{phone:x.phone,jid:x.jid,lidLabel:T(R.participant,i)})}),e.jsxs("div",{style:{fontSize:11.5,color:"var(--text-4)"},children:[x.reason==="REMOVED"?e.jsx("span",{style:{color:"var(--amber)"},children:T(R.removed,i)}):e.jsx("span",{style:{color:"var(--green)"},children:T(R.left,i)}),x.leaveTs?e.jsxs("span",{style:{marginLeft:6},children:["· ",new Date(x.leaveTs*1e3).toLocaleDateString(xa[i]||"en-US")]}):null]})]})]},P))]})]})}function Bc({sessionId:t,groupJid:n,canGroup:o=!0,existingJids:i=[],onClose:s,onAdded:f,locale:l="en"}){const[c,d]=r.useState([]),[v,k]=r.useState(!0),[x,P]=r.useState(""),[A,y]=r.useState(new Set),[w,m]=r.useState(!1);r.useEffect(()=>{if(!o){k(!1);return}let u=!1;const p=new URLSearchParams({sessionId:t,search:x,limit:"100"});return M.get(`/wa/chat/contacts?${p}`).then(({data:b})=>{if(u)return;const se=Array.isArray(b==null?void 0:b.contacts)?b.contacts:[];d(se.filter(C=>!i.includes(C.jid)))}).catch(()=>!u&&d([])).finally(()=>!u&&k(!1)),()=>{u=!0}},[t,x]);const I=u=>{y(p=>{const b=new Set(p);return b.has(u)?b.delete(u):b.add(u),b})},U=async()=>{if(!o){W.error(Jt(l));return}if(A.size!==0){m(!0);try{await M.post("/wa/chat/group-action",{sessionId:t,groupJid:n,action:"add",payload:{participants:[...A]}}),W.success(T(R.addedN,l).replace("{n}",A.size)),f==null||f()}catch{W.error(T(R.addFail,l))}finally{m(!1)}}};return o?e.jsx("div",{className:"cv2-modal-backdrop",onClick:s,children:e.jsxs("div",{className:"cv2-modal",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"ttl",children:T(R.addMembers,l)}),e.jsx("div",{className:"sub",children:A.size>0?T(A.size>1?R.selectedMany:R.selectedOne,l).replace("{n}",A.size):T(R.selectContacts,l)})]}),e.jsx(ne,{content:T(R.close,l),position:"bottom",children:e.jsx("button",{className:"x",onClick:s,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"cv2-modal-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",value:x,onChange:u=>P(u.target.value),placeholder:T(R.searchContact,l),autoFocus:!0})]}),e.jsxs("div",{className:"cv2-modal-list",children:[v&&e.jsx("div",{className:"empty",children:T(R.loading,l)}),!v&&c.length===0&&e.jsx("div",{className:"empty",children:T(R.noContacts,l)}),c.map(u=>{const p=A.has(u.jid);return e.jsxs("button",{className:`cv2-target-row ${p?"selected":""}`,onClick:()=>I(u.jid),children:[e.jsx("span",{className:`sel-check ${p?"on":""}`,children:p&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),e.jsx("div",{className:"av",children:u.imgUrl?e.jsx("img",{src:u.imgUrl,alt:""}):Fs(lt(u.name,{phone:u.phone,jid:u.jid,lidLabel:T(R.contact,l)}))}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:lt(u.name,{phone:u.phone,jid:u.jid,lidLabel:T(R.contact,l)})}),e.jsx("div",{className:"ph",children:Vt(u.phone||u.jid)})]})]},u.jid)})]}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:s,children:T(R.cancel,l)}),e.jsx("button",{className:"confirm",onClick:U,disabled:w||A.size===0,children:w?T(R.adding,l):`${T(R.add,l)} ${A.size||""}`.trim()})]})]})}):e.jsx("div",{className:"cv2-modal-backdrop",onClick:s,children:e.jsxs("div",{className:"cv2-modal",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{className:"ttl",children:T(R.addMembers,l)}),e.jsx(ne,{content:T(R.close,l),position:"bottom",children:e.jsx("button",{className:"x",onClick:s,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{padding:"24px 20px",textAlign:"center",color:"var(--text-3)",fontSize:13,lineHeight:1.5},children:Jt(l)})]})})}function Uc({sessionId:t,groupJid:n,canGroup:o=!0,onClose:i,onChange:s,locale:f="en"}){const[l,c]=r.useState([]),[d,v]=r.useState(!0),[k,x]=r.useState(new Set),P=r.useCallback(async()=>
2{if(!o){v(!1);return}v(!0);try{const{data:y}=await M.get(`/wa/chat/group-pending-requests?sessionId=${t}&jid=${encodeURIComponent(n)}`),w=Array.isArray(y==null?void 0:y.requests)?y.requests:[];c(w),s==null||s(w.length)}catch{}finally{v(!1)}},[t,n,s,o]);r.useEffect(()=>{P()},[P]);const A=async(y,w)=>{if(!o){W.error(Jt(f));return}x(m=>{const I=new Set(m);return I.add(y.jid),I});try{await M.post("/wa/chat/group-action",{sessionId:t,groupJid:n,action:"requestParticipantsUpdate",payload:{participants:[y.jid],action:w==="decline"?"reject":"approve"}});const m=l.filter(I=>I.jid!==y.jid);c(m),s==null||s(m.length)}catch{W.error(T(R.fail,f))}finally{x(m=>{const I=new Set(m);return I.delete(y.jid),I})}};return o?e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal",onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"ttl",children:T(R.pendingRequests,f)}),e.jsx("div",{className:"sub",children:T(R.waitingApproval,f).replace("{n}",l.length)})]}),e.jsx(ne,{content:T(R.close,f),position:"bottom",children:e.jsx("button",{className:"x",onClick:i,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"cv2-modal-list",children:[d&&e.jsx("div",{className:"empty",children:T(R.loading,f)}),!d&&l.length===0&&e.jsx("div",{className:"empty",children:T(R.noRequests,f)}),l.map(y=>e.jsxs("div",{className:"cv2-target-row",style:{cursor:"default"},children:[e.jsx("div",{className:"av",children:Fs(lt(y.name,{phone:y.phone,jid:y.jid,lidLabel:T(R.participant,f)}))}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:lt(y.name,{phone:y.phone,jid:y.jid,lidLabel:T(R.participant,f)})}),e.jsx("div",{className:"ph",children:Vt(y.phone||y.jid)})]}),e.jsxs("div",{style:{display:"flex",gap:6,marginLeft:"auto"},children:[e.jsx("button",{onClick:()=>A(y,"decline"),disabled:k.has(y.jid),style:{padding:"5px 10px",borderRadius:5,background:"transparent",border:"1px solid var(--hairline-strong)",color:"var(--text-3)",fontSize:12,fontFamily:"inherit",cursor:"pointer"},children:T(R.decline,f)}),e.jsx("button",{onClick:()=>A(y,"approve"),disabled:k.has(y.jid),style:{padding:"5px 10px",borderRadius:5,background:"var(--green)",border:0,color:"var(--on-accent)",fontSize:12,fontWeight:600,fontFamily:"inherit",cursor:"pointer"},children:T(R.approve,f)})]})]},y.jid))]})]})}):e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal",onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{className:"ttl",children:T(R.pendingRequests,f)}),e.jsx(ne,{content:T(R.close,f),position:"bottom",children:e.jsx("button",{className:"x",onClick:i,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{padding:"24px 20px",textAlign:"center",color:"var(--text-3)",fontSize:13,lineHeight:1.5},children:Jt(f)})]})})}const pa={display:"flex",flexDirection:"column",alignItems:"center",gap:5,padding:"9px 14px",borderRadius:8,background:"var(--surface-2)",border:"1px solid var(--hairline)",color:"var(--text-2)",cursor:"pointer",fontFamily:"inherit",fontSize:11.5,fontWeight:500,minWidth:64},Zs={display:"flex",alignItems:"center",gap:9,width:"calc(100% - 28px)",margin:"6px 14px",padding:"10px 12px",background:"transparent",border:0,borderRadius:7,color:"var(--rose)",fontFamily:"inherit",fontSize:13,fontWeight:500,cursor:"pointer",textAlign:"left",transition:"background 100ms"},ls={display:"flex",alignItems:"center",gap:9,width:"100%",padding:"7px 10px",borderRadius:5,background:"transparent",border:0,color:"var(--text-2)",fontFamily:"inherit",fontSize:13,cursor:"pointer",textAlign:"left"},Oc=Object.keys(gi).map(Number);function ki({value:t,onChange:n,t:o}){return e.jsx("div",{className:"cv2-lbl-colors",children:Oc.map(i=>e.jsx("button",{type:"button",className:`cv2-lbl-color${t===i?" on":""}`,style:{background:gi[i]},onClick:()=>n(i),"aria-label":o(`cor ${i}`,`color ${i}`,`color ${i}`),children:t===i&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})},i))})}function Gc({label:t,sessionId:n,locale:o,onChanged:i,onConfirmAsk:s,t:f}){const[l,c]=r.useState(!1),[d,v]=r.useState(Ht(t,o)),[k,x]=r.useState(t.color??0),[P,A]=r.useState(!1),y=async()=>
2{if(!(!d.trim()||P)){A(!0);try{await M.post("/wa/chat/label-update",{sessionId:n,labelId:t.id,name:d.trim(),color:k}),c(!1),i==null||i()}catch{}finally{A(!1)}}},w=()=>{s==null||s({title:f("Apagar etiqueta?","Delete label?","¿Borrar etiqueta?"),message:f(`"${Ht(t,o)}" será removida de todas as conversas.`,`"${Ht(t,o)}" will be removed from all chats.`,`"${Ht(t,o)}" se quitará de todos los chats.`),confirmLabel:f("Apagar","Delete","Borrar"),onConfirm:async()=>{try{await M.delete("/wa/chat/label",{data:{sessionId:n,labelId:t.id}}),i==null||i()}catch{}}})};return l?e.jsxs("div",{className:"cv2-lbl-edit",children:[e.jsx("input",{className:"cv2-input",value:d,onChange:m=>v(m.target.value),maxLength:100,autoFocus:!0,onKeyDown:m=>{m.key==="Enter"&&y(),m.key==="Escape"&&c(!1)}}),e.jsx(ki,{value:k,onChange:x,t:f}),e.jsxs("div",{className:"cv2-lbl-actions",children:[e.jsx("button",{className:"cv2-lbl-btn ghost",onClick:()=>c(!1),children:f("Cancelar","Cancel","Cancelar")}),e.jsx("button",{className:"cv2-lbl-btn primary",onClick:y,disabled:P||!d.trim(),children:f("Salvar","Save","Guardar")})]})]}):e.jsxs("div",{className:"cv2-lbl-row",children:[e.jsx("span",{className:"cv2-lbl-dot",style:{background:Ds(t.color)}}),e.jsx("span",{className:"cv2-lbl-name",children:Ht(t,o)}),e.jsx(ne,{content:f("Editar","Edit","Editar"),position:"top",children:e.jsx("button",{className:"cv2-lbl-icon",onClick:()=>c(!0),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-edit"})})})}),e.jsx(ne,{content:f("Apagar","Delete","Borrar"),position:"top",children:e.jsx("button",{className:"cv2-lbl-icon danger",onClick:w,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})})})})]})}function Vc({sessionId:t,labels:n=[],locale:o="pt",onClose:i,onChanged:s,onConfirmAsk:f}){const l=ba(),[c,d]=r.useState(!1),[v,k]=r.useState(""),[x,P]=r.useState(0),[A,y]=r.useState(!1),w=(I,U,u)=>o==="en"?U:o==="es"?u:I,m=async()=>{if(!(!v.trim()||A)){y(!0);try{await M.post("/wa/chat/label-create",{sessionId:t,name:v.trim(),color:x}),k(""),P(0),d(!1),s==null||s()}catch{}finally{y(!1)}}};return _s.createPortal(e.jsx("div",{className:"cv2-portal","data-cv2-theme":l,children:e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal cv2-lbl-modal",style:{maxWidth:440,display:"flex",flexDirection:"column"},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{className:"ttl",children:w("Gerenciar etiquetas","Manage labels","Gestionar etiquetas")}),e.jsx(ne,{content:w("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:i,"aria-label":w("Fechar","Close","Cerrar"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"cv2-lbl-body",children:[n.length===0&&!c&&e.jsx("div",{className:"cv2-lbl-empty",children:w("Nenhuma etiqueta ainda","No labels yet","Sin etiquetas")}),n.map(I=>e.jsx(Gc,{label:I,sessionId:t,locale:o,onChanged:s,onConfirmAsk:f,t:w},I.id)),c?e.jsxs("div",{className:"cv2-lbl-edit",children:[e.jsx("input",{className:"cv2-input",placeholder:w("Nome da etiqueta","Label name","Nombre de la etiqueta"),value:v,onChange:I=>k(I.target.value),maxLength:100,autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&m(),I.key==="Escape"&&(d(!1),k(""))}}),e.jsx(ki,{value:x,onChange:P,t:w}),e.jsxs("div",{className:"cv2-lbl-actions",children:[e.jsx("button",{className:"cv2-lbl-btn ghost",onClick:()=>{d(!1),k("")},children:w("Cancelar","Cancel","Cancelar")}
2),e.jsx("button",{className:"cv2-lbl-btn primary",onClick:m,disabled:A||!v.trim(),children:w("Criar","Create","Crear")})]})]}):e.jsxs("button",{className:"cv2-lbl-new",onClick:()=>d(!0),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-add"})}),w("Nova etiqueta","New label","Nueva etiqueta")]})]})]})})}),document.body)}const Gr={pt:{ttl:"Selecione uma conversa",sub:"Escolha um chat na barra lateral pra começar",types:{web:{name:"WhatsApp Web",desc:"Conectado pelo QR Code, espelhando o seu celular."},web_business:{name:"WhatsApp Web Business",desc:"WhatsApp Business conectado pelo QR Code, espelhando o seu celular."},coex:{name:"Coexistência",desc:"WhatsApp Business no celular e aqui ao mesmo tempo, pela API oficial."},cloud:{name:"Cloud API",desc:"Número oficial pela API da Meta, direto na nuvem."}},e2e:"Mensagens protegidas com criptografia de ponta a ponta",cloudNote:"Mensagens via API oficial da Meta"},en:{ttl:"Select a conversation",sub:"Choose a chat from the sidebar to start messaging",types:{web:{name:"WhatsApp Web",desc:"Connected via QR Code, mirroring your phone."},web_business:{name:"WhatsApp Web Business",desc:"WhatsApp Business connected via QR Code, mirroring your phone."},coex:{name:"Coexistence",desc:"WhatsApp Business on your phone and here at the same time, via the official API."},cloud:{name:"Cloud API",desc:"Official number via the Meta API, straight from the cloud."}},e2e:"Messages secured with end-to-end encryption",cloudNote:"Messages via the official Meta API"},es:{ttl:"Selecciona una conversación",sub:"Elige un chat de la barra lateral para empezar",types:{web:{name:"WhatsApp Web",desc:"Conectado por Código QR, reflejando tu celular."},web_business:{name:"WhatsApp Web Business",desc:"WhatsApp Business conectado por Código QR, reflejando tu celular."},coex:{name:"Coexistencia",desc:"WhatsApp Business en el celular y aquí al mismo tiempo, vía la API oficial."},cloud:{name:"Cloud API",desc:"Número oficial por la API de Meta, directo en la nube."}},e2e:"Mensajes protegidos con cifrado de extremo a extremo",cloudNote:"Mensajes vía la API oficial de Meta"}},Hc={web:"#ci-iphone",web_business:"#ci-iphone",coex:"#ci-link",cloud:"#ci-cloud"},Jc={web:"var(--sky)",web_business:"var(--green)",coex:"var(--purple-light)",cloud:"var(--indigo-light)"};function Yc({locale:t="pt",session:n=null}){const{settings:o}=bs(),i=Gr[t]||Gr.pt,s=vi(n),f=i.types[s]||i.types.web,l=n!=null&&n.phone?bt(n.phone):null,c=[ji(n),l].filter(Boolean).join(" · ")||null;return e.jsx("section",{className:"chat-thread cv2-empty",children:e.jsxs("div",{className:"cv2-empty-inner",children:[e.jsx("h2",{className:"cv2-empty-ttl",children:i.ttl}),e.jsx("p",{className:"cv2-empty-sub",children:i.sub}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cv2-glass",children:[e.jsx("span",{className:"cv2-glass-ic",children:e.jsx("svg",{style:{color:Jc[s]},children:e.jsx("use",{href:Hc[s]})})}),e.jsxs("span",{className:"cv2-glass-tx",children:[e.jsxs("span",{className:"nm",children:[f.name,e.jsx("span",{className:"dot"})]}),c&&e.jsx("span",{className:`mt ${It("blurNames",o)}`,children:c})]})]}),e.jsx("p",{className:"cv2-empty-desc",children:f.desc})]}),e.jsxs("div",{className:"cv2-empty-foot",children:[e.jsx("svg",{children:e.jsx("use",{href:s==="cloud"?"#ci-cloud":"#ci-lock"})}),e.jsx("span",{children:s==="cloud"?i.cloudNote:i.e2e})]})]})})}function Qc({message:t,position:n,isCloud:o,isGroup:i,isChannel:s,amIAdmin:f,sendBlocked:l,aiEnabled:c=!1,onAction:d,onClose:v,locale:k="pt"}){const x=r.useRef(null),[P,A]=r.useState(n),[y,w]=r.useState(null),[m,I]=r.useState(!1),[U,u]=r.useState(!1),p=r.useRef(null),b=()=>{p.current&&(clearTimeout(p.current),p.current=null),u(!0)},se=()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(()=>u(!1),160)};r.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const C=(K,Re,_e)=>k==="es"?Re:k==="en"?_e:K;if(r.useLayoutEffect(()=>{const K=x.current;if(!K)return;const Re=()=>{const _e=window.innerWidth,Y=window.innerHeight,Oe=Y-16,Je=K.scrollHeight,Be=Math.min(Je,Oe),Qe=K.offsetWidth,Me=Math.min(Math.max(8,n.x),Math.max(8,_e-Qe-8)),De=Math.min(Math.max(8,n.y),Math.max(8,Y-Be-8));A(xt=>xt.x===Me&&xt.y===De?xt:{x:Me,y:De}),w(xt=>{const ut=Je>Oe?Oe:null;return xt===ut?xt:ut})};return Re(),window.addEventListener("resize",Re),()=>window.removeEventListener("resize",Re)},[n.x,n.y,m]),r.useEffect(()=>{const K=Y=>{x.current&&!x.current.contains(Y.target)&&(v==null||v())},Re=Y=>{Y.key==="Escape"&&(v==null||v())},_e=setTimeout(()=>{document.addEventListener("mousedown",K),document.addEventListener("keydown",Re)},0);return()=>{clearTimeout(_e),document.removeEventListener("mousedown",K),document.removeEventListener("keydown",Re)}},[v]),!t)return null;
2const H=!!t.fromMe,Q=Bo(t),O=Date.now()/1e3,oe=O-(t.timestamp||O),ke=H&&t.msgType==="text"&&oe<900&&!o,Ae=H&&oe<172800&&!o,ve=i&&!H&&!!f&&oe<172800&&!o,_=yi(t),$=t.msgType==="audio"||t.mediaType==="audio",X=$&&!t.textContent&&!t.transcription,ce=i&&!H,Z=!!(t.textContent||t.text),D=t.msgType||"text",ae=Z&&(D==="text"||D==="chat"||D==="image"||D==="video"||D==="document");return t.deleted?e.jsx("div",{ref:x,className:"ctx-menu ctx-menu-floating",style:{position:"fixed",top:P.y,left:P.x,zIndex:9e3},onClick:K=>K.stopPropagation(),children:t.restorable!==!1?e.jsxs("button",{className:"item",onClick:()=>{d==null||d("restore"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-history"})}),C("Restaurar mensagem","Restaurar mensaje","Restore message")]}):e.jsx("div",{className:"item",style:{opacity:.6,cursor:"default",fontStyle:"italic"},children:C("Não pode ser restaurada","No se puede restaurar","Cannot be restored")})}):e.jsxs("div",{ref:x,className:"ctx-menu ctx-menu-floating",style:{position:"fixed",top:P.y,left:P.x,zIndex:9e3,...y?{maxHeight:y,overflowY:"auto"}:null},onClick:K=>K.stopPropagation(),children:[e.jsx(Uo,{mine:Q,locale:k,onPick:K=>{d==null||d("react",K),v==null||v()},onPickerToggle:I}),!l&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("reply"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-reply"})}),C("Responder","Responder","Reply")]}),ce&&!l&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("reply-privately"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-user"})}),C("Responder no privado","Responder en privado","Reply privately")]}),e.jsxs("button",{className:"item",onClick:()=>{d==null||d("copy"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-copy"})}),C("Copiar","Copiar","Copy")]}),ae&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("translate"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-globe"})}),C("Traduzir","Traducir","Translate")]}),c&&Z&&D!=="audio"&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("ai-extract"),v==null||v()},children:[e.jsx("span",{style:{width:15,height:15,display:"inline-flex",alignItems:"center",justifyContent:"center",color:"var(--indigo-light)",fontSize:12},children:"✦"}),C("Extrair dados","Extraer datos","Extract data")]}),c&&(D==="image"||t.mediaType==="image")&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("ai-extract"),v==null||v()},children:[e.jsx("span",{style:{width:15,height:15,display:"inline-flex",alignItems:"center",justifyContent:"center",color:"var(--indigo-light)",fontSize:12},children:"✦"}),C("Ler imagem (dados)","Leer imagen (datos)","Read image (data)")]}),c&&$&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("ai-extract"),v==null||v()},children:[e.jsx("span",{style:{width:15,height:15,display:"inline-flex",alignItems:"center",justifyContent:"center",color:"var(--indigo-light)",fontSize:12},children:"✦"}),C("Resumir áudio","Resumir audio","Summarize audio")]}),X&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("transcribe"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-transcribe"})}),C("Transcrever áudio","Transcribir audio","Transcribe audio")]}),ke&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("edit"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-edit"})}),C("Editar","Editar","Edit")]}),_&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("forward"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-forward"})}),C("Encaminhar","Reenviar","Forward")]}),!o&&!s&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("star"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:t.isStarred?"#ci-star-fill":"#ci-star"})}),t.isStarred?C("Remover estrela","Quitar estrella","Unstar"):C("Marcar com estrela","Destacar","Star")]}),!o&&!s&&(t.isPinned?e.jsxs("button",{className:"item",onClick:()=>{d==null||d("unpin"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-pin-fill"})}),C("Desafixar","Desfijar","Unpin")]}):e.jsxs("div",{className:"pin-sub",style:{position:"relative"},onMouseEnter:b,onMouseLeave:se,children:[e.jsxs("button",{className:"item",onClick:()=>u(K=>!K),children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-pin"})}),C("Fixar","Fijar","Pin"),e.jsx("svg",{style:{marginLeft:"auto",width:13,height:13,opacity:.6},children:e.jsx("use",{href:"#ci-chev-r"})})]}),U&&e.jsx("div",{className:"ctx-submenu",style:{position:"absolute",top:0,...P.x>(typeof window<"u"?window.innerWidth:9999)/2?{right:"calc(100% - 4px)"}:{left:"calc(100% - 4px)"}},children:[{lbl:C("24 horas","24 horas","24 hours"),time:86400},{lbl:C("7 dias","7 días","7 days"),time:604800},{lbl:C("90 dias","90 días","90 days"),time:7776e3}].map(K=>e.jsx("button",{className:"item",onClick:()=>{d==null||d("pin",{time:K.time}),v==null||v()},children:K.lbl},K.time))})]})),_&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("select"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-check"})}),C("Selecionar","Seleccionar","Select")]}),H&&!o&&e.jsxs("button",{className:"item",onClick:()=>{d==null||d("message-info"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-info"})}),C("Dados da mensagem","Info del mensaje","Message info")]}),e.jsx("div",{className:"sep"}),e.jsxs("button",{className:"item danger",onClick:()=>{d==null||d("delete-me"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-trash"})}
2),C("Excluir para mim","Eliminar para mí","Delete for me")]}),(Ae||ve)&&e.jsxs("button",{className:"item danger",onClick:()=>{d==null||d("delete-all"),v==null||v()},children:[e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-trash"})}),ve?C("Apagar para todos (admin)","Eliminar para todos (admin)","Delete for everyone (admin)"):C("Excluir para todos","Eliminar para todos","Delete for everyone")]})]})}const Vr={pt:{title:"Atendimento humano",waiting:"Aguardando",mine:"Meus atendimentos",claim:"Assumir",open:"Abrir",close:"Encerrar",contact:"Contato",someone:"Um contato",wantsHuman:t=>`${t} quer atendimento humano`,claimed:"Você assumiu este atendimento",taken:"Outro atendente já assumiu",claimErr:"Erro ao assumir",closedCsat:"Encerrado — pesquisa de satisfação enviada",closed:"Atendimento encerrado",closeErr:"Erro ao encerrar",copied:"Fala copiada",copyTitle:"Copiar a primeira fala sugerida"},es:{title:"Atención humana",waiting:"En espera",mine:"Mis atenciones",claim:"Asumir",open:"Abrir",close:"Finalizar",contact:"Contacto",someone:"Un contacto",wantsHuman:t=>`${t} quiere atención humana`,claimed:"Asumiste esta atención",taken:"Otro agente ya la asumió",claimErr:"Error al asumir",closedCsat:"Finalizada — encuesta de satisfacción enviada",closed:"Atención finalizada",closeErr:"Error al finalizar",copied:"Mensaje copiado",copyTitle:"Copiar el primer mensaje sugerido"},en:{title:"Human handoff",waiting:"Waiting",mine:"My conversations",claim:"Take",open:"Open",close:"Close",contact:"Contact",someone:"A contact",wantsHuman:t=>`${t} wants a human agent`,claimed:"You took this conversation",taken:"Another agent already took it",claimErr:"Could not take it",closedCsat:"Closed — satisfaction survey sent",closed:"Conversation closed",closeErr:"Could not close",copied:"Message copied",copyTitle:"Copy the suggested first message"}},Kc=t=>{const n=Number(t)||0;return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}min`:`${Math.floor(n/3600)}h`},ma=t=>({display:"inline-flex",alignItems:"center",gap:5,height:30,padding:"0 12px",borderRadius:9,border:t==="ghost"?"1px solid var(--hairline-strong,rgba(255,255,255,.16))":0,background:t==="accent"?"var(--accent,#6366f1)":t==="ok"?"var(--ok,#22c55e)":"transparent",color:t==="ghost"?"var(--text,#fff)":"var(--on-accent,#fff)",fontSize:12.5,fontWeight:650,cursor:"pointer",whiteSpace:"nowrap",flexShrink:0});function Hr({children:t,first:n}){return e.jsx("div",{style:{fontSize:10.5,fontWeight:700,letterSpacing:".04em",textTransform:"uppercase",color:"var(--text-4,#6a6a74)",padding:n?"2px 4px 0":"6px 4px 0"},children:t})}function Jr({t,waitSec:n,action:o,tx:i}){let s=null;try{s=t.ai_brief?JSON.parse(t.ai_brief):null}catch{s=null}return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"9px 10px",borderRadius:12,background:"var(--surface-3,#26262e)",border:"1px solid var(--hairline,rgba(255,255,255,.06))"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:11},children:[e.jsx(Xc,{name:t.contact_name}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13.5,fontWeight:600,color:"var(--text,#fff)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t.contact_name||i.contact}),e.jsxs("div",{style:{fontSize:11.5,color:"var(--text-3,#8a8a94)",display:"flex",alignItems:"center",gap:8,marginTop:2},children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontVariantNumeric:"tabular-nums"},children:[e.jsx(No,{size:11})," ",Kc(n)]}),t.reason?e.jsxs("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:120},children:["· ",t.reason]}):null]})]}),o]}),s&&(s.summary||s.blocker)&&e.jsxs("div",{style:{borderRadius:9,padding:"7px 9px",fontSize:12,lineHeight:1.45,color:"var(--text-2,#c8c8d0)",background:"color-mix(in srgb, var(--accent,#6366f1) 8%, transparent)",border:"1px solid color-mix(in srgb, var(--accent,#6366f1) 24%, transparent)"},children:[e.jsx("span",{style:{color:"var(--accent,#8b8bf5)",fontWeight:700,marginRight:5},children:"✦"}),s.summary,s.blocker?e.jsxs("div",{style:{marginTop:4,color:"var(--warn,#f0b95a)"},children:["⚠ ",s.blocker]}
2):null,s.opening?e.jsxs("button",{onClick:()=>{try{navigator.clipboard.writeText(s.opening),W.success(i.copied)}catch{}},style:{display:"block",width:"100%",textAlign:"left",marginTop:6,padding:"6px 8px",borderRadius:8,background:"var(--surface-2,#1d1d24)",border:"1px solid var(--hairline,rgba(255,255,255,.08))",color:"var(--text,#fff)",fontSize:12,lineHeight:1.4,cursor:"pointer"},title:i.copyTitle,children:["“",s.opening,"” ",e.jsx("span",{style:{color:"var(--text-4,#6a6a74)"},children:"⧉"})]}):null]})]})}function Xc({name:t}){const n=(t||"?").trim().charAt(0).toUpperCase();return e.jsx("div",{style:{width:38,height:38,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:15,fontWeight:700,color:"var(--accent,#8b8bf5)",background:"color-mix(in srgb, var(--accent,#6366f1) 16%, transparent)"},children:n})}function Zc({socket:t,onOpen:n}){const{locale:o}=ds(),i=Vr[o]||Vr.pt,[s,f]=r.useState([]),[l,c]=r.useState([]),[d,v]=r.useState(!1),[k,x]=r.useState(null),P=r.useRef(Date.now()),[,A]=r.useState(0),y=r.useCallback(()=>{M.get("/wa/handoff/queue").then(({data:u})=>{P.current=Date.now(),f(u.queue||[]),c(u.mine||[])}).catch(()=>{})},[]);r.useEffect(()=>{y()},[y]),r.useEffect(()=>{if(!s.length&&!l.length)return;const u=setInterval(()=>A(p=>p+1),1e3);return()=>clearInterval(u)},[s.length,l.length]),r.useEffect(()=>{if(!t)return;const u=se=>{if(!(!se||!se.id)){f(C=>C.some(H=>H.id===se.id)?C:[{...se,wait_seconds:0},...C]),v(!0);try{W(i.wantsHuman(se.contact_name||i.someone))}catch{}}},p=se=>{se!=null&&se.id&&f(C=>C.filter(H=>H.id!==se.id))},b=se=>{se!=null&&se.id&&(f(C=>C.filter(H=>H.id!==se.id)),c(C=>C.filter(H=>H.id!==se.id)))};return t.on("handoff:new",u),t.on("handoff:claimed",p),t.on("handoff:resolved",b),t.on("connect",y),()=>{t.off("handoff:new",u),t.off("handoff:claimed",p),t.off("handoff:resolved",b),t.off("connect",y)}},[t,y,i]);const w=async u=>{var p,b,se;x(u.id);try{await M.post(`/wa/handoff/${u.id}/claim`),f(C=>C.filter(H=>H.id!==u.id)),c(C=>C.some(H=>H.id===u.id)?C:[{...u},...C]),W.success(i.claimed),n&&n(u.session_id,u.jid,u.contact_name)}catch(C){((p=C==null?void 0:C.response)==null?void 0:p.status)===409?(W(i.taken),f(H=>H.filter(Q=>Q.id!==u.id))):W.error(((se=(b=C==null?void 0:C.response)==null?void 0:b.data)==null?void 0:se.error)||i.claimErr)}finally{x(null)}},m=async u=>{var p,b;x(u.id);try{const{data:se}=await M.post(`/wa/handoff/${u.id}/resolve`,{resolution:"resolved"});c(C=>C.filter(H=>H.id!==u.id)),W.success(se!=null&&se.csatSent?i.closedCsat:i.closed)}catch(se){W.error(((b=(p=se==null?void 0:se.response)==null?void 0:p.data)==null?void 0:b.error)||i.closeErr)}finally{x(null)}};if(!s.length&&!l.length)return null;const I=u=>(u.wait_seconds||0)+Math.floor((Date.now()-P.current)/1e3),U=s.length+l.length;return e.jsxs("div",{style:{position:"fixed",right:22,bottom:22,zIndex:500,width:d?340:"auto",maxWidth:"calc(100vw - 44px)"},children:[d&&e.jsxs("div",{style:{background:"var(--surface-2,#1c1c22)",border:"1px solid var(--hairline-strong,rgba(255,255,255,.14))",borderRadius:16,boxShadow:"var(--shadow-pop,0 18px 48px -12px rgba(0,0,0,.6))",overflow:"hidden",marginBottom:10,animation:"cvhqRise .18s ease both"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9,padding:"13px 15px",borderBottom:"1px solid var(--hairline,rgba(255,255,255,.08))"},children:[e.jsx(nn,{size:16,style:{color:"var(--accent,#8b8bf5)"}}),e.jsx("span",{style:{fontSize:14,fontWeight:700,color:"var(--text,#fff)",flex:1},children:i.title}),e.jsx("span",{style:{fontSize:12,fontWeight:700,color:"var(--accent,#8b8bf5)",fontVariantNumeric:"tabular-nums"},children:U})]}),e.jsxs("div",{style:{maxHeight:380,overflowY:"auto",padding:8,display:"flex",flexDirection:"column",gap:7},children:[s.length>0&&e.jsx(Hr,{first:!0,children:i.waiting}),s.map(u=>e.jsx(Jr,{t:u,tx:i,waitSec:I(u),action:e.jsxs("button",{onClick:()=>w(u),disabled:k===u.id,style:{...ma("accent"),opacity:k===u.id?.6:1},children:[e.jsx(hi,{size:13})," ",k===u.id?"…":i.claim]})},u.id)),l.length>0&&e.jsx(Hr,{first:!s.length,children:i.mine}),l.map(u=>e.jsx(Jr,{t:u,tx:i,waitSec:I(u),action:e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>n&&n(u.session_id,u.jid,u.contact_name),style:ma("ghost"),children:i.open}),e.jsxs("button",{onClick:()=>m(u),disabled:k===u.id,style:{...ma("ok"),opacity:k===u.id?.6:1},children:[e.jsx(fi,{size:13})," ",k===u.id?"…":i.close]})]})},u.id))]})]}),e.jsxs("button",{onClick:()=>v(u=>!u),style:{display:"flex",alignItems:"center",gap:9,height:44,padding:"0 16px 0 14px",borderRadius:999,border:"1px solid var(--hairline-strong,rgba(255,255,255,.14))",background:"var(--surface-2,#1c1c22)",color:"var(--text,#fff)",cursor:"pointer",boxShadow:"var(--shadow-pop,0 12px 32px -10px rgba(0,0,0,.55))",marginLeft:"auto"},children:[e.jsxs("span",{style:{position:"relative",display:"inline-flex"},children:[e.jsx(nn,{size:17,style:{color:"var(--accent,#8b8bf5)"}}),s.length>0&&e.jsx("span",{style:{position:"absolute",top:-7,right:-9,minWidth:17,height:17,padding:"0 4px",borderRadius:999,background:"var(--rose,#f43f5e)",color:"#fff",fontSize:10.5,fontWeight:700,display:"flex",alignItems:"center",justifyContent:"center",border:"2px s
2olid var(--surface-2,#1c1c22)",fontVariantNumeric:"tabular-nums"},children:s.length})]}),e.jsx("span",{style:{fontSize:13.5,fontWeight:650},children:i.title}),e.jsx(wo,{size:15,style:{color:"var(--text-3,#8a8a94)",transform:d?"rotate(180deg)":"none",transition:"transform .15s"}})]}),e.jsx("style",{children:"@keyframes cvhqRise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}"})]})}const Yr={pt:{aiOff:"IA indisponível agora",noTpl:"Nenhum template aprovado nesta WABA",checking:"Verificando janela de atendimento…",cswOn:"Janela 24h ativa",cswOnSub:"você pode enviar qualquer tipo de mensagem",fepToo:"· FEP 72h também aberta (grátis)",expires:"expira em",reengageTip:"A IA escreve uma retomada que dá motivo pro contato responder — a resposta dele renova a janela. Vira rascunho, você revisa.",writing:"✦ Escrevendo…",reengage:"✦ Reengajar antes de fechar",fepOn:"Janela FEP ativa",fepOnSub:"apenas templates grátis até",pickTip:"A IA escolhe, entre os seus templates aprovados, o que melhor continua ESTA conversa",picking:"✦ Escolhendo…",suggest:"✦ Sugerir",suggestTpl:"✦ Sugerir template",addTpl:"+ Template",closed:"Janela fechada",closedSub:"só envio de template aprovado",sendTpl:"+ Enviar template"},es:{aiOff:"IA no disponible ahora",noTpl:"Ninguna plantilla aprobada en esta WABA",checking:"Verificando la ventana de atención…",cswOn:"Ventana de 24 h activa",cswOnSub:"puedes enviar cualquier tipo de mensaje",fepToo:"· FEP de 72 h también abierta (gratis)",expires:"vence en",reengageTip:"La IA escribe un mensaje de retomada que le da al contacto un motivo para responder — su respuesta renueva la ventana. Queda como borrador para que lo revises.",writing:"✦ Escribiendo…",reengage:"✦ Reactivar antes de que cierre",fepOn:"Ventana FEP activa",fepOnSub:"solo plantillas gratuitas hasta",pickTip:"La IA elige, entre tus plantillas aprobadas, la que mejor continúa ESTA conversación",picking:"✦ Eligiendo…",suggest:"✦ Sugerir",suggestTpl:"✦ Sugerir plantilla",addTpl:"+ Plantilla",closed:"Ventana cerrada",closedSub:"solo envío de plantilla aprobada",sendTpl:"+ Enviar plantilla"},en:{aiOff:"AI unavailable right now",noTpl:"No approved template in this WABA",checking:"Checking the service window…",cswOn:"24h window open",cswOnSub:"you can send any type of message",fepToo:"· 72h FEP also open (free)",expires:"expires in",reengageTip:"The AI writes a follow-up that gives the contact a reason to reply — their reply renews the window. It becomes a draft for you to review.",writing:"✦ Writing…",reengage:"✦ Re-engage before it closes",fepOn:"FEP window open",fepOnSub:"free templates only until",pickTip:"The AI picks, among your approved templates, the one that best continues THIS conversation",picking:"✦ Picking…",suggest:"✦ Suggest",suggestTpl:"✦ Suggest template",addTpl:"+ Template",closed:"Window closed",closedSub:"approved templates only",sendTpl:"+ Send template"}},Qr=t=>{const n=Math.max(0,Math.floor(t));if(n<=0)return"0min";const o=Math.floor(n/3600),i=Math.floor(n%3600/60);return o>0?`${o}h ${i}min`:`${i}min`};function el({sessionId:t,chat:n,session:o,aiEnabled:i=!1,onOpenTemplatePicker:s,onWindowState:f}){const{locale:l}=ds(),c=Yr[l]||Yr.pt,[d,v]=r.useState(null),[,k]=r.useState(0),[x,P]=r.useState(0),A=r.useRef(0),[y,w]=r.useState(null),m=async()=>{var H,Q;if(!y){w("reengage");try{const{data:O}=await M.post("/wa/chat-ai/reengage",{sessionId:t,jid:n.jid});window.dispatchEvent(new CustomEvent("pragmaz:cv2-paste",{detail:{jid:n.jid,text:O.text}}))}catch(O){W.error(((Q=(H=O==null?void 0:O.response)==null?void 0:H.data)==null?void 0:Q.error)||c.aiOff)}finally{w(null)}}},I=async()=>{var H,Q;if(!y){w("pick");try{const O=await Xo(t);if(!(O!=null&&O.length)){W.error(c.noTpl);return}const oe=_=>{var $;return(($=(_.components||[]).find(X=>String(X.type).toUpperCase()==="BODY"))==null?void 0:$.text)||""},ke=O.slice(0,20).map(_=>({name:_.name,category:_.category,body:oe(_)})),{data:Ae}=await M.post("/wa/chat-ai/pick-template",{sessionId:t,jid:n.jid,candidates:ke}),ve=Ae.name?O.find(_=>_.name===Ae.name):null;if(!ve){s==null||s();return}Ae.reason&&W.success(`✦ ${Ae.reason}`),s==null||s(ve)}catch(O){W.error(((Q=(H=O==null?void 0:O.response)==null?void 0:H.data)==null?void 0:Q.error)||
2c.aiOff)}finally{w(null)}}};r.useEffect(()=>{const H=Q=>{var ke;const O=Q.detail||{};if(O.sessionId&&O.sessionId!==t)return;const oe=(ke=n==null?void 0:n.jid)==null?void 0:ke.split("@")[0];O.contactWaId&&oe&&O.contactWaId!==oe||P(Ae=>Ae+1)};return window.addEventListener("pragmaz:cv2-window-refresh",H),()=>window.removeEventListener("pragmaz:cv2-window-refresh",H)},[t,n==null?void 0:n.jid]),r.useEffect(()=>{if(!t||!(n!=null&&n.jid)){v(null);return}if(!((o==null?void 0:o.provider_type)==="cloud_api"||(o==null?void 0:o.provider_type)==="coexistence")){v(null);return}const Q=n.jid.split("@")[0];let O=!1;const oe=async()=>{try{const{data:Ae}=await M.get(`/meta/sessions/${encodeURIComponent(t)}/window?contact=${encodeURIComponent(Q)}`);if(O)return;v(Ae||null),A.current=Date.now()}catch{O||v(null)}};oe();const ke=setInterval(oe,6e4);return()=>{O=!0,clearInterval(ke)}},[t,n==null?void 0:n.jid,o==null?void 0:o.provider_type,x]),r.useEffect(()=>{if(!d||!d.csw_open&&!d.fep_open)return;const H=setInterval(()=>k(Q=>Q+1),1e3);return()=>clearInterval(H)},[d==null?void 0:d.csw_open,d==null?void 0:d.fep_open]),r.useEffect(()=>{if(!d){f==null||f({cswOpen:!0,fepOpen:!1,canSendFreeform:!0,loaded:!1});return}const H=Math.max(0,Math.floor((Date.now()-A.current)/1e3)),Q=Math.max(0,(d.csw_remaining_sec||0)-H),O=Math.max(0,(d.fep_remaining_sec||0)-H),oe=!!d.csw_open&&Q>0,ke=!!d.fep_open&&O>0;f==null||f({cswOpen:oe,fepOpen:ke,canSendFreeform:oe,loaded:!0})},[d,f]);const U=(o==null?void 0:o.provider_type)==="cloud_api"||(o==null?void 0:o.provider_type)==="coexistence";if(!d)return U?e.jsxs("div",{className:"ct-window",style:{background:"rgba(255,255,255,0.02)",borderColor:"var(--hairline)"},children:[e.jsx("span",{className:"ic",style:{color:"var(--text-3)"},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsx("span",{className:"t",style:{color:"var(--text-3)"},children:c.checking})]}):null;const u=Math.max(0,Math.floor((Date.now()-A.current)/1e3)),p=Math.max(0,(d.csw_remaining_sec||0)-u),b=Math.max(0,(d.fep_remaining_sec||0)-u),se=!!d.csw_open&&p>0,C=!!d.fep_open&&b>0;return se?e.jsxs("div",{className:"ct-window",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-msg"})})}),e.jsxs("span",{className:"t",children:[e.jsx("strong",{children:c.cswOn})," · ",c.cswOnSub,C&&e.jsx("span",{style:{marginLeft:8,color:"var(--text-3)"},children:c.fepToo})]}),e.jsxs("span",{className:"time",children:[c.expires," ",Qr(p)]}),i&&p<3*3600&&e.jsx("button",{onClick:m,disabled:!!y,title:c.reengageTip,style:{background:"color-mix(in srgb, var(--indigo) 14%, transparent)",color:"var(--indigo-light)",border:"1px solid color-mix(in srgb, var(--indigo) 35%, transparent)",padding:"4px 10px",borderRadius:5,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",whiteSpace:"nowrap"},children:y==="reengage"?c.writing:c.reengage})]}):C?e.jsxs("div",{className:"ct-window warn",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})})}),e.jsxs("span",{className:"t",children:[e.jsx("strong",{children:c.fepOn})," · ",c.fepOnSub," ",Qr(b)]}),i&&e.jsx("button",{onClick:I,disabled:!!y,title:c.pickTip,style:{background:"color-mix(in srgb, var(--indigo) 14%, transparent)",color:"var(--indigo-light)",border:"1px solid color-mix(in srgb, var(--indigo) 35%, transparent)",padding:"4px 10px",borderRadius:5,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",marginRight:6},children:y==="pick"?c.picking:c.suggest}),e.jsx("button",{onClick:s,style:{background:"rgba(245,158,11,0.15)",color:"var(--amber)",border:"1px solid rgba(245,158,11,0.30)",padding:"4px 10px",borderRadius:5,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},children:c.addTpl})]}):e.jsxs("div",{className:"ct-window",style:{background:"rgba(255,255,255,0.02)",borderColor:"var(--hairline)"},children:[e.jsx("span",{className:"ic",style:{color:"var(--text-3)"},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-lock"})})}),e.jsxs("span",{className:"t",style:{color:"var(--text-3)"},children:[e.jsx("strong",{style:{color:"var(--text-2)"},children:c.closed})," · ",c.closedSub]}),i&&e.jsx("button",{onClick:I,disabled:!!y,title:c.pickTip,style:{background:"color-mix(in srgb, var(--indigo) 14%, transparent)",color:"var(--indigo-light)",border:"1px solid color-mix(in srgb, var(--indigo) 35%, transparent)",padding:"4px 10px",borderRadius:5,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit",marginRight:6},children:y==="pick"?c.picking:c.suggestTpl}),e.jsx("button",{onClick:s,style:{background:"var(--indigo)",color:"white",border:0,padding:"4px 10px",borderRadius:5,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:"inherit"},children:c.sendTpl})]})}const js=5,tl=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase();function sl({message:t,messages:n,currentChatJid:o,sessionId:i,providerType:s,locale:f="pt",onClose:l,onForwarded:c}){const d=(O,oe,ke)=>f==="es"?oe:f==="en"?ke:O,v=s==="cloud_api"||s==="coexistence",[k,x]=r.useState([]),[P,A]=r.useState(!0),[y,w]=r.useState(""),[m,I]=r.useState(()=>new Set),[U,u]=r.useState(!1),p=r.useMemo(()=>Array.isArray(n)&&n.length?n:t?[t]:[],[n,t]),b=r.useMemo(()=>
2p.filter(yi),[p]),se=p.length-b.length;r.useEffect(()=>{let O=!1;const oe=new URLSearchParams({sessionId:i,filter:"all",limit:"500"});return M.get(`/wa/chat/list?${oe}`).then(({data:ke})=>{if(O)return;let Ae=Array.isArray(ke==null?void 0:ke.chats)?ke.chats:[];Ae=Ae.filter(ve=>ve.jid!==o),v&&(Ae=Ae.filter(ve=>{const _=ve.jid||"";return _.endsWith("@g.us")||_.includes("@lid")?!1:/^\d{8,15}$/.test(_.replace(/@.*$/,"").replace(/\D+/g,""))})),x(Ae)}).catch(()=>{}).finally(()=>!O&&A(!1)),()=>{O=!0}},[i,o,v]),r.useEffect(()=>{const O=oe=>{oe.key==="Escape"&&(l==null||l())};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[l]);const C=r.useMemo(()=>{const O=y.trim().toLowerCase();return O?k.filter(oe=>(oe.name||"").toLowerCase().includes(O)||(oe.jid||"").includes(O)):k},[k,y]),H=O=>{I(oe=>{const ke=new Set(oe);return ke.has(O)?ke.delete(O):ke.size<js?ke.add(O):W(d(`Máximo ${js} chats`,`Máximo ${js} chats`,`Maximum ${js} chats`),{icon:"⚠️"}),ke})},Q=async()=>{if(!(U||m.size===0||b.length===0)){u(!0);try{const{data:O}=v?await M.post(`/meta/sessions/${encodeURIComponent(i)}/forward`,{msgIds:b.map(oe=>oe.msgId),targets:[...m]}):await M.post("/wa/chat/forward",{sessionId:i,originJid:o,msgIds:b.map(oe=>oe.msgId),targetJids:[...m]});c==null||c({forwarded:(O==null?void 0:O.forwarded)||0,expected:(O==null?void 0:O.expected)||b.length*m.size,msgsCount:b.length,targetCount:m.size,results:O==null?void 0:O.results}),l==null||l()}catch{W.error(d("Falha ao encaminhar","Error al reenviar","Forward failed"))}finally{u(!1)}}};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:l,children:e.jsxs("div",{className:"cv2-modal",onClick:O=>O.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"ttl",children:[d("Encaminhar","Reenviar","Forward")," ",b.length===1?d("mensagem","mensaje","message"):`${b.length} ${d("mensagens","mensajes","messages")}`]}),e.jsxs("div",{className:"sub",children:[d(`Selecione até ${js} conversas`,`Seleccione hasta ${js} chats`,`Select up to ${js} chats`),se>0&&e.jsxs("span",{style:{color:"var(--text-4)",marginLeft:6},children:["· ",se," ",d(se>1?"não encaminháveis":"não encaminhável",se>1?"no reenviables":"no reenviable",(se>1,"not forwardable"))]}),v&&e.jsxs("span",{style:{color:"var(--text-4)",marginLeft:6},children:["· ",d("Cloud: só 1:1","Cloud: solo 1:1","Cloud: 1:1 only")]})]})]}),e.jsx(ne,{content:d("Fechar","Cerrar","Close"),position:"left",children:e.jsx("button",{className:"x",onClick:l,"aria-label":d("Fechar","Cerrar","Close"),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{className:"cv2-modal-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",placeholder:d("Buscar conversas","Buscar chats","Search chats"),value:y,onChange:O=>w(O.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"cv2-modal-list",children:[P&&e.jsx("div",{className:"empty",children:d("Carregando…","Cargando…","Loading…")}),!P&&C.length===0&&e.jsx("div",{className:"empty",children:d("Nenhuma conversa","Ningún chat","No chats")}),C.map(O=>{const oe=m.has(O.jid);return e.jsxs("button",{className:`cv2-target-row ${oe?"selected":""}`,onClick:()=>H(O.jid),children:[e.jsx("span",{className:`sel-check ${oe?"on":""}`,children:oe&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),e.jsxs("div",{className:"av",children:[O.imgUrl?e.jsx("img",{src:O.imgUrl,alt:""}):tl(O.isGroup?O.name:lt(O.name,{phone:O.phone,jid:O.jid})),O.isGroup&&e.jsx("span",{className:"g",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-users"})})})]}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:O.isGroup?O.name||"Grupo":lt(O.name,{phone:O.phone,jid:O.jid})}),e.jsx("div",{className:"ph",children:O.isGroup?d("Grupo","Grupo","Group"):bt(O.jid)})]})]},O.jid)})]}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsx("span",{className:"count",children:m.size>0?d(`${m.size} selecionado${m.size>1?"s":""}`,`${m.size} seleccionado${m.size>1?"s":""}`,`${m.size} selected`):d("Nenhum selecionado","Ninguno seleccionado","None selected")}),e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:l,children:d("Cancelar","Cancelar","Cancel")}),e.jsx("button",{className:"confirm",onClick:Q,disabled:U||m.size===0,children:U?d("Enviando…","Enviando…","Sending…"):d("Encaminhar","Reenviar","Forward")})]})]})})}const Kr=15;function nl({message:t,sessionId:n,jid:o,locale:i="pt",onClose:s}){const f=(t==null?void 0:t.textContent)||(t==null?void 0:t.text)||"",[l,c]=r.useState(f),[d,v]=r.useState(!1),k=r.useRef(null),x=r.useMemo(()=>
2{const w=Number((t==null?void 0:t.timestamp)||0);return(Math.floor(Date.now()/1e3)-w)/60>Kr},[t==null?void 0:t.timestamp]),P=r.useMemo(()=>{const w=Number((t==null?void 0:t.timestamp)||0),m=(Math.floor(Date.now()/1e3)-w)/60;return Math.max(0,Math.ceil(Kr-m))},[t==null?void 0:t.timestamp]);r.useEffect(()=>{if(k.current){k.current.focus();const w=k.current.value.length;k.current.setSelectionRange(w,w)}},[]);const A=r.useRef(null);r.useEffect(()=>{const w=m=>{var I;m.key==="Escape"&&(s==null||s()),m.key==="Enter"&&(m.metaKey||m.ctrlKey)&&((I=A.current)==null||I.call(A))};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[s]);const y=async()=>{if(d||x)return;const w=l.trim();if(!w){W.error(i==="en"?"Text cannot be empty":i==="es"?"El texto no puede estar vacío":"Texto não pode ser vazio");return}if(w===f){s==null||s();return}v(!0);try{await M.post("/wa/chat/send",{sessionId:n,jid:o,type:"edit",content:{text:w,key:{remoteJid:o,fromMe:!0,id:t.msgId}}}),W.success(i==="en"?"Edited":i==="es"?"Editado":"Editada"),s==null||s()}catch{W.error(i==="en"?"Edit failed":i==="es"?"Error al editar":"Falha ao editar")}finally{v(!1)}};return A.current=y,e.jsx("div",{className:"cv2-modal-backdrop",onClick:s,children:e.jsxs("div",{className:"cv2-modal",onClick:w=>w.stopPropagation(),style:{maxWidth:480},children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"ttl",style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("svg",{style:{width:16,height:16,color:"var(--indigo-light)"},children:e.jsx("use",{href:"#ci-edit"})}),i==="en"?"Edit message":i==="es"?"Editar mensaje":"Editar mensagem"]}),e.jsx("div",{className:"sub",children:x?e.jsx("span",{style:{color:"var(--rose)"},children:i==="en"?"15-min edit window expired":i==="es"?"Ventana de 15 min expirada":"Janela de 15min expirada"}):i==="en"?`${P}min left to edit`:i==="es"?`Quedan ${P}min para editar`:`Restam ${P}min pra editar`})]}),e.jsx(ne,{content:i==="en"?"Close":i==="es"?"Cerrar":"Fechar",position:"bottom",children:e.jsx("button",{className:"x",onClick:s,"aria-label":i==="en"?"Close":i==="es"?"Cerrar":"Fechar",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{style:{padding:"12px 18px"},children:[e.jsx("div",{style:{fontSize:11.5,color:"var(--text-4)",textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:600,marginBottom:6},children:"Original"}),e.jsx("div",{style:{background:"var(--surface-2)",border:"1px solid var(--hairline)",borderRadius:6,padding:"8px 10px",fontSize:13,color:"var(--text-3)",whiteSpace:"pre-wrap",maxHeight:80,overflowY:"auto",marginBottom:12},children:f}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-4)",textTransform:"uppercase",letterSpacing:"0.08em",fontWeight:600,marginBottom:6},children:i==="en"?"New version":i==="es"?"Nueva versión":"Nova versão"}),e.jsx("textarea",{ref:k,value:l,onChange:w=>c(w.target.value),disabled:x,placeholder:i==="en"?"Edit the text":i==="es"?"Edita el texto":"Edite o texto",style:{width:"100%",minHeight:80,padding:"9px 12px",background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:8,color:"var(--text)",fontFamily:"inherit",fontSize:14,lineHeight:1.45,resize:"vertical",outline:"none"}}),e.jsx("div",{style:{fontSize:11.5,color:"var(--text-4)",marginTop:6},children:i==="en"?"Cmd/Ctrl+Enter to save · Esc to cancel":i==="es"?"Cmd/Ctrl+Enter para guardar · Esc para cancelar":"Cmd/Ctrl+Enter pra salvar · Esc pra cancelar"})]}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:s,children:i==="en"?"Cancel":"Cancelar"}),e.jsx("button",{className:"confirm",onClick:y,disabled:d||x||!l.trim(),children:d?i==="en"?"Saving…":i==="es"?"Guardando…":"Salvando…":i==="en"?"Save":i==="es"?"Guardar":"Salvar"})]})]})})}const al=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase(),Xr={pt:{you:"Você",all:"Todos",loading:"Carregando…",empty:"Nenhuma reação",remove:"· remover"},en:{you:"You",all:"All",loading:"Loading…",empty:"No reactions",remove:"· remove"},es:{you:"Tú",all:"Todos",loading:"Cargando…",empty:"Sin reacciones",remove:"· quitar"}};function rl({message:t,sessionId:n,locale:o="pt",onClose:i,onRemove:s}){const f=Xr[o]||Xr.pt,[l,c]=r.useState([]),[d,v]=r.useState(!0),[k,x]=r.useState("all");r.useEffect(()=>{if(!n||!(t!=null&&t.msgId)){v(!1);return}let y=!1;return v(!0),M.get(`/wa/chat/reactions?sessionId=${encodeURIComponent(n)}&msgId=${encodeURIComponent(t.msgId)}`).then(({data:w})=>{if(y)return;let m=Array.isArray(w==null?void 0:w.reactions)?w.reactions:[];m.length===0&&t.reaction&&(m=[{jid:t.reactionFromMe?"me":t.jid||"",emoji:t.reaction,name:t.reactionFromMe?f.you:t.pushName||t.contactName||"",timestamp:t.timestamp}]),c(m)}).catch(()=>{!y&&t.reaction&&c([{jid:t.reactionFromMe?"me":t.jid||"",emoji:t.reaction,name:t.reactionFromMe?f.you:t.pushName||t.contactName||"",timestamp:t.timestamp}])}).finally(()=>!y&&v(!1)),()=>{y=!0}},[n,t==null?void 0:t.msgId]),r.useEffect(()=>{const y=w=>{w.key==="Escape"&&(i==null||i())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]);const P=r.useMemo(()=>{const y=new Map;for(const w of l)y.set(w.emoji,(y.get(w.emoji)||0)+1);
2return[...y.entries()].map(([w,m])=>({em:w,n:m}))},[l]),A=k==="all"?l:l.filter(y=>y.emoji===k);return e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"rx-popover",onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:"rx-tabs",children:[e.jsxs("button",{className:`rx-tab ${k==="all"?"active":""}`,onClick:()=>x("all"),children:[e.jsx("span",{children:f.all}),e.jsx("span",{className:"n",children:l.length})]}),P.map(y=>e.jsxs("button",{className:`rx-tab ${k===y.em?"active":""}`,onClick:()=>x(y.em),children:[e.jsx("span",{className:"em",children:y.em}),e.jsx("span",{className:"n",children:y.n})]},y.em))]}),e.jsxs("div",{className:"rx-list",children:[d&&e.jsx("div",{style:{padding:14,textAlign:"center",color:"var(--text-4)",fontSize:13},children:f.loading}),!d&&A.length===0&&e.jsx("div",{style:{padding:14,textAlign:"center",color:"var(--text-4)",fontSize:13},children:f.empty}),A.map((y,w)=>{const m=y.jid==="me"||y.isMe||y.fromMe;return e.jsx(ne,{content:m?o==="en"?"Tap to remove your reaction":o==="es"?"Toca para quitar tu reacción":"Toque pra remover sua reação":"",position:"right",children:e.jsxs("div",{className:"who",onClick:()=>m&&(s==null?void 0:s(t)),style:{cursor:m?"pointer":"default"},children:[e.jsx("div",{className:"av",children:y.imgUrl?e.jsx("img",{src:y.imgUrl,alt:"",style:{width:"100%",height:"100%",borderRadius:"50%",objectFit:"cover"}}):al(lt(y.name,{jid:y.jid}))}),e.jsxs("div",{className:"nm",children:[lt(y.name,{jid:y.jid}),m&&e.jsx("span",{style:{marginLeft:6,fontSize:11.5,color:"var(--indigo-light)",fontWeight:500},children:f.remove})]}),e.jsx("span",{className:"em",children:y.emoji})]})},(y.jid||"")+y.emoji+w)})]})]})})}function il({sessionId:t,jid:n,messages:o,locale:i="pt",onJumpToMessage:s,onClose:f}){const[l,c]=r.useState(""),[d,v]=r.useState([]),[k,x]=r.useState(0),[P,A]=r.useState(!1),y=r.useRef(null),w=r.useRef(null);r.useEffect(()=>{var I;return(I=y.current)==null||I.focus(),()=>clearTimeout(w.current)},[]),r.useEffect(()=>{if(clearTimeout(w.current),!l.trim()){v([]),x(0);return}w.current=setTimeout(async()=>{A(!0);try{const I=new URLSearchParams({sessionId:t,jid:n,query:l,limit:"50"}),{data:U}=await M.get(`/wa/chat/search?${I}`),u=Array.isArray(U==null?void 0:U.results)?U.results:[];v(u),x(0)}catch{const I=l.toLowerCase(),U=(o||[]).filter(u=>(u.textContent||u.text||"").toLowerCase().includes(I));v(U),x(0)}finally{A(!1)}},400)},[l,t,n,o]),r.useEffect(()=>{if(!d.length)return;const I=d[k];I&&(s==null||s(I.msg_id||I.msgId,I.timestamp))},[k,d,s]);const m=I=>{if(I.key==="Escape"){I.preventDefault(),f==null||f();return}d.length&&(I.key==="ArrowDown"||I.key==="Enter"?(I.preventDefault(),x(U=>(U+1)%d.length)):I.key==="ArrowUp"&&(I.preventDefault(),x(U=>(U-1+d.length)%d.length)))};return e.jsxs("div",{className:"ct-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{ref:y,type:"text",value:l,onChange:I=>c(I.target.value),onKeyDown:m,placeholder:i==="en"?"Search in conversation":i==="es"?"Buscar en esta conversación":"Buscar nesta conversa"}),e.jsx("span",{className:"count",children:P?"…":d.length>0?`${k+1} / ${d.length}`:l.trim()?"0":""}),e.jsxs("div",{className:"nav",children:[e.jsx(ne,{content:i==="en"?"Previous":"Anterior",position:"bottom",children:e.jsx("button",{onClick:()=>x(I=>(I-1+d.length)%Math.max(1,d.length)),disabled:!d.length,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-u"})})})}),e.jsx(ne,{content:i==="en"?"Next":i==="es"?"Siguiente":"Próximo",position:"bottom",children:e.jsx("button",{onClick:()=>x(I=>(I+1)%Math.max(1,d.length)),disabled:!d.length,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-d"})})})})]}),e.jsx(ne,{content:i==="en"?"Close (Esc)":i==="es"?"Cerrar (Esc)":"Fechar (Esc)",position:"bottom",children:e.jsx("button",{onClick:f,style:{padding:5,color:"var(--text-3)",background:"transparent",border:0,cursor:"pointer",borderRadius:5,display:"inline-flex"},children:e.jsx("svg",{style:{width:14,height:14},children:e.jsx("use",{href:"#ci-x"})})})})]})}const Zr={pt:{media:"[mídia]",one:"mensagem fixada",many:"mensagens fixadas",click:t=>`Clique pra ${t?"esconder":"ver"}`,hide:"Esconder",expand:"Expandir",you:"Você",unpin:"Desafixar"},es:{media:"[multimedia]",one:"mensaje fijado",many:"mensajes fijados",click:t=>`Haz clic para ${t?"ocultar":"ver"}`,hide:"Ocultar",expand:"Expandir",you:"Tú",unpin:"Desfijar"},en:{media:"[media]",one:"pinned message",many:"pinned messages",click:t=>`Click to ${t?"hide":"view"}`,hide:"Hide",expand:"Expand",you:"You",unpin:"Unpin"}};function ol({pins:t,onUnpin:n,onJumpToMsg:o}){const{locale:i}=ds(),s=Zr[i]||Zr.pt,[f,l]=r.useState(!1);if(!t||t.length===0)return null;const c=t.map(d=>(d.text||s.media).slice(0,40)).join(" · ");return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"pin-banner",onClick:()=>l(d=>!d),children:[e.jsx("div",{className:"accent"}),e.jsxs("div",{className:"body",children:[e.jsxs("div",{className:"head",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-pin-fill"})}),e.jsxs("span",{className:"lbl",children:[t.length," ",t.length===1?s.one:s.many
2]}),e.jsx("span",{className:"count",children:s.click(f)})]}),e.jsx("div",{className:"preview",children:c})]}),e.jsx(ne,{content:f?s.hide:s.expand,position:"bottom",children:e.jsx("button",{className:"x",onClick:d=>{d.stopPropagation(),l(v=>!v)},children:e.jsx("svg",{children:e.jsx("use",{href:f?"#ci-chev-u":"#ci-chev-d"})})})})]}),f&&e.jsx("div",{className:"pins-list",children:t.map((d,v)=>e.jsxs("div",{className:"pin-item",onClick:()=>o==null?void 0:o(d.msgId),children:[e.jsx("span",{className:"num",children:v+1}),e.jsxs("div",{className:"txt",children:[e.jsxs("div",{className:"from",children:[d.from||(d.fromMe?s.you:"")," · ",d.date||""]}),e.jsx("div",{className:"msg",children:d.text||s.media})]}),e.jsx(ne,{content:s.unpin,position:"left",children:e.jsx("button",{className:"unpin",onClick:k=>{k.stopPropagation(),n==null||n(d.msgId)},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]},d.msgId))})]})}const ei={pt:{soon:"em instantes",inMin:t=>`em ${t} min`,inH:t=>`em ${t} h`,inD:t=>`em ${t} ${t===1?"dia":"dias"}`,reply:"Follow-up encerrado — o contato respondeu",optout:"Follow-up encerrado — contato descadastrou",manual:"Follow-up interrompido",paused:"Follow-up pausado",active:"Em follow-up",step:"etapa",resume:"Retome pelo card no funil para continuar a sequência",next:t=>`Próximo toque ${t}`,running:"Sequência ativa",autoStop:" · para automaticamente se o contato responder",failed:"Follow-up falhou",completed:"Follow-up concluído",ended:"Follow-up encerrado"},es:{soon:"en instantes",inMin:t=>`en ${t} min`,inH:t=>`en ${t} h`,inD:t=>`en ${t} ${t===1?"día":"días"}`,reply:"Seguimiento finalizado — el contacto respondió",optout:"Seguimiento finalizado — el contacto se dio de baja",manual:"Seguimiento interrumpido",paused:"Seguimiento en pausa",active:"En seguimiento",step:"etapa",resume:"Retómalo desde la tarjeta en el embudo para continuar la secuencia",next:t=>`Próximo toque ${t}`,running:"Secuencia activa",autoStop:" · se detiene automáticamente si el contacto responde",failed:"El seguimiento falló",completed:"Seguimiento completado",ended:"Seguimiento finalizado"},en:{soon:"in a moment",inMin:t=>`in ${t} min`,inH:t=>`in ${t} h`,inD:t=>`in ${t} ${t===1?"day":"days"}`,reply:"Follow-up ended — the contact replied",optout:"Follow-up ended — the contact opted out",manual:"Follow-up stopped",paused:"Follow-up paused",active:"In follow-up",step:"step",resume:"Resume it from the card in the pipeline to continue the sequence",next:t=>`Next touch ${t}`,running:"Sequence active",autoStop:" · stops automatically if the contact replies",failed:"Follow-up failed",completed:"Follow-up completed",ended:"Follow-up ended"}};function cl(t,n){if(!t)return null;const o=new Date(t).getTime()-Date.now();if(!Number.isFinite(o))return null;if(o<=6e4)return n.soon;const i=Math.round(o/6e4);if(i<60)return n.inMin(i);const s=Math.round(i/60);if(s<24)return n.inH(s);const f=Math.round(s/24);return n.inD(f)}const ha={reply:{icon:"#ci-check",k:"reply",tone:"ok"},optout:{icon:"#ci-x",k:"optout",tone:"off"},manual:{icon:"#ci-pause",k:"manual",tone:"off"}};function ll({followup:t}){const{locale:n}=ds(),o=ei[n]||ei.pt;if(!t)return null;if(t.status==="active"||t.status==="paused"){const s=t.status==="paused",f=cl(t.next_run_at,o);return e.jsxs("div",{className:`fu-banner${s?" paused":""}`,children:[e.jsx("div",{className:"accent"}),e.jsxs("div",{className:"body",children:[e.jsxs("span",{className:"pill",children:[e.jsx("svg",{children:e.jsx("use",{href:s?"#ci-pause":"#ci-send"})}),s?o.paused:o.active," · ",o.step," ",t.step,"/",t.total]}),e.jsxs("span",{className:"sub",children:[s?o.resume:f?o.next(f):o.running,!s&&t.stop_on_reply?o.autoStop:""]})]})]})}const i=t.status==="failed"?{icon:"#ci-x",txt:o.failed+(t.reason?` — ${t.reason}`:""),tone:"off"}:t.status==="completed"?{icon:"#ci-check",txt:o.completed,tone:"ok"}:ha[t.stopped_reason]?{...ha[t.stopped_reason],txt:o[ha[t.stopped_reason].k]}:{icon:"#ci-check",txt:o.ended,tone:"ok"};return e.jsxs("div",{className:`fu-banner term ${i.tone}`,children:[e.jsx("div",{className:"accent"}),e.jsx("div",{className:"body",children:e.jsxs("span",{className:"pill",children:[e.jsx("svg",{children:e.jsx("use",{href:i.icon})}),i.txt]})})]})}const dl=(t,n)=>
2t?new Date(t*1e3).toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";function ul({sessionId:t,msg:n,locale:o="pt",onClose:i}){const[s,f]=r.useState(null),[l,c]=r.useState(!0),d=(A,y,w)=>o==="en"?y:o==="es"?w:A;if(r.useEffect(()=>{if(!n)return;c(!0);const A=new URLSearchParams({sessionId:t,msgId:n.msgId,jid:n.jid});M.get(`/wa/chat/message-info?${A}`).then(({data:y})=>f(y)).catch(()=>f({recipients:[],isGroup:!1,status:null})).finally(()=>c(!1))},[t,n]),!n)return null;const v=((s==null?void 0:s.recipients)||[]).filter(A=>A.event==="read"||A.event==="played"),k=((s==null?void 0:s.recipients)||[]).filter(A=>A.event==="delivered"),x=({r:A})=>{var y;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 0"},children:[e.jsx("div",{style:{width:30,height:30,borderRadius:"50%",background:"var(--surface-3)",overflow:"hidden",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",fontSize:13,color:"var(--text-3)"},children:A.imgUrl?e.jsx("img",{src:A.imgUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):(y=(lt(A.name,{jid:A.jid})||"?")[0])==null?void 0:y.toUpperCase()}),e.jsx("span",{style:{flex:1,fontSize:14,color:"var(--text)"},children:lt(A.name,{jid:A.jid})}),e.jsx("span",{style:{fontSize:12,color:"var(--text-4)"},children:dl(A.ts,o)})]})},P=({icon:A,color:y,label:w,list:m})=>e.jsxs("div",{style:{marginTop:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12,textTransform:"uppercase",letterSpacing:".04em",color:"var(--text-4)",marginBottom:4},children:[e.jsx("svg",{style:{width:15,height:15,color:y},children:e.jsx("use",{href:A})}),w," ",m.length>0?`· ${m.length}`:""]}),m.length===0?e.jsx("div",{style:{fontSize:13,color:"var(--text-4)",padding:"4px 0"},children:"—"}):m.map((I,U)=>e.jsx(x,{r:I},I.jid||U))]});return e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal",style:{maxWidth:380,width:"90%"},onClick:A=>A.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsx("strong",{style:{fontSize:14},children:d("Dados da mensagem","Message info","Info del mensaje")}),e.jsx(ne,{content:d("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{onClick:i,style:{background:"transparent",border:0,color:"var(--text-3)",cursor:"pointer",display:"inline-flex"},children:e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:[n.textContent&&e.jsx("div",{style:{fontSize:13,color:"var(--text-3)",padding:"8px 10px",background:"var(--surface-3)",borderRadius:8,maxHeight:80,overflow:"hidden"},children:n.textContent.slice(0,160)}),l?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4)",padding:20,fontSize:13},children:"…"}):s!=null&&s.isGroup?e.jsxs(e.Fragment,{children:[e.jsx(P,{icon:"#ci-check2",color:"var(--indigo-light)",label:d("Lida por","Read by","Leída por"),list:v}),e.jsx(P,{icon:"#ci-check2",color:"var(--text-3)",label:d("Entregue a","Delivered to","Entregada a"),list:k})]}):e.jsx("div",{style:{marginTop:14,fontSize:14},children:Number(s==null?void 0:s.status)>=4?e.jsxs("div",{style:{color:"var(--indigo-light)",display:"flex",alignItems:"center",gap:6},children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-check2"})}),d("Lida","Read","Leída")]}):Number(s==null?void 0:s.status)>=3?e.jsxs("div",{style:{color:"var(--text-2)",display:"flex",alignItems:"center",gap:6},children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-check2"})}),d("Entregue","Delivered","Entregada")]}):e.jsxs("div",{style:{color:"var(--text-3)",display:"flex",alignItems:"center",gap:6},children:[e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-check"})}),d("Enviada","Sent","Enviada")]})})]})]})})}const pl=(t,n)=>t?new Date(t*1e3).toLocaleDateString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}):"";function ml({sessionId:t,jid:n,locale:o="pt",onClose:i,onJump:s,onUnstar:f}){const[l,c]=r.useState(null),d=(k,x,P)=>o==="en"?x:o==="es"?P:k,v=()=>{const k=new URLSearchParams({sessionId:t,jid:n,limit:"100"});M.get(`/wa/chat/starred?${k}`).then(({data:x})=>c(Array.isArray(x==null?void 0:x.starred)?x.starred:[])).catch(()=>c([]))};return r.useEffect(v,[t,n]),e.jsx("div",{className:"cv2-modal-backdrop",onClick:i,children:e.jsxs("div",{className:"cv2-modal",style:{maxWidth:420,width:"92%",maxHeight:"80vh",display:"flex",flexDirection:"column"},onClick:k=>k.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[e.jsxs("strong",{style:{fontSize:14,display:"inline-flex",alignItems:"center",gap:6},children:[e.jsx("svg",{style:{width:17,height:17,color:"var(--amber, #f5b945)"},children:e.jsx("use",{href:"#ci-star-fill"})}),d("Mensagens favoritas","Starred messages","Mensajes destacados")]}),e.jsx(ne,{content:d("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{onClick:i,style:{background:"transparent",border:0,color:"var(--text-3)",cursor:"pointer",display:"inline-flex"},children:e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{overflowY:"auto",flex:1,minHeight:0},children:l==null?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4)",padding:20,fontSize:13},children:"…"}):l.length===0?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4)",padding:24,fontSize:13}
2,children:d("Nenhuma mensagem favoritada","No starred messages","Sin mensajes destacados")}):l.map(k=>e.jsxs("div",{className:"starred-item",style:{display:"flex",alignItems:"flex-start",gap:8,padding:"8px 6px",borderBottom:"1px solid var(--hairline)",cursor:"pointer"},onClick:()=>{s==null||s(k.msgId,k.timestamp),i==null||i()},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{fontSize:12,color:"var(--text-4)",marginBottom:2},children:[k.from||""," · ",pl(k.timestamp,o)]}),e.jsx("div",{style:{fontSize:14,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.text||`[${k.msgType||"mídia"}]`})]}),e.jsx(ne,{content:d("Remover estrela","Unstar","Quitar"),position:"left",children:e.jsx("button",{onClick:x=>{x.stopPropagation(),f==null||f(k),c(P=>P.filter(A=>A.msgId!==k.msgId))},style:{background:"transparent",border:0,color:"var(--amber, #f5b945)",cursor:"pointer",flexShrink:0,display:"inline-flex",padding:2},children:e.jsx("svg",{style:{width:16,height:16},children:e.jsx("use",{href:"#ci-star-fill"})})})})]},k.msgId))})]})})}const hl=[{key:"cold",pt:"Frio",en:"Cold",es:"Frío",color:"#38bdf8"},{key:"warm",pt:"Morno",en:"Warm",es:"Tibio",color:"#f59e0b"},{key:"hot",pt:"Quente",en:"Hot",es:"Caliente",color:"#ef4444"}],ti=t=>{const n=new Date(t);return isNaN(n.getTime())?null:n.toISOString()},sn=(t,n)=>{if(!t)return"";const o=new Date(t);return isNaN(o.getTime())?"":o.toLocaleString(n==="en"?"en-US":n==="es"?"es-ES":"pt-BR",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})},Sn=()=>{const t=new Date(Date.now()+36e5),n=o=>String(o).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`},Cn={company:{pt:"Empresa",en:"Company",es:"Empresa"},deal_value:{pt:"Valor",en:"Deal value",es:"Valor"},temperature:{pt:"Temperatura",en:"Temperature",es:"Temperatura"},fullName:{pt:"Nome",en:"Name",es:"Nombre"},email:{pt:"E-mail",en:"Email",es:"Correo"},source:{pt:"Origem",en:"Source",es:"Origen"}},En={sent:{pt:"enviado",en:"sent",es:"enviado"},failed:{pt:"falhou",en:"failed",es:"falló"},pending:{pt:"pendente",en:"pending",es:"pendiente"},skipped:{pt:"pulado",en:"skipped",es:"omitido"}};function fl(t,n,o){const i=f=>sn(f,o),s=t.kind;if(s==="card_created")return{icon:"🎯",desc:n("Contato adicionado ao CRM","Contact added to CRM","Contacto añadido al CRM")};if(s==="note")return{icon:"📝",desc:t.text};if(s==="note_deleted")return{icon:"🗑",desc:n("Nota apagada","Note deleted","Nota eliminada")+(t.text?`: ${t.text}`:""),actor:t.actor};if(s==="move")return{icon:t.conversion?"🏆":"↪",desc:`${t.from||"—"} → ${t.to||"—"}`+(t.conversion?` · ${n("conversão","conversion","conversión")}`:"")};if(s==="profile_updated"){const f=(t.changed||[]).map(l=>Cn[l]?n(Cn[l].pt,Cn[l].en,Cn[l].es):l).join(", ");return{icon:"✏️",desc:n("Cadastro atualizado","Profile updated","Ficha actualizada")+(f?` (${f})`:""),actor:t.actor}}if(s==="schedule"){const f=t.template_name?`📄 ${t.template_name}`:t.text?`"${String(t.text).slice(0,40)}"`:n("mensagem","message","mensaje");return t.sub==="sent"?{icon:"✅",desc:`${n("Envio realizado","Sent","Enviado")} ${f}`}:t.sub==="failed"?{icon:"⚠️",desc:n("Falha no envio agendado","Scheduled send failed","Falló el envío programado")}:{icon:"📤",desc:`${n("Envio agendado","Send scheduled","Envío programado")} ${f}`+(t.scheduled_at?` · ${i(t.scheduled_at)}`:"")+(t.status==="cancelled"?` · ${n("cancelado","cancelled","cancelado")}`:"")}}if(s==="reminder")return t.sub==="notified"?{icon:"🔔",desc:`${n("Lembrete disparado","Reminder fired","Recordatorio disparado")}: ${t.title||""}`}:{icon:"⏰",desc:`${n("Lembrete criado","Reminder created","Recordatorio creado")}: ${t.title||""}`+(t.remind_at?` · ${i(t.remind_at)}`:"")+(t.status==="cancelled"?` · ${n("cancelado","cancelled","cancelado")}`:"")};if(s==="followup"){const f=t.template_name?` (${t.template_name})`:"";if(t.sub==="started")return{icon:"▶️",desc:n("Follow-up iniciado","Follow-up started","Follow-up iniciado")+f};if(t.sub==="completed")return{icon:"🏁",desc:n("Follow-up concluído","Follow-up completed","Follow-up completado")};if(t.sub==="failed")return{icon:"⚠️",desc:n("Follow-up falhou","Follow-up failed","Follow-up falló")};if(t.sub==="paused")return{icon:"⏸️",desc:n("Follow-up pausado","Follow-up paused","Follow-up pausado"),actor:t.actor};if(t.sub==="resumed")return{icon:"▶️",desc:n("Follow-up retomado","Follow-up resumed","Follow-up reanudado"),actor:t.actor};if(t.sub==="stopped")return{icon:"⏹️",desc:n("Follow-up parado","Follow-up stopped","Follow-up detenido"),actor:t.actor};const l=En[t.status]?n(En[t.status].pt,En[t.status].en,En[t.status].es):t.status||"";return{icon:"⚙️",desc:`Follow-up · ${n("passo","step","paso")} #${(t.step??0)+1} · ${l}`+(t.error?` — ${t.error}`:"")}}if(s==="assignment"){const f=t.to||n("fila","queue","cola");
2return{icon:"👤",desc:t.action==="unassign"?n("Conversa devolvida à fila","Returned to queue","Devuelta a la cola"):t.action==="reassign"?`${n("Reatribuída para","Reassigned to","Reasignada a")} ${f}`:`${n("Atribuída para","Assigned to","Asignada a")} ${f}`,actor:t.by}}return{icon:"•",desc:t.desc||""}}function gl({sessionId:t,chat:n,locale:o="pt",theme:i="dark",onClose:s,onJumpToMessage:f}){const l=(z,Ce,ye)=>o==="en"?Ce:o==="es"?ye:z,[c,d]=r.useState(null),[v,k]=r.useState(!1),[x,P]=r.useState("cadastro"),[A,y]=r.useState({fullName:"",email:"",company:"",deal_value:"",temperature:"",source:""}),[w,m]=r.useState(!1),[I,U]=r.useState(null),[u,p]=r.useState(""),[b,se]=r.useState(null),[C,H]=r.useState(null),[Q,O]=r.useState([]),[oe,ke]=r.useState(""),[Ae,ve]=r.useState(Sn),[_,$]=r.useState("text"),[X,ce]=r.useState(""),[Z,D]=r.useState(""),[ae,K]=r.useState(Sn),[Re,_e]=r.useState(!1),[Y,Oe]=r.useState(null);r.useEffect(()=>{let z=!0;return M.post("/wa/kanban/contact/ensure",{sessionId:t,jid:n.jid}).then(({data:Ce})=>{if(!z)return;d(Ce.id);const ye=Ce.card||{},at=ye.profile||{};y({fullName:at.fullName||"",email:at.email||"",company:ye.company||"",deal_value:ye.deal_value!=null?String(ye.deal_value):"",temperature:ye.temperature||"",source:at.source||""})}).catch(Ce=>{var ye,at;z&&(k(!0),W.error(((at=(ye=Ce.response)==null?void 0:ye.data)==null?void 0:at.error)||l("Falha ao abrir ficha","Failed to open card","Error al abrir")))}),()=>{z=!1}},[t,n.jid]);const Je=r.useCallback(()=>{c&&M.get(`/wa/kanban/cards/${c}/notes`).then(({data:z})=>U((z==null?void 0:z.notes)||[])).catch(()=>U([]))},[c]),Be=r.useCallback(()=>{c&&M.get(`/wa/kanban/cards/${c}/reminders`).then(({data:z})=>se((z==null?void 0:z.reminders)||[])).catch(()=>se([]))},[c]),Qe=r.useCallback(()=>{c&&M.get(`/wa/kanban/cards/${c}/schedules`).then(({data:z})=>H((z==null?void 0:z.schedules)||[])).catch(()=>H([]))},[c]),Me=r.useCallback(()=>{c&&(Oe(null),M.get(`/wa/kanban/cards/${c}/timeline`).then(({data:z})=>Oe((z==null?void 0:z.items)||[])).catch(()=>Oe([])))},[c]);r.useEffect(()=>{c&&(x==="notas"&&I==null&&Je(),x==="agenda"&&(b==null&&Be(),C==null&&Qe(),Q.length||M.get("/wa/templates",{params:{sessionId:t}}).then(({data:z})=>O(Array.isArray(z==null?void 0:z.templates)?z.templates:Array.isArray(z)?z:[])).catch(()=>{})))},[x,c]),r.useEffect(()=>{x==="historico"&&c&&Me()},[x,c,Me]);const De=async()=>{var z,Ce;if(c){m(!0);try{await M.put(`/wa/kanban/cards/${c}/profile`,{company:A.company||null,deal_value:A.deal_value===""?null:Number(A.deal_value),temperature:A.temperature||null,profile:{fullName:A.fullName||"",email:A.email||"",source:A.source||""}}),W.success(l("Cadastro salvo","Saved","Guardado"))}catch(ye){W.error(((Ce=(z=ye.response)==null?void 0:z.data)==null?void 0:Ce.error)||l("Falha ao salvar","Save failed","Error al guardar"))}finally{m(!1)}}},xt=async()=>{const z=u.trim();if(!(!z||!c))try{const{data:Ce}=await M.post(`/wa/kanban/cards/${c}/notes`,{text:z});U(ye=>[{id:Ce.id,text:z,created_at:new Date().toISOString()},...ye||[]]),p("")}catch{W.error(l("Falha ao adicionar nota","Failed to add note","Error al añadir"))}},ut=async z=>{U(Ce=>(Ce||[]).filter(ye=>ye.id!==z));try{await M.delete(`/wa/kanban/cards/${c}/notes/${z}`)}catch{Je()}},mt=async()=>{var ye,at;const z=oe.trim();if(!z){W.error(l("Descreva o lembrete","Describe the reminder","Describe el recordatorio"));return}const Ce=ti(Ae);if(!Ce){W.error(l("Data inválida","Invalid date","Fecha inválida"));return}_e(!0);try{await M.post(`/wa/kanban/cards/${c}/reminder`,{title:z,remind_at:Ce}),W.success(l("Lembrete criado","Reminder set","Recordatorio creado")),ke(""),ve(Sn()),Be()}catch(L){W.error(((at=(ye=L.response)==null?void 0:ye.data)==null?void 0:at.error)||l("Falha ao criar","Failed","Error"))}finally{_e(!1)}},st=async z=>{se(Ce=>(Ce||[]).map(ye=>ye.id===z?{...ye,status:"cancelled"}:ye));try{await M.delete(`/wa/kanban/reminders/${z}`)}catch{Be()}},kt=async()=>{var Ce,ye;const z=ti(ae);if(!z){W.error(l("Data inválida","Invalid date","Fecha inválida"));return}if(_==="text"&&!X.trim()){W.error(l("Escreva a mensagem","Write the message","Escribe el mensaje"));return}if(_==="template"&&!Z){W.error(l("Escolha um template","Pick a template","Elige una plantilla"));return}_e(!0);try{await M.post(`/wa/kanban/cards/${c}/schedule`,_==="text"?{kind:"text",text:X.trim(),scheduled_at:z}:{kind:"template",template_id:Number(Z),scheduled_at:z}
2),W.success(l("Envio agendado","Send scheduled","Envío programado")),ce(""),D(""),K(Sn()),Qe()}catch(at){W.error(((ye=(Ce=at.response)==null?void 0:Ce.data)==null?void 0:ye.error)||l("Falha ao agendar","Failed to schedule","Error al programar"))}finally{_e(!1)}},At=async z=>{H(Ce=>(Ce||[]).map(ye=>ye.id===z?{...ye,status:"cancelled"}:ye));try{await M.delete(`/wa/kanban/schedules/${z}`)}catch{Qe()}},dt={width:"100%",padding:"8px 10px",background:"var(--surface-3,#1f1f24)",border:"1px solid var(--hairline,rgba(255,255,255,.08))",borderRadius:7,color:"var(--text,#fafafa)",fontFamily:"inherit",fontSize:13,outline:"none"},jt={fontSize:11,color:"var(--text-3,#71717a)",marginBottom:4,display:"block",textTransform:"uppercase",letterSpacing:".03em"},G={background:"var(--surface-2,#18181c)",border:"1px solid var(--hairline,rgba(255,255,255,.08))",borderRadius:9,padding:12},me={padding:"7px 12px",background:"transparent",border:0,borderRadius:6,color:"var(--indigo-light,#818cf8)",fontFamily:"inherit",fontSize:12.5,fontWeight:500,cursor:"pointer"},Se={padding:"7px 10px",background:"var(--surface-3,#1f1f24)",border:"1px solid var(--hairline,rgba(255,255,255,.08))",borderRadius:6,color:"var(--text-2,#a1a1aa)",fontFamily:"inherit",fontSize:12,cursor:"pointer"},Fe=z=>{const Ce={pending:["var(--amber,#f59e0b)",l("agendado","pending","pendiente")],notified:["var(--green,#10b981)",l("notificado","notified","notificado")],sent:["var(--green,#10b981)",l("enviado","sent","enviado")],cancelled:["var(--text-4,#52525b)",l("cancelado","cancelled","cancelado")],failed:["var(--rose,#e88a8a)",l("falhou","failed","falló")]},[ye,at]=Ce[z]||["var(--text-4,#52525b)",z];return e.jsx("span",{style:{fontSize:11,color:ye,fontWeight:600},children:at})},le=[{key:"cadastro",label:l("Cadastro","Profile","Ficha")},{key:"notas",label:l("Notas","Notes","Notas")},{key:"agenda",label:l("Agenda","Schedule","Agenda")},{key:"historico",label:l("Histórico","History","Historial")}],Xe=lt(n.name,{phone:n.phone,jid:n.jid});return _s.createPortal(e.jsx("div",{onClick:s,className:"cv2-portal","data-cv2-theme":i,style:{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",zIndex:9998,display:"flex",justifyContent:"flex-end"},children:e.jsxs("div",{onClick:z=>z.stopPropagation(),style:{width:440,maxWidth:"94vw",height:"100%",background:"var(--surface,#0f0f12)",borderLeft:"1px solid var(--hairline-strong,rgba(255,255,255,.12))",display:"flex",flexDirection:"column",boxShadow:"-24px 0 70px -16px rgba(0,0,0,.6)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"14px 16px",borderBottom:"1px solid var(--hairline,rgba(255,255,255,.08))"},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:"50%",overflow:"hidden",flexShrink:0,background:"var(--surface-3,#1f1f24)",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-3,#71717a)",fontWeight:700},children:n.imgUrl?e.jsx("img",{src:n.imgUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"cover"}}):(Xe||"?").slice(0,2).toUpperCase()}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:700,fontSize:15,color:"var(--text,#fafafa)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Xe}),e.jsx("div",{style:{fontSize:12,color:"var(--text-3,#71717a)"},children:bt(n.phone)||bt(n.jid)||""})]}),e.jsx(ne,{content:l("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{onClick:s,"aria-label":"Fechar",style:{background:"transparent",border:0,color:"var(--text-3,#71717a)",cursor:"pointer",display:"inline-flex",padding:4},children:e.jsx("svg",{style:{width:18,height:18},children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{display:"flex",gap:2,padding:"8px 12px 0",borderBottom:"1px solid var(--hairline,rgba(255,255,255,.08))"},children:le.map(z=>e.jsx("button",{onClick:()=>P(z.key),style:{flex:1,padding:"8px 4px",background:"transparent",border:0,borderBottom:`2px solid ${x===z.key?"var(--accent,#7c6cff)":"transparent"}`,color:x===z.key?"var(--text,#fafafa)":"var(--text-3,#71717a)",fontFamily:"inherit",fontSize:13,fontWeight:x===z.key?600:500,cursor:"pointer"},children:z.label},z.key))}),e.jsx("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:16},children:v?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:28,fontSize:13},children:l("Não foi possível abrir a ficha.","Could not open the card.","No se pudo abrir.")}):c==null?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:28,fontSize:13},children:"…"}):x==="cadastro"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{children:[e.jsx("label",{style:jt,children:l("Nome","Name","Nombre")}),e.jsx("input",{style:dt,value:A.fullName,onChange:z=>y(Ce=>({...Ce,fullName:z.target.value})),placeholder:Xe})]}),e.jsxs("div",{children:[e.jsx("label",{style:jt,children:l("E-mail","Email","Correo")}),e.jsx("input",{style:dt,type:"email",value:A.email,onChange:z=>y(Ce=>({...Ce,email:z.target.value}))})]}),e.jsxs("div",{children:[e.jsx("label",{style:jt,children:l("Empresa","Company","Empresa")}),e.jsx("input",{style:dt,value:A.company,onChange:z=>y(Ce=>({...Ce,company:z.target.value}))})]}),e.jsxs("div",{style:{display:"flex",gap:10},children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{style:jt,children:l("Valor (R$)","Deal value","Valor")}),e.jsx("input",{style:dt,type:"number",step:"0.01",value:A.deal_value,onChange:z=>y(Ce=>({...Ce,deal_value:z.target.value}))})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{style:jt,children:l("Origem","Source","Origen")}
2),e.jsx("input",{style:dt,value:A.source,onChange:z=>y(Ce=>({...Ce,source:z.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx("label",{style:jt,children:l("Temperatura","Temperature","Temperatura")}),e.jsx("div",{style:{display:"flex",gap:6},children:hl.map(z=>{const Ce=A.temperature===z.key;return e.jsx("button",{onClick:()=>y(ye=>({...ye,temperature:Ce?"":z.key})),style:{flex:1,padding:"7px 6px",borderRadius:7,border:`1px solid ${Ce?z.color:"var(--hairline,rgba(255,255,255,.08))"}`,background:Ce?z.color+"22":"transparent",color:Ce?z.color:"var(--text-3,#71717a)",fontFamily:"inherit",fontSize:12,fontWeight:600,cursor:"pointer"},children:l(z.pt,z.en,z.es)},z.key)})})]}),e.jsx("button",{onClick:De,disabled:w,style:{...me,opacity:w?.6:1,marginTop:4},children:w?"…":l("Salvar cadastro","Save","Guardar")})]}):x==="notas"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("input",{style:dt,value:u,onChange:z=>p(z.target.value),onKeyDown:z=>z.key==="Enter"&&xt(),placeholder:l("Nova nota…","New note…","Nueva nota…")}),e.jsx(ne,{content:l("Adicionar nota","Add note","Añadir nota"),position:"top",children:e.jsx("button",{onClick:xt,style:me,children:"+"})})]}),I==null?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:20,fontSize:13},children:"…"}):I.length===0?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:20,fontSize:13},children:l("Nenhuma nota ainda.","No notes yet.","Sin notas.")}):I.map(z=>e.jsxs("div",{style:{...G,display:"flex",gap:8,alignItems:"flex-start"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:"var(--text,#fafafa)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:z.text}),e.jsx("div",{style:{fontSize:11,color:"var(--text-4,#52525b)",marginTop:4},children:sn(z.created_at,o)})]}),e.jsx(ne,{content:l("Apagar nota","Delete note","Eliminar nota"),position:"left",children:e.jsx("button",{onClick:()=>ut(z.id),style:{background:"transparent",border:0,color:"var(--text-4,#52525b)",cursor:"pointer",padding:2},children:e.jsx("svg",{style:{width:15,height:15},children:e.jsx("use",{href:"#ci-trash"})})})})]},z.id))]}):x==="agenda"?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs("div",{style:{...G,display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:700,color:"var(--text,#fafafa)"},children:["⏰ ",l("Lembrete","Reminder","Recordatorio")]}),e.jsx("div",{style:{fontSize:11,color:"var(--text-3,#71717a)",marginTop:-4},children:l("Só te avisa no horário (não envia nada ao cliente).","Just notifies you at the time (sends nothing to the client).","Solo te avisa a la hora (no envía nada al cliente).")}),e.jsx("input",{style:dt,value:oe,onChange:z=>ke(z.target.value),placeholder:l("Ex.: ligar para o cliente","e.g. call the client","Ej.: llamar al cliente")}),e.jsx("input",{style:dt,type:"datetime-local",value:Ae,onChange:z=>ve(z.target.value)}),e.jsx("button",{onClick:mt,disabled:Re,style:{...me,opacity:Re?.6:1},children:l("Criar lembrete","Set reminder","Crear recordatorio")})]}),(b||[]).filter(z=>z.status!=="cancelled").length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:(b||[]).map(z=>e.jsxs("div",{style:{...G,display:"flex",gap:8,alignItems:"center",padding:10},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:"var(--text,#fafafa)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z.title}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-4,#52525b)",marginTop:2},children:[sn(z.remind_at,o)," · ",Fe(z.status)]})]}),z.status==="pending"&&e.jsx("button",{onClick:()=>st(z.id),style:Se,children:l("Cancelar","Cancel","Cancelar")}
2)]},z.id))}),e.jsxs("div",{style:{...G,display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:700,color:"var(--text,#fafafa)"},children:["📤 ",l("Envio agendado","Scheduled send","Envío programado")]}),e.jsx("div",{style:{fontSize:11,color:"var(--text-3,#71717a)",marginTop:-4},children:l("Envia uma mensagem ao cliente no horário.","Sends a message to the client at the time.","Envía un mensaje al cliente a la hora.")}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>$("text"),style:{flex:1,...Se,borderColor:_==="text"?"var(--accent,#7c6cff)":"var(--hairline,rgba(255,255,255,.08))",color:_==="text"?"var(--text,#fafafa)":"var(--text-3,#71717a)"},children:l("Texto","Text","Texto")}),e.jsx("button",{onClick:()=>$("template"),style:{flex:1,...Se,borderColor:_==="template"?"var(--accent,#7c6cff)":"var(--hairline,rgba(255,255,255,.08))",color:_==="template"?"var(--text,#fafafa)":"var(--text-3,#71717a)"},children:l("Template","Template","Plantilla")})]}),_==="text"?e.jsx("textarea",{style:{...dt,minHeight:64,resize:"vertical"},value:X,onChange:z=>ce(z.target.value),placeholder:l("Mensagem…","Message…","Mensaje…")}):e.jsxs("select",{style:dt,value:Z,onChange:z=>D(z.target.value),children:[e.jsx("option",{value:"",children:l("Escolha um template…","Pick a template…","Elige una plantilla…")}),Q.map(z=>e.jsx("option",{value:z.id,children:z.name},z.id))]}),e.jsx("input",{style:dt,type:"datetime-local",value:ae,onChange:z=>K(z.target.value)}),e.jsx("button",{onClick:kt,disabled:Re,style:{...me,opacity:Re?.6:1},children:l("Agendar envio","Schedule send","Programar envío")})]}),(C||[]).length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:(C||[]).map(z=>e.jsxs("div",{style:{...G,display:"flex",gap:8,alignItems:"center",padding:10},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:"var(--text,#fafafa)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z.kind==="template"?`📄 ${z.template_name||l("Template","Template","Plantilla")}`:z.text||""}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-4,#52525b)",marginTop:2},children:[sn(z.scheduled_at,o)," · ",Fe(z.status)]})]}),z.status==="pending"&&e.jsx("button",{onClick:()=>At(z.id),style:Se,children:l("Cancelar","Cancel","Cancelar")}
2)]},z.id))})]}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:Y==null?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:20,fontSize:13},children:"…"}):Y.length===0?e.jsx("div",{style:{textAlign:"center",color:"var(--text-4,#52525b)",padding:20,fontSize:13},children:l("Sem histórico ainda.","No history yet.","Sin historial.")}):Y.map((z,Ce)=>{const ye=fl(z,l,o);return e.jsxs("div",{style:{display:"flex",gap:8,padding:"7px 0",borderBottom:"1px solid var(--hairline,rgba(255,255,255,.06))"},children:[e.jsx("span",{style:{fontSize:13,width:18,textAlign:"center",flexShrink:0},children:ye.icon}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,color:ye.incoming?"var(--text,#fafafa)":"var(--text-2,#a1a1aa)",wordBreak:"break-word"},children:ye.desc}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-4,#52525b)",marginTop:2},children:[sn(z.at,o),ye.actor?` · ${ye.actor}`:""]})]})]},`${z.kind}-${z.sub||""}-${z.at}-${Ce}`)})})})]})}),document.body)}function xl({count:t,allMine:n,onCancel:o,onForward:i,onCopy:s,onStar:f,onDownload:l,onDelete:c,locale:d="pt"}){const v=(k,x,P)=>d==="es"?x:d==="en"?P:k;return e.jsxs("div",{className:"bulk-bar",children:[e.jsx(ne,{content:v("Sair da seleção","Salir de la selección","Exit selection"),position:"bottom",children:e.jsx("button",{className:"close-btn",onClick:o,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})}),e.jsxs("span",{className:"count",children:[e.jsx("span",{className:"num",children:t})," ",v(t===1?"selecionada":"selecionadas",t===1?"seleccionada":"seleccionadas","selected")]}),e.jsx("span",{className:"spacer"}),e.jsx(ne,{content:v("Encaminhar","Reenviar","Forward"),position:"bottom",children:e.jsx("button",{className:"act",onClick:i,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-forward"})})})}),e.jsx(ne,{content:v("Favoritar","Destacar","Star"),position:"bottom",children:e.jsx("button",{className:"act",onClick:f,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-star"})})})}),e.jsx(ne,{content:v("Copiar texto","Copiar texto","Copy text"),position:"bottom",children:e.jsx("button",{className:"act",onClick:s,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-copy"})})})}),e.jsx(ne,{content:v("Baixar mídia","Descargar","Download media"),position:"bottom",children:e.jsx("button",{className:"act",onClick:l,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-download"})})})}),e.jsx(ne,{content:n?v("Apagar","Eliminar","Delete"):v("Apagar pra mim","Eliminar para mí","Delete for me"),position:"bottom",children:e.jsx("button",{className:"act danger",onClick:c,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-trash"})})})})]})}const si={pt:["Confirmar","Cancelar"],es:["Confirmar","Cancelar"],en:["Confirm","Cancel"]};function vl({title:t,message:n,confirmLabel:o,cancelLabel:i,variant:s="danger",alert:f=!1,onConfirm:l,onClose:c}){const{locale:d}=ds(),[v,k]=si[d]||si.pt;o==null&&(o=v),i==null&&(i=k),r.useEffect(()=>{const P=A=>{A.key==="Escape"&&(c==null||c()),A.key==="Enter"&&(l==null||l(),c==null||c())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[c,l]);const x={};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:c,children:e.jsxs("div",{className:"cv2-modal",onClick:P=>P.stopPropagation(),style:{maxWidth:380},children:[e.jsx("div",{className:"cv2-modal-head",children:e.jsxs("div",{children:[e.jsx("div",{className:"ttl",children:t}),n&&e.jsx("div",{className:"sub",style:{marginTop:4,lineHeight:1.5,color:"var(--text-2)"},children:n})]})}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsx("div",{className:"spacer"}),!f&&e.jsx("button",{className:"cancel",onClick:c,children:i}),e.jsx("button",{className:`confirm${s==="danger"?" danger":""}`,style:x,onClick:()=>{l==null||l(),c==null||c()},autoFocus:!0,children:o})]})]})})}const Si=["image","video","audio","document","sticker"];function wa(t){try{if(!t||!t.first_step)return null;const n=typeof t.first_step=="string"?JSON.parse(t.first_step):t.first_step;if(!n||typeof n!="object"||!n.msg_type)return null;let o=n.content;
2if(typeof o=="string")try{o=JSON.parse(o)}catch{o={}}return{msgType:String(n.msg_type),content:o&&typeof o=="object"?o:{}}}catch{return null}}function va(t){var n;try{if(t!=null&&t.first_text_content){const o=typeof t.first_text_content=="string"?JSON.parse(t.first_text_content):t.first_text_content;if(o!=null&&o.text)return String(o.text)}}catch{}try{const o=wa(t);if((n=o==null?void 0:o.content)!=null&&n.caption)return String(o.content.caption)}catch{}return""}function jl(t){if(!t||typeof t!="string"||!t.includes("{"))return t;const n=/\{\{\s*[a-z_][a-z0-9_]*\s*\}\}/gi,o=[];let i=t.replace(n,f=>{const l=o.length;return o.push(f),`VAR${l}`}),s=100;for(;s-- >0;){const f=i.match(/\{([^{}]+)\}/);if(!f)break;const l=f[1].includes("|")?f[1].split("|"):[f[1]];i=i.slice(0,f.index)+l[Math.floor(Math.random()*l.length)]+i.slice(f.index+f[0].length)}return(i.includes("{")||i.includes("}"))&&(i=i.replace(/[{}]/g,"")),i.replace(/VAR(\d+)/g,(f,l)=>o[parseInt(l,10)]||"")}function bl(t){const n=Math.round(t/1e3);if(n<60)return`${n}s`;const o=Math.floor(n/60),i=n%60;return i>0?`${o}m ${i}s`:`${o}m`}function yl(t,n){if(t<=0)return n==="en"?"now":n==="es"?"ahora":"agora";if(t<60)return`${t}s`;const o=Math.floor(t/60),i=t%60;return i>0?`${o}m ${i}s`:`${o}m`}function wl({sessionId:t,chatJid:n,quickTemplates:o=[],metaTemplates:i=[],isCloud:s,canSendFreeform:f=!0,permsBlocked:l=!1,permsReason:c="",activeExecution:d,onCancelExecution:v,onOpenTemplatePicker:k,locale:x="pt"}){const P=bs(),A=r.useRef(null),y=r.useRef(null),w=r.useRef(null),m=r.useRef(!1),[I,U]=r.useState({l:!1,r:!1}),[u,p]=r.useState(null),[b,se]=r.useState(!1),[C,H]=r.useState(""),[Q,O]=r.useState(Date.now()),[oe,ke]=r.useState({}),[Ae,ve]=r.useState(null),[_,$]=r.useState(null),[X,ce]=r.useState(null),[Z,D]=r.useState({code:"en",enabled:!1});r.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]),r.useEffect(()=>{if(!t||!n){D({code:"en",enabled:!1});return}let G=!0;M.get("/wa/chat/translate-pref",{params:{sessionId:t,jid:n}}).then(({data:Se})=>{G&&D({code:(Se==null?void 0:Se.lang)||"en",enabled:!!(Se!=null&&Se.enabled)})}).catch(()=>{G&&D({code:"en",enabled:!1})});const me=Se=>{const Fe=Se.detail||{};Fe.sessionId===t&&Fe.jid===n&&D({code:Fe.code||"en",enabled:!!Fe.enabled})};return window.addEventListener("pragmaz:cv2-translate",me),()=>{G=!1,window.removeEventListener("pragmaz:cv2-translate",me)}},[t,n]);const ae=Number((d==null?void 0:d.totalSteps)??(d==null?void 0:d.total_steps)??0),K=d&&["pending","running"].includes(d.status)&&ae>1,Re=d==null?void 0:d.nextFireAt;r.useEffect(()=>{if(!K||!Re)return;const G=setInterval(()=>
2O(Date.now()),500);return()=>clearInterval(G)},[K,Re]);const _e=(i||[]).map(G=>({...G,_meta:!0})),Y=(o||[]).map(G=>({...G,_internal:!0})),Oe=Y.map(G=>G.id).join(","),Je=r.useMemo(()=>{if(!X)return Y;const G=new Map(Y.map(Se=>[Se.id,Se])),me=[];for(const Se of X)G.has(Se)&&(me.push(G.get(Se)),G.delete(Se));return[...me,...G.values()]},[Oe,X]);r.useEffect(()=>{ce(null)},[Oe]);const Be=s?[..._e,...Je]:Je,Qe=C.trim().toLowerCase(),Me=Qe?Be.filter(G=>String(G.name||"").toLowerCase().includes(Qe)):Be,De=Be.filter(G=>!G._meta).map(G=>G.id).join(",");r.useEffect(()=>{if(!n)return;const G=Be.filter(Se=>!Se._meta).map(Se=>({tpl:Se,raw:va(Se)})).filter(({tpl:Se,raw:Fe})=>Fe&&oe[`${n}|${Se.id}`]===void 0);if(!G.length)return;let me=!1;return(async()=>{const Se=await Promise.all(G.map(({tpl:Fe,raw:le})=>M.post("/wa/templates/preview-variables",{text:le,chatJid:n}).then(Xe=>{var z;return{id:Fe.id,expanded:((z=Xe.data)==null?void 0:z.expanded)||le}}).catch(()=>({id:Fe.id,expanded:le}))));me||ke(Fe=>{const le={...Fe};for(const{id:Xe,expanded:z}of Se)le[`${n}|${Xe}`]=z;return le})})(),()=>{me=!0}},[n,De]),r.useEffect(()=>{var G;b&&((G=w.current)==null||G.focus())},[b]),r.useEffect(()=>{const G=A.current;if(!G)return;const me=()=>{const Fe=G.scrollWidth>G.clientWidth+1;U({l:Fe&&G.scrollLeft>4,r:Fe&&G.scrollLeft+G.clientWidth<G.scrollWidth-4})};me(),G.addEventListener("scroll",me,{passive:!0}),window.addEventListener("resize",me);const Se=setTimeout(me,100);return()=>{G.removeEventListener("scroll",me),window.removeEventListener("resize",me),clearTimeout(Se)}},[Me.length]);const xt=G=>{const me=A.current;me&&me.scrollBy({left:G*Math.round(me.clientWidth*.7),behavior:"smooth"})},ut=()=>Z.enabled&&Z.code?Z.code:void 0,mt=async G=>{var me,Se;if(!u){if(l){W.error(c||(x==="en"?"Sending unavailable in this chat":x==="es"?"Envío no disponible en este chat":"Envio indisponível neste chat"));return}if(s&&G._meta){k==null||k(G);return}if(s&&!f){W.error(x==="en"?"Window closed — approved template only":x==="es"?"Ventana de 24 h cerrada — solo plantilla aprobada":"Janela 24h fechada — só template aprovado");return}p(G.id);try{const Fe=Ko(P.getDevicePref(t))||void 0,le=ut()||void 0;if(s&&G._internal){const Xe=String(n||"").split("@")[0].split(":")[0];await M.post(`/meta/sessions/${encodeURIComponent(t)}/run-internal-template`,{templateId:G.id,to:Xe,translateLang:le,signaturePrefix:Fe})}else await M.post(`/wa/templates/${G.id}/run`,{sessionId:t,chatJid:n,translateLang:le,signaturePrefix:Fe})}catch(Fe){const le=(Se=(me=Fe==null?void 0:Fe.response)==null?void 0:me.data)==null?void 0:Se.error;W.error(le==="janela_fechada"?x==="en"?"Window closed — approved template only":x==="es"?"Ventana de 24 h cerrada — solo plantilla aprobada":"Janela 24h fechada — só template aprovado":x==="en"?"Template failed":x==="es"?"Error al ejecutar la plantilla":"Falha ao executar template")}finally{y.current=setTimeout(()=>p(null),600)}}},st=async G=>{var le,Xe,z,Ce;if(l||s&&!f){W.error(l?c||(x==="en"?"Sending unavailable in this chat":x==="es"?"Envío no disponible en este chat":"Envio indisponível neste chat"):x==="en"?"Window closed — approved template only":x==="es"?"Ventana de 24 h cerrada — solo plantilla aprobada":"Janela 24h fechada — só template aprovado");return}let me=oe[`${n}|${G.id}`];if(!me){const ye=va(G);if(ye)try{const{data:at}=await M.post("/wa/templates/preview-variables",{text:ye,chatJid:n});me=(at==null?void 0:at.expanded)||ye}catch{me=ye}}const Se=wa(G),Fe=Se&&Si.includes(Se.msgType);if(me){const ye=jl(me);window.dispatchEvent(new CustomEvent("pragmaz:cv2-paste",{detail:{text:ye,sessionId:t,jid:n}}))}if(Fe){const ye=((le=Se.content)==null?void 0:le.publicUrl)||((Xe=Se.content)==null?void 0:Xe.url);ye&&/^https?:\/\//.test(ye)&&window.dispatchEvent(new CustomEvent("pragmaz:attach-media",{detail:{sessionId:t,jid:n,url:ye,fileName:((z=Se.content)==null?void 0:z.fileName)||void 0,mimetype:((Ce=Se.content)==null?void 0:Ce.mimetype)||void 0}}))}!me&&!Fe&&W.error(x==="en"?"Nothing to edit":x==="es"?"Nada para editar":"Nada pra editar")},kt=G=>me=>{if(!m.current){me.preventDefault();return}m.current=!1,ve(G),me.dataTransfer.effectAllowed="move";try{me.dataTransfer.setData("text/plain",String(G))}catch{}},At=G=>me=>{Ae==null||Ae===G||(me.preventDefault(),me.dataTransfer.dropEffect="move",$(G))},dt=()=>{ve(null),$(null)},jt=G=>async me=>{me.preventDefault();const Se=Ae;if(ve(null),$(null),!Se||Se===G)return;const Fe=Je.map(z=>z.id),le=Fe.indexOf(Se),Xe=Fe.indexOf(G);if(!(le===-1||Xe===-1)){Fe.splice(le,1),Fe.splice(Xe,0,Se),ce(Fe);try{await M.post("/wa/templates/reorder",{ids:Fe})}catch{}}};if(Be.length===0&&!K)return null;if(K){const G=d.templateName||d.template_name||"Template",me=d.currentStep??d.current_step??0,Se=d.totalSteps??d.total_steps??0,Fe=d.progress!=null?d.progress:Se>0?Math.round(me/Se*100):0,le=Re?Math.max(0,Re-Q):0,Xe=Re&&le>1500;return e.jsx("div",{className:"qs-bar-wrap qs-progress-wrap",children:e.jsxs("div",{className:"qs-progress",children:[e.jsxs("div",{className:"qs-prog-top",children:[e.jsx("span",{className:"qs-prog-ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-zap"})})}),e.jsx("span",{className:"qs-prog-name",children:G}),e.jsxs("span",{className:"qs-prog-step",children:[me,"/",Se]}),Xe&&e.jsxs("span",{className:"qs-prog-cd",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-clock"})}),x==="en"?"next in":x==="es"?"próxima en":"próxima em"," ",yl(Math.ceil(le/1e3),x)]}),e.jsxs("span",{className:"qs-prog-pct",children:[Fe,"%"]}),e.jsx(ne,{position:"top",content:x==="en"?"Cancel send":x==="es"?"Cancelar envío":"Cancelar envio",children:e.jsx("button",{className:"qs-prog-x",onClick:()=>v==null?void 0:v(d),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{className:"qs-prog-track",children:e.jsx("div",{className:"qs-prog-fill",style:{width:`${Fe}%`}})})]})})}return e.jsxs("div",{className:"qs-bar-wrap",children:[e.jsx(ne,{position:"top",content:x==="en"?"Search templates":x==="es"?"Buscar plantillas":"Buscar templates",children:e.jsx("button",{className:`qs-search-btn${b?" active":""}`,onClick:()=>{se(G=>!G),b&&H("")},children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})})}),b&&e.jsxs("div",{className:"qs-search-input",children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})}),e.jsx("input",{ref:w,type:"text",value:C,onChange:G=>H(G.target.value),onKeyDown:G=>{G.key==="Escape"&&(se(!1),H(""))},placeholder:x==="en"?"Search templates…":x==="es"?"Buscar plantillas…":"Buscar templates…"})]}),e.jsx(ne,{position:"top",content:x==="en"?"Scroll left":x==="es"?"Desplazar a la izquierda":"Rolar para a esquerda",children:e.jsx("button",{className:`qs-bar-arrow${I.l?"":" disabled"}`,onClick:()=>xt(-1),disabled:!I.l,"aria-label":"Esquerda",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-l"})})})}),e.jsx("div",{className:"qs-bar",ref:A,children:Me.map(G=>{if(G._meta)return e.jsx(ne,{position:"top",delay:150,content:l?c:`${G.name}${G.language?" · "+G.language:""}${G.category?" · "+G.category:""}`,children:e.jsxs("button",{className:"qs-chip meta",disabled:l,style:l?{opacity:.5,cursor:"not-allowed"}:void 0,onClick:()=>mt(G),children:[e.jsx("svg",{children:e.jsx("use",{href:"#ci-cloud"})}),G.name]})},"m"+(G.id||G.name));const me=u===G.id,Se=!Qe&&!me&&!l,Fe=l||s&&!f,le=_===G.id&&Ae!==G.id;return e.jsx(ne,{position:"top",delay:150,className:"!whitespace-normal max-w-[320px]",content:Fe?l?c||(x==="en"?"Sending unavailable in this chat":x==="es"?"Envío no dis
2ponible en este chat":"Envio indisponível neste chat"):x==="en"?"Window closed — opens when the contact replies":x==="es"?"Ventana de 24h cerrada — se abre cuando el contacto responda":"Janela 24h fechada — abre quando o contato responder":e.jsx(Nl,{tpl:G,expanded:oe[`${n}|${G.id}`],locale:x,reorderable:Se}),children:e.jsxs("div",{className:`qs-chip tpl${me?" sending":""}${Ae===G.id?" dragging":""}${le?" over":""}`,draggable:Se,onDragStart:kt(G.id),onDragOver:At(G.id),onDragEnd:dt,onDrop:jt(G.id),style:Fe?{opacity:.5}:void 0,children:[Se&&e.jsx("span",{className:"drag",onMouseDown:()=>{m.current=!0},onMouseUp:()=>{m.current=!1},onClick:Xe=>Xe.stopPropagation(),children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-drag"})})}),e.jsxs("button",{className:"qs-main",disabled:me||Fe,style:Fe?{cursor:"not-allowed"}:void 0,onClick:Xe=>{me||Fe||(Xe.shiftKey||Xe.altKey?st(G):mt(G))},children:[me?e.jsx("span",{className:"qs-spin"}):e.jsx("svg",{children:e.jsx("use",{href:"#ci-zap"})}),e.jsx("span",{className:"nm",children:G.name}),G.step_count>1&&e.jsx("span",{className:"step-n",children:G.step_count})]}),e.jsx("button",{className:"qs-edit",disabled:me||Fe,onClick:Xe=>{Xe.stopPropagation(),!Fe&&st(G)},"aria-label":"edit",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-edit"})})})]})},"i"+(G.id||G.name))})}),e.jsx(ne,{position:"top",content:x==="en"?"Scroll right":x==="es"?"Desplazar a la derecha":"Rolar para a direita",children:e.jsx("button",{className:`qs-bar-arrow${I.r?"":" disabled"}`,onClick:()=>xt(1),disabled:!I.r,"aria-label":"Direita",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-chev-r"})})})})]})}function Nl({tpl:t,expanded:n,locale:o,reorderable:i=!1}){var P;const s=Number((t==null?void 0:t.step_count)||((P=t==null?void 0:t.steps_summary)==null?void 0:P.length)||1),f=Number((t==null?void 0:t.total_delay_ms)||0),l=wa(t),c=va(t),d=n||c,v=l&&Si.concat("location").includes(l.msgType),k={pt:{steps:"mensagens",total:"tempo",cap:"Legenda",prev:"Prévia",none:"Sem texto",click:"envia",edit:"editar",drag:"arrastar p/ reordenar"},en:{steps:"messages",total:"time",cap:"Caption",prev:"Preview",none:"No text",click:"send",edit:"edit",drag:"drag to reorder"},es:{steps:"mensajes",total:"tiempo",cap:"Leyenda",prev:"Vista",none:"Sin texto",click:"enviar",edit:"editar",drag:"arrastrar p/ reordenar"}}[o]||{steps:"messages",total:"time",cap:"Caption",prev:"Preview",none:"No text",click:"send",edit:"edit",drag:"drag to reorder"},x={pt:{image:"🖼 Imagem",video:"🎥 Vídeo",audio:"🎤 Áudio",document:"📎 Documento",sticker:"🎭 Figurinha",location:"📍 Localização"},en:{image:"🖼 Image",video:"🎥 Video",audio:"🎤 Audio",document:"📎 Document",sticker:"🎭 Sticker",location:"📍 Location"},es:{image:"🖼 Imagen",video:"🎥 Video",audio:"🎤 Audio",document:"📎 Documento",sticker:"🎭 Pegatina",location:"📍 Ubicación"}}[o]||{};return e.jsxs("div",{className:"max-w-[300px] text-left whitespace-normal",children:[e.jsxs("div",{className:"text-xs uppercase tracking-wider font-semibold mb-1",style:{color:"var(--text)"},children:["⚡ ",t.name]}),t.description&&e.jsx("div",{className:"text-xs mb-1.5",style:{color:"var(--text-2)"},children:t.description}),v&&e.jsx("div",{className:"text-xs font-semibold mb-1",style:{color:"var(--indigo)"},children:x[l.msgType]||l.msgType}),d?e.jsxs("div",{className:"rounded px-2 py-1.5 mb-1.5",style:{background:"color-mix(in srgb, var(--emerald) 12%, transparent)",border:"1px solid color-mix(in srgb, var(--emerald) 28%, transparent)"},children:[e.jsxs("div",{className:"text-xs uppercase tracking-wider font-bold mb-0.5",style:{color:"var(--emerald)"},children:[v?k.cap:k.prev," →"]}),e.jsx("div",{className:"text-xs whitespace-pre-wrap break-words leading-snug",style:{color:"var(--text)"},children:d.length>240?d.slice(0,240)+"…":d})]}):v?null:e.jsx("div",{className:"text-xs italic mb-1.5",style:{color:"var(--text-3)"},children:k.none}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",style:{color:"var(--text-3)"},children:[e.jsxs("span",{children:["📊 ",s," ",k.steps]}),f>0&&e.jsxs("span",{children:["⏱ ",k.total,": ",bl(f)]})]}),e.jsxs("div",{className:"mt-1.5 pt-1.5 text-xs",style:{borderTop:"1px solid var(--hairline)",color:"var(--text-3)"},children:[e.jsx("span",{className:"font-semibold",style:{color:"var(--text-2)"},children:"Click"})," ",k.click," · ",e.jsx("span",{className:"font-semibold",style:{color:"var(--text-2)"},children:"⇧Click"})," ",k.edit,i&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"font-semibold",style:{color:"var(--text-2)"},children:"⠿"})," ",k.drag]})]})]})}const ni=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase();function kl({sessionId:t,providerType:n,onClose:o,onOpenChat:i,locale:s="pt"}){const f=n==="cloud_api"||n==="coexistence",l=f,[c,d]=r.useState("contact"),v=l?c:"contact",[k,x]=r.useState(""),[P,A]=r.useState([]),[y,w]=r.useState(!1),[m,I]=r.useState(""),[U,u]=r.useState(null),p=r.useRef(null),[b,se]=r.useState("pick"),[C,H]=r.useState([]),[Q,O]=r.useState(""),[oe,ke]=r.useState(!1),[Ae,ve]=r.useState(null),_=(D,ae,K)=>s==="en"?ae:s==="es"?K:D;r.useEffect(()=>{if(!(b!=="group"&&v!=="contact"||!t))return clearTimeout(p.current),p.current=setTimeout(async()=>{w(!0);try{const D=new URLSearchParams({sessionId:t,q:k.trim(),limit:"60"}),{data:ae}=await M.get(`/wa/chat/contacts?${D}`);A((ae==null?void 0:ae.contacts)||[])}catch{A([])}w(!1)},250),()=>clearTimeout(p.current)},[v,k,t,b]),r.useEffect(()=>{const D=ae=>
2{ae.key==="Escape"&&(o==null||o())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[o]);const $=D=>{var K;const ae=D.lid||D.jid;i==null||i(ae,{jid:ae,name:D.name,imgUrl:D.imgUrl,pnJid:(K=D.jid)!=null&&K.endsWith("@s.whatsapp.net")?D.jid:null,lid:D.lid||null,isGroup:!1,lastMessage:null,unreadCount:0}),o==null||o()},X=()=>{const D=m.replace(/\D/g,"");if(!/^\d{8,15}$/.test(D)){u(s==="en"?"Invalid number (use country code)":s==="es"?"Número no válido (usa el código de país, ej.: 5511987654321)":"Número inválido (use DDI, ex: 5511987654321)");return}const ae=`${D}@s.whatsapp.net`;i==null||i(ae,{jid:ae,name:bt(D),isGroup:!1,pnJid:ae,lastMessage:null,unreadCount:0}),o==null||o()},ce=D=>{ve(null);const ae=D.lid||D.jid;H(K=>K.some(Re=>(Re.lid||Re.jid)===ae)?K.filter(Re=>(Re.lid||Re.jid)!==ae):[...K,D])},Z=async()=>{var K,Re,_e;if(f){ve(Jt(s));return}const D=b==="community",ae=Q.trim();if(!ae){ve(D?_("Dê um nome à comunidade","Name the community","Ponle un nombre a la comunidad"):_("Dê um nome ao grupo","Name the group","Ponle un nombre al grupo"));return}if(!D&&C.length===0){ve(_("Selecione ao menos 1 participante","Select at least 1 participant","Selecciona al menos 1 participante"));return}ke(!0),ve(null);try{const Y=C.map(Me=>{var De;return(De=Me.jid)!=null&&De.endsWith("@s.whatsapp.net")?Me.jid:Me.lid||Me.jid}).filter(Boolean),Oe={subject:ae,participants:Y};D&&(Oe.parent=!0);const{data:Je}=await M.post("/wa/chat/group-action",{sessionId:t,action:"create",payload:Oe}),Be=Je==null?void 0:Je.result,Qe=Be==null?void 0:Be.id;if(!Qe)throw new Error("no group id");i==null||i(Qe,{jid:Qe,name:(Be==null?void 0:Be.subject)||ae,isGroup:!0,imgUrl:null,memberCount:((K=Be==null?void 0:Be.participants)==null?void 0:K.length)||Y.length+1,lastMessage:null,unreadCount:0}),o==null||o()}catch(Y){ve(((_e=(Re=Y.response)==null?void 0:Re.data)==null?void 0:_e.error)||Y.message||_("Falha ao criar grupo","Failed to create group","Error al crear el grupo"))}finally{ke(!1)}};if(b==="group"||b==="community"){const D=b==="community",ae=K=>C.some(Re=>(Re.lid||Re.jid)===(K.lid||K.jid));return e.jsx("div",{className:"cv2-modal-backdrop",onClick:o,children:e.jsxs("div",{className:"cv2-modal",onClick:K=>K.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(ne,{content:_("Voltar","Back","Atrás"),position:"bottom",children:e.jsx("button",{className:"x",onClick:()=>{se("pick"),H([]),O(""),ve(null)},children:e.jsx("svg",{style:{transform:"scaleX(-1)"},children:e.jsx("use",{href:"#ci-arrow-r"})})})}),e.jsx("div",{className:"ttl",children:D?_("Nova comunidade","New community","Nueva comunidad"):_("Novo grupo","New group","Nuevo grupo")})]}),e.jsx(ne,{content:_("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:o,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsxs("div",{style:{padding:"12px 16px 6px"},children:[e.jsx("input",{type:"text",value:Q,maxLength:100,onChange:K=>{O(K.target.value),ve(null)},placeholder:D?_("Nome da comunidade","Community name","Nombre de la comunidad"):_("Nome do grupo","Group name","Nombre del grupo"),autoFocus:!0,style:{width:"100%",padding:"9px 12px",background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:8,color:"var(--text)",fontFamily:"inherit",fontSize:14,outline:"none"}}),C.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:8},children:C.map(K=>e.jsxs("span",{onClick:()=>ce(K),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"3px 8px",background:"rgba(99,102,241,0.14)",border:"1px solid rgba(99,102,241,0.3)",borderRadius:12,fontSize:12,color:"var(--indigo-light)",cursor:"pointer"},children:[lt(K.name,{phone:K.phone,jid:K.jid}),e.jsx("svg",{style:{width:12,height:12},children:e.jsx("use",{href:"#ci-x"})})]},K.lid||K.jid))})]}),e.jsxs("div",{className:"cv2-modal-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",value:k,onChange:K=>x(K.target.value),placeholder:_("Buscar contato","Search contact","Buscar contacto")})]}),e.jsxs("div",{className:"cv2-modal-list",children:[y&&e.jsx("div",{className:"empty",children:_("Buscando…","Searching…","Buscando…")}),!y&&P.length===0&&e.jsx("div",{className:"empty",children:_("Nenhum contato","No contacts","Ningún contacto")}),P.map(K=>e.jsxs("button",{className:`cv2-target-row ${ae(K)?"selected":""}`,onClick:()=>ce(K),children:[e.jsx("span",{className:`sel-check ${ae(K)?"on":""}`,children:ae(K)&&e.jsx("svg",{children:e.jsx("use",{href:"#ci-check"})})}),e.jsx("div",{className:"av",children:K.imgUrl?e.jsx("img",{src:K.imgUrl,alt:""}
2):ni(lt(K.name,{phone:K.phone,jid:K.jid}))}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:lt(K.name,{phone:K.phone,jid:K.jid})}),e.jsx("div",{className:"ph",children:bt(K.phone||K.jid)})]})]},K.lid||K.jid))]}),Ae&&e.jsx("div",{style:{padding:"0 16px",fontSize:13,color:"var(--rose)"},children:Ae}),e.jsxs("div",{className:"cv2-modal-foot",children:[e.jsxs("span",{className:"count",children:[C.length," ",_("selecionado(s)","selected","seleccionado(s)")]}),e.jsx("div",{className:"spacer"}),e.jsx("button",{className:"cancel",onClick:()=>{se("pick"),H([]),O("")},children:_("Cancelar","Cancel","Cancelar")}),e.jsx("button",{className:"confirm",onClick:Z,disabled:oe||!Q.trim()||!D&&C.length===0,children:oe?_("Criando…","Creating…","Creando…"):D?_("Criar comunidade","Create community","Crear comunidad"):_("Criar grupo","Create group","Crear grupo")})]})]})})}return e.jsx("div",{className:"cv2-modal-backdrop",onClick:o,children:e.jsxs("div",{className:"cv2-modal",onClick:D=>D.stopPropagation(),children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsx("div",{className:"ttl",children:s==="en"?"Open conversation":s==="es"?"Abrir conversación":"Abrir conversa"}),e.jsx(ne,{content:_("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"x",onClick:o,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),!f&&e.jsxs("button",{onClick:()=>{se("group"),x(""),ve(null)},style:{display:"flex",alignItems:"center",gap:11,width:"100%",padding:"12px 16px",background:"transparent",border:0,borderBottom:"1px solid var(--hairline)",cursor:"pointer",textAlign:"left"},children:[e.jsx("div",{style:{width:38,height:38,borderRadius:"50%",background:"var(--indigo)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",flexShrink:0},children:e.jsx("svg",{style:{width:18,height:18},children:e.jsx("use",{href:"#ci-users"})})}),e.jsx("span",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:_("Novo grupo","New group","Nuevo grupo")})]}),!f&&e.jsxs("button",{onClick:()=>{se("community"),H([]),O(""),x(""),ve(null)},style:{display:"flex",alignItems:"center",gap:11,width:"100%",padding:"12px 16px",background:"transparent",border:0,borderBottom:"1px solid var(--hairline)",cursor:"pointer",textAlign:"left"},children:[e.jsx("div",{style:{width:38,height:38,borderRadius:"50%",background:"var(--emerald, #10b981)",display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",flexShrink:0},children:e.jsx("svg",{style:{width:18,height:18},children:e.jsx("use",{href:"#ci-users"})})}),e.jsx("span",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:_("Nova comunidade","New community","Nueva comunidad")})]}),l&&e.jsx("div",{style:{display:"flex",borderBottom:"1px solid var(--hairline)",padding:"0 8px"},children:["contact","number"].map(D=>e.jsx("button",{onClick:()=>d(D),style:{padding:"11px 14px",fontSize:13,fontWeight:500,background:"transparent",border:0,cursor:"pointer",borderBottom:c===D?"2px solid var(--indigo-light)":"2px solid transparent",color:c===D?"var(--indigo-light)":"var(--text-3)",fontFamily:"inherit"},children:D==="contact"?s==="en"?"My contacts":s==="es"?"Mis contactos":"Meus contatos":s==="en"?"New number":s==="es"?"Número nuevo":"Novo número"},D))}),v==="contact"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cv2-modal-search",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-search"})})}),e.jsx("input",{type:"text",value:k,onChange:D=>x(D.target.value),placeholder:_("Buscar contato","Search contact","Buscar contacto"),autoFocus:!0})]}),e.jsxs("div",{className:"cv2-modal-list",children:[y&&e.jsx("div",{className:"empty",children:_("Buscando…","Searching…","Buscando…")}),!y&&P.length===0&&e.jsx("div",{className:"empty",children:_("Nenhum contato","No contacts","Ningún contacto")}),P.map(D=>e.jsxs("button",{className:"cv2-target-row",onClick:()=>$(D),children:[e.jsx("div",{className:"av",children:D.imgUrl?e.jsx("img",{src:D.imgUrl,alt:""}):ni(D.name)}),e.jsxs("div",{className:"info",children:[e.jsx("div",{className:"nm",children:D.name||bt(D.phone||D.jid)}),e.jsx("div",{className:"ph",children:bt(D.phone||D.jid)})]})]},D.lid||D.jid))]}),!l&&e.jsx("div",{style:{padding:"10px 16px",borderTop:"1px solid var(--hairline)",fontSize:12,color:"var(--text-3)",lineHeight:1.45},children:_("Só dá pra abrir conversa com contatos salvos na agenda do celular. Salve o número no celular e ele aparece aqui.","You can only start chats with contacts saved on your phone. Save the number on your phone and it shows up here.","Solo puedes abrir conversación con contactos guardados en la agenda del móvil. Guarda el número y aparecerá aquí.")})]}):e.jsxs("div",{style:{padding:18},children:[e.jsx("div",{style:{fontSize:12,color:"var(--text-2)",marginBottom:6}
2,children:_("Número com DDI (ex: 5511987654321)","Number with country code (e.g. 5511987654321)","Número con código de país (ej.: 5511987654321)")}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("input",{type:"text",value:m,onChange:D=>{I(D.target.value),u(null)},onKeyDown:D=>D.key==="Enter"&&X(),placeholder:"5511987654321",autoFocus:!0,style:{flex:1,padding:"9px 12px",background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:8,color:"var(--text)",fontFamily:"inherit",fontSize:14,outline:"none"}}),e.jsx("button",{onClick:X,className:"confirm",style:{padding:"7px 12px",background:"transparent",border:0,borderRadius:6,color:"var(--indigo-light)",fontFamily:"inherit",fontSize:12.5,fontWeight:500,cursor:"pointer"},children:s==="en"?"Open":"Abrir"})]}),e.jsx("div",{style:{marginTop:10,fontSize:12,color:"var(--text-3)",lineHeight:1.4},children:s==="en"?"Cloud/Coex: the chat opens by sending an approved template (24h window is closed for new contacts).":s==="es"?"Cloud/Coex: la conversación se abre enviando una plantilla aprobada (la ventana de 24 h está cerrada para contactos nuevos).":"Cloud/Coex: a conversa abre enviando um template aprovado (a janela de 24h fica fechada pra contato novo)."}),U&&e.jsx("div",{style:{marginTop:10,fontSize:13,color:"var(--rose)"},children:U})]})]})})}function Sl({until:t,onClose:n,locale:o="pt"}){const i=(c,d,v)=>o==="en"?d:o==="es"?v:c;r.useEffect(()=>{const c=d=>{d.key==="Escape"&&(n==null||n())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[n]);const s=t?Math.max(1,Math.ceil((new Date(t).getTime()-Date.now())/864e5)):null,f=s===1?i("dia","day","día"):i("dias","days","días"),l=[{icon:"✓",color:"var(--green, #25d366)",text:i("Você ainda pode usar o WhatsApp no seu dispositivo principal (celular) sem restrições.","You can still use WhatsApp on your main device (phone) without restrictions.","Aún puedes usar WhatsApp en tu dispositivo principal (celular) sin restricciones.")},{icon:"✕",color:"var(--text-3, #8a8a8f)",text:i("No momento, não será possível iniciar novas conversas nem usar alguns outros recursos.","For now, you can’t start new chats or use some other features.","Por ahora, no podrás iniciar nuevas conversaciones ni usar algunas otras funciones.")},{icon:"🔔",color:"var(--text-3, #8a8a8f)",text:i("O WhatsApp avisa no aparelho principal quando as restrições forem suspensas.","WhatsApp will notify you on your main device when the restrictions are lifted.","WhatsApp te avisará en el dispositivo principal cuando se levanten las restricciones.")}];return e.jsx("div",{className:"cv2-modal-backdrop",onClick:n,children:e.jsxs("div",{className:"cv2-modal",onClick:c=>c.stopPropagation(),style:{maxWidth:440,padding:"26px 26px 22px",textAlign:"center",overflowY:"auto"},children:[s!=null&&e.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,marginBottom:16},children:[e.jsxs("span",{style:{background:"var(--surface-2)",border:"1px solid var(--hairline-strong)",borderRadius:16,padding:"5px 14px",fontSize:15,fontWeight:600,color:"var(--text)"},children:[s," ",f]}),e.jsx("span",{style:{display:"inline-flex",width:22,height:22,borderRadius:"50%",background:"#f59e0b",color:"#1a1a1a",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:800},children:"!"})]}),e.jsx("h2",{style:{fontSize:19,fontWeight:700,color:"var(--text)",margin:"4px 0 10px",lineHeight:1.3},children:i("No momento, sua conta está restringida nos dispositivos conectados","Your account is currently restricted on connected devices","En este momento, tu cuenta está restringida en los dispositivos conectados")}),e.jsx("p",{style:{fontSize:13.5,color:"var(--text-2)",lineHeight:1.5,margin:"0 auto 18px",maxWidth:380},children:i("A atividade recente da sua conta pode caracterizar envio de spam, mensagens automáticas ou em massa.","Your account’s recent activity may look like spam, automated or bulk messaging.","La actividad reciente de tu cuenta puede parecer envío de spam, mensajes automáticos o masivos.")}
2),e.jsx("div",{style:{textAlign:"left",display:"flex",flexDirection:"column",gap:15,margin:"4px 0 22px"},children:l.map((c,d)=>e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12},children:[e.jsx("span",{style:{flexShrink:0,width:26,height:26,borderRadius:"50%",border:`1.5px solid ${c.color}`,color:c.color,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:14,marginTop:1},children:c.icon}),e.jsx("span",{style:{fontSize:13.5,color:"var(--text)",lineHeight:1.45},children:c.text})]},d))}),e.jsx("button",{onClick:n,style:{padding:"9px 22px",background:"transparent",border:"1px solid var(--hairline-strong)",borderRadius:20,color:"var(--text)",fontFamily:"inherit",fontSize:14,fontWeight:600,cursor:"pointer"},children:i("Fechar","Close","Cerrar")})]})})}const Cl=t=>(t||"?").trim().split(/\s+/).slice(0,2).map(n=>n[0]).join("").toUpperCase(),El=t=>{if(!t)return"";const n=new Date(t);return isNaN(n.getTime())?"":n.toLocaleString([],{dateStyle:"short",timeStyle:"short"})},ai={pt:{you:"Você",member:"Participante",noName:"Sem nome",empty:"Ninguém votou nesta opção"},en:{you:"You",member:"Member",noName:"No name",empty:"No one voted for this option"},es:{you:"Tú",member:"Miembro",noName:"Sin nombre",empty:"Nadie votó por esta opción"}};function Il({data:t,onClose:n,locale:o="pt"}){const i=ai[o]||ai.pt,[s,f]=r.useState(()=>{if(typeof(t==null?void 0:t.focusOption)=="number")return t.focusOption;const d=((t==null?void 0:t.options)||[]).findIndex(v=>v.name===(t==null?void 0:t.focusOption));return d>=0?d:0});if(r.useEffect(()=>{const d=v=>{v.key==="Escape"&&(n==null||n())};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[n]),!t)return null;const l=t.options||[],c=l[s]||l[0]||{voters:[]};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:n,children:e.jsxs("div",{className:"cv2-modal",onClick:d=>d.stopPropagation(),style:{maxWidth:420},children:[e.jsxs("div",{className:"cv2-modal-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"ttl",style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("svg",{style:{width:16,height:16,color:"var(--indigo-light)"},children:e.jsx("use",{href:"#ci-poll"})}),t.pollName||(o==="en"?"Poll":o==="es"?"Encuesta":"Enquete")]}),e.jsxs("div",{className:"sub",children:[t.totalVotes||0," ",t.totalVotes===1?o==="en"?"vote":"voto":o==="en"?"votes":"votos"]})]}),e.jsx(ne,{content:o==="en"?"Close":o==="es"?"Cerrar":"Fechar",position:"left",children:e.jsx("button",{className:"x",onClick:n,children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-x"})})})})]}),e.jsx("div",{style:{display:"flex",overflowX:"auto",borderBottom:"1px solid var(--hairline)",padding:"0 8px",scrollbarWidth:"none"},children:l.map((d,v)=>{var k;return e.jsxs("button",{onClick:()=>f(v),style:{display:"flex",alignItems:"center",gap:6,whiteSpace:"nowrap",padding:"10px 12px",fontSize:13,fontWeight:500,background:"transparent",border:0,cursor:"pointer",fontFamily:"inherit",borderBottom:s===v?"2px solid var(--indigo-light)":"2px solid transparent",color:s===v?"var(--indigo-light)":"var(--text-3)"},children:[e.jsx("span",{style:{maxWidth:140,overflow:"hidden",textOverflow:"ellipsis"},children:d.name}),e.jsx("span",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:18,height:16,padding:"0 5px",borderRadius:999,fontSize:11.5,fontWeight:600,background:s===v?"rgba(99,102,241,0.18)":"var(--surface-3)",color:s===v?"var(--indigo-light)":"var(--text-3)"},children:d.count??(((k=d.voters)==null?void 0:k.length)||0)})]},v)})}),e.jsxs("div",{className:"cv2-modal-list",style:{maxHeight:320},children:[(c.voters||[]).length===0&&e.jsx("div",{className:"empty",children:i.empty}),(c.voters||[]).map((d,v)=>e.jsxs("div",{className:"cv2-target-row",style:{cursor:"default"},children:[e.jsx("div",{className:"av",children:d.imgUrl?e.jsx("img",{src:d.imgUrl,alt:""}):Cl(lt(d.name,{jid:d.jid,phone:d.phone,lidLabel:i.member}))}),e.jsxs("div",{className:"info",children:[e.jsxs("div",{className:"nm",children:[lt(d.name,{jid:d.jid,phone:d.phone,lidLabel:i.member})||i.noName,d.isMe&&e.jsx("span",{style:{marginLeft:6,fontSize:11.5,color:"var(--indigo-light)",fontWeight:500},children:i.you})]}),e.jsx("div",{className:"ph",children:El(d.votedAt)})]})]},v))]})]})})}const ri={pt:{loading:"Carregando convite...",errorTitle:"Não foi possível carregar este convite",errorDesc:"O link pode estar expirado, ter sido revogado ou ser inválido.",blockedTitle:"Grupos indisponíveis neste dispositivo",errByCode:{400:{t:"Não foi possível carregar este convite",d:"Tente de novo em instantes."},401:{t:"Você foi removido deste grupo",d:"O link está válido — mas este número não volta a este grupo, porque um admin o removeu."},404:{t:"Este grupo não existe mais",d:"O grupo foi apagado."},405:{t:"Você foi removido da comunidade",d:"Fora da comunidade, este número não entra nos grupos dela."},409:{t:"Você já está neste grupo",d:"Este número já é membro — o grupo está na sua lista de conversas."},410:{t:"O link de convite foi redefinido",d:"Um admin gerou um link novo. Peça o link atual."},412:{t:"A comunidade está cheia",d:"Não há vaga na comunidade deste grupo."},419:{t:"O grupo está cheio",d:"O grupo atingiu o limite de membros."},426:{t:"Este grupo exige aprovação",d:"Um admin precisa aprovar a entrada, e o pedido não pôde ser enviado por aqui."},429:{t:"Limite de grupos atingido",d:"Este número entrou em grupos demais agora há pouco. Tente mais tarde."},436:{t:"Convite indisponível",d:"O WhatsApp bloqueou temporariamente a entrada por este link."}},createdAt:"Criado em",members:"membros",join:"Entrar no grupo",request:"Enviar pedido",cancel:"Cancelar",joining:"Entrando...",requesting:"Env
2iando pedido...",approvalHint:"Um admin deve aprovar seu pedido.",successJoined:"Você entrou no grupo!",successRequested:"Pedido enviado. Aguarde aprovação do admin.",errAccept:"Falha ao processar o convite.",readMore:"Ler mais",readLess:"Ler menos",close:"Fechar"},en:{loading:"Loading invite...",errorTitle:"Unable to load this invite",errorDesc:"The link may be expired, revoked, or invalid.",blockedTitle:"Groups unavailable on this device",errByCode:{400:{t:"Unable to load this invite",d:"Please try again in a moment."},401:{t:"You were removed from this group",d:"The link is valid — but this number can't rejoin, because an admin removed it."},404:{t:"This group no longer exists",d:"The group was deleted."},405:{t:"You were removed from the community",d:"Outside the community, this number can't join its groups."},409:{t:"You are already in this group",d:"This number is already a member — the group is in your chat list."},410:{t:"The invite link was reset",d:"An admin generated a new link. Ask for the current one."},412:{t:"The community is full",d:"There is no room left in this group's community."},419:{t:"The group is full",d:"The group reached its member limit."},426:{t:"This group requires approval",d:"An admin must approve the request, and it couldn't be sent from here."},429:{t:"Group join limit reached",d:"This number joined too many groups recently. Try again later."},436:{t:"Invite unavailable",d:"WhatsApp temporarily blocked joining through this link."}},createdAt:"Created on",members:"members",join:"Join group",request:"Send request",cancel:"Cancel",joining:"Joining...",requesting:"Sending request...",approvalHint:"An admin must approve your request.",successJoined:"You joined the group!",successRequested:"Request sent. Awaiting admin approval.",errAccept:"Failed to process the invite.",readMore:"Read more",readLess:"Read less",close:"Close"},es:{loading:"Cargando invitación...",errorTitle:"No se pudo cargar esta invitación",errorDesc:"El enlace puede estar vencido, revocado o no ser válido.",blockedTitle:"Grupos no disponibles en este dispositivo",errByCode:{400:{t:"No se pudo cargar esta invitación",d:"Inténtalo de nuevo en un momento."},401:{t:"Te eliminaron de este grupo",d:"El enlace es válido — pero este número no vuelve a este grupo, porque un admin lo eliminó."},404:{t:"Este grupo ya no existe",d:"El grupo fue eliminado."},405:{t:"Te eliminaron de la comunidad",d:"Fuera de la comunidad, este número no entra a sus grupos."},409:{t:"Ya estás en este grupo",d:"Este número ya es miembro — el grupo está en tu lista de chats."},410:{t:"El enlace de invitación fue restablecido",d:"Un admin generó un enlace nuevo. Pide el enlace actual."},412:{t:"La comunidad está llena",d:"No hay lugar en la comunidad de este grupo."},419:{t:"El grupo está lleno",d:"El grupo alcanzó el límite de miembros."},426:{t:"Este grupo requiere aprobación",d:"Un admin debe aprobar la entrada, y la solicitud no pudo enviarse desde aquí."},429:{t:"Límite de grupos alcanzado",d:"Este número entró a demasiados grupos hace poco. Inténtalo más tarde."},436:{t:"Invitación no disponible",d:"WhatsApp bloqueó temporalmente la entrada por este enlace."}},createdAt:"Creado el",members:"miembros",join:"Entrar al grupo",request:"Enviar solicitud",cancel:"Cancelar",joining:"Entrando...",requesting:"Enviando solicitud...",approvalHint:"Un admin debe aprobar tu solicitud.",successJoined:"¡Te uniste al grupo!",successRequested:"Solicitud enviada. Esperando aprobación del admin.",errAccept:"No se pudo procesar la invitación.",readMore:"Leer más",readLess:"Leer menos",close:"Cerrar"}};function Al(t,n="pt"){if(!t)return null;const o=Number(t),i=o>1e12?o:o*1e3,s=new Date(i);if(isNaN(s.getTime()))return null;try{return s.toLocaleDateString(n==="pt"?"pt-BR":n==="es"?"es-ES":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"})}catch{return s.toLocaleDateString()}}async function fa(t,n,o){const i=localStorage.getItem("token"),s=await fetch("/api/wa/chat/group-action",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({sessionId:t,action:n,payload:o})});if(!s.ok){const l=await s.json().catch(()=>({})),c=new Error((l==null?void 0:l.error)||`HTTP ${s.status}`);throw c.waCode=typeof(l==null?void 0:l.code)=="number"?l.code:null,c}const f=await s.json();return(f==null?void 0:f.result)??f}async function Rl(t,n){if(!n)return null;try{const o=localStorage.getItem("token"),i=t?`jid=${encodeURIComponent(n)}&sessionId=${encodeURIComponent(t)}`:`jid=${encodeURIComponent(n)}`,s=await fetch(`/api/wa/chat/avatar?${i}`,{headers:{Authorization:`Bearer ${o}`}});if(!s.ok)return null;const f=await s.json();return(f==null?void 0:f.url)||(f==null?void 0:f.imgUrl)||null}catch{return null}}function Ml({code:t,v4:n,sessionId:o,canGroup:i=!0,locale:s="pt",onClose:f}){var ve;const l=ri[s]||ri.pt,[c,d]=r.useState(null),[v,k]=r.useState(null),[x,P]=r.useState(!0),[A,y]=r.useState(null),[w,m]=r.useState(null),[I,U]=r.useState(!1),[u,p]=r.useState(null),[b,se]=r.useState(!1);r.useEffect(()=>{const _=$=>{$.key==="Escape"&&!I&&(f==null||f())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[I,f]),r.useEffect(()=>{if(!i){P(!1),m("blocked"),y(Jt(s));return}let _=!0;return(async()=>{try{P(!0),y(null),m(null);const $=await fa(o,"getInviteInfo",{code:t});if(!_)return;d($||{}),$!=null&&$.pictureUrl?k($.pictureUrl):$!=null&&$.id&&Rl(o,$.id).then(X=>{_&&X&&k(X)})}catch($){_&&(m($.waCode??null),y($.message||String($)))}finally{_&&P(!1)}})(),()=>{_=!1}},[t,o]);const C=!!(c!=null&&c.joinApprovalMode),H=(c==null?void 0:c.size)||((ve=c==null?void 0:c.participants)==null?void 0:ve.length)||0,Q=Al(c==null?void 0:c.creation,s),O=String((c==null?void 0:c.desc)||"").trim(),oe=O.length>140,ke=!oe||b?O:O.slice(0,140)+"…",Ae=async()=>{var _;if(!I){if(!i){Ks.error(Jt(s));return}U(!0);try{const $=n?await fa(o,"acceptInviteV4",{key:n.key,inviteMessage:n.inviteMessage}):await fa(o,"acceptInvite",{code:t});(typeof $=="string"?$:($==null?void 0:$.id)||null)&&!C?(p("joined"),Ks.success(l.successJoined)):(p("requested"),Ks.success(l.successRequested)),setTimeout(()=>f==null?void 0:f(),1400)}catch($){const X=typeof $.waCode=="number"?(_=l.errByCode)==null?void 0:_[$.waCode]:null,ce=(X==null?void 0:X.d)||$.message||l.errAccept;/304|already|joined|pending/i.test($.message||"")&&C?(p("requested"),Ks.success(l.successRequested),setTimeout(()=>f==null?void 0:f(),1400)):Ks.error(ce)}finally{U(!1)}}};return e.jsx("div",{className:"cv2-fork fixed inset-0 z-[80] flex items-center justify-center bg-black/70 backdrop-blur-sm",onClick:()=>!I&&(f==null?void 0:f()),children:e.jsxs("div",{className:"relative bg-dark-800 border border-gray-700/60 rounded-[10px] w-full max-w-sm mx-4 overflow-hidden shadow-2xl",onClick:_=>_.stopPropagation(),children:[e.jsx(ne,{content:l.close,position:"left",children:e.jsx("button",{onClick:()=>!I&&(f==null?void 0:f()),className:"absolute top-3 right-3 text-gray-500 hover:text-gray-200 transition-colors p-1.5 rounded-md hover:bg-dark-700",disabled:I,"aria-label":l.close,children:e.jsx(ya,{size:18})})}),e.jsxs("div",{className:"px-8 pt-10 pb-7",children:[x&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-10",children:[e.jsx(Sr,{size:32,className:"text-indigo-400 animate-spin mb
2-3"}),e.jsx("p",{className:"text-sm text-gray-400",children:l.loading})]}),!x&&A&&(()=>{var D;const _=typeof w=="number"?(D=l.errByCode)==null?void 0:D[w]:null,$=w==="blocked",X=$?l.blockedTitle:(_==null?void 0:_.t)||l.errorTitle,ce=$?A:(_==null?void 0:_.d)||l.errorDesc,Z=!$&&!_;return e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-red-500/10 border border-red-500/30 flex items-center justify-center mb-4",children:e.jsx(ko,{size:26,className:"text-red-400"})}),e.jsx("p",{className:"text-base font-semibold text-gray-100 mb-1.5",children:X}),e.jsx("p",{className:"text-xs text-gray-500 leading-relaxed",children:ce}),Z&&e.jsx("p",{className:"text-xs text-gray-600 mt-3 font-mono break-all px-2",children:A})]})})(),!x&&!A&&c&&e.jsxs("div",{className:"flex flex-col items-center text-center",children:[e.jsx("div",{className:"w-24 h-24 rounded-full overflow-hidden bg-indigo-500/15 border border-gray-700/50 flex items-center justify-center mb-5 shrink-0",children:v?e.jsx("img",{src:v,alt:c.subject||(s==="en"?"Group":"Grupo"),className:"w-full h-full object-cover",onError:()=>k(null)}):e.jsx(nn,{size:40,className:"text-indigo-400/70"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-50 leading-tight px-3 break-words",children:c.subject||(s==="en"?"Group":"Grupo")}),Q&&e.jsxs("p",{className:"text-xs text-gray-500 mt-1.5",children:[l.createdAt," ",Q]}),H>0&&e.jsxs("div",{className:"mt-4 inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-dark-700 border border-gray-700/50 text-xs text-gray-400",children:[e.jsx(nn,{size:11}),"+",H," ",l.members]}),O&&e.jsxs("div",{className:"mt-5 text-sm text-gray-300 leading-relaxed whitespace-pre-wrap break-words px-2",children:[ke,oe&&e.jsx("button",{type:"button",onClick:()=>se(_=>!_),className:"ml-1 text-indigo-400 hover:text-indigo-300 font-medium text-xs",children:b?l.readLess:l.readMore})]}),C&&!u&&e.jsx("p",{className:"text-xs text-amber-300/90 mt-5",children:l.approvalHint}),u&&e.jsxs("div",{className:"mt-5 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-emerald-500/15 border border-emerald-500/30 text-emerald-300 text-xs font-medium",children:[e.jsx(fi,{size:13}),u==="joined"?l.successJoined:l.successRequested]}),!u&&e.jsxs("div",{className:"mt-7 w-full flex items-center justify-center gap-1",children:[e.jsx("button",{type:"button",onClick:()=>!I&&(f==null?void 0:f()),disabled:I,className:"flex-1 max-w-[140px] py-2.5 text-sm text-emerald-400 hover:text-emerald-300 font-semibold transition-colors disabled:opacity-50",children:l.cancel}),e.jsxs("button",{type:"button",onClick:Ae,disabled:I,className:"flex-1 max-w-[180px] py-2.5 px-4 bg-gray-900 hover:bg-black border border-gray-700 text-white text-sm font-semibold rounded-full transition-colors disabled:opacity-60 disabled:cursor-not-allowed inline-flex items-center justify-center gap-2",children:[I&&e.jsx(Sr,{size:14,className:"animate-spin"}),I?C?l.requesting:l.joining:C?l.request:l.join]})]})]})]})]})})}const $l=["tom","clima","exige você","exige voce","status","tone","mood","needs you","climate","ánimo","animo","requiere","requiere de ti","tono"],ii=/^\s*(?:[-•*–—]|\d+[.)])\s+/,Tl=/^\s*\d+[.)]\s+/,Fl=/^\s{0,3}#{1,6}\s+(.*)$/,oi=/(\*\*[^*\n]+\*\*|`[^`\n]+`|\*[^*\n]+\*)/g;function $s(t,n){const o=String(t??"");if(!o)return null;const i=[];let s=0,f;for(oi.lastIndex=0;(f=oi.exec(o))!==null;){f.index>s&&i.push(o.slice(s,f.index));const l=f[0];l.startsWith("**")?i.push(e.jsx("b",{children:l.slice(2,-2)},`${n}b${f.index}`)):l.startsWith("`")?i.push(e.jsx("code",{children:l.slice(1,-1)},`${n}c${f.index}`)):i.push(e.jsx("i",{children:l.slice(1,-1)},`${n}i${f.index}`)),s=f.index+l.length}return s<o.length&&i.push(o.slice(s)),i.length?i:o}const ja=t=>String(t||"").replace(/\*\*|`|^\*|\*$/g,"").trim();function ci(t){let n=String(t||"").trim();const o=n.match(/^\*\*([\s\S]+)\*\*$/);o&&!o[1].includes("**")&&(n=o[1].trim());let i=n.match(/^\*\*([^*\n]{1,44}?):?\*\*\s*[:—–-]?\s+([\s\S]+)$/);return i?{label:i[1].trim(),body:i[2].trim()}:(i=n.match(/^\*\*([^*\n]{1,60}
2?):?\*\*\s*$/),i&&!/:\s/.test(i[1])?{label:i[1].trim(),body:""}:(i=n.match(/^([^—\n]{1,44}?)\s+[—–]\s+([\s\S]+)$/),i&&!/[.!?]$/.test(i[1])?{label:ja(i[1]),body:i[2].trim()}:(i=n.match(/^([^:\n]{1,44}?):\s+([\s\S]+)$/),i&&!/[.!?,;]$/.test(i[1])?{label:ja(i[1]),body:i[2].trim()}:{label:"",body:n})))}function _l(t){const n=String(t||"").trim();return/^[⚠️!]+\s*/.test(n)?{flag:"warn",text:n.replace(/^[⚠️!]+\s*/,"")}:/^[✅✔☑]\s*/.test(n)?{flag:"done",text:n.replace(/^[✅✔☑]\s*/,"")}:/[⚠️]$/.test(n)?{flag:"warn",text:n.replace(/\s*[⚠️]+$/,"")}:/[✅✔☑]$/.test(n)?{flag:"done",text:n.replace(/\s*[✅✔☑]+$/,"")}:{flag:"",text:n}}function Dl(t){const n=String(t??"").replace(/\r\n?/g,`
3`).split(`
4`),o=[],i=[];let s=null,f=[];const l=()=>{f.length&&(o.push({t:"p",text:f.join(" ").trim()}),f=[])},c=()=>{s!=null&&s.items.length&&o.push({t:"ul",ordered:s.ordered,items:s.items}),s=null};for(const d of n){const v=d.replace(/\s+$/,"");if(!v.trim()){l(),c();continue}const k=v.match(Fl);if(k){l(),c(),o.push({t:"h",text:ja(k[1])});continue}if(ii.test(v)){l();const A=Tl.test(v);(!s||s.ordered!==A)&&(c(),s={ordered:A,items:[]});const{flag:y,text:w}=_l(v.replace(ii,""));s.items.push({...ci(w),flag:y});continue}if(s&&/^\s{2,}\S/.test(d)){const A=s.items[s.items.length-1];if(A){A.body=`${A.body} ${v.trim()}`.trim();continue}}
4const{label:x,body:P}=ci(v);if(x&&P&&$l.includes(x.toLowerCase())){l(),c(),i.push({label:x,body:P});continue}c(),f.push(v.trim())}return l(),c(),i.length&&o.push({t:"meta",items:i}),o}function Ll(t){const n=[];for(const o of t){const i=n[n.length-1];if(i&&o.label&&i.label===o.label){i.lines.push({body:o.body,flag:o.flag});continue}n.push({label:o.label,lines:[{body:o.body,flag:o.flag}]})}return n}const Pl=(t,n)=>t.length<=16&&n.length<=92;function li({text:t,className:n=""}){const o=Dl(t);return o.length?e.jsx("div",{className:`cvai-md ${n}`.trim(),children:o.map((i,s)=>{if(i.t==="h")return e.jsx("h4",{className:"cvai-md-h",children:$s(i.text,`h${s}`)},s);if(i.t==="p")return e.jsx("p",{className:"cvai-md-p",children:$s(i.text,`p${s}`)},s);if(i.t==="meta")return e.jsx("div",{className:"cvai-md-meta",children:i.items.map((c,d)=>e.jsxs("div",{className:"cvai-md-chip",children:[e.jsx("span",{className:"k",children:c.label}),e.jsx("span",{className:"v",children:$s(c.body,`m${s}_${d}`)})]},d))},s);const f=i.ordered?"ol":"ul",l=i.ordered?i.items.map(c=>({label:c.label,lines:[{body:c.body,flag:c.flag}]})):Ll(i.items);return e.jsx(f,{className:`cvai-md-list${i.ordered?" ord":""}`,children:l.map((c,d)=>{const v=c.lines.length===1?c.lines[0]:null,k=v&&c.label&&Pl(c.label,v.body);return e.jsxs("li",{className:`cvai-md-li${v!=null&&v.flag?` ${v.flag}`:""}${k?" inl":""}`,children:[c.label&&e.jsx("span",{className:"cvai-md-k",children:$s(c.label,`k${s}_${d}`)}),v?v.body&&e.jsx("span",{className:"cvai-md-v",children:$s(v.body,`v${s}_${d}`)}):e.jsx("span",{className:"cvai-md-sub",children:c.lines.map((x,P)=>e.jsx("span",{className:`cvai-md-v${x.flag?` ${x.flag}`:""}`,children:$s(x.body,`s${s}_${d}_${P}`)},P))})]},d)})},s)})}):null}const zl=[{key:"summary",pt:"Resumo",en:"Summary",es:"Resumen"},{key:"unread",pt:"Desde que li",en:"Since read",es:"Desde leído"},{key:"agreements",pt:"Combinado",en:"Agreed",es:"Acordado"},{key:"pending",pt:"Pendências",en:"Pending",es:"Pendientes"},{key:"foryou",pt:"Pra você",en:"For you",es:"Para ti"},{key:"whois",pt:"Quem é quem",en:"Who is who",es:"Quién es quién"},{key:"tasks",pt:"Tarefas",en:"Tasks",es:"Tareas"},{key:"ficha",pt:"Ficha",en:"Card",es:"Ficha"},{key:"ensaio",pt:"Ensaio",en:"Practice",es:"Ensayo"},{key:"ask",pt:"Perguntar",en:"Ask",es:"Preguntar"}],di={full_name:{pt:"Nome",en:"Name",es:"Nombre"},company:{pt:"Empresa",en:"Company",es:"Empresa"},email:{pt:"E-mail",en:"Email",es:"Correo"},deal_value:{pt:"Valor do negócio",en:"Deal value",es:"Valor"},source:{pt:"Origem",en:"Source",es:"Origen"},temperature:{pt:"Temperatura",en:"Temperature",es:"Temperatura"}};function Wl({sessionId:t,jid:n,chatName:o,isGroup:i=!1,locale:s="pt",onClose:f,onUseText:l}){var _;const c=$=>$[s]||$.pt,[d,v]=r.useState("summary"),[k,x]=r.useState({}),[P,A]=r.useState(""),[y,w]=r.useState(!1),[m,I]=r.useState(null),[U,u]=r.useState(null),p=r.useCallback(async()=>{var $,X,ce;u({loading:!0});try{const[{data:Z},{data:D}]=await Promise.all([M.post("/wa/kanban/contact/ensure",{sessionId:t,jid:n}),M.post("/wa/chat-ai/crm-scan",{sessionId:t,jid:n})]),ae=Z.card||{},K=ae.profile||{},Re={full_name:K.fullName||"",company:ae.company||"",email:K.email||"",deal_value:ae.deal_value!=null&&Number(ae.deal_value)>0?String(ae.deal_value):"",source:K.source||"",temperature:ae.temperature||""},_e={};for(const Y of Object.keys(di)){const Oe=($=D.fields)==null?void 0:$[Y];Oe!=null&&Oe!==""&&!Re[Y]&&(_e[Y]=Oe)}u({cardId:Z.id,card:ae,cur:Re,found:_e,promises:D.promises||[],applied:{}})}catch(Z){u({error:((ce=(X=Z==null?void 0:Z.response)==null?void 0:X.data)==null?void 0:ce.error)||c({pt:"Não deu pra montar a ficha agora",en:"Could not build the card right now",es:"No se pudo armar la ficha ahora"})})}},[t,n]),[b,se]=r.useState({turns:[],busy:!1,fb:null,input:""}),C=async $=>{se(X=>({...X,busy:!0}));try{const{data:X}=await M.post("/wa/chat-ai/roleplay",{sessionId:t,jid:n,action:"reply",turns:$});se(ce=>({...ce,busy:!1,turns:[...$,{role:"contact",text:X.text}]}))}catch(X){se(ce=>{var Z,D;return{...ce,busy:!1,fb:{error:((D=(Z=X==null?void 0:X.response)==null?void 0:Z.data)==null?void 0:D.error)||
4c({pt:"IA indisponível agora",en:"AI unavailable",es:"IA no disponible"})}}})}},H=()=>{const $=b.input.trim();if(!$||b.busy)return;const X=[...b.turns,{role:"you",text:$}];se(ce=>({...ce,input:"",turns:X})),C(X)},Q=async()=>{se($=>({...$,busy:!0}));try{const{data:$}=await M.post("/wa/chat-ai/roleplay",{sessionId:t,jid:n,action:"feedback",turns:b.turns});se(X=>({...X,busy:!1,fb:$}))}catch($){se(X=>{var ce,Z;return{...X,busy:!1,fb:{error:((Z=(ce=$==null?void 0:$.response)==null?void 0:ce.data)==null?void 0:Z.error)||c({pt:"IA indisponível agora",en:"AI unavailable",es:"IA no disponible"})}}})}};r.useEffect(()=>{d==="ensaio"&&b.turns.length===0&&!b.busy&&!b.fb&&C([])},[d]);const O=async($,X)=>{if(!(U!=null&&U.cardId))return;const ce={};$==="company"?ce.company=X:$==="deal_value"?ce.deal_value=X:$==="temperature"?ce.temperature=X:ce.profile={...U.card.profile||{},[$==="full_name"?"fullName":$]:X};try{await M.put(`/wa/kanban/cards/${U.cardId}/profile`,ce),u(Z=>({...Z,applied:{...Z.applied,[$]:!0},card:{...Z.card,...ce.profile?{profile:ce.profile}:ce}}))}catch(Z){u(D=>{var ae,K;return{...D,error:((K=(ae=Z==null?void 0:Z.response)==null?void 0:ae.data)==null?void 0:K.error)||c({pt:"Falha ao aplicar",en:"Failed to apply",es:"No se pudo aplicar"})}})}},oe=async($,X)=>{if(!(U!=null&&U.cardId))return;let ce=$.when?new Date($.when):null;(!ce||isNaN(ce.getTime())||ce.getTime()<Date.now())&&(ce=new Date,ce.setDate(ce.getDate()+1),ce.setHours(9,0,0,0));try{await M.post(`/wa/kanban/cards/${U.cardId}/reminder`,{title:$.text.slice(0,160),remind_at:ce.toISOString()}),u(Z=>({...Z,promises:Z.promises.map((D,ae)=>ae===X?{...D,done:!0}:D)}))}catch(Z){u(D=>{var ae,K;return{...D,error:((K=(ae=Z==null?void 0:Z.response)==null?void 0:ae.data)==null?void 0:K.error)||c({pt:"Falha ao criar lembrete",en:"Failed to create reminder",es:"No se pudo crear el recordatorio"})}})}},ke=r.useCallback(async $=>{x(X=>({...X,[$]:{loading:!0}}));try{const{data:X}=await M.post("/wa/chat-ai/read",{sessionId:t,jid:n,view:$});x(ce=>({...ce,[$]:{text:X.text}}))}catch(X){x(ce=>{var Z,D;return{...ce,[$]:{error:((D=(Z=X==null?void 0:X.response)==null?void 0:Z.data)==null?void 0:D.error)||c({pt:"IA indisponível agora",en:"AI unavailable",es:"IA no disponible"})}}})}},[t,n]);r.useEffect(()=>{if(d==="ficha"){U||p();return}d!=="ask"&&!k[d]&&ke(d)},[d,k,ke,U,p]);const Ae=async()=>{var X,ce;const $=P.trim();if(!(!$||y)){w(!0),I(null);try{const{data:Z}=await M.post("/wa/chat-ai/ask",{sessionId:t,jid:n,question:$});I({text:Z.text})}catch(Z){I({error:((ce=(X=Z==null?void 0:Z.response)==null?void 0:X.data)==null?void 0:ce.error)||c({pt:"IA indisponível agora",en:"AI unavailable",es:"IA no disponible"})})}finally{w(!1)}}},ve=d==="ask"?null:k[d];return e.jsx("div",{className:"cv2-modal-backdrop",onClick:f,children:e.jsxs("div",{className:"cv2-modal cvai-panel",onClick:$=>$.stopPropagation(),children:[e.jsxs("div",{className:"cvai-panel-head",children:[e.jsxs("strong",{children:["✦ ",c({pt:"Esta conversa",en:"This chat",es:"Este chat"})]}),e.jsx("span",{className:"cvai-panel-sub",children:o||""}),e.jsx("span",{style:{flex:1}}),e.jsx(ne,{content:c({pt:"Atualizar",en:"Refresh",es:"Actualizar"}),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:()=>{d==="ficha"?p():d!=="ask"&&ke(d)},children:"↻"})}),e.jsx(ne,{content:c({pt:"Fechar",en:"Close",es:"Cerrar"}),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:f,children:"✕"})})]}),e.jsx("div",{className:"cvai-tabs",children:zl.filter($=>(!["ficha","ensaio"].includes($.key)||!i)&&(!["foryou","whois","tasks"].includes($.key)||i)).map($=>e.jsx("button",{className:`cvai-tab${d===$.key?" on":""}`,onClick:()=>v($.key),children:c($)},$.key))}),e.jsxs("div",{className:"cvai-panel-body",children:[d!=="ask"&&e.jsxs(e.Fragment,{children:[(ve==null?void 0:ve.loading)&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),(ve==null?void 0:ve.error)&&e.jsx("div",{className:"cvai-err",children:ve.error}),(ve==null?void 0:ve.text)&&e.jsx("div",{className:"cvai-readout",children:e.jsx(li,{text:ve.text})})]}),d==="ficha"&&e.jsxs(e.Fragment,{children:[(U==null?void 0:U.loading)&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),(U==null?void 0:U.error)&&e.jsx("div",{className:"cvai-err",children:U.error}),U&&!U.loading&&!U.error&&e.jsxs(e.Fragment,{children:[Object.keys(U.found).length===0&&e.jsx("div",{className:"cvai-hint",style:{marginBottom:10},children:c({pt:"Nada novo pra ficha — o que a conversa mostra já está preenchido.",en:"Nothing new — what the chat shows is already filled.",es:"Nada nuevo — lo que muestra el chat ya está."})}),Object.entries(U.found).map(([$,X])=>e.jsxs("div",{className:"cvai-field",style:{cursor:"default"},children:[e.jsx("span",{className:"fk",children:c(di[$])}),e.jsx("span",{className:"fv",children:$==="deal_value"?`R$ ${Number(X).toFixed(2)}`:String(X)}),U.applied[$]?e.jsx("span",{style:{color:"var(--green)",fontSize:12,flexShrink:0},children:"✓"}):e.jsx("button",{className:"cvai-mini",onClick:()=>O($,X),children:c({pt:"Aplicar",en:"Apply",es:"Aplicar"})})]},$)),U.promises.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cvai-hint",style:{margin:"12px 2px 7px",fontWeight:600,color:"var(--indigo-light)"},children:["✦ ",c({pt:"Você prometeu",en:"You promised",es:"Prometiste"})]}),U.promises.map(($,X)=>e.jsxs("div",{className:"cvai-field",style:{cursor:"default"},children:[e.jsxs("span",{className:"fv",style:{fontWeight:450},children:["“",$.text,"”",$.when?e.jsxs("span",{style:{color:"var(--text-3)"}
4,children:[" · ",new Date($.when).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})]}):null]}),$.done?e.jsxs("span",{style:{color:"var(--green)",fontSize:12,flexShrink:0},children:["✓ ",c({pt:"lembrete",en:"reminder",es:"record."})]}):e.jsx("button",{className:"cvai-mini",onClick:()=>oe($,X),children:c({pt:"Criar lembrete",en:"Remind me",es:"Recordar"})})]},X))]}),e.jsx("div",{className:"cvai-hint",style:{marginTop:10},children:c({pt:"A IA nunca sobrescreve campo preenchido — só oferece o que falta. Lembrete sem data vai pra amanhã às 09:00.",en:"AI never overwrites filled fields. Undated reminders go to tomorrow 9am.",es:"La IA nunca sobrescribe campos llenos."})})]})]}),d==="ensaio"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cvai-hint",style:{marginBottom:9},children:c({pt:"A IA faz o papel DESTE contato (mesmo caso, mesmo jeito). Treine a resposta — nada aqui toca a conversa real.",en:"The AI plays THIS contact. Practice your reply — nothing touches the real chat.",es:"La IA hace de ESTE contacto. Nada toca el chat real."})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:7,marginBottom:10},children:[b.turns.map(($,X)=>e.jsx("div",{style:{display:"flex",justifyContent:$.role==="you"?"flex-end":"flex-start"},children:e.jsx("span",{style:{maxWidth:"82%",padding:"7px 11px",fontSize:13,lineHeight:1.45,whiteSpace:"pre-wrap",borderRadius:$.role==="you"?"12px 12px 4px 12px":"12px 12px 12px 4px",background:$.role==="you"?"color-mix(in srgb, var(--indigo) 13%, var(--surface))":"var(--surface-2)",border:`1px solid ${$.role==="you"?"color-mix(in srgb, var(--indigo) 26%, transparent)":"var(--hairline)"}`,color:"var(--text)"},children:$.text})},X)),b.busy&&!b.fb&&e.jsxs("div",{className:"cvai-hint",children:["✦ ",c({pt:"contato digitando…",en:"contact typing…",es:"escribiendo…"})]})]}),b.fb&&!b.fb.error&&e.jsxs("div",{className:"cvai-readout",style:{marginBottom:10},children:[c({pt:"Nota do ensaio",en:"Practice score",es:"Nota"}),": ",e.jsxs("b",{children:[b.fb.score??"—","/10"]}),b.fb.good?`
5✔ ${b.fb.good}`:"",(b.fb.tips||[]).map(($,X)=>`
6→ ${$}`).join("")]}),((_=b.fb)==null?void 0:_.error)&&e.jsx("div",{className:"cvai-err",children:b.fb.error}),!b.fb&&e.jsxs("div",{className:"cvai-askrow",children:[e.jsx("input",{className:"cvai-input",value:b.input,disabled:b.busy,onChange:$=>se(X=>({...X,input:$.target.value})),onKeyDown:$=>{$.key==="Enter"&&H()},placeholder:c({pt:"Sua resposta de treino…",en:"Your practice reply…",es:"Tu respuesta…"})}),e.jsx("button",{className:"cvai-btn",disabled:b.busy||!b.input.trim(),onClick:H,children:"➤"})]}),e.jsxs("div",{className:"cvai-foot",style:{paddingLeft:0},children:[!b.fb&&b.turns.some($=>$.role==="you")&&e.jsx("button",{className:"cvai-mini",disabled:b.busy,onClick:Q,children:c({pt:"Encerrar e avaliar",en:"Finish & score",es:"Terminar y evaluar"})}),e.jsx("button",{className:"cvai-mini ghost",disabled:b.busy,onClick:()=>{se({turns:[],busy:!1,fb:null,input:""}),C([])},children:c({pt:"Recomeçar",en:"Restart",es:"Reiniciar"})})]})]}),d==="ask"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cvai-askrow",children:[e.jsx("input",{className:"cvai-input",value:P,autoFocus:!0,onChange:$=>A($.target.value),onKeyDown:$=>{$.key==="Enter"&&Ae()},placeholder:c({pt:"ex.: qual o prazo de troca? o que ficou de valor?",en:"e.g. what did we agree on price?",es:"ej.: ¿qué quedó de valor?"})}),e.jsx("button",{className:"cvai-btn",disabled:y||!P.trim(),onClick:Ae,children:y?"…":c({pt:"Perguntar",en:"Ask",es:"Preguntar"})})]}),e.jsx("div",{className:"cvai-hint",style:{padding:"2px 2px 8px"},children:c({pt:"Consulta sua — o contato não vê nada.",en:"Your query — the contact sees nothing.",es:"Consulta tuya — el contacto no ve nada."})}),y&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{})]}),(m==null?void 0:m.error)&&e.jsx("div",{className:"cvai-err",children:m.error}),(m==null?void 0:m.text)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cvai-readout",children:e.jsx(li,{text:m.text})}),e.jsxs("div",{className:"cvai-foot",style:{paddingLeft:0},children:[e.jsx("button",{className:"cvai-mini",onClick:()=>{l==null||l(m.text),f==null||f()},children:c({pt:"Usar como resposta",en:"Use as reply",es:"Usar como respuesta"})}),e.jsx("button",{className:"cvai-mini ghost",onClick:()=>{try{navigator.clipboard.writeText(m.text)}catch{}},children:c({pt:"Copiar",en:"Copy",es:"Copiar"})})]})]})]})]})]})})}function ql({state:t,locale:n="pt",onClose:o}){const i=(l,c,d)=>n==="en"?c:n==="es"?d:l,s=(t==null?void 0:t.fields)||[],f=async l=>{try{await navigator.clipboard.writeText(l),W.success(i("Copiado","Copied","Copiado"))}catch{W.error(i("Falha ao copiar","Copy failed","Error al copiar"))}};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:o,children:e.jsxs("div",{className:"cv2-modal cvai-panel",style:{maxWidth:420},onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"cvai-panel-head",children:[e.jsxs("strong",{children:["✦ ",i("Dados da mensagem","Message data","Datos del mensaje")]}),e.jsx("span",{style:{flex:1}}),e.jsx(ne,{content:i("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:o,children:"✕"})})]}),e.jsxs("div",{className:"cvai-panel-body",children:[(t==null?void 0:t.loading)&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),(t==null?void 0:t.error)&&e.jsx("div",{className:"cvai-err",children:t.error}),(t==null?void 0:t.summary)&&e.jsx("div",{className:"cvai-readout",style:{marginBottom:10},children:t.summary}),!(t!=null&&t.loading)&&!(t!=null&&t.error)&&!(t!=null&&t.summary)&&s.length===0&&e.jsx("div",{className:"cvai-hint",children:i("Nenhum dado estruturado nesta mensagem.","No structured data in this message.","Sin datos estructurados en este mensaje.")}),s.map((l,c)=>e.jsxs("button",{className:"cvai-field",onClick:()=>f(l.value),children:[e.jsx("span",{className:"fk",children:l.label}),e.jsx("span",{className:"fv",children:l.value}),e.jsx("span",{className:"fc",children:"⧉"})]},c)),s.length>1&&e.jsx("div",{className:"cvai-foot",style:{paddingLeft:0},children:e.jsx("button",{className:"cvai-mini",onClick:()=>f(s.map(l=>`${l.label}: ${l.value}`).join(`
7`)),children:i("Copiar tudo","Copy all","Copiar todo")})})]})]})})}const Bl=t=>(n,o,i)=>t==="en"?o:t==="es"?i:n;function Ul(t,n,o){const i=(n||"").trim();switch(t){case"image":return o("Foto","Photo","Foto");case"video":return o("Vídeo","Video","Video");case"audio":return o("Áudio","Audio","Audio");case"document":return i||o("Documento","Document","Documento");case"sticker":return o("Figurinha","Sticker","Figurita");case"contact":return"👤 "+(i||o("Contato","Contact","Contacto"));case"location":return o("Localização","Location","Ubicación");case"poll":return i||o("Enquete","Poll","Encuesta");default:return i}}function Ol(t,n="pt"){const o=Bl(n),i=t&&t.lastMessage||null;if(!i)return"";const s=i.msgType,f=(i.text||"").replace(/\s+/g," ").trim();if(s==="reaction"){const d=i.reaction||{};if(!d.emoji)return"";const v=Ul(d.targetType,d.targetText,o);return`${i.fromMe?o("Você reagiu com","You reacted with","Reaccionaste con"):`${d.actor?d.actor+" ":""}${o("reagiu com","reacted with","reaccionó con")}`} ${d.emoji}${v?` ${o("a:","to:","a:")} "${v}"`:""}`}if(s==="revoked"||s==="revoke")return i.fromMe?o("Você apagou esta mensagem","You deleted this message","Eliminaste este mensaje"):o("Esta mensagem foi apagada","This message was deleted","Este mensaje fue eliminado");const l=i.fromMe?o("Você: ","You: ","Tú: "):t.isGroup&&i.pushName?`${i.pushName}: `:"",c=(()=>{switch(s){case"image":return`🖼 ${f||o("Foto","Photo","Foto")}`;case"video":return`🎬 ${f||o("Vídeo","Video","Video")}`;case"audio":return`🎤 ${o("Áudio","Audio","Audio")}
7`;case"document":return`📄 ${f||o("Documento","Document","Documento")}`;case"poll":return`📊 ${f||o("Enquete","Poll","Encuesta")}`;case"sticker":return o("Figurinha","Sticker","Figurita");case"location":return`📍 ${o("Localização","Location","Ubicación")}`;case"contact":case"contacts":return`👤 ${f||o("Contato","Contact","Contacto")}`;case"unsupported":return o("Mensagem não suportada","Unsupported message","Mensaje no compatible");default:return f}})();return c?`${l}${c}`:""}const Gl=(t,n="pt")=>{if(!t.lastTs||t.lastFromMe!==!1||!t.needsReply)return null;const o=Math.floor((Date.now()/1e3-Number(t.lastTs))/3600);return o<1?n==="en"?"waiting <1h":n==="es"?"esperando <1h":"aguarda <1h":o<48?n==="en"?`waiting ${o}h`:n==="es"?`esperando ${o}h`:`aguarda ${o}h`:n==="en"?`waiting ${Math.floor(o/24)}d`:n==="es"?`esperando ${Math.floor(o/24)}d`:`aguarda ${Math.floor(o/24)}d`};function Vl({sessionId:t,chats:n=[],locale:o="pt",onSelectChat:i,onClose:s,onCount:f}){const l=(I,U,u)=>o==="en"?U:o==="es"?u:I,[c,d]=r.useState(null),[v,k]=r.useState(0),[x,P]=r.useState(null),A=r.useRef(!0);r.useEffect(()=>()=>{A.current=!1},[]);const y=r.useCallback(async()=>{const{data:I}=await M.get("/wa/chat-ai/insights",{params:{sessionId:t}}),u=Object.entries(I.insights||{}).map(([p,b])=>({jid:p,...b})).filter(p=>p.needsReply||(p.priority||0)>=45).sort((p,b)=>(b.priority||0)-(p.priority||0)||(p.lastTs||0)-(b.lastTs||0));return A.current&&(d(u),f==null||f(u.length)),u},[t,f]);r.useEffect(()=>{let I=!1;return(async()=>{var U,u;try{await y();for(let p=0;p<4&&!I;p++){const{data:b}=await M.post("/wa/chat-ai/triage-sync",{sessionId:t});if(I)return;if(!b.queued){k(0);break}if(k(b.queued),await new Promise(se=>setTimeout(se,13e3)),I)return;await y()}if(I)return;k(0),await y()}catch(p){I||P(((u=(U=p==null?void 0:p.response)==null?void 0:U.data)==null?void 0:u.error)||l("IA indisponível agora","AI unavailable","IA no disponible"))}})(),()=>{I=!0}},[t]);const w=r.useCallback(I=>n.find(U=>U.jid===I)||null,[n]),m=I=>{const U=w(I.jid);U?i==null||i(U):i==null||i({jid:I.jid,name:I.name||I.jid.split("@")[0],isGroup:!1}),s==null||s()};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:s,children:e.jsxs("div",{className:"cv2-modal cvai-panel",style:{maxWidth:640},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"cvai-panel-head",children:[e.jsxs("strong",{children:["✦ ",l("Radar — o que precisa de você","Radar — what needs you","Radar — lo que te necesita")]}),e.jsx("span",{style:{flex:1}}),v>0&&e.jsx("span",{className:"cvai-hint",style:{color:"var(--indigo-light)"},children:l(`analisando ${v} ${v===1?"conversa":"conversas"}…`,`analyzing ${v} ${v===1?"chat":"chats"}…`,`analizando ${v}…`)}),e.jsx(ne,{content:l("Reanalisar","Re-analyze","Reanalizar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:async()=>{var I,U;try{const{data:u}=await M.post("/wa/chat-ai/triage-sync",{sessionId:t});if(!A.current)return;k(u.queued||0),setTimeout(()=>{A.current&&(k(0),y().catch(()=>{}))},13e3)}catch(u){A.current&&P(((U=(I=u==null?void 0:u.response)==null?void 0:I.data)==null?void 0:U.error)||l("Não deu pra reanalisar agora","Could not re-analyze","No se pudo reanalizar"))}},children:"↻"})}),e.jsx(ne,{content:l("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:s,children:"✕"})})]}),e.jsxs("div",{className:"cvai-panel-body",children:[x&&e.jsx("div",{className:"cvai-err",children:x}),c===null&&!x&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),c!==null&&c.length===0&&v===0&&e.jsx("div",{className:"cvai-hint",style:{padding:"18px 4px",textAlign:"center",fontSize:13},children:l("Nada exige você agora. 🎉","Nothing needs you right now. 🎉","Nada te necesita ahora. 🎉")}),c!==null&&c.map(I=>{const U=w(I.jid),u=U&&(U.name||U.pushName)||I.name||I.jid.split("@")[0],p=Ol(U,o)||I.lastText||"",b=Gl(I,o),se=(I.priority||0)>=70;return e.jsxs("button",{className:"cvrad-i",onClick:()=>m(I),children:[e.jsx("span",{className:"cvrad-av",children:String(u).trim().charAt(0).toUpperCase()||"?"}),e.jsxs("span",{className:"cvrad-c",children:[e.jsx("span",{className:"cvrad-n",children:u}),e.jsx("span",{className:"cvrad-p",children:p||"…"})]}),e.jsxs("span",{className:"cvrad-tags",children:[e.jsx("span",{className:`cvrad-why${se?" hi":""}`,children:I.reason||l("prioridade alta","high priority","prioridad alta")}),b&&e.jsx("span",{className:"cvrad-wait",children:b})]})]},I.jid)}),e.jsx("div",{className:"cvai-hint",style:{marginTop:8},children:l("Sua lista de conversas não muda nada — o Radar é uma janela à parte. Análise só roda com o painel aberto (últimos 7 dias, 1:1).","Your chat list never changes — the Radar is a separate window. Analysis only runs while open.","Tu lista de chats no camb
7ia — el Radar es aparte.")})]})]})})}const Hl={saudacao:"Saudação",sondagem:"Sondagem",objecao:"Objeção",fechamento:"Fechamento"},ui={ok:{txt:"ok",c:"var(--green)"},partial:{txt:"parcial",c:"var(--amber)"},miss:{txt:"falta",c:"var(--rose)"},na:{txt:"—",c:"var(--text-4)"}};function Jl({v:t}){const n=ui[t]||ui.na;return e.jsx("span",{style:{fontSize:10.5,fontWeight:600,padding:"2px 8px",borderRadius:999,whiteSpace:"nowrap",color:n.c,background:`color-mix(in srgb, ${n.c} 12%, transparent)`,border:`1px solid color-mix(in srgb, ${n.c} 26%, transparent)`},children:n.txt})}function Yl({sessionId:t,locale:n="pt",onClose:o}){const i=(m,I,U)=>n==="en"?I:n==="es"?U:m,[s,f]=r.useState(7),[l,c]=r.useState(null),[d,v]=r.useState(0),[k,x]=r.useState(null),P=r.useRef(!0);r.useEffect(()=>()=>{P.current=!1},[]);const A=r.useCallback(async m=>{const{data:I}=await M.get("/wa/chat-ai/qa-report",{params:{sessionId:t,days:m}});P.current&&c(I)},[t]),y=r.useRef(s);r.useEffect(()=>{y.current=s},[s]),r.useEffect(()=>{let m=!1;return(async()=>{var I,U;try{for(let u=0;u<4&&!m;u++){const{data:p}=await M.post("/wa/chat-ai/qa-sync",{sessionId:t});if(m)return;if(!p.queued){v(0);break}if(v(p.queued),await new Promise(b=>setTimeout(b,16e3)),m)return;await A(y.current)}if(m)return;v(0),await A(y.current)}catch(u){m||x(((U=(I=u==null?void 0:u.response)==null?void 0:I.data)==null?void 0:U.error)||i("IA indisponível agora","AI unavailable","IA no disponible"))}})(),()=>{m=!0}},[t]),r.useEffect(()=>{A(s).catch(()=>{})},[s,A]);const w=l!=null&&l.biggestGap?`${Hl[l.biggestGap.item]||l.biggestGap.item} (${l.biggestGap.pct}%)`:null;return e.jsx("div",{className:"cv2-modal-backdrop",onClick:o,children:e.jsxs("div",{className:"cv2-modal cvai-panel",style:{maxWidth:760},onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"cvai-panel-head",children:[e.jsxs("strong",{children:["✦ ",i("Qualidade dos atendimentos","Service quality","Calidad de atención")]}),e.jsx("span",{style:{display:"flex",gap:4,marginLeft:10},children:[7,14].map(m=>e.jsxs("button",{className:`cvai-tab${s===m?" on":""}`,style:{height:24},onClick:()=>f(m),children:[m,"d"]},m))}),e.jsx("span",{style:{flex:1}}),d>0&&e.jsx("span",{className:"cvai-hint",style:{color:"var(--indigo-light)"},children:i(`avaliando ${d}…`,`scoring ${d}…`,`evaluando ${d}…`)}),e.jsx(ne,{content:i("Reavaliar","Re-score","Reevaluar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:async()=>{var m,I;try{const{data:U}=await M.post("/wa/chat-ai/qa-sync",{sessionId:t});if(!P.current)return;v(U.queued||0),setTimeout(()=>{P.current&&(v(0),A(y.current).catch(()=>{}))},16e3)}catch(U){P.current&&x(((I=(m=U==null?void 0:U.response)==null?void 0:m.data)==null?void 0:I.error)||i("Não deu pra reavaliar agora","Could not re-score","No se pudo reevaluar"))}},children:"↻"})}),e.jsx(ne,{content:i("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:o,children:"✕"})})]}),e.jsxs("div",{className:"cvai-panel-body",children:[k&&e.jsx("div",{className:"cvai-err",children:k}),!l&&!k&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:26,flexWrap:"wrap",marginBottom:14},children:[e.jsxs("div",{children:[e.jsx("div",{className:"cvai-hint",style:{textTransform:"uppercase",letterSpacing:".07em",fontSize:10},children:i("Nota média","Avg score","Nota media")}),e.jsx("div",{style:{fontFamily:"var(--fm, monospace)",fontSize:26,fontWeight:600,color:"var(--text)"},children:l.avgScore??"—"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"cvai-hint",style:{textTransform:"uppercase",letterSpacing:".07em",fontSize:10},children:i("Avaliados","Evaluated","Evaluados")}),e.jsx("div",{style:{fontFamily:"var(--fm, monospace)",fontSize:26,fontWeight:600,color:"var(--text)"},children:l.total??0})]}),w&&e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{className:"cvai-hint",style:{textTransform:"uppercase",letterSpacing:".07em",fontSize:10},children:i("Maior buraco","Biggest gap","Mayor hueco")}),e.jsx("div",{style:{fontSize:15,fontWeight:650,color:"var(--amber)",marginTop:6},children:w})]})]}),(l.attendants||[]).length===0&&d===0&&e.jsx("div",{className:"cvai-hint",style:{padding:"10px 2px"},children:i("Nenhum atendimento avaliável no período.","Nothing to evaluate in this period.","Nada evaluable en el período.")}),(l.attendants||[]).length>0&&e.jsx("div",{style:{overflowX:"auto"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12.5},children:[e.jsx("thead",{children:e.jsx("tr",{children:[i("Atendente","Agent","Agente"),i("Nota","Score","Nota"),"Saud.","Sond.","Obj.","Fech.",i("O que corrigir","What to fix","Qué corregir")].map((m,I)=>e.jsx("th",{style:{textAlign:"left",fontFamily:"var(--fm, monospace)",fontSize:9.5,fontWeight:600,letterSpacing:".08em",textTransform:"uppercase",color:"var(--text-4)",padding:"7px 9px",borderBottom:"1px solid var(--hairline)",whiteSpace:"nowrap"},children:m},I))})}),e.jsx("tbody",{children:(l.attendants||[]).map(m=>e.jsxs("tr",{children:[e.jsxs("td",{style:{padding:"9px",borderBottom:"1px solid var(--hairline)",fontWeight:600,color:"var(--text)",whiteSpace:"nowrap"},children:[m.name||i("Dono","Owner","Dueño")," ",e.jsxs("span",{style:{color:"var(--text-4)",fontWeight:400},children:["· ",m.evaluated]})]}),e.jsx("td",{style:{padding:"9px",borderBottom:"1px solid var(--hairline)"},children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:7},children:[e.jsx("span",{style:{fontFamily:"var(--fm, monospace)",fontWeight:600,color:"var(--text)"},children:m.avgScore??"—"}),m.avgScore!=null&&e.jsx("span",{style:{width:54,height:5,borderRadius:3,background:"var(--fill)",overflow:"hidden",display:"inline-block"},children:e.jsx("span",{style:{display:"block",height:"100%",width:`${Math.max(0,Math.min(100,m.avgScore*10))}%`,borderRadius:3,background:m.avgScore>=8?"var(--green)":m.avgScore>=6?"var(--amber)":"var(--rose)"}})})]})}),["saudacao","sondagem","objecao","fechamento"].map(I=>e.jsx("td",{style:{padding:"9px",borderBottom:"1px solid var(--hairline)"},children:e.jsx(Jl,{v:m.items[I]})},I)),e.jsx("td",{style:{padding:"9px",borderBottom:"1px solid var(--hairline)",color:"var(--text-3)",maxWidth:260},children:m.topFix||"—"})]}
7,m.userId))})]})}),(l.lossReasons||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"cvai-hint",style:{margin:"14px 2px 7px",fontWeight:600,color:"var(--indigo-light)"},children:["✦ ",i("Motivos de perda no período","Loss reasons","Motivos de pérdida")]}),(l.lossReasons||[]).map((m,I)=>e.jsxs("div",{className:"cvai-field",style:{cursor:"default"},children:[e.jsx("span",{className:"fv",style:{fontWeight:450},children:m.reason}),e.jsxs("span",{style:{fontFamily:"var(--fm, monospace)",fontSize:12,color:"var(--text-3)",flexShrink:0},children:["×",m.count]})]},I))]}),e.jsx("div",{className:"cvai-hint",style:{marginTop:12},children:i(`Avaliação automática de conversas 1:1 com diálogo — atendimentos dos últimos ${s} dias. Nota e checklist são da IA: use como radar, a palavra final é sua.`,`Automatic evaluation of 1:1 chats with dialogue — last ${s} days. AI scores are a radar; final word is yours.`,`Evaluación automática — últimos ${s} días. La palabra final es tuya.`)})]})]})]})})}function Ql({sessionId:t=null,locale:n="pt",onClose:o,onChanged:i}){const s=(C,H,Q)=>n==="en"?H:n==="es"?Q:C,[f,l]=r.useState(null),[c,d]=r.useState({id:null,trigger:"",instruction:""}),[v,k]=r.useState(!1),[x,P]=r.useState(null),[A,y]=r.useState(!1);r.useEffect(()=>{M.get("/wa/chat-ai/tone").then(({data:C})=>P(C.tone||"")).catch(()=>P(""))},[]);const w=async()=>{var C,H;try{await M.put("/wa/chat-ai/tone",{tone:x}),y(!0),setTimeout(()=>y(!1),1800)}catch(Q){W.error(((H=(C=Q==null?void 0:Q.response)==null?void 0:C.data)==null?void 0:H.error)||s("Falha ao salvar","Save failed","Error"))}},m=()=>M.get("/wa/chat-ai/shortcuts").then(({data:C})=>l(C.shortcuts||[])).catch(()=>l([]));r.useEffect(()=>{m()},[]);const I=async()=>{var Q,O;const C=c.trigger.trim().replace(/^\//,""),H=c.instruction.trim();if(!C||H.length<5){W.error(s("Preencha gatilho e instrução","Fill trigger and instruction","Rellena gatillo e instrucción"));return}k(!0);try{await M.post("/wa/chat-ai/shortcuts",{id:c.id||void 0,trigger:C,instruction:H}),d({id:null,trigger:"",instruction:""}),await m(),i==null||i(),W.success(s("Atalho salvo","Shortcut saved","Atajo guardado"))}catch(oe){W.error(((O=(Q=oe==null?void 0:oe.response)==null?void 0:Q.data)==null?void 0:O.error)||s("Falha ao salvar","Save failed","Error al guardar"))}finally{k(!1)}},[U,u]=r.useState(null),p=async()=>{var C,H;if(!(!t||U==="busy")){u("busy");try{const{data:Q}=await M.post("/wa/chat-ai/suggest-shortcuts",{sessionId:t});u(Q.suggestions||[])}catch(Q){u([]),W.error(((H=(C=Q==null?void 0:Q.response)==null?void 0:C.data)==null?void 0:H.error)||s("IA indisponível agora","AI unavailable","IA no disponible"))}}},b=async C=>{var H,Q;try{await M.post("/wa/chat-ai/shortcuts",{trigger:C.trigger,instruction:C.instruction}),u(O=>Array.isArray(O)?O.filter(oe=>oe.trigger!==C.trigger):O),await m(),i==null||i(),W.success(`/${C.trigger} `+s("criado","created","creado"))}catch(O){W.error(((Q=(H=O==null?void 0:O.response)==null?void 0:H.data)==null?void 0:Q.error)||s("Falha ao criar","Create failed","Error"))}},se=async C=>{try{await M.delete(`/wa/chat-ai/shortcuts/${C}`),await m(),i==null||i()}catch{W.error(s("Falha ao remover","Delete failed","Error al borrar"))}};return e.jsx("div",{className:"cv2-modal-backdrop",onClick:o,children:e.jsxs("div",{className:"cv2-modal cvai-panel",style:{maxWidth:480},onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"cvai-panel-head",children:[e.jsxs("strong",{children:["✦ ",s("IA do chat — ajustes","Chat AI — settings","IA del chat — ajustes")]}),e.jsx("span",{style:{flex:1}}),e.jsx(ne,{content:s("Fechar","Close","Cerrar"),position:"bottom",children:e.jsx("button",{className:"cvai-x",onClick:o,children:"✕"})})]}),e.jsxs("div",{className:"cvai-panel-body",children:[e.jsx("div",{className:"cvai-hint secao",children:s("Tom da casa","House tone","Tono de la casa")}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:7,marginBottom:16},children:[e.jsx("textarea",{className:"cvai-input",style:{height:60,padding:"8px 11px",resize:"vertical",fontFamily:"inherit"},value:x??"",disabled:x===null,maxLength:400,onChange:C=>P(C.target.value),placeholder:s("ex.: Trate por você. Direto e caloroso. Emoji só se o contato usar primeiro. Nunca prometa prazo sem confirmar.","e.g.: Warm and direct. Emoji only if the contact uses first.","ej.: Directo y cálido.")}),e.jsx("div",{style:{display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:e.jsx("button",{className:"cvai-btn",disabled:x===null,onClick:w,children:A?"✓ "+s("Salvo","Saved","Guardado"):s("Salvar tom","Save tone","Guardar tono")})}),e.jsx("span",{className:"cvai-hint",children:s("Vale pra reescrita, sugestões e atalhos. Se o dispositivo tem Agente I.A., a persona dele prevalece.","Used by rewrite, suggestions and shortcuts. An assigned AI agent persona takes precedence.","Vale para reescritura, sugerencias y atajos.")})]}),e.jsx("div",{className:"cvai-hint secao",style:{marginTop:20},children:s("Atalhos /","Shortcuts /","Atajos /")}),e.jsx("div",{className:"cvai-hint",style:{marginBottom:10},children:s("Digite /gatilho no campo de mensagem e a IA escreve seguindo a instrução — usando o contexto da conversa aberta. O mesmo atalho sai diferente em cada chat.","Type /trigger in the message box and the AI writes it following the instruction — with the open chat as context.","Escribe /gatillo y la IA redacta según la instrucción — con el contexto del chat abierto.")}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:14},children:[e.jsxs("div",{style:{display:"flex",gap:8}
7,children:[e.jsx("input",{className:"cvai-input",style:{maxWidth:150},value:c.trigger,onChange:C=>d(H=>({...H,trigger:C.target.value})),placeholder:s("/prazo","/eta","/plazo")}),e.jsx("button",{className:"cvai-btn",disabled:v,onClick:I,children:c.id?s("Salvar","Save","Guardar"):s("Criar","Create","Crear")}),c.id&&e.jsx("button",{className:"cvai-mini ghost",onClick:()=>d({id:null,trigger:"",instruction:""}),children:s("Cancelar","Cancel","Cancelar")})]}),e.jsx("textarea",{className:"cvai-input",style:{height:74,padding:"8px 11px",resize:"vertical",fontFamily:"inherit"},value:c.instruction,onChange:C=>d(H=>({...H,instruction:C.target.value})),maxLength:600,placeholder:s("ex.: Informe o prazo padrão: pedidos até 14h saem no mesmo dia e chegam em 2 a 5 dias úteis. Peça o CEP se ainda não tiver.","e.g.: State the standard ETA...","ej.: Informa el plazo estándar...")})]}),t&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("button",{className:"cvai-mini",disabled:U==="busy",onClick:p,children:U==="busy"?s("minerando seus atendimentos…","mining your chats…","minando…"):"✦ "+s("Sugerir atalhos do que o time mais escreve","Suggest from what the team writes most","Sugerir de lo más escrito")}),Array.isArray(U)&&U.length===0&&U!=="busy"&&e.jsx("div",{className:"cvai-hint",style:{marginTop:6},children:s("Nada repetido o bastante pra virar atalho (ainda).","Nothing repeated enough yet.","Nada repetido aún.")}),Array.isArray(U)&&U.map(C=>e.jsxs("div",{className:"cvai-field",style:{cursor:"default",marginTop:7},children:[e.jsxs("span",{className:"fk",style:{width:110},children:["/",C.trigger]}),e.jsxs("span",{className:"fv",style:{fontWeight:400,color:"var(--text-2)",whiteSpace:"normal"},children:[C.instruction.slice(0,120),C.instruction.length>120?"…":""]}),e.jsx("button",{className:"cvai-mini",onClick:()=>b(C),children:s("Criar","Create","Crear")})]},C.trigger))]}),f===null&&e.jsxs("div",{className:"cvai-skel",children:[e.jsx("span",{}),e.jsx("span",{})]}),f&&f.length===0&&e.jsx("div",{className:"cvai-hint",children:s("Nenhum atalho ainda. Crie o primeiro acima.","No shortcuts yet.","Sin atajos aún.")}),f&&f.map(C=>e.jsxs("div",{className:"cvai-field",style:{cursor:"default"},children:[e.jsxs("span",{className:"fk",style:{width:84},children:["/",C.trigger]}),e.jsxs("span",{className:"fv",style:{fontWeight:400,color:"var(--text-2)",whiteSpace:"normal"},children:[C.instruction.slice(0,110),C.instruction.length>110?"…":""]}),e.jsx(ne,{content:s("Editar","Edit","Editar"),position:"top",children:e.jsx("button",{className:"cvai-x",onClick:()=>d({id:C.id,trigger:"/"+C.trigger,instruction:C.instruction}),children:"✎"})}),e.jsx(ne,{content:s("Remover","Delete","Borrar"),position:"top",children:e.jsx("button",{className:"cvai-x",onClick:()=>se(C.id),children:"🗑"})})]},C.id))]})]})})}const In=t=>Array.isArray(t)?t.filter(n=>!xi(n)):[],en="cv2.activeSessionId",Kl=30,pi=(t,n="pt")=>{const o=t!=null&&t.cycleEnd?new Date(t.cycleEnd).toLocaleDateString(n==="en"?"en-US":n==="es"?"es":"pt-BR",{day:"2-digit",month:"long"}):null,i=t&&t.total>0?n==="en"?` (used ${t.used} of ${t.total})`:n==="es"?` (usaste ${t.used} de ${t.total})`:` (usou ${t.used} de ${t.total})`:"";return n==="en"?`Monthly limit for new chats reached${i}. This contact hasn’t replied to you yet, so the chat can’t be started right now — the limit resets${o?` on ${o}`:" next cycle"}. Chats with people who already replied to you work normally.`:n==="es"?`Se alcanzó el límite mensual de conversaciones nuevas${i}. Este contacto aún no te ha respondido, así que la conversación no se puede iniciar ahora — el límite se renueva${o?` el ${o}`:" en el próximo ciclo"}. Las conversaciones con quienes ya te respondieron siguen con normalidad.`:`Limite mensal de conversas novas atingido${i}. Este contato ainda não te respondeu, então a conversa não pode ser iniciada agora — o limite renova${o?` em ${o}`:" no próximo ciclo"}. Conversas de quem já te respondeu seguem normais.`},Xl=new Set(["connected","connecting"]),ga=[],An=t=>(Array.isArray(t==null?void 0:t.sessions)?t.sessions:Array.isArray(t)?t:[]).filter(o=>o&&Xl.has(o.status)&&!o.waba_is_banned),Zl=()=>e.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",ry:"2"}),e.jsx("line",{x1:"12",y1:"18",x2:"12.01",y2:"18"})]});function hd(){var tr,sr,nr,ar,rr,ir;const{socket:t,setSelectedChatJid:n,clearUnreadCount:o,voiceCall:i}=So()||{},{locale:s}=ds(),{user:f}=mi(),l=Co(),c=Eo(),d=r.useRef(null),[v,k]=r.useState(Io);r.useCallback(()=>{k(a=>Ao(a==="dark"?"light":"dark"))},[]),r.useEffect(()=>Ro(k),[]);const[x,P]=r.useState(()=>{try{return localStorage.getItem("chat_pinnedSessionId")||null}catch{return null}}),A=a=>{!a||!ze.current||M.post("/wa/chat/read",{sessionId:ze.current,keys:[{remoteJid:a,fromMe:!1,id:"dummy"}]}).finally(()=>{o&&o()}).catch(()=>{})},[y,w]=r.useState([]),[m,I]=r.useState(!1),U=r.useRef((()=>{try{const a=new URLSearchParams(window.location.search);return a.get("jid")&&a.get("session")||null}catch{return null}})()),[u,p]=r.useState(()=>{try{return U.current||localStorage.getItem("chat_pinnedSessionId")||localStorage.getItem(en
7)||null}catch{return null}}),b=r.useMemo(()=>y.find(a=>a.session_id===u)||null,[y,u]),[se,C]=r.useState({sid:null,list:ga}),H=se.sid===u?se.list:ga,Q=r.useCallback(a=>{C(g=>{const h=typeof a=="function"?a(g.list):a;return h===g.list?g:{sid:g.sid,list:h}})},[]),O=r.useCallback((a,g,h)=>!a||a!==ze.current||h!==void 0&&h!==(hs.current||"").trim()?!1:(C({sid:a,list:g}),!0),[]),[oe,ke]=r.useState(!1),[Ae,ve]=r.useState(!1),[_,$]=r.useState("all"),[X,ce]=r.useState(""),[Z,D]=r.useState([]),[ae,K]=r.useState([]),Re=r.useRef(null),_e=r.useRef(null),[Y,Oe]=r.useState(!1),Je=200,[Be,Qe]=r.useState(0),[Me,De]=r.useState(!1),xt=r.useRef(Je),[ut,mt]=r.useState([]),[st,kt]=r.useState(!1),At=r.useCallback(()=>{const a=ze.current;a&&M.get(`/wa/chat/labels?sessionId=${a}`).then(({data:g})=>mt(In(g==null?void 0:g.labels))).catch(()=>{})},[]),[dt,jt]=r.useState([]),[G,me]=r.useState(!1),[Se,Fe]=r.useState({}),[le,Xe]=r.useState(0),[z,Ce]=r.useState(0),[ye,at]=r.useState({enabled:!1,columns:[],columnId:null,cardId:null}),[L,Ze]=r.useState(null),[rt,_t]=r.useState(null),[Yt,Qt]=r.useState(0),[Rt,de]=r.useState(null),[$t,Ut]=r.useState([]),q=r.useRef(null),[he,et]=r.useState(null),[re,tt]=r.useState(!1),[pt,Et]=r.useState(!1),[wt,He]=r.useState([]),[Ls,rn]=r.useState(!1),[Kt,us]=r.useState(null),[Ps,Ot]=r.useState(!0),[J,We]=r.useState(!1),[it,ot]=r.useState({}),[ft,Xt]=r.useState({}),[Ee,ht]=r.useState(null),[Lt,ps]=r.useState({canSendFreeform:!0,loaded:!1}),[ss,Zt]=r.useState(!1),[Pt,Gt]=r.useState(0);r.useEffect(()=>{const a=()=>Gt(g=>g+1);return window.addEventListener("pragmaz:cv2-prefs",a),()=>window.removeEventListener("pragmaz:cv2-prefs",a)},[]);const[zs,Ws]=r.useState(!1),[Ci,Mn]=r.useState(!1),[Na,qs]=r.useState(null),[Ei,$n]=r.useState(!1),[Ii,ka]=r.useState(null),[Ai,Tn]=r.useState(!1),[Ri,Sa]=r.useState(!1);r.useEffect(()=>{const a=()=>Sa(!0);return window.addEventListener("pragmaz:cv2-ai-settings",a),()=>window.removeEventListener("pragmaz:cv2-ai-settings",a)},[]);const Mi=!(f!=null&&f.team_role)||(f==null?void 0:f.team_role)==="owner"||(f==null?void 0:f.team_role)==="manager"||(f==null?void 0:f.is_team_owner)===!0;r.useEffect(()=>{$n(!1),ka(null),Tn(!1)},[u]),r.useEffect(()=>{Mn(!1),qs(null)},[L==null?void 0:L.jid]);const[$i,Bs]=r.useState(null),[Tt,Fn]=r.useState(null),Ti=r.useMemo(()=>Tt?{x:Tt.x,y:Tt.y}:null,[Tt==null?void 0:Tt.x,Tt==null?void 0:Tt.y]);r.useEffect(()=>{u&&Zt(wn(u,"infoPanelOpen",!1)===!0)},[u,L==null?void 0:L.jid,Pt]);const[_n,Dn]=r.useState(null),[Ln,Ca]=r.useState(null),[Ea,Pn]=r.useState(null),[on,Ia]=r.useState(!1),[ys,zn]=r.useState(new Set),[ms,zt]=r.useState(null),cn=r.useRef(null),ln=r.useRef(null),[Fi,Wn]=r.useState([]),[_i,Aa]=r.useState([]),[Di,ws]=r.useState(null),[Li,Ra]=r.useState(!1),[Pi,Ma]=r.useState(!1),[$a,dn]=r.useState(null),[zi,Us]=r.useState(!1),[Wi,Os]=r.useState(null),[Ta,qn]=r.useState(!1),[Fa,Bn]=r.useState(null),[qi,Un]=r.useState(null),$e=r.useRef(new Map),Ns=r.useRef(new Map);r.useRef(new Map);const xe=r.useRef(null),ze=r.useRef(u),_a=r.useRef(null),un=r.useRef(null),ns=r.useRef(_),hs=r.useRef(""),Da=r.useRef(null),On=r.useRef(f),pn=r.useRef(0),as=r.useRef(!0),La=r.useRef(!1),ks=r.useRef(null);r.useEffect(()=>{xe.current=L},[L]),r.useEffect(()=>{const a=typeof window<"u"?window.visualViewport:null;if(!a)return;const g=document.documentElement,h=()=>{const S=window.innerHeight-a.height-a.offsetTop;g.style.setProperty("--kb",(S>60?S:0)+"px")};return a.addEventListener("resize",h),a.addEventListener("scroll",h),h(),()=>{a.removeEventListener("resize",h),a.removeEventListener("scroll",h),g.style.removeProperty("--kb")}},[]),r.useEffect(()=>{ze.current=u},[u]);const Pa=r.useRef(b);r.useEffect(()=>{Pa.current=b},[b]);const mn=r.useRef([]);r.useEffect(()=>{mn.current=H},[H]);const za=r.useRef([]);r.useEffect(()=>{za.current=wt},[wt]);const Ss=r.useCallback(async a=>{var h,S;const g=ze.current;if(!(!g||!a))try{const F=new URLSearchParams({sessionId:g,jid:a,limit:"50"}),{data:j}=await M.get(`/wa/chat/messages?${F}`);
7if(((h=xe.current)==null?void 0:h.jid)!==a)return;const B=Array.isArray(j==null?void 0:j.messages)?j.messages.filter(Ke=>Ke.jid===a):[];if(!B.length)return;const ee=$e.current.get(a)||[],Le=new Set(ee.map(Ke=>Ke.msgId)),Ie=Ns.current.get(a)||[],fe=[...B,...Ie].filter(Ke=>Ke.msgId&&!Le.has(Ke.msgId));if(!fe.length)return;const Ue=[...ee,...fe].sort((Ke,Ft)=>(Ke.timestamp||0)-(Ft.timestamp||0));$e.current.set(a,Ue),((S=xe.current)==null?void 0:S.jid)===a&&He(Ue)}catch{}},[]);r.useEffect(()=>{const a=setInterval(()=>{var h;if(document.visibilityState!=="visible")return;const g=(h=xe.current)==null?void 0:h.jid;g&&Ss(g)},2e4);return()=>clearInterval(a)},[Ss]),r.useEffect(()=>{let a=0;const g=()=>{var F;if(document.visibilityState!=="visible")return;const h=Date.now();if(h-a<3e3)return;a=h;const S=(F=xe.current)==null?void 0:F.jid;S&&Ss(S)};return document.addEventListener("visibilitychange",g),window.addEventListener("focus",g),()=>{document.removeEventListener("visibilitychange",g),window.removeEventListener("focus",g)}},[Ss]);const Bi=r.useMemo(()=>{for(let a=wt.length-1;a>=0;a--){const g=wt[a];if(g&&!g.fromMe&&g.msgId)return g.msgId}return null},[wt]),Gs=r.useCallback(a=>{var S;const g=ze.current,h=a||((S=xe.current)==null?void 0:S.jid);if(!g||!h){Ut([]);return}M.get(`/wa/chat/pins?sessionId=${encodeURIComponent(g)}&jid=${encodeURIComponent(h)}`).then(({data:F})=>{var j;((j=xe.current)==null?void 0:j.jid)===h&&Ut(Array.isArray(F==null?void 0:F.pins)?F.pins:[])}).catch(()=>{})},[]);r.useEffect(()=>{q.current=Gs},[Gs]),r.useEffect(()=>{if(!u||!(L!=null&&L.jid)){Ut([]);return}Gs(L.jid)},[u,L==null?void 0:L.jid,Gs]);const[Ui,Vs]=r.useState(null),es=r.useRef(null),Oi=r.useCallback((a=7e3)=>{es.current&&clearTimeout(es.current),es.current=setTimeout(()=>Vs(null),a)},[]);r.useEffect(()=>{if(es.current&&(clearTimeout(es.current),es.current=null),Vs(null),!u||!(L!=null&&L.jid)||L.isGroup)return;let a=!0;return M.get("/wa/kanban/contact/followup",{params:{sessionId:u,jid:L.jid}}).then(({data:g})=>{a&&Vs((g==null?void 0:g.followup)||null)}).catch(()=>{}),()=>{a=!1}},[u,L==null?void 0:L.jid,L==null?void 0:L.isGroup]),r.useEffect(()=>{ns.current=_},[_]),r.useEffect(()=>{hs.current=X},[X]),r.useEffect(()=>{On.current=f},[f]),r.useEffect(()=>{const a=new AbortController;return M.get("/wa/sessions?minimal=true",{signal:a.signal}).then(({data:g})=>{w(An(g))}).catch(()=>{}).finally(()=>I(!0)),()=>a.abort()},[]);const Wa=r.useRef(!1);r.useEffect(()=>{var g;if(!y.length)return;if(!Wa.current){Wa.current=!0;const h=y.filter(ee=>ee.status==="connected"),S=x&&h.some(ee=>ee.session_id===x),F=u&&y.some(ee=>ee.session_id===u),B=U.current&&y.some(ee=>ee.session_id===U.current)?U.current:S?x:F?u:((g=h[0]||y[0])==null?void 0:g.session_id)||null;if(B&&B!==u){p(B);try{localStorage.setItem(en,B)}catch{}}return}if(u&&y.find(h=>h.session_id===u))return;const a=y.find(h=>h.status==="connected")||y[0];if(a){p(a.session_id);try{localStorage.setItem(en,a.session_id)}catch{}}},[y,u,x]),r.useEffect(()=>{if(u)try{localStorage.setItem(en,u)}catch{}},[u]);const qa=r.useRef(u),Gn=r.useRef(new Map),Cs=r.useCallback(a=>Gn.current.get(a)||{filter:"all",search:""},[]);r.useEffect(()=>{if(qa.current===u)return;qa.current=u;const{filter:a,search:g}=Cs(u);ns.current=a,hs.current=g,$(a),ce(g),Ze(null),_t(null),He([]);try{$e.current.clear()}catch{}ot({}),Xt({}),C({sid:null,list:ga}),Xe(0),Ce(0),mt([]),ht(null),n&&n(null)},[u]),r.useEffect(()=>{if(!u||!y.length)return;const a=y.find(g=>g.session_id===u);if(a){if(a.sync_status==="syncing"){const g=a.sync_last_batch_at?new Date(a.sync_last_batch_at).getTime():0,h=g>0&&Date.now()-g>3e4;ht(S=>({messages:Math.max(a.sync_messages||0,(S==null?void 0:S.messages)||0),chats:Math.max(a.sync_chats||0,(S==null?void 0:S.chats)||0),contacts:Math.max(a.sync_contacts||0,(S==null?void 0:S.contacts)||0),progress:Math.max(a.sync_progress||0,(S==null?void 0:S.progress)||0),paused:h,lastBatchAt:(S==null?void 0:S.lastBatchAt)||Date.now()}))}else if(a.sync_status==="done")ht(null);else if(a.provider_type==="coexistence"){const g=a.waba_history_sync_status;ht(g==="syncing"||g==="waiting_user"?h=>{const S=(h==null?void 0:h.progress)||0;return{messages:Math.max(a.waba_history_messages||0,(h==null?void 0:h.messages)||0),chats:Math.max(a.waba_history_chats||0,(h==null?void 0:h.chats)||0),contacts:0,progress:S,paused:!1,indeterminate:S<=0,kind:"coex"}}:null)}}},[u,y]);const Gi=r.useCallback(a=>{const g=ze.current;g&&Gn.current.set(g,{...Cs(g),filter:a}),ns.current=a,$(a)},[Cs]),rs=r.useCallback(a=>{const g=ze.current;g&&Gn.current.set(g,{...Cs(g),search:a}),hs.current=a,ce(a)},[Cs]);r.useEffect(()=>{if(!u)return;const a=Cs(u);if(_!==a.filter||X!==a.search)return;Oe(!0);const g=new URLSearchParams({sessionId:u,filter:_.startsWith("label:")?`labels:${_.slice(6)}`:_,...X.trim()?{search:X.trim()}:{},limit:String(Je)});xt.current=Je;const h=u,S=X.trim();M.get(`/wa/chat/list?${g}`).then(({data:F})=>{O(h,Array.isArray(F==null?void 0:F.chats)?F.chats:[],S)&&(Qe(Number(F==null?void 0:F.total)||0),ke(!!(F!=null&&F.hasAiAgent)),ve(!!(F!=null&&F.hasChatbot)))}).catch(()=>{O(h,[],S)&&(Qe(0),ke(!1),ve(!1))}).finally(()=>{ze.current===h&&Oe(!1)})},[u,_,X,O]);const Vi=r.useCallback(()=>{const a=ze.current;if(!a||Me)return;const g=mn.current.length;if(Be&&g>=Be)return;De(!0);const h=ns.current||"all",S=new URLSearchParams({sessionId:a,filter:h.startsWith("label:")?`labels:${h.slice(6)}`:h,...X.trim()?{search:X.trim()}:{},limit:String(Je),offset:String(g)});M.get(`/wa/chat/list?${S}`).then(({data:F})=>{if(ze.current!==a)return;const j=Array.isArray(F==null?void 0:F.chats)?F.chats:[];Qe(Number(F==null?void 0:F.total)||0),j.length&&Q(B=>{const ee=new Set(B.map(Ie=>Ie.jid)),Le=[...B,...j.filter(Ie=>!ee.has(Ie.jid))];return xt.current=Math.max(xt.current,Le.length),Le})}).catch(()=>{}).finally(()=>De(!1))},[Me,Be,X]);r.useEffect(()=>{const a=X.trim();if(!u||a.length<2){D([]),K([]);return}D([]),K([]);let g=!0;const h=setTimeout(async()=>{var j,B;const[S,F]=await Promise.allSettled([M.get(`/wa/chat/contacts?sessionId=${u}&q=${encodeURIComponent(a)}&limit=20`),M.get(`/wa/chat/search?sessionId=${u}&query=${encodeURIComponent(a)}&limit=30`)]);g&&(D(S.status==="fulfilled"?((j=S.value.data)==null?void 0:j.contacts)||[]:[]),K(F.status==="fulfilled"?((B=F.value.data)==null?void 0:B.results)||[]:[]))},280);return()=>{g=!1,clearTimeout(h)}},[u,X]),r.useEffect(()=>{D([]),K([]),Re.current=null},[u]);const Es=r.useCallback(async a=>{var h,S;const g=ze.current;if(g)try{const[F,j]=await Promise.allSettled([a?M.get(`/wa/chat/schedules?sessionId=${g}&jid=${encodeURIComponent(a)}`):Promise.resolve(null),M.get(`/wa/chat/schedules?sessionId=${g}`)]);if(ze.current!==g)return;a&&F.status==="fulfilled"&&F.value&&jt(((h=F.value.data)==null?void 0:h.schedules)||[]),j.status==="fulfilled"&&Fe(((S=j.value.data)==null?void 0:S.byJid)||{})}catch{}},[]);r.useEffect(()=>{un.current=Es},[Es]),r.useEffect(()=>{if(!u){jt([]),Fe({});return}jt([]),Es((L==null?void 0:L.jid)||null)},[u,L==null?void 0:L.jid,Es]),r.useEffect(()=>{if(!u){Xe(0);return}const a=u;M.get(`/wa/chat/list?sessionId=${a}&filter=archived&limit=1`).then(({data:g})=>{ze.current===a&&Xe((g==null?void 0:g.total)||0)}).catch(()=>{})},[u]),r.useEffect(()=>{if(!u){Ce(0);return}const a=u;M.get(`/wa/chat/list?sessionId=${a}&filter=channels&limit=1`).then(({data:g})=>{ze.current===a&&Ce((g==null?void 0:g.total)||0)}).catch(()=>{})},[u]),r.useEffect(()=>{if(!u){mt([]);return}const a=u;M.get(`/wa/chat/labels?sessionId=${a}`).then(({data:g})=>{ze.current===a&&mt(In(g==null?void 0:g.labels))}).catch(()=>{ze.current===a&&mt([])})},[u]);const Ba=!((tr=f==null?void 0:f.dashboard_plan)!=null&&tr.limits)||!!f.dashboard_plan.limits.kanban_enabled,Hs=L==null?void 0:L.jid,Ua=!!(L!=null&&L.isGroup);r.useEffect(()=>{if(!Ba||!u||!Hs||Ua){at({enabled:!1,columns:[],columnId:null,cardId:null});return}let a=!0;return M.get("/wa/kanban/contact/column",{params:{sessionId:u,jid:Hs}}).then(({data:g})=>{a&&at({enabled:!!(g!=null&&g.enabled),columns:Array.isArray(g==null?void 0:g.columns)?g.columns:[],columnId:(g==null?void 0:g.column_id)??null,cardId:(g==null?void 0:g.card_id)??null})}).catch(()=>{a&&at({enabled:!1,columns:[],columnId:null,cardId:null})}),()=>{a=!1}},[Ba,u,Hs,Ua]);const Hi=r.useCallback(async a=>{var F,j;const g=u,h=Hs;if(!g||!h)return;const S=ye;at(B=>({...B,columnId:a.id}));try{const{data:B}=await M.post("/wa/kanban/contact/column",{sessionId:g,jid:h,column_id:a.id});at(ee=>({...ee,columnId:(B==null?void 0:B.column_id)??a.id,cardId:(B==null?void 0:B.card_id)??ee.cardId})),W.success(s==="en"?`Moved to “${a.name}”`:s==="es"?`Movido a “${a.name}”`:`Movido para “${a.name}”`)}catch(B){at(S),W.error(((j=(F=B==null?void 0:B.response)==null?void 0:F.data)==null?void 0:j.error)||(s==="en"?"Failed to change stage":s==="es"?"Error al cambiar la etapa":"Falha ao mudar a etapa"))}},[u,Hs,ye,s]);r.useEffect(()=>{if(!u){Wn([]);return}const a=u;M.get("/wa/templates",{params:{sessionId:a}}).then(({data:g})=>{if(ze.current!==a)return;const h=Array.isArray(g==null?void 0:g.templates)?g.templates:Array.isArray(g)?g:[];Wn(h.filter(S=>S.is_quick_send&&(S.step_count??1)>0))}).catch(()=>{ze.current===a&&Wn([])})},[u]),r.useEffect(()=>{const a=(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence";if(!u||!a){Aa([]);return}let g=!1;const h=u;return Mo(()=>import("./meta-3f0h279n.js"),__vite__mapDeps([0,1,2])).then(S=>{S.default.listSessionTemplates(h,{status:"APPROVED"}).then(F=>{g||ze.current!==h||Aa(Array.isArray(F==null?void 0:F.templates)?F.templates:Array.isArray(F)?F:[])}).catch(()=>{})}).catch(()=>{}),()=>{g=!0}},[u,b==null?void 0:b.provider_type]),r.useEffect(()=>{if(!u||!(L!=null&&L.jid)){ws(null);return}let a=!1;const g=new URLSearchParams({sessionId:u,chatJid:L.jid});return M.get(`/wa/templates/executions/active?${g}`).then(({data:h})=>{if(a)return;const S=Array.isArray(h==null?void 0:h.executions)?h.executions[0]:(h==null?void 0:h.execution)||null;ws(S||null)}
7).catch(()=>{a||ws(null)}),()=>{a=!0}},[u,L==null?void 0:L.jid]);const Vn=r.useMemo(()=>{const a=(X||"").trim().length>0,g=_==="channels"||_==="groups"||a?H:H.filter(S=>_==="archived"?S.isArchived===!0:S.isArchived!==!0),h=wn(u,"unreadOnTop",!1)===!0;return g.sort((S,F)=>{var j,B;if(S.isPinned!==F.isPinned)return S.isPinned?-1:1;if(h){const ee=(S.unreadCount||0)>0,Le=(F.unreadCount||0)>0;if(ee!==Le)return ee?-1:1}return(((j=F.lastMessage)==null?void 0:j.timestamp)||0)-(((B=S.lastMessage)==null?void 0:B.timestamp)||0)})},[H,u,_,X,Pt]),is=r.useCallback(async a=>{var S,F;if(!a||!a.jid)return;{const j=(S=mn.current)==null?void 0:S.find(Ie=>Ie.jid===a.jid),B=a.jid.endsWith("@g.us"),ee=a.jid.endsWith("@newsletter"),Le=!a.name||a.name===a.jid;j?a={...j,...a,name:Le&&j.name||a.name,imgUrl:a.imgUrl||j.imgUrl||null,isGroup:a.isGroup!==void 0?a.isGroup:j.isGroup??B,isNewsletter:a.isNewsletter!==void 0?a.isNewsletter:j.isNewsletter??ee,aiPaused:a.aiPaused!==void 0?a.aiPaused:j.aiPaused,chatbotPaused:a.chatbotPaused!==void 0?a.chatbotPaused:j.chatbotPaused}:a={...a,isGroup:a.isGroup!==void 0?a.isGroup:B,isNewsletter:a.isNewsletter!==void 0?a.isNewsletter:ee,name:Le?B?s==="en"?"Group":"Grupo":Xs(a.jid):a.name}}if(rs(""),((F=xe.current)==null?void 0:F.jid)===a.jid){Qt(j=>j+1),(a.unreadCount||0)>0&&(A(a.jid),Q(j=>j.map(B=>B.jid===a.jid?{...B,unreadCount:0}:B)));return}Ze(a),Bs(null),Fn(null),Ws(!1),_t(null),ps({canSendFreeform:!0,loaded:!1}),ot(j=>j[a.jid]?{[a.jid]:j[a.jid]}:{}),(a.unreadCount||0)>0&&(A(a.jid),Q(j=>j.map(B=>B.jid===a.jid?{...B,unreadCount:0}:B)));const g=$e.current.get(a.jid);g?($e.current.delete(a.jid),$e.current.set(a.jid,g),He(g)):He([]),!a.isGroup&&!a.jid.endsWith("@lid")&&!a.jid.endsWith("@newsletter")&&M.post("/wa/chat/subscribe-presence",{sessionId:u,jid:a.jid}).catch(()=>{}),M.get(`/wa/chat/contact?sessionId=${u}&jid=${encodeURIComponent(a.jid)}`).then(({data:j})=>{var Ft,Wt,Ye;if(((Ft=xe.current)==null?void 0:Ft.jid)!==a.jid)return;let B=j==null?void 0:j.amIAdmin;if(B===void 0){const Ge=(j==null?void 0:j.myJid)||(j==null?void 0:j.myLid),ct=Ge&&((j==null?void 0:j.participants)||[]).find(Ve=>Ve.jid===Ge||Ve.lid===Ge||(Ve.jid||"").split("@")[0]===(Ge||"").split("@")[0]);B=!!(ct&&(ct.role==="admin"||ct.role==="superadmin"))}const ee=(j==null?void 0:j.amIMember)!==!1,Le=!!(j!=null&&j.announcement)||!!(j!=null&&j.restrictSend),Ie=!a.isGroup&&(j==null?void 0:j.reachoutTimelocked)===!0&&(j==null?void 0:j.hasTcToken)===!1,fe=!a.isGroup&&(j==null?void 0:j.newchatCapped)===!0&&(j==null?void 0:j.hasTcToken)===!1;let Ue=!0,Ke=null;if(j!=null&&j.readOnly?(Ue=!1,Ke=s==="en"?"WhatsApp channel — only channel admins can post.":s==="es"?"Canal de WhatsApp — solo quienes administran el canal pueden publicar.":"Canal do WhatsApp — só quem administra o canal pode publicar."):j!=null&&j.isBlocked?(Ue=!1,Ke=s==="en"?"Contact blocked":s==="es"?"Contacto bloqueado":"Contato bloqueado"):Ie?(Ue=!1,Ke=s==="en"?"Your account is temporarily restricted by WhatsApp (anti-spam). This contact hasn’t replied to you yet, so the message wouldn’t be delivered. Ask them to message you first.":s==="es"?"Tu cuenta tiene una restricción temporal de WhatsApp (antispam). Este contacto aún no te ha respondido, así que el mensaje no se entregaría. Pídele que te escriba primero.":"Conta em restrição temporária do WhatsApp (anti-spam). Este contato ainda não te respondeu, então a mensagem não seria entregue. Peça para a pessoa te escrever primeiro."):fe?(Ue=!1,Ke=pi(j==null?void 0:j.newchatQuota,s)):a.isGroup&&(j==null?void 0:j.amIMember)===!1?(Ue=!1,Ke=s==="en"?"You’re not a member of this group":s==="es"?"No eres miembro de este grupo":"Você não é membro deste grupo"):a.isGroup&&Le&&!B&&(Ue=!1,Ke=s==="en"?"Only admins can send messages":s==="es"?"Solo los admins pueden enviar mensajes":"Apenas admins podem enviar mensagens"),_t({canSend:Ue,reason:Ke,amIMember:ee,amIAdmin:B,restrictSend:Le,isBlocked:!!(j!=null&&j.isBlocked),reachoutBlocked:Ie,newchatBlocked:fe,newchatQuota:(j==null?void 0:j.newchatQuota)||null}),a.isGroup){const Ge=(j==null?void 0:j.name)||null,ct=(j==null?void 0:j.imgUrl)||null,Ve=(j==null?void 0:j.size)||((Wt=j==null?void 0:j.participants)==null?void 0:Wt.length)||0;Ze(nt=>nt&&nt.jid===a.jid?{...nt,name:Ge||nt.name,imgUrl:ct||nt.imgUrl,memberCount:Ve||nt.memberCount,participantsCount:Ve||nt.participantsCount,participants:(j==null?void 0:j.participants)||nt.participants}:nt),(Ge||ct)&&Q(nt=>nt.map(yt=>yt.jid===a.jid?{...yt,name:Ge||yt.name,imgUrl:ct||yt.imgUrl}:yt)),ct||(Ye=gn.current)==null||Ye.call(gn,a.jid)}else{const Ge=(j==null?void 0:j.name)||(j==null?void 0:j.displayName)||null,ct=(j==null?void 0:j.imgUrl)||null;(Ge||ct)&&(Ze(Ve=>{if(!Ve||Ve.jid!==a.jid)return Ve;const nt=!Ve.name||Ve.name===Ve.jid||Ve.name===Xs(Ve.jid)||Ve.name===bt(Ve.jid);return{...Ve,name:nt&&Ge?Ge:Ve.name,imgUrl:Ve.imgUrl||ct}}),(Ge||ct)&&Q(Ve=>Ve.map(nt=>nt.jid===a.jid?{...nt,name:nt.name||Ge,imgUrl:nt.imgUrl||ct}:nt)))}}).catch(()=>{var j;
7((j=xe.current)==null?void 0:j.jid)===a.jid&&_t({canSend:!0})}),rn(!0),Ot(!0),as.current=!0;const h=++pn.current;try{const j=new URLSearchParams({sessionId:u,jid:a.jid,limit:"50"}),{data:B}=await M.get(`/wa/chat/messages?${j}`);if(h!==pn.current||u!==ze.current)return;let ee=Array.isArray(B==null?void 0:B.messages)?B.messages:[];const Le=Ns.current.get(a.jid)||[];if(Le.length){const Ie=new Set(ee.map(Ue=>Ue.msgId)),fe=Le.filter(Ue=>!Ie.has(Ue.msgId));fe.length&&(ee=[...ee,...fe].sort((Ue,Ke)=>(Ue.timestamp||0)-(Ke.timestamp||0))),Ns.current.set(a.jid,Le.filter(Ue=>!Ie.has(Ue.msgId)))}if(ee.length<50&&(Ot(!1),as.current=!1),$e.current.size>=Kl){const Ie=$e.current.keys().next().value;Ie&&Ie!==a.jid&&$e.current.delete(Ie)}$e.current.set(a.jid,ee),He(ee)}catch{h===pn.current&&(Ot(!1),as.current=!1)}finally{h===pn.current&&rn(!1)}},[u,rs,s]),Hn=r.useRef({jid:null,ts:0});r.useEffect(()=>{var F;const a=L==null?void 0:L.jid;if(!a||Ls||!u)return;const g=H.find(j=>j.jid===a),h=((F=g==null?void 0:g.lastMessage)==null?void 0:F.timestamp)||0;if(!h)return;const S=(wt||[]).reduce((j,B)=>Math.max(j,B.timestamp||0),0);h!==S&&(Hn.current.jid===a&&Hn.current.ts===h||(Hn.current={jid:a,ts:h},Ss(a)))},[H,L==null?void 0:L.jid,wt,Ls,u,Ss]);const hn=r.useCallback(async a=>{var g;if(!(!a||!a.endsWith("@g.us")||!u))try{const{data:h}=await M.get(`/wa/chat/avatar?sessionId=${u}&jid=${encodeURIComponent(a)}`),S=h==null?void 0:h.url;if(!S)return;Q(F=>F.map(j=>j.jid===a?{...j,imgUrl:S}:j)),((g=xe.current)==null?void 0:g.jid)===a&&Ze(F=>F&&{...F,imgUrl:S})}catch{}},[u]),Oa=r.useCallback(async a=>{var g,h;if(!(!a||!a.endsWith("@g.us")||!u))try{const{data:S}=await M.get(`/wa/chat/contact?sessionId=${u}&jid=${encodeURIComponent(a)}`),F=(S==null?void 0:S.name)||null,j=(S==null?void 0:S.imgUrl)||null,B=(S==null?void 0:S.size)||((g=S==null?void 0:S.participants)==null?void 0:g.length)||0;(F||j)&&Q(ee=>ee.map(Le=>Le.jid===a?{...Le,name:F||Le.name,imgUrl:j||Le.imgUrl}:Le)),((h=xe.current)==null?void 0:h.jid)===a&&Ze(ee=>ee&&{...ee,name:F||ee.name,imgUrl:j||ee.imgUrl,memberCount:B||ee.memberCount,participantsCount:B||ee.participantsCount,participants:(S==null?void 0:S.participants)||ee.participants}),j||hn(a)}catch{}},[u,hn]),fn=r.useRef(null);r.useEffect(()=>{fn.current=Oa},[Oa]);const gn=r.useRef(null);r.useEffect(()=>{gn.current=hn},[hn]);const xn=r.useRef(new Set);r.useEffect(()=>{xn.current=new Set},[u]);const Ga=r.useCallback(async a=>{var g;if(!(!a||!u)&&!xn.current.has(a)){xn.current.add(a);try{const{data:h}=await M.get(`/wa/chat/avatar?sessionId=${encodeURIComponent(u)}&jid=${encodeURIComponent(a)}`);h!=null&&h.url&&(Q(S=>S.map(F=>F.jid===a?{...F,imgUrl:h.url}:F)),((g=xe.current)==null?void 0:g.jid)===a&&Ze(S=>S&&{...S,imgUrl:h.url}))}catch{}}},[u]);r.useEffect(()=>{if((b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence"||!u)return;Vn.filter(h=>!h.imgUrl&&!h.isGroup&&h.jid&&!xn.current.has(h.jid)).slice(0,25).forEach(h=>Ga(h.jid))},[Vn,b,u,Ga]);const Ji=r.useCallback(async()=>{var S;const a=xe.current;if(!a||!as.current||J)return;const g=$e.current.get(a.jid)||[];if(!g.length)return;const h=g.reduce((F,j)=>Math.min(F,j.timestamp||1/0),1/0);if(isFinite(h)){We(!0);try{const F=new URLSearchParams({sessionId:ze.current,jid:a.jid,before:String(h),limit:"50"}),{data:j}=await M.get(`/wa/chat/messages?${F}`),B=Array.isArray(j==null?void 0:j.messages)?j.messages:[];if(B.length<50&&(Ot(!1),as.current=!1),B.length&&((S=xe.current)==null?void 0:S.jid)===a.jid){const ee=new Set(g.map(fe=>fe.msgId)),Le=B.filter(fe=>!ee.has(fe.msgId));Le.length||(Ot(!1),as.current=!1);const Ie=[...Le,...g].sort((fe,Ue)=>(fe.timestamp||0)-(Ue.timestamp||0));$e.current.set(a.jid,Ie),He(Ie)}}catch{Ot(!1),as.current=!1}finally{We(!1)}}},[J]);r.useEffect(()=>{const a=()=>{const S=xe.current,F=ze.current;!(S!=null&&S.jid)||!F||M.get(`/wa/chat/contact?sessionId=${F}&jid=${encodeURIComponent(S.jid)}`).then(({data:j})=>{var Ke;if(((Ke=xe.current)==null?void 0:Ke.jid)!==S.jid)return;let B=j==null?void 0:j.amIAdmin;if(B===void 0){const Ft=(j==null?void 0:j.myJid)||(j==null?void 0:j.myLid),Wt=Ft&&((j==null?void 0:j.participants)||[]).find(Ye=>
7Ye.jid===Ft||Ye.lid===Ft||(Ye.jid||"").split("@")[0]===(Ft||"").split("@")[0]);B=!!(Wt&&(Wt.role==="admin"||Wt.role==="superadmin"))}const ee=!!(j!=null&&j.announcement)||!!(j!=null&&j.restrictSend),Le=!S.isGroup&&(j==null?void 0:j.reachoutTimelocked)===!0&&(j==null?void 0:j.hasTcToken)===!1,Ie=!S.isGroup&&(j==null?void 0:j.newchatCapped)===!0&&(j==null?void 0:j.hasTcToken)===!1;let fe=!0,Ue=null;j!=null&&j.isBlocked?(fe=!1,Ue=s==="en"?"Contact blocked":s==="es"?"Contacto bloqueado":"Contato bloqueado"):Le?(fe=!1,Ue=s==="en"?"Your account is temporarily restricted by WhatsApp (anti-spam). This contact hasn’t replied to you yet, so the message wouldn’t be delivered. Ask them to message you first.":s==="es"?"Tu cuenta tiene una restricción temporal de WhatsApp (antispam). Este contacto aún no te ha respondido, así que el mensaje no se entregaría. Pídele que te escriba primero.":"Conta em restrição temporária do WhatsApp (anti-spam). Este contato ainda não te respondeu, então a mensagem não seria entregue. Peça para a pessoa te escrever primeiro."):Ie?(fe=!1,Ue=pi(j==null?void 0:j.newchatQuota,s)):S.isGroup&&(j==null?void 0:j.amIMember)===!1?(fe=!1,Ue=s==="en"?"You’re not a member of this group":s==="es"?"No eres miembro de este grupo":"Você não é membro deste grupo"):S.isGroup&&ee&&!B&&(fe=!1,Ue=s==="en"?"Only admins can send messages":s==="es"?"Solo los admins pueden enviar mensajes":"Apenas admins podem enviar mensagens"),_t({canSend:fe,reason:Ue,amIMember:(j==null?void 0:j.amIMember)!==!1,amIAdmin:B,restrictSend:ee,isBlocked:!!(j!=null&&j.isBlocked),reachoutBlocked:Le,newchatBlocked:Ie,newchatQuota:(j==null?void 0:j.newchatQuota)||null})}).catch(()=>{})};let g=null;const h=()=>{clearTimeout(g),g=setTimeout(a,800)};return window.addEventListener("pragmaz:block-changed",h),window.addEventListener("pragmaz:group-update",h),window.addEventListener("pragmaz:group-participants",h),()=>{clearTimeout(g),window.removeEventListener("pragmaz:block-changed",h),window.removeEventListener("pragmaz:group-update",h),window.removeEventListener("pragmaz:group-participants",h)}},[s]),r.useEffect(()=>{if(!t||!u)return;const a=N=>{var Ys;if(!N||N.sessionId!==u)return;const E=N.message||N;if(!E||!E.jid||!E.msgId||E.msgType==="reaction")return;const V=(Ys=xe.current)==null?void 0:Ys.jid,te=!!E.patch,ie=$e.current.get(E.jid)||[],we=ie.filter(Pe=>Pe.msgId===E.msgId||E.fromMe&&Pe._optimistic&&Pe.fromMe&&(Pe.textContent||"")===(E.textContent||"")&&Math.abs((Pe.timestamp||0)-(E.timestamp||0))<30).find(Pe=>Pe.quotedId);let ue=we&&!E.quotedId?{...E,quotedId:we.quotedId,quotedText:E.quotedText||we.quotedText,quotedName:E.quotedName??we.quotedName}:E;if(E.fromMe){const Pe=ie.find(qt=>qt.msgId===E.msgId);if(Pe){const qt=Number(Pe.status||0),As=Number(ue.status||0);qt>=2&&As<qt&&(ue={...ue,status:Pe.status}),Pe.groupAck&&!ue.groupAck&&(ue={...ue,groupAck:Pe.groupAck})}}const qe=[...(Ns.current.get(E.jid)||[]).filter(Pe=>Pe.msgId!==E.msgId),ue].slice(-100);Ns.current.set(E.jid,qe);let Ne=ie;E.fromMe&&(Ne=Ne.filter(Pe=>!(Pe._optimistic&&Pe.fromMe&&String(Pe.msgId||"").startsWith("opt_")&&(Pe.textContent||"")===(E.textContent||"")&&Math.abs((Pe.timestamp||0)-(E.timestamp||0))<30)));let Te=Ne.findIndex(Pe=>Pe.msgId===E.msgId),vt=!1;Te<0&&E.fromMe&&(Te=Ne.findIndex(Pe=>Pe._optimistic&&Pe.fromMe&&(Pe.textContent||"")===(E.textContent||"")&&Math.abs((Pe.timestamp||0)-(E.timestamp||0))<30),vt=Te>=0);let St;if(Te>=0){const Pe=Ne[Te],qt={...Pe,...ue,_optimistic:!1};Pe.timestamp&&(qt.timestamp=Pe.timestamp),Pe.localUrl&&!ue.localUrl&&(qt.localUrl=Pe.localUrl),vt&&(qt._key=Pe._key||Pe.msgId),St=Ne.map((As,Bt)=>Bt===Te?qt:As)}else St=[...Ne,ue];$e.current.set(E.jid,St),V===E.jid&&He(St),Q(Pe=>{const qt=Pe.find(Mt=>Mt.jid===E.jid),As={text:E.textContent||"",fromMe:E.fromMe,timestamp:E.timestamp,msgType:E.msgType,pushName:E.fromMe?null:E.pushName||null};if(qt)return Pe.map(Mt=>{var Nr,kr;if(Mt.jid!==E.jid)return Mt;const wr=!((Nr=Mt.lastMessage)!=null&&Nr.timestamp)||(E.timestamp||0)>=Mt.lastMessage.timestamp;if(te)return wr?{...Mt,lastMessage:{...Mt.lastMessage||{},text:E.textContent||((kr=Mt.lastMessage)==null?void 0:kr.text)||""}}:Mt;const Qs={...Mt,...wr?{lastMessage:As}:null,unreadCount:V===E.jid?0:(Mt.unreadCount||0)+(E.fromMe?0:1)};return typeof E.isArchived=="boolean"&&(Qs.isArchived=E.isArchived),typeof E.isPinned=="boolean"&&(Qs.isPinned=E.isPinned),typeof E.isMuted=="boolean"&&(Qs.isMuted=E.isMuted),E.verifiedBizName&&/^\+?[\d\s().-]+$/.test(Mt.name||"")&&(Qs.name=E.verifiedBizName),Qs});if(te)return Pe;const Bt=On.current,na=Bt==null?void 0:Bt.team_role;if(!(!na||na==="owner"||na==="manager"||(Bt==null?void 0:Bt.team_scope)==="all")&&(Bt==null?void 0:Bt.team_scope)!=="queue"||(hs.current||"").trim())return Pe;const aa=ns.current;if(E.jid.endsWith("@newsletter")?aa!=="channels":aa!=="all"&&aa!=="unread")return Pe;const ra=E.jid.endsWith("@g.us");return ra&&setTimeout(()=>{var Mt;return(Mt=fn.current)==null?void 0:Mt.call(fn,E.jid)},0),[{jid:E.jid,name:ra?s==="en"?"Group":"Grupo":E.contactName||E.verifiedBizName||E.pushName||Xs(E.jid),isGroup:ra,isNewsletter:E.jid.endsWith("@newsletter"),imgUrl:null,lastMessage:As,unreadCount:E.fromMe?0:1,isPinned:!1,isMuted:!1,isArchived:!1},...Pe]}
7),!E.fromMe&&!te&&(Xt(Pe=>Pe[E.jid]?{...Pe,[E.jid]:!1}:Pe),V===E.jid&&(d.current&&clearTimeout(d.current),d.current=setTimeout(()=>A(E.jid),800)))},g=N=>{if(!N||N.sessionId!==u)return;(Array.isArray(N.updates)?N.updates:[N.update||N]).forEach(V=>{var we,ue;const te=V.jid;if(!te||!V.msgId)return;if(V.broadcastId){const qe=($e.current.get(te)||[]).map(Ne=>Ne.msgId===V.msgId?{...Ne,broadcastId:V.broadcastId,campaignName:V.campaignName||null}:Ne);if($e.current.set(te,qe),((we=xe.current)==null?void 0:we.jid)===te&&He(qe),V.status==null)return}if(V.status==null)return;const je=($e.current.get(te)||[]).map(pe=>{var vt;if(pe.msgId!==V.msgId)return pe;const qe=Number(pe.status||0),Ne=Number(V.status);if(Ne<qe&&qe>=2&&!(Ne===-1&&qe<3))return pe;const Te=((vt=V.error)==null?void 0:vt.code)!=null?{metaErrorCode:V.error.code,...V.error.detail?{metaErrorDetail:V.error.detail}:{}}:null;return{...pe,status:V.status,...Te||{}}});$e.current.set(te,je),((ue=xe.current)==null?void 0:ue.jid)===te&&He(je)})},h=N=>{var V;if(!N||N.sessionId!==u)return;(((V=N==null?void 0:N.data)==null?void 0:V.keys)||[]).forEach(te=>{var pe,qe;const ie=te.remoteJid||te.jid,je=te.id||te.msgId;if(!ie||!je)return;const we=$e.current.get(ie)||[],ue=we.map(Ne=>Ne.msgId===je?{...Ne,deleted:!0,deletedType:Ne.msgType}:Ne);if($e.current.set(ie,ue),((pe=xe.current)==null?void 0:pe.jid)===ie&&He(ue),te.isLast){const Ne=te.fromMe!=null?!!te.fromMe:((qe=we.find(Te=>Te.msgId===je))==null?void 0:qe.fromMe)??!1;Q(Te=>Te.map(vt=>vt.jid===ie?{...vt,lastMessage:{...vt.lastMessage||{},msgType:"revoked",text:null,reaction:null,fromMe:Ne}}:vt))}})},S=N=>{var je;if(!N||N.sessionId!==u)return;const{jid:E,msgId:V,isLast:te}=N;if(!V)return;const ie=we=>we.map(ue=>ue.msgId===V?{...ue,deleted:!0,deletedType:ue.deletedType||ue.msgType,deletedForMe:!0}:ue);if(E){const we=$e.current.get(E);we&&$e.current.set(E,ie(we)),((je=xe.current)==null?void 0:je.jid)===E&&He(ue=>ie(ue))}te&&E&&Q(we=>we.map(ue=>ue.jid===E?{...ue,lastMessage:{...ue.lastMessage||{},msgType:"revoked",text:null,reaction:null}}:ue))},F=N=>{var je;if(!N||N.sessionId!==u)return;const{jid:E,msgId:V,preview:te}=N;if(!V)return;const ie=we=>we.map(ue=>ue.msgId===V?{...ue,deleted:!1,deletedType:null,deletedForMe:!1}:ue);if(E){const we=$e.current.get(E);we&&$e.current.set(E,ie(we)),((je=xe.current)==null?void 0:je.jid)===E&&He(ue=>ie(ue))}if(te&&(te.jid||E)){const we=te.jid||E;Q(ue=>ue.map(pe=>pe.jid===we?{...pe,lastMessage:{...pe.lastMessage||{},msgType:te.msgType,text:te.text,fromMe:te.fromMe}}:pe))}},j=N=>{var qe;if(!N||N.sessionId!==u)return;const E=N.data||N,{msgId:V,jid:te,newText:ie,editedTimestamp:je,isLast:we}=E;if(!V||!te)return;const pe=($e.current.get(te)||[]).map(Ne=>Ne.msgId===V?{...Ne,textContent:ie,editedTimestamp:je,msgType:"text"}:Ne);$e.current.set(te,pe),((qe=xe.current)==null?void 0:qe.jid)===te&&He(pe),we&&Q(Ne=>Ne.map(Te=>Te.jid===te?{...Te,lastMessage:{...Te.lastMessage||{},text:ie}}:Te))},B=async N=>{var je;if(!N||N.sessionId!==u)return;const E=N.data||N,V=N.jid||E.jid,{msgId:te}=E;if(!(!V||!te||!($e.current.get(V)||[]).some(we=>we.msgId===te)))try{const we=new URLSearchParams({sessionId:u,jid:V,limit:"50"}),{data:ue}=await M.get(`/wa/chat/messages?${we}`),pe=(Array.isArray(ue==null?void 0:ue.messages)?ue.messages:[]).find(Te=>Te.msgId===te);if(!pe||!pe.borrowedText&&!pe.borrowedMedia)return;const qe=$e.current.get(V)||[];if(!qe.some(Te=>Te.msgId===te))return;const Ne=qe.map(Te=>Te.msgId===te?{...Te,borrowedText:pe.borrowedText||null,borrowedMedia:pe.borrowedMedia||null}:Te);$e.current.set(V,Ne),((je=xe.current)==null?void 0:je.jid)===V&&He(Ne)}catch{}},ee=N=>{if(!N||N.sessionId!==u)return;(Array.isArray(N.reactions)?N.reactions:N.data?[{msgId:N.data.msgId,emoji:N.data.reaction,fromMe:N.data.reactionFromMe}]:[]).forEach(V=>{if(!V.msgId)return;Array.from($e.current.entries()).forEach(([ie,je])=>{var ue;if(!je.find(pe=>pe.msgId===V.msgId))return;const we=je.map(pe=>pe.msgId===V.msgId?{...pe,reaction:V.emoji||null,reactionFromMe:!!V.fromMe,_rxPending:void 0,_rxPendingAt:void 0}:pe);$e.current.set(ie,we),((ue=xe.current)==null?void 0:ue.jid)===ie&&He(we)})})},Le=N=>{var E,V;!N||N.sessionId!==u||(N.msgId&&N.jid&&((E=ln.current)==null||E.call(ln,N.jid,N.msgId,{_rxPending:void 0,_rxPendingAt:void 0})),(V=cn.current)==null||V.call(cn,N.code,N.detail))},Ie=N=>{if(!N||N.sessionId!==u)return;const{jid:E,presences:V}=N;if(!E||!V)return;const te=Object.keys(V)[0],ie=V[te];if(!ie)return;ot(pe=>({...pe,[E]:{...ie,lastSeen:ie.lastSeen||ie.last_seen}}));const je=ie.lastKnownPresence==="composing",we=ie.lastKnownPresence==="recording";let ue=ie.participantName||null;if(!ue&&E.endsWith("@g.us")&&te){const pe=(za.current||[]).find(qe=>qe.participant===te&&qe.pushName);ue=(pe==null?void 0:pe.pushName)||Rn(te)||null}Xt(pe=>({...pe,[E]:je||we?{type:we?"recording":"composing",participant:ue}:!1}))},fe=()=>{const N=ze.current;if(!N)return;const E=ns.current,V=new URLSearchParams({sessionId:N,filter:E.startsWith("label:")?`labels:${E.slice(6)}`:E,limit:String(xt.current)});M.get(`/wa/chat/list?${V}`).then(({data:te})=>{O(N,Array.isArray(te==null?void 0:te.chats)?te.chats:[])}).catch(()=>{})},Ue=()=>{ks.current||(ks.current=setTimeout(()=>{ks.current=null;const N=ze.current;if(!N)return;fe();const E=xe.current;if(E!=null&&E.jid){const V=E.jid,te=new URLSearchParams({sessionId:N,jid:V,limit:"50"});M.get(`/wa/chat/messages?${te}`).then(({data:ie})=>{var je;N!==ze.current||((je=xe.current)==null?void 0:je.jid)!==V||Array.isArray(ie==null?void 0:ie.messages)&&He(ie.messages.filter(we=>we.jid===V))}).catch(()=>{})}},1500))},Ke=N=>
7{if(!(!N||N.sessionId!==u)){if(N.isLatest){ht(null),fe(),M.get("/wa/sessions?minimal=true").then(({data:E})=>{w(An(E))}).catch(()=>{});return}ht(E=>({messages:((E==null?void 0:E.messages)||0)+(N.messages||0),chats:((E==null?void 0:E.chats)||0)+(N.chats||0),contacts:((E==null?void 0:E.contacts)||0)+(N.contacts||0),progress:N.progress!=null?N.progress:(E==null?void 0:E.progress)||0,paused:!1,lastBatchAt:Date.now()})),Ue()}},Ft=N=>{if(!N||N.sessionId!==u)return;const E=N.status;if(E==="completed"||E==="declined"){ht(null),E==="completed"&&Ue();return}ht(V=>({messages:Math.max(N.messages||0,(V==null?void 0:V.messages)||0),chats:Math.max(N.chats||0,(V==null?void 0:V.chats)||0),contacts:0,progress:N.progress!=null?Math.max(N.progress,(V==null?void 0:V.progress)||0):(V==null?void 0:V.progress)||0,paused:!1,indeterminate:N.progress==null,kind:"coex"})),Ue()},Wt={sent:"2",delivered:"3",read:"4",failed:"-1",played:"5"},Ye=N=>{var ie,je,we,ue,pe;if(!N||!String(ze.current||"").startsWith("cloud_"))return;const E=N.msg_id||N.message_id||N.msgId,V=Wt[N.status]||(typeof N.status=="string"?N.status:null);if(!E||!V||N.status==="failed"&&((ie=N.error)==null?void 0:ie.code)==="TTL")return;let te=null;N.status==="failed"&&(te={},((je=N.error)!=null&&je.title||(we=N.error)!=null&&we.message)&&(te.errorDetail=N.error.title||N.error.message),(ue=N.error)!=null&&ue.code&&(te.metaErrorCode=N.error.code));for(const[qe,Ne]of $e.current.entries()){const Te=Ne.findIndex(Pe=>Pe.msgId===E);if(Te<0)continue;const vt=Number(Ne[Te].status||0),St=Number(V);if(St<vt&&vt>=2&&!(St===-1&&vt<3))return;const Ys=Ne.map(Pe=>Pe.msgId===E?{...Pe,status:V,...te||{}}:Pe);$e.current.set(qe,Ys),((pe=xe.current)==null?void 0:pe.jid)===qe&&He(Ys);return}},Ge=N=>{var ue,pe,qe;if(!N)return;const E=N.sessionId||(N.waba_id&&N.phone_number_id?`cloud_${N.waba_id}_${N.phone_number_id}`:null);if(E&&E!==ze.current)return;const V=N.from_phone||N.from;if(!V)return;const te=String(V).includes("@")?String(V):`${V}@s.whatsapp.net`,ie=(ue=xe.current)==null?void 0:ue.jid,je=N.text||N.body||N.body_text||N.caption||((pe=N.message)==null?void 0:pe.textContent)||"",we=N.timestamp||Math.floor(Date.now()/1e3);if(Q(Ne=>Ne.map(Te=>{var St;if(Te.jid!==te)return Te;const vt=!((St=Te.lastMessage)!=null&&St.timestamp)||we>=Te.lastMessage.timestamp;return{...Te,...vt?{lastMessage:{text:je,fromMe:!1,timestamp:we,msgType:N.type||"text"}}:null,unreadCount:ie===te?0:(Te.unreadCount||0)+1}})),fe(),ie===te&&window.dispatchEvent(new CustomEvent("pragmaz:cv2-window-refresh",{detail:{sessionId:ze.current,contactWaId:te.split("@")[0]}})),((qe=xe.current)==null?void 0:qe.jid)===te&&ze.current){const Ne=new URLSearchParams({sessionId:ze.current,jid:te,limit:"50"});M.get(`/wa/chat/messages?${Ne}`).then(({data:Te})=>{var St;if(((St=xe.current)==null?void 0:St.jid)!==te)return;const vt=Array.isArray(Te==null?void 0:Te.messages)?Te.messages:[];$e.current.set(te,vt),He(vt)}).catch(()=>{})}},ct=N=>{var ie,je,we;if(!N||N.sessionId!==u)return;const E=N.chats||((ie=N.data)==null?void 0:ie.chats);if(Array.isArray(E)){Q(pe=>pe.map(qe=>{const Ne=E.find(Te=>(Te.jid||Te.id)===qe.jid);return Ne?{...qe,...Ne}:qe}));const ue=E.find(pe=>{var qe;return(pe.jid||pe.id)===((qe=xe.current)==null?void 0:qe.jid)});ue&&Ze(pe=>pe&&pe.jid===(ue.jid||ue.id)?{...pe,...ue}:pe)}const V=N.groups||((je=N.data)==null?void 0:je.groups);if(Array.isArray(V)){Q(pe=>pe.map(qe=>{const Ne=V.find(Te=>(Te.jid||Te.id)===qe.jid);return Ne?{...qe,name:Ne.subject||Ne.name||qe.name}:qe}));const ue=(we=xe.current)==null?void 0:we.jid;ue&&V.some(pe=>(pe.jid||pe.id)===ue)&&window.dispatchEvent(new CustomEvent("pragmaz:group-update",{detail:{jid:ue}}))}const te=N.data;te!=null&&te.id&&(te!=null&&te.action)&&window.dispatchEvent(new CustomEvent("pragmaz:group-participants",{detail:te}))},Ve=N=>{var qe;if(!N||N.sessionId!==ze.current)return;const E=On.current,V=Number((E==null?void 0:E.id)??(E==null?void 0:E.userId)),te=N.assigned_user_id==null?null:Number(N.assigned_user_id),ie=Array.isArray(N.access_member_ids)?N.access_member_ids.map(Number):[];Q(Ne=>Ne.map(Te=>Te.jid===N.jid?{...Te,assigned_user_id:te,agent_name:N.agent_name||null}:Te)),Ze(Ne=>Ne&&Ne.jid===N.jid?{...Ne,assigned_user_id:te,agent_name:N.agent_name||null}:Ne);const je=E==null?void 0:E.team_role;if(!je||je==="owner"||je==="manager"||(E==null?void 0:E.team_scope)==="all")return;if(!(ie.includes(V)||((E==null?void 0:E.team_scope)==="queue"?te===V||te==null:te===V))){Q(Ne=>Ne.filter(Te=>Te.jid!==N.jid)),((qe=xe.current)==null?void 0:qe.jid)===N.jid&&(Ze(null),n&&n(null));return}clearTimeout(Da.current),Da.current=setTimeout(()=>{const Ne=ze.current;if(!Ne)return;const Te=ns.current,vt=new URLSearchParams({sessionId:Ne,filter:Te.startsWith("label:")?`labels:${Te.slice(6)}`:Te,...hs.current.trim()?{search:hs.current.trim()}:{},limit:String(xt.current)});M.get(`/wa/chat/list?${vt}`).then(({data:St})=>{O(Ne,Array.isArray(St==null?void 0:St.chats)?St.chats:[])}).catch(()=>{})},180)},nt=N=>{var E,V;!N||N.sessionId!==ze.current||N.jid&&N.jid===((E=xe.current)==null?void 0:E.jid)&&((V=q.current)==null||V.call(q,N.jid))},yt=N=>{var te;if(!N||N.sessionId!==ze.current||!N.msgId)return;const E=ie=>ie.map(je=>je.msgId===N.msgId?{...je,isStarred:!!N.starred}:je),V=N.jid;if(V){const ie=$e.current.get(V);ie&&$e.current.set(V,E(ie)),((te=xe.current)==null?void 0:te.jid)===V&&He(je=>E(je))}else He(ie=>E(ie))},yn=N=>{if(!N||N.sessionId!==ze.current||!Array.isArray(N.items))return;const E=new Map;for(const V of N.items)!(V!=null&&V.jid)||!(V!=null&&V.msgId)||(E.has(V.jid)||E.set(V.jid,[]),E.get(V.jid).push(V));for(const[V,te]of E.entries()){const ie=$e.current.get(V);if(!ie)continue;const je=xe.current,we=(je==null?void 0:je.jid)===V?Math.max(0,Number(je.memberCount||je.participantsCount||0)-1):0,ue=new Map(te.map(Ne=>[Ne.msgId,Ne]));let pe=!1;const qe=ie.map(Ne=>{const Te=ue.get(Ne.msgId);if(!Te||!Ne.fromMe)return Ne;pe=!0;const vt=Ne.groupAck||{got:0,read:0,total:we};return{...Ne,groupAck:{got:(Number(vt.got)||0)+(Number(Te.got)||0),read:(Number(vt.read)||0)+(Number(Te.read)||0),total:Number(vt.total)||we}}});pe&&($e.current.set(V,qe),(je==null?void 0:je.jid)===V&&He(qe))}},or=()=>{M.get("/wa/sessions?minimal=true").then(({data:N})=>{w(An(N))}).catch(()=>{})},cr=N=>{N&&N.sessionId===ze.current&&(xe.current=null,Ze(null),He([]),Q([]),ht(null),mt([]),$e.current.clear(),Ns.current.clear(),n&&n(null)),M.get("/wa/sessions?minimal=true").then(({data:V})=>{const te=An(V);if(w(te),!te.find(ie=>ie.session_id===ze.current)){const ie=te.length>0?te[0].session_id:null;if(p(ie),ie)try{localStorage.setItem(en,ie)}catch{}}}).catch(()=>{})},lr=N=>{N!=null&&N.label&&(xi(N.label)||mt(E=>{const V=N.label;return V.deleted?E.filter(ie=>
7(ie.id||ie.name)!==(V.id||V.name)):E.find(ie=>(ie.id||ie.name)===(V.id||V.name))?E.map(ie=>(ie.id||ie.name)===(V.id||V.name)?{...ie,...V}:ie):[...E,V]}))},dr=()=>{const N=ze.current;N&&M.get(`/wa/chat/labels?sessionId=${N}`).then(({data:E})=>{mt(In(E==null?void 0:E.labels))}).catch(()=>{}),fe()},ur=N=>{var V;if(!N||N.sessionId!==u)return;const E=N.jids||[];E.length&&(Q(te=>te.filter(ie=>!E.includes(ie.jid))),E.includes((V=xe.current)==null?void 0:V.jid)&&(Ze(null),He([])))},pr=N=>{var E;!N||N.sessionId!==u||N.chatJid&&N.chatJid!==((E=xe.current)==null?void 0:E.jid)||(["completed","cancelled","failed"].includes(N.status)?ws(null):ws(N))},mr=N=>{!N||N.sessionId!==u||window.dispatchEvent(new CustomEvent("pragmaz:poll-vote",{detail:{pollMsgId:N.pollMsgId,pollJid:N.pollJid}}))};let hr=0;const fr=()=>{const N=La.current;if(La.current=!0,!N)return;const E=Date.now();if(E-hr<2e3)return;hr=E;const V=ze.current;if(!V)return;if(!t.recovered){const ie=new URLSearchParams({sessionId:V,filter:ns.current||"all",limit:String(xt.current)});M.get(`/wa/chat/list?${ie}`).then(({data:je})=>{Array.isArray(je==null?void 0:je.chats)&&O(V,je.chats)}).catch(()=>{})}const te=xe.current;if(te!=null&&te.jid){const ie=te.jid,je=new URLSearchParams({sessionId:V,jid:ie,limit:"50"});M.get(`/wa/chat/messages?${je}`).then(({data:we})=>{var ue;if(!(V!==ze.current||((ue=xe.current)==null?void 0:ue.jid)!==ie)&&Array.isArray(we==null?void 0:we.messages)){const pe=we.messages.filter(qe=>qe.jid===ie);$e.current.set(ie,pe),He(pe)}}).catch(()=>{})}},gr=N=>{var V;const E=N==null?void 0:N.msgId;if(E)for(const[te,ie]of $e.current.entries()){const je=ie.findIndex(ue=>ue.msgId===E);if(je===-1)continue;const we=ie.map((ue,pe)=>pe===je?{...ue,_mediaNonce:(ue._mediaNonce||0)+1}:ue);$e.current.set(te,we),((V=xe.current)==null?void 0:V.jid)===te&&He(we);break}},xr=N=>{var te;const E=(N==null?void 0:N.data)||N;if(!E||!E.msgId)return;try{window.dispatchEvent(new CustomEvent("pragmaz:live-location",{detail:{...E,sessionId:(N==null?void 0:N.sessionId)||E.sessionId}}))}catch{}const V=E.msgId;for(const[ie,je]of $e.current.entries()){const we=je.findIndex(pe=>pe.msgId===V);if(we===-1)continue;const ue=je.map((pe,qe)=>qe===we?{...pe,isLive:!0,liveFinalLat:E.lat,liveFinalLng:E.lng,liveAccuracy:E.accuracy??pe.liveAccuracy,liveSpeed:E.speed??pe.liveSpeed,liveHeading:E.heading??pe.liveHeading,liveSeq:E.seq??pe.liveSeq,liveUpdatedAt:E.ts||Date.now(),liveExpiresAt:E.expiresAt??pe.liveExpiresAt}:pe);$e.current.set(ie,ue),((te=xe.current)==null?void 0:te.jid)===ie&&He(ue);break}};t.on("chat:message",a),t.on("chat:live-location",xr),t.on("chat:message-update",g),t.on("chat:message-delete",h),t.on("chat:message-localdelete",S),t.on("chat:message-restore",F),t.on("chat:message-edit",j),t.on("chat:message-borrow",B),t.on("chat:reaction",ee),t.on("chat:reaction-failed",Le),t.on("chat:presence",Ie),t.on("chat:sync-progress",Ke),t.on("meta.history.progress",Ft),t.on("chat:deleted",ur),t.on("template:progress",pr),t.on("chat:poll-vote",mr),t.on("chat:media-ready",gr),t.on("meta.message.status",Ye),t.on("meta.message.inbound",Ge),t.on("chat:update",ct),t.on("chat:group-update",ct),t.on("chat:group-participants",ct),t.on("chat:assignment",Ve),t.on("chat:pins-changed",nt),t.on("chat:message-starred",yt),t.on("chat:receipt",yn),t.on("wa:connected",or),t.on("wa:disconnected",cr);const vr=N=>{var V;if(!N||N.sessionId!==ze.current)return;const E=N.schedule;E&&E.jid===((V=xe.current)==null?void 0:V.jid)&&jt(te=>{const ie=te.findIndex(we=>we.id===E.id);if(ie===-1)return[...te,E].sort((we,ue)=>new Date(we.scheduledAt)-new Date(ue.scheduledAt));const je=[...te];return je[ie]=E,je}),clearTimeout(_a.current),_a.current=setTimeout(()=>{var te;return(te=un.current)==null?void 0:te.call(un,null)},400)};t.on("chat:schedule-updated",vr),t.on("chat:label-edit",lr),t.on("chat:labels-changed",dr);const jr=N=>{!N||N.sessionId!==u||window.dispatchEvent(new CustomEvent("pragmaz:cv2-window-refresh",{detail:N}))};t.on("meta.window.update",jr);const br=N=>{var E;!N||N.sessionId!==u||((E=xe.current)==null?void 0:E.jid)===N.jid&&(N.status==="active"||N.status==="paused"?(es.current&&(clearTimeout(es.current),es.current=null),Vs({step:N.step,total:N.total,status:N.status,next_run_at:N.next_run_at,stop_on_reply:N.stop_on_reply})):(Vs({status:N.status,stopped_reason:N.stopped_reason,reason:N.reason}),Oi(7e3)))};t.on("kanban:followup-updated",br);const yr=N=>{var E;!N||N.sessionId!==u||((E=xe.current)==null?void 0:E.jid)===N.jid&&at(V=>
7V.enabled?{...V,columnId:N.to_column_id,cardId:N.id??V.cardId}:V)};return t.on("kanban:card-moved",yr),t.on("connect",fr),()=>{t.off("connect",fr),t.off("chat:message",a),t.off("chat:live-location",xr),t.off("chat:message-update",g),t.off("chat:message-delete",h),t.off("chat:message-localdelete",S),t.off("chat:message-restore",F),t.off("chat:message-edit",j),t.off("chat:message-borrow",B),t.off("chat:reaction",ee),t.off("chat:reaction-failed",Le),t.off("chat:presence",Ie),t.off("chat:sync-progress",Ke),t.off("meta.history.progress",Ft),t.off("chat:deleted",ur),t.off("meta.message.status",Ye),t.off("meta.message.inbound",Ge),t.off("chat:update",ct),t.off("chat:group-update",ct),t.off("chat:group-participants",ct),t.off("chat:assignment",Ve),t.off("chat:pins-changed",nt),t.off("chat:message-starred",yt),t.off("chat:receipt",yn),t.off("wa:connected",or),t.off("wa:disconnected",cr),t.off("chat:schedule-updated",vr),t.off("chat:label-edit",lr),t.off("chat:labels-changed",dr),t.off("template:progress",pr),t.off("chat:poll-vote",mr),t.off("meta.window.update",jr),t.off("kanban:followup-updated",br),t.off("kanban:card-moved",yr),t.off("chat:media-ready",gr),ks.current&&(clearTimeout(ks.current),ks.current=null)}},[t,u]),r.useEffect(()=>{if(!Ee||Ee.kind==="coex")return;const a=setInterval(()=>{if(!Ee)return;Date.now()-(Ee.lastBatchAt||0)>3e4&&!Ee.paused&&ht(h=>h&&{...h,paused:!0})},5e3);return()=>clearInterval(a)},[Ee]);const Jn=r.useCallback(async(a,g,h)=>{var F;if(!a||!a.jid)return;const S=j=>Ze(B=>B&&B.jid===a.jid?{...B,...j}:B);try{if(g==="pin"){if(h&&(mn.current||[]).filter(B=>B.isPinned&&B.jid!==a.jid).length>=3){W.error(s==="en"?"You can pin up to 3 chats":s==="es"?"Puedes fijar hasta 3 chats":"Você pode fixar até 3 conversas");return}Q(j=>j.map(B=>B.jid===a.jid?{...B,isPinned:!!h}:B)),S({isPinned:!!h}),await M.post("/wa/chat/modify",{sessionId:u,jid:a.jid,action:"pin",value:!!h})}else g==="archive"?(Q(j=>j.map(B=>B.jid===a.jid?{...B,isArchived:!!h}:B)),S({isArchived:!!h}),Xe(j=>Math.max(0,j+(h?1:-1))),await M.post("/wa/chat/modify",{sessionId:u,jid:a.jid,action:"archive",value:!!h})):g==="mute"?(Q(j=>j.map(B=>B.jid===a.jid?{...B,isMuted:!!h,muteExpiration:h||null}:B)),S({isMuted:!!h,muteExpiration:h||null}),await M.post("/wa/chat/modify",{sessionId:u,jid:a.jid,action:"mute",value:h||null})):g==="markUnread"?(Q(j=>j.map(B=>B.jid===a.jid?{...B,unreadCount:Math.max(B.unreadCount||0,1)}:B)),S({unreadCount:Math.max(a.unreadCount||0,1)}),await M.post("/wa/chat/modify",{sessionId:u,jid:a.jid,action:"markUnread",value:!0})):g==="markRead"?(Q(j=>j.map(B=>B.jid===a.jid?{...B,unreadCount:0}:B)),S({unreadCount:0}),await M.post("/wa/chat/modify",{sessionId:u,jid:a.jid,action:"markRead",value:!0}),o==null||o()):g==="delete"&&(Q(j=>j.filter(B=>B.jid!==a.jid)),((F=xe.current)==null?void 0:F.jid)===a.jid&&(Ze(null),He([])),await M.post("/wa/chat/delete",{sessionId:u,jids:[a.jid],deleteOnPhone:!0}))}catch{W.error(s==="en"?"Failed — reload the page":s==="es"?"Error — recarga la página":"Falha — recarregue a página")}},[u,s]),Yi=r.useCallback(a=>{a&&P(g=>{const h=g===a?null:a;try{h?localStorage.setItem("chat_pinnedSessionId",h):localStorage.removeItem("chat_pinnedSessionId")}catch{}return W.success(h?s==="en"?"Device pinned — opens by default":s==="es"?"Dispositivo fijado — abre por defecto":"Dispositivo fixado — abre por padrão":s==="en"?"Device unpinned":s==="es"?"Dispositivo desfijado":"Dispositivo desafixado"),h})},[s]),Qi=r.useCallback(async()=>{Q(a=>a.map(g=>({...g,unreadCount:0}))),o==null||o();try{await M.post("/wa/chat/mark-all-read",{sessionId:u}),W.success(s==="en"?"All chats marked as read":s==="es"?"Todos marcados como leídos":"Todas marcadas como lidas")}catch{W.error(s==="en"?"Failed to mark as read":s==="es"?"Error al marcar como leídos":"Falha ao marcar como lidas")}},[u,o,s]),Ki=r.useCallback(async(a,g)=>{var h;if(a!=null&&a.length){Q(S=>S.filter(F=>!a.includes(F.jid))),a.includes((h=xe.current)==null?void 0:h.jid)&&(Ze(null),He([]));try{await M.post("/wa/chat/delete",{sessionId:u,jids:a,deleteOnPhone:!!g}),W.success(s==="en"?"Chats deleted":s==="es"?"Chats borrados":"Conversas apagadas")}catch{W.error(s==="en"?"Failed to delete — reload the page":s==="es"?"Error al eliminar — recarga la página":"Falha ao apagar — recarregue")}}},[u,s]),Va=r.useCallback((a,g,h,S)=>{const F=String(g),j=S&&S.name!=null?S:ut.find(ee=>String(ee.id)===F)||S||{id:g},B=ee=>{if(!ee||ee.jid!==a)return ee;const Le=Array.isArray(ee.labels)?ee.labels:[];return h==="add"?Le.some(Ie=>String(Ie.id??Ie.name)===F)?ee:{...ee,labels:[...Le,j]}:{...ee,labels:Le.filter(Ie=>String(Ie.id??Ie.name)!==F)}};Q(ee=>ee.map(B)),Ze(ee=>B(ee)),u&&M.get(`/wa/chat/labels?sessionId=${u}`).then(({data:ee})=>mt(In(ee==null?void 0:ee.labels))).catch(()=>{})},[ut,u]),Xi=r.useCallback(a=>{var g;Q(h=>h.filter(S=>S.jid!==a)),((g=xe.current)==null?void 0:g.jid)===a&&(Ze(null),He([])),$e.current.delete(a),Zt(!1)},[]),fs=r.useCallback((a,g)=>{Q(h=>h.find(S=>S.jid===a)?h:[g,...h]),is(g)},[is]);r.useEffect(()=>{const a=async g=>{const{phone:h,name:S}=g.detail||{};if(!h)return;const F=String(h).replace(/\D/g,""),j=ze.current;try{const{data:ee}=await M.post("/wa/chat/on-whatsapp",{sessionId:j,phone:F});if(ee!=null&&ee.exists&&ee.jid){fs(ee.jid,{jid:ee.jid,name:S||ee.name||bt(ee.phone)||F,isGroup:!1,pnJid:ee.pnJid||null,lid:ee.lid||null,imgUrl:ee.imgUrl||null,lastMessage:null,unreadCount:0});return}}catch{}const B=`${F}@s.whatsapp.net`;fs(B,{jid:B,name:S||bt(F)||F,isGroup:!1})};
7return window.addEventListener("pragmaz:cv-open-contact",a),()=>window.removeEventListener("pragmaz:cv-open-contact",a)},[fs]);const Zi=r.useCallback(a=>{const g=(a==null?void 0:a.phone)||String((a==null?void 0:a.jid)||"").replace("@s.whatsapp.net","");g&&(window.dispatchEvent(new CustomEvent("pragmaz:cv-open-contact",{detail:{phone:g,name:a.name}})),rs(""))},[rs]),eo=r.useCallback(a=>{var g;if(a!=null&&a.jid){if(((g=xe.current)==null?void 0:g.jid)===a.jid){_e.current&&_e.current(a.msg_id,a.timestamp),rs("");return}Re.current={jid:a.jid,msgId:a.msg_id,ts:a.timestamp},fs(a.jid,{jid:a.jid,name:a.name||String(a.jid).replace("@s.whatsapp.net",""),isGroup:String(a.jid).endsWith("@g.us"),imgUrl:a.img_url||null,lastMessage:null,unreadCount:0}),rs("")}},[fs,rs]),Dt=r.useCallback((a,g,h)=>{var j;const S=B=>B.map(ee=>ee.msgId===g?{...ee,...h}:ee),F=$e.current.get(a);F&&$e.current.set(a,S(F)),((j=xe.current)==null?void 0:j.jid)===a&&He(B=>S(B))},[]),Yn=r.useCallback(async(a,g={})=>{if(!(a!=null&&a.msgId)||!(a!=null&&a.jid))return;if(g.showOriginal!==void 0){Dt(a.jid,a.msgId,{_trShowOrig:!!g.showOriginal});return}const h=(a.msgType==="audio"?a.transcription||a.textContent:a.textContent||a.text)||"";if(!h.trim()){W.error(s==="es"?"Sin texto para traducir":s==="en"?"No text to translate":"Sem texto para traduzir");return}const S=g.code||(s==="es"?"es":s==="en"?"en":"pt");Dt(a.jid,a.msgId,{_trLoading:!0,_trErr:!1,_trShowOrig:!1});try{const{data:F}=await M.post("/wa/chat/translate",{text:h,target:S});if(!(F!=null&&F.result))throw new Error("empty");Dt(a.jid,a.msgId,{_tr:{lang:S,text:F.result},_trLoading:!1,_trErr:!1,_trShowOrig:!1})}catch{Dt(a.jid,a.msgId,{_trLoading:!1,_trErr:!0}),W.error(s==="es"?"Error al traducir":s==="en"?"Translation failed":"Falha ao traduzir")}},[s,Dt]),vn=r.useCallback((a,g)=>{zt({alert:!0,variant:"danger",title:s==="es"?"No se pudo reaccionar":s==="en"?"Couldn't react":"Não foi possível reagir",message:$o(a,g,s),confirmLabel:s==="es"?"Entendido":s==="en"?"Got it":"Entendi",onConfirm:()=>zt(null)})},[s]);r.useEffect(()=>{cn.current=vn},[vn]),r.useEffect(()=>{ln.current=Dt},[Dt]);const Qn=r.useCallback(async(a,g)=>{var F;if(!a)return;const h=b==null?void 0:b.provider_type,S=h==="cloud_api"||h==="coexistence";Dt(a.jid,a.msgId,{_rxPending:g,_rxPendingAt:Date.now()});try{S?await M.post(`/meta/sessions/${encodeURIComponent(u)}/send-reaction`,{to:a.jid.split("@")[0],message_id:a.msgId,emoji:g}):await M.post("/wa/chat/send",{sessionId:u,jid:a.jid,type:"reaction",content:{emoji:g,key:{remoteJid:a.jid,fromMe:!!a.fromMe,id:a.msgId}}});const j=Date.now();Dt(a.jid,a.msgId,{_rxPendingAt:j}),setTimeout(()=>{const B=$e.current.get(a.jid),ee=B==null?void 0:B.find(Le=>Le.msgId===a.msgId);(ee==null?void 0:ee._rxPendingAt)===j&&Dt(a.jid,a.msgId,{_rxPending:void 0,_rxPendingAt:void 0})},65e3)}catch(j){Dt(a.jid,a.msgId,{_rxPending:void 0,_rxPendingAt:void 0});const B=((F=j==null?void 0:j.response)==null?void 0:F.data)||{};vn(B.code||B.error_code||null,B.error||(j==null?void 0:j.message)||null)}},[b,u,vn,Dt]),to=r.useCallback(async(a,g)=>{var j,B,ee,Le,Ie,fe,Ue,Ke,Ft,Wt;const h=Tt==null?void 0:Tt.msg;if(!h)return;const S=b==null?void 0:b.provider_type,F=S==="cloud_api"||S==="coexistence";if(a==="restore"){Ha(h);return}if(a==="reply"){Bs({msgId:h.msgId,jid:h.jid,text:h.textContent||`[${h.msgType||"msg"}]`,fromMe:h.fromMe,pushName:h.pushName});return}if(a==="copy"){const Ye=h.msgType==="audio"?h.transcription||h.textContent||"":h.textContent||"";if(!Ye){W.error(s==="en"?"No text to copy":s==="es"?"Sin texto para copiar":"Sem texto pra copiar");return}try{await navigator.clipboard.writeText(Ye),W.success(s==="en"?"Copied":"Copiado")}catch{W.error(s==="en"?"Copy failed":s==="es"?"Error al copiar":"Falha ao copiar")}return}if(a==="forward"){Dn({message:h});return}if(a==="translate"){Yn(h,g);return}if(a==="ai-extract"){qs({loading:!0});try{const{data:Ye}=await M.post("/wa/chat-ai/extract",{sessionId:u,jid:h.jid,msgId:h.msgId});qs({fields:Ye.fields||[],summary:Ye.summary||null})}catch(Ye){qs({error:((B=(j=Ye==null?void 0:Ye.response)==null?void 0:j.data)==null?void 0:B.error)||(s==="en"?"AI unavailable right now":s==="es"?"IA no disponible ahora":"IA indisponível agora")})}return}if(a==="reply-privately"){const Ye=h.participant;if(!Ye){W.error(s==="en"?"Unknown participant":s==="es"?"Participante desconocido":"Participante desconhecido");return}try{const{data:Ge}=await M.get(`/wa/chat/contact?sessionId=${encodeURIComponent(u)}&jid=${encodeURIComponent(Ye)}`),ct=(Ge==null?void 0:Ge.lid)||(Ye.includes("@")?Ye:`${Ye}@s.whatsapp.net`),Ve=Ge!=null&&Ge.pnJid?String(Ge.pnJid).split("@")[0]:null,nt={jid:ct,phone:Ve,n
7ame:(Ge==null?void 0:Ge.name)||(Ge==null?void 0:Ge.pushName)||Xs(Ye,s==="en"?"Participant":"Participante"),isGroup:!1};Q(yt=>yt.find(yn=>yn.jid===ct)?yt:[nt,...yt]),is(nt),setTimeout(()=>Bs({msgId:h.msgId,jid:h.jid,text:h.textContent||`[${h.msgType||"msg"}]`,fromMe:!1,pushName:h.pushName}),350)}catch{W.error(s==="en"?"Failed to open private chat":s==="es"?"Error al abrir la conversación privada":"Falha ao abrir conversa privada")}return}if(a==="transcribe"){Ja(h);return}if(a==="edit"){Ca(h);return}if(a==="star"){const Ye=!h.isStarred,Ge=Ve=>nt=>nt.map(yt=>yt.msgId===h.msgId?{...yt,isStarred:Ve}:yt),ct=Ve=>{const nt=$e.current.get(h.jid);nt&&$e.current.set(h.jid,Ge(Ve)(nt))};((ee=xe.current)==null?void 0:ee.jid)===h.jid&&He(Ve=>Ge(Ye)(Ve)),ct(Ye);try{await M.post("/wa/chat/star",{sessionId:u,jid:h.jid,msgId:h.msgId,fromMe:h.fromMe,star:Ye}),W.success(Ye?s==="en"?"Message starred":s==="es"?"Mensaje destacado":"Mensagem favoritada":s==="en"?"Star removed":s==="es"?"Estrella quitada":"Estrela removida")}catch(Ve){((Le=xe.current)==null?void 0:Le.jid)===h.jid&&He(nt=>Ge(!Ye)(nt)),ct(!Ye),W.error(((fe=(Ie=Ve==null?void 0:Ve.response)==null?void 0:Ie.data)==null?void 0:fe.error)||(s==="en"?"Failed to star":s==="es"?"Error al destacar":"Falha ao favoritar"))}return}if(a==="message-info"){et(h);return}if(a==="pin"||a==="unpin"){const Ye=a==="pin";try{await M.post("/wa/chat/pin",{sessionId:u,jid:h.jid,msgId:h.msgId,fromMe:h.fromMe,participant:h.participant||void 0,pin:Ye,time:(g==null?void 0:g.time)||86400}),(Ue=q.current)==null||Ue.call(q,h.jid),W.success(Ye?s==="en"?"Message pinned":s==="es"?"Mensaje fijado":"Mensagem fixada":s==="en"?"Message unpinned":s==="es"?"Mensaje desfijado":"Mensagem desafixada")}catch(Ge){W.error(((Ft=(Ke=Ge==null?void 0:Ge.response)==null?void 0:Ke.data)==null?void 0:Ft.error)||(s==="en"?"Failed to pin":s==="es"?"Error al fijar":"Falha ao fixar"))}return}if(a==="select"){ao(h);return}if(a==="react"){await Qn(h,g);return}if(a==="delete-me"){const Ye=ct=>ct.map(Ve=>Ve.msgId===h.msgId?{...Ve,deleted:!0,deletedType:Ve.msgType,deletedForMe:!0}:Ve),Ge=$e.current.get(h.jid);Ge&&$e.current.set(h.jid,Ye(Ge)),((Wt=xe.current)==null?void 0:Wt.jid)===h.jid&&He(ct=>Ye(ct));try{await M.post("/wa/chat/message/delete-for-me",{sessionId:u,jid:h.jid,msgId:h.msgId})}catch{W.error(s==="en"?"Failed to delete":s==="es"?"Error al eliminar":"Falha ao excluir")}return}if(a==="delete-all"){if(F){W.error(s==="en"?"Cloud API doesn’t support delete for everyone":s==="es"?"La Cloud API no permite eliminar para todos":"Cloud API não suporta apagar para todos");return}zt({title:s==="en"?"Delete for everyone?":s==="es"?"¿Eliminar para todos?":"Apagar para todos?",message:s==="en"?"This message will be removed for everyone in the conversation. This cannot be undone.":s==="es"?"El mensaje se eliminará para todos en la conversación. Esta acción no se puede deshacer.":"A mensagem será removida para todos na conversa. Esta ação não pode ser desfeita.",confirmLabel:s==="en"?"Delete for everyone":s==="es"?"Eliminar para todos":"Apagar para todos",danger:!0,onConfirm:async()=>{var Ye;try{const Ge={remoteJid:h.jid,fromMe:!!h.fromMe,id:h.msgId};!h.fromMe&&h.participant&&(Ge.participant=h.participant),await M.post("/wa/chat/send",{sessionId:u,jid:h.jid,type:"delete",content:{key:Ge}});const ct=nt=>nt.map(yt=>yt.msgId===h.msgId?{...yt,deleted:!0,deletedType:yt.msgType}:yt),Ve=$e.current.get(h.jid);Ve&&$e.current.set(h.jid,ct(Ve)),((Ye=xe.current)==null?void 0:Ye.jid)===h.jid&&He(nt=>ct(nt))}catch{W.error(s==="en"?"Failed to delete":s==="es"?"Error al eliminar":"Falha ao excluir")}}});return}},[Tt,u,b,Yn,Qn,s]),Ha=r.useCallback(async a=>{var S;if(!(a!=null&&a.msgId)||!(a!=null&&a.jid))return;const g=F=>F.map(j=>j.msgId===a.msgId?{...j,deleted:!1,deletedType:null,deletedForMe:!1}:j),h=$e.current.get(a.jid);h&&$e.current.set(a.jid,g(h)),((S=xe.current)==null?void 0:S.jid)===a.jid&&He(F=>g(F));try{await M.post("/wa/chat/message/restore",{sessionId:u,jid:a.jid,msgId:a.msgId})}catch{W.error(s==="en"?"Failed to restore":s==="es"?"Error al restaurar":"Falha ao restaurar")}},[u,s]),so=r.useCallback(a=>Pn(a),[]),no=r.useCallback(async(a,g)=>{if(a&&Array.isArray(a.options)){dn(a);return}const h=a;try{const S=new URLSearchParams({sessionId:u,pollMsgId:h.msgId}),{data:F}=await M.get(`/wa/chat/poll-votes?${S}`);dn({pollName:h.pollName||h.textContent||(s==="en"?"Poll":s==="es"?"Encuesta":"Enquete"),options:(F==null?void 0:F.options)||[],totalVotes:(F==null?void 0:F.totalVotes)||0,focusOption:g})}catch{dn({pollName:h.pollName||(s==="en"?"Poll":s==="es"?"Encuesta":"Enquete"),options:[],totalVotes:0,focusOption:g})}},[u,s]),Ja=r.useCallback(async a=>{const g=a.jid,h=S=>{var B;const j=($e.current.get(g)||[]).map(ee=>ee.msgId===a.msgId?{...ee,...S}:ee);$e.current.set(g,j),((B=xe.current)==null?void 0:B.jid)===g&&He(j)};h({transcribing:!0});try{const{data:S}=await M.post("/wa/chat/transcribe",{sessionId:u,msgId:a.msgId});h({transcribing:!1,transcription:(S==null?void 0:S.transcription)||(S==null?void 0:S.text)||"—"})}catch{h({transcribing:!1,transcription:s==="en"?"⚠️ Transcription failed":s==="es"?"⚠️ Error al transcribir":"⚠️ Erro ao transcrever"})}},[u,s]),ao=r.useCallback(a=>{Ia(!0),zn(new Set([a.msgId]))},[]),Ya=r.useCallback(a=>{zn(g=>{const h=new Set(g);if(h.has(a.msgId))h.delete(a.msgId);else{if(h.size>=30)return W(s==="en"?"Max 30 messages":s==="es"?"Máx. 30 mensajes":"Máx 30 mensagens",{icon:"⚠️"}),g;h.add(a.msgId)}return h})},[s]),gs=r.useCallback(()=>{Ia(!1),zn(new Set)},[]);r.useEffect(()=>{gs()},[L==null?void 0:L.jid,gs]);const Nt=r.useMemo(()=>wt.filter(a=>ys.has(a.msgId)),[wt,ys]),Qa=Nt.length>0&&Nt.every(a=>a.fromMe),ro=()=>{Nt.length!==0&&Dn({messages:Nt})},io=async()=>{const a=Nt.map(g=>
7g.textContent||"").filter(Boolean).join(`
8
9`);if(!a)return W(s==="en"?"No text to copy":s==="es"?"Sin texto para copiar":"Sem texto pra copiar",{icon:"⚠️"});try{await navigator.clipboard.writeText(a),W.success(s==="en"?`${Nt.length} ${Nt.length===1?"message copied":"messages copied"}`:s==="es"?`${Nt.length} ${Nt.length===1?"mensaje copiado":"mensajes copiados"}`:`${Nt.length} ${Nt.length===1?"mensagem copiada":"mensagens copiadas"}`),gs()}catch{W.error(s==="en"?"Copy failed":s==="es"?"Error al copiar":"Falha ao copiar")}},oo=async()=>{const a=Array.from(ys),g=wt.filter(h=>a.includes(h.msgId));if(g.length){He(h=>h.map(S=>a.includes(S.msgId)?{...S,isStarred:!0}:S));for(const h of g)M.post("/wa/chat/star",{sessionId:u,jid:h.jid,msgId:h.msgId,fromMe:h.fromMe,star:!0}).catch(()=>{});W.success(s==="en"?`${g.length} message${g.length>1?"s":""} starred`:s==="es"?`${g.length} mensaje${g.length>1?"s":""} destacado${g.length>1?"s":""}`:`${g.length} favoritada(s)`),gs()}},co=()=>{const a=Array.from(ys),g=wt.filter(h=>a.includes(h.msgId)&&["image","video","audio","document"].includes(h.msgType)&&!h.isViewOnce);if(!g.length){W.error(s==="en"?"No media selected":s==="es"?"Ningún archivo multimedia seleccionado":"Nenhuma mídia selecionada");return}g.forEach((h,S)=>{setTimeout(()=>{const F=document.createElement("a");F.href=`/api/wa/chat/media/${encodeURIComponent(h.msgId)}?sessionId=${encodeURIComponent(u)}`,F.download="",F.target="_blank",document.body.appendChild(F),F.click(),F.remove()},S*350)}),W.success(s==="en"?`${g.length} download${g.length>1?"s":""}`:s==="es"?`${g.length} descarga${g.length>1?"s":""}`:`${g.length} download(s)`),gs()},lo=()=>{if(Nt.length===0)return;const a=Qa?"everyone":"me";zt({title:s==="en"?`Delete ${Nt.length} message${Nt.length>1?"s":""}?`:s==="es"?`¿Eliminar ${Nt.length} mensaje${Nt.length>1?"s":""}?`:`Apagar ${Nt.length} ${Nt.length>1?"mensagens":"mensagem"}?`,message:a==="everyone"?s==="en"?"This will be deleted for all participants.":s==="es"?"Se eliminará para todos los participantes.":"Será apagada pra todos os participantes.":s==="en"?"Only visible to you on this device.":s==="es"?"Solo visible para ti en este dispositivo.":"Só visível pra você nesse dispositivo.",confirmLabel:s==="en"?"Delete":s==="es"?"Eliminar":"Apagar",onConfirm:async()=>{let g=0;for(const h of Nt)try{await M.post("/wa/chat/send",{sessionId:u,jid:h.jid,type:"delete",content:{key:{remoteJid:h.jid,fromMe:!!h.fromMe,id:h.msgId}}})}catch{g++}g>0&&W.error(s==="en"?`Failed to delete ${g} message${g>1?"s":""}`:s==="es"?`Error al eliminar ${g} mensaje${g>1?"s":""}`:`${g} falha(s) ao apagar`),gs()}})},Ka=r.useRef(0),uo=r.useCallback((a,g)=>{var Le;const h=(Le=xe.current)==null?void 0:Le.jid,S=ze.current,F=Pa.current;if(!h||!S||!a)return;const j=typeof a=="string"?{displayText:a}:a||{},B=j.displayText||j.text||j.title||j.id||"";if(!B)return;if((F==null?void 0:F.provider_type)==="cloud_api"||(F==null?void 0:F.provider_type)==="coexistence"){M.post(`/meta/sessions/${encodeURIComponent(S)}/send-text`,{to:h.split("@")[0],text:B}).catch(()=>W.error(s==="en"?"Failed to send":s==="es"?"Error al enviar":"Falha ao enviar"));return}if(j.kind&&(g!=null&&g.msgId)){M.post("/wa/chat/send",{sessionId:S,jid:h,type:"buttonReply",content:{id:j.id||B,displayText:B,index:j.index||0,kind:j.kind==="plain"?"plain":j.kind==="nativeFlow"?"nativeFlow":"template",...j.kind==="nativeFlow"?{nativeName:j.nativeName||"quick_reply",paramsJson:j.paramsJson||null}:{},originalMsgId:g.msgId,originalJid:h,...g.participant?{originalParticipant:g.participant}:{}}}).catch(()=>W.error(s==="en"?"Failed to send":s==="es"?"Error al enviar":"Falha ao enviar"));return}M.post("/wa/chat/send",{sessionId:S,jid:h,type:"text",content:{text:B}}).catch(()=>W.error(s==="en"?"Failed to send":s==="es"?"Error al enviar":"Falha ao enviar"))},[s]),xs=r.useCallback(async(a,g)=>{var F,j;if(!a)return;if(document.getElementById(`m-${a}`)){de({msgId:a,nonce:++Ka.current});return}const h=ze.current,S=(F=xe.current)==null?void 0:F.jid;if(!(!h||!S||!g))try{const B=new URLSearchParams({sessionId:h,jid:S,around:String(g),limit:"50"}),{data:ee}=await M.get(`/wa/chat/messages?${B}`);if(((j=xe.current)==null?void 0:j.jid)!==S)return;const Le=(Array.isArray(ee==null?void 0:ee.messages)?ee.messages:[]).filter(Ie=>Ie.jid===S);if(!Le.length)return;$e.current.set(S,Le),Ot(!0),as.current=!0,He(Le),de({msgId:a,nonce:++Ka.current})}catch{}},[]);_e.current=xs,r.useEffect(()=>{const a=Re.current;a&&(L==null?void 0:L.jid)===a.jid&&wt.length&&(xs(a.msgId,a.ts),Re.current=null)},[L,wt,xs]);const Xa=(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence",Kn=Xa&&Lt.loaded&&!Lt.canSe
9ndFreeform,Is=r.useMemo(()=>{var a;return((a=f==null?void 0:f.beta)==null?void 0:a.is_beta)===!0&&wn(u,"chatAiEnabled",!0)!==!1},[(sr=f==null?void 0:f.beta)==null?void 0:sr.is_beta,u,Pt]),ts=r.useMemo(()=>wn(u,"adKanbanInChat",!1)===!0,[u,Pt]),[po,jn]=r.useState(null),[bn,Xn]=r.useState(null),Za=r.useRef(0),Js=r.useCallback((a,g)=>{const h=++Za.current;if(!a||!g||g.endsWith("@g.us")||g.endsWith("@newsletter")){Xn(null);return}M.get("/wa/chat/anuncio-kanban/contato",{params:{sessionId:a,jid:g}}).then(({data:S})=>{var F;h===Za.current&&ze.current===a&&((F=xe.current)==null?void 0:F.jid)===g&&Xn(S)}).catch(()=>{})},[]);r.useEffect(()=>{if(jn(null),!ts||!u)return;let a=!0;const g=u;return M.get("/wa/chat/anuncio-kanban",{params:{sessionId:g}}).then(({data:h})=>{a&&jn(h)}).catch(()=>{}),()=>{a=!1}},[ts,u]),r.useEffect(()=>{Xn(null),ts&&Js(u,L==null?void 0:L.jid)},[ts,u,L==null?void 0:L.jid,Js]),r.useEffect(()=>{if(!t||!ts)return;const a=u;let g=null;const h=()=>{clearTimeout(g),g=setTimeout(()=>{var Ue;M.get("/wa/chat/anuncio-kanban",{params:{sessionId:a}}).then(({data:Ke})=>{ze.current===a&&jn(Ke)}).catch(()=>{});const fe=(Ue=xe.current)==null?void 0:Ue.jid;fe&&Js(a,fe)},500)},S=(fe,Ue)=>jn(Ke=>Ke&&{...Ke,contatos:{...Ke.contatos,[fe]:[Ue==null?null:Number(Ue),(Ke.contatos[fe]||[null,null])[1]]}}),F=(fe,Ue)=>{var Ke;!fe||fe.sessionId!==a||!fe.jid||(Ue!==void 0&&S(fe.jid,Ue),((Ke=xe.current)==null?void 0:Ke.jid)===fe.jid&&Js(a,fe.jid))},j=fe=>{if(fe&&fe.sessionId===a&&!fe.jid)return h();F(fe,fe==null?void 0:fe.to_column_id)},B=fe=>F(fe,fe==null?void 0:fe.column_id),ee=fe=>F(fe,null),Le=fe=>F(fe,void 0),Ie=fe=>{(!fe||!fe.sessionId||fe.sessionId===a)&&h()};return t.on("kanban:card-moved",j),t.on("kanban:card-created",B),t.on("kanban:card-removed",ee),t.on("kanban:card-updated",Le),t.on("kanban:column-changed",Ie),()=>{clearTimeout(g),t.off("kanban:card-moved",j),t.off("kanban:card-created",B),t.off("kanban:card-removed",ee),t.off("kanban:card-updated",Le),t.off("kanban:column-changed",Ie)}},[t,ts,u,Js]);const Zn=rt&&rt.canSend===!1||Kn,er=(rt==null?void 0:rt.canSend)===!1?(rt==null?void 0:rt.reason)||"":Kn?s==="en"?"Window closed — approved template only":s==="es"?"Ventana de 24 h cerrada — solo plantilla aprobada":"Janela 24h fechada — só template aprovado":"",mo=(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence",ea=r.useRef(null),[ho,fo]=r.useState(0),ta=r.useCallback((a,g,h)=>{g&&(ea.current={sessionId:a||null,jid:g,name:h||g},a&&a!==ze.current&&p(a),fo(S=>S+1))},[]);r.useEffect(()=>{const a=ea.current;a&&(a.sessionId&&a.sessionId!==u||(ea.current=null,is({jid:a.jid,name:a.name})))},[ho,u,is]);const sa=r.useRef(null);return r.useEffect(()=>{const a=c.search;if(!a){sa.current=null;return}if(!m||!y.length||a===sa.current)return;const g=new URLSearchParams(a),h=g.get("jid");if(!h)return;sa.current=a;const S=g.get("session"),F=S&&y.some(j=>j.session_id===S)?S:null;ta(F,h,g.get("name")),l(c.pathname,{replace:!0})},[c,m,y,ta,l]),e.jsx(To.Provider,{value:v,children:e.jsx(Fo,{children:e.jsxs("div",{className:"cv2","data-cv2-theme":v,children:[e.jsx(Oo,{}),e.jsx(Zc,{socket:t,onOpen:ta}),m?y.length===0?e.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",padding:24,boxSizing:"border-box"},children:e.jsx(ec,{icon:Zl,title:s==="en"?"Connect a device first":s==="es"?"Conecta un dispositivo primero":"Conecte um dispositivo primeiro",hint:s==="en"?"You need a connected WhatsApp to open your chats. Connect one in Devices.":s==="es"?"Necesitas un WhatsApp conectado para abrir tus chats. Conéctalo en Dispositivos.":"Você precisa de um WhatsApp conectado pra abrir as conversas. Conecte um em Dispositivos."})}):e.jsxs("div",{className:`chat-app${L&&ss?"":" no-info"}`,"data-view":L?"thread":"list",children:[e.jsx(dc,{open:G,onClose:()=>me(!1),schedules:dt,locale:s,onChanged:()=>{var a;return Es((a=xe.current)==null?void 0:a.jid)},onConfirmAsk:zt}),e.jsx(sc,{aiEnabled:Is,onOpenRadar:()=>$n(!0),radarCount:Ii,onOpenQa:Mi?()=>Tn(!0):null,sessions:y,activeSession:b,onChangeSession:a=>{a!==u&&(p(a),Ze(null),He([]),$e.current.clear(),ot({}),Xt({}),D([]),K([]),Re.current=null)},chats:Vn,adKanban:ts?po:null,chatsLoading:Y,onLoadMore:Vi,chatsLoadingMore:Me,chatsTotal:Be,chatsLoaded:H.length,selectedJid:L==null?void 0:L.jid,onSelectChat:is,onConvAction:Jn,onConfirmAsk:zt,onNewChat:()=>Ra(!0),onChannelAction:async a=>{var g,h,S,F;try{const{data:j}=await M.post("/wa/chat/newsletter-action",{sessionId:u,...a});W.success(a.action==="create"?s==="en"?"Channel created":s==="es"?"Canal creado":"Canal criado":s==="en"?"You joined the channel":s==="es"?"Entraste en el canal":"Você entrou no canal");const B=((g=j==null?void 0:j.result)==null?void 0:g.id)||((h=j==null?void 0:j.result)==null?void 0:h.jid),ee=u,Le=new URLSearchParams({sessionId:ee,filter:"channels",limit:"50"});return M.get(`/wa/chat/list?${Le}`).then(({data:Ie})=>{O(ee,Array.isArray(Ie==null?void 0:Ie.chats)?Ie.chats:[])&&Ce(Number(Ie==null?void 0:Ie.total)||0)}).catch(()=>{}),B&&setTimeout(()=>{var Ie;return fs(B,{jid:B,name:((Ie=j==null?void 0:j.result)==null?void 0:Ie.name)||Xs(B),isNewsletter:!0,isGroup:!1})},500),!0}catch(j){return W.error(((F=(S=j==null?void 0:j.response)==null?void 0:S.data)==null?void 0:F.error)||(s==="en"?"Failed":s==="es"?"No funcionó":"Não deu certo")),!1}},chatFilter:_,onChangeFilter:Gi,chatSearch:X,onChangeSearch:rs,searchContacts:Z,searchMessages:ae,onOpenContact:Zi,onOpenMessage:eo,labels:ut,archivedCount:le,channelsCount:z,syncing:Ee,typingMap:ft,presenceMap:it,onDeviceOptions:()=>qn(!0),onMarkAllRead:Qi,onAddDevice:()=>l("/dashboard/devices"),canAddDevice:!(f!=null&&f.team_role)||(f==null?void 0:f.is_team_owner)===!0,onBulkDelete:Ki,pinnedSessionId:x,onTogglePinDevice:Yi,locale:s}),L?e.jsxs("section",{className:"chat-thread",children:[on?e.jsx(xl,{count:ys.size,allMine:Qa,onCancel:gs,onForward:ro,onCopy:io,onStar:oo,onDownload:co,onDelete:lo,locale:s}):e.jsx(bc,{chat:L,session:b,sessionId:u,presence:it[L.jid],typing:ft[L.jid],lastRecvMsgId:Bi,scheduleCount:((nr=Se[L.jid])==null?void 0:nr.pending)||0,scheduleFailed:((ar=Se[L.jid])==null?void 0:ar.failed)||0,onOpenSchedules:()=>me(!0),onBack:()=>{Zt(!1),Ws(!1),Ze(null),n&&n(null)},onToggleInfo:()=>Zt(a=>!a),onToggleSearch:()=>Ws(a=>!a),theme:v,onContactSaved:(a,g,h=!0)=>{Q(S=>S.map(F=>F.jid===a?{...F,isSavedContact:h,name:g}:F)),Ze(S=>(S==null?void 0:S.jid)===a?{...S,isSavedContact:h,name:g}:S)},onConvAction:Jn,onConfirmAsk:zt,onOpenStarred:()=>tt(!0),aiEnabled:Is,onOpenAi:()=>Mn(!0),onOpenCrm:()=>Et(!0),labels:ut,onLabelChange:Va,onManageLabels:()=>kt(!0),kanban:ye,onKanbanColumnChange:Hi,infoOpen:ss,searchOpen:zs,locale:s,hasAiAgent:oe,onAiPauseChange:(a,g)=>{Q(h=>h.map(S=>S.jid===a?{...S,aiPaused:g}:S)),Ze(h=>(h==null?void 0:h.jid)===a?{...h,aiPaused:g}:h)},hasChatbot:Ae,onChatbotPauseChange:(a,g)=>{Q(h=>h.map(S=>S.jid===a?{...S,chatbotPaused:g}:S)),Ze(h=>(h==null?void 0:h.jid)===a?{...h,chatbotPaused:g}:h)},canCall:Cr(f,"chat.calls")&&(b==null?void 0:b.provider_type)!=="coexistence"&&!(L!=null&&L.isGroup)&&!!(L!=null&&L.phone),canVideoCall:Cr(f,"chat.calls")&&((b==null?void 0:b.provider_type)||"web")==="web"&&!(L!=null&&L.isGroup)&&!!(L!=null&&L.phone)&&_o().encode,onStartCall:(a=!1)=>i==null?void 0:i.startCall({sessionId:u,devicePhone:(b==null?void 0:b.phone)||null,deviceType:(b==null?void 0:b.provider_type)||"web",phone:L.phone,name:L.name||L.pushName||L.phone,jid:L.jid,avatar:L.avatar,video:a===!0})}),e.jsx(el,{sessionId:u,chat:L,session:b,aiEnabled:Is,onWindowState:ps,onOpenTemplatePicker:a=>{Os(a||null),Us(!0)}}),zs&&e.jsx(il,{sessionId:u,jid:L.jid,messages:wt,onJumpToMessage:xs,onClose:()=>Ws(!1),locale:s}),e.jsx(ol,{pins:$t,onJumpToMsg:a=>{const g=wt.find(h=>h.msgId===a);xs(a,g==null?void 0:g.timestamp)},onUnpin:a=>{M.post("/wa/chat/pin",{sessionId:u,jid:L.jid,msgId:a,pin:!1}
9).then(()=>Gs(L.jid)).catch(()=>{})}}),e.jsx(ll,{followup:Ui}),e.jsx(Go,{messages:wt,loading:Ls,adPreview:ts&&(bn==null?void 0:bn.anuncio)||null,chat:L,session:b,sessionId:u,typing:ft[L.jid],selectionMode:on,selectedMsgIds:ys,onToggleSelect:Ya,onContextMenu:(a,g)=>on?Ya(a):Fn({msg:{...a,isPinned:$t.some(h=>h.msgId===a.msgId)},...g}),onShowReactions:so,onTranscribe:Ja,onShowPollVoters:no,onGroupInvite:a=>{a&&typeof a=="object"?(Un(a.v4||null),Bn(a.code||"v4")):(Un(null),Bn(a))},hasMore:Ps,loadingMore:J,onLoadMore:Ji,scrollBottomNonce:Yt,jumpTarget:Rt,onReply:a=>Bs({msgId:a.msgId,jid:a.jid,text:a.textContent||`[${a.msgType||"msg"}]`,fromMe:a.fromMe,pushName:a.pushName}),onReact:Qn,sendBlocked:Zn,onButtonReply:uo,onOpenLiveLocation:a=>us(a),onRestore:Ha,onTranslate:Yn,locale:s}),!on&&e.jsx(wl,{sessionId:u,chatJid:L.jid,quickTemplates:Fi,metaTemplates:_i,isCloud:(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence",canSendFreeform:!Xa||Lt.loaded&&Lt.canSendFreeform,permsBlocked:(rt==null?void 0:rt.canSend)===!1,permsReason:er,activeExecution:Di,onCancelExecution:a=>{var F;const g=a.id||a.executionId,h=(F=xe.current)==null?void 0:F.jid,S=typeof g=="string"&&g.startsWith("meta_");zt({title:s==="en"?"Cancel execution?":s==="es"?"¿Cancelar ejecución?":"Cancelar execução?",message:s==="en"?"The template in progress will be stopped.":s==="es"?"La plantilla en curso se detendrá.":"O template em andamento será interrompido.",confirmLabel:s==="en"?"Cancel execution":s==="es"?"Cancelar ejecución":"Cancelar execução",onConfirm:async()=>{var j;try{S?await M.post(`/meta/sessions/${encodeURIComponent(u)}/run-internal-template/cancel`,{executionId:g}):await M.post(`/wa/templates/executions/${g}/cancel`,{sessionId:u})}catch{}((j=xe.current)==null?void 0:j.jid)===h&&ws(null)}})},onOpenTemplatePicker:a=>{Os(a||null),Us(!0)},locale:s}),Zn?rt!=null&&rt.reachoutBlocked?e.jsx("div",{className:"composer disabled-shell",children:e.jsx("div",{className:"disabled-banner",style:{justifyContent:"center",textAlign:"center"},children:e.jsxs("span",{className:"t",style:{color:"var(--text-2)"},children:[s==="en"?"Your account is restricted on connected devices. You can’t start new chats right now. ":s==="es"?"Tu cuenta está restringida en los dispositivos conectados. No puedes iniciar nuevas conversaciones ahora. ":"Sua conta está restringida nos dispositivos conectados. Não é possível iniciar novas conversas no momento. ",e.jsx("button",{onClick:()=>Ma(!0),style:{color:"var(--green, #25d366)",background:"none",border:0,cursor:"pointer",font:"inherit",fontWeight:600,padding:0},children:s==="en"?"Learn more":s==="es"?"Más información":"Saiba mais"})]})})}):rt!=null&&rt.newchatBlocked?e.jsx("div",{className:"composer disabled-shell",children:e.jsx("div",{className:"disabled-banner",style:{justifyContent:"center",textAlign:"center"},children:e.jsx("span",{className:"t",style:{color:"var(--text-2)"},children:(()=>{const a=rt==null?void 0:rt.newchatQuota,g=a!=null&&a.cycleEnd?new Date(a.cycleEnd).toLocaleDateString(s==="en"?"en-US":s==="es"?"es":"pt-BR",{day:"2-digit",month:"long"}):null,h=a&&a.total>0?` (${a.used}/${a.total})`:"";return s==="en"?`You can’t start any more new chats${h}${g?` until ${g}`:""}. Keep replying in your existing chats normally.`:s==="es"?`No puedes iniciar más chats nuevos${h}${g?` hasta el ${g}`:""}. Sigue respondiendo con normalidad en tus chats actuales.`:`Você atingiu o limite de conversas novas${h}${g?` — renova em ${g}`:""}. Responder quem já te escreveu continua normal.`})()})})}):e.jsx("div",{className:"composer disabled-shell",children:e.jsxs("div",{className:"disabled-banner",children:[e.jsx("span",{className:"ic",children:e.jsx("svg",{children:e.jsx("use",{href:"#ci-lock"})})}),e.jsxs("span",{className:"t",children:[e.jsx("strong",{children:s==="en"?"Sending unavailable":s==="es"?"Envío no disponible":"Envio indisponível"})," · ",er]}),Kn&&e.jsx("button",{className:"alt-btn",onClick:()=>{Os(null),Us(!0)},children:s==="en"?"Send template":s==="es"?"Enviar plantilla":"Env
9iar template"})]})}):e.jsx(Vo,{chat:L,session:b,sessionId:u,locale:s,aiEnabled:Is,onScheduled:()=>{var a;return Es((a=xe.current)==null?void 0:a.jid)},replyTo:$i,onClearReply:()=>Bs(null),onSent:a=>{var S,F;a!=null&&a.permBlocked&&((S=xe.current)==null?void 0:S.jid)===a.jid&&_t(j=>({...j||{canSend:!0},canSend:!1,reason:a.permReason||(s==="en"?"Only admins can send messages":s==="es"?"Solo los admins pueden enviar mensajes":"Apenas admins podem enviar mensagens")}));const g=$e.current.get(L.jid)||[];let h;if(a._replaceId){const{_replaceId:j,...B}=a,ee=g.findIndex(Ie=>Ie.msgId===j),Le=g.findIndex(Ie=>Ie.msgId===B.msgId&&Ie.msgId!==j);if(ee>=0&&Le>=0){const Ie=g[ee];h=g.filter(fe=>fe.msgId!==j).map(fe=>fe.msgId===B.msgId?{...Ie,...fe,_optimistic:!1}:fe)}else ee>=0?h=g.map(Ie=>{if(Ie.msgId!==j)return Ie;const fe={...Ie,...B,_optimistic:!1},Ue=Number(Ie.status||0),Ke=Number(B.status);return B.status!=null&&Ke<Ue&&Ue>=2&&(fe.status=Ie.status),fe._key=Ie._key||j,fe}):h=g}else h=g.findIndex(B=>B.msgId===a.msgId)>=0?g.map(B=>B.msgId===a.msgId?{...B,...a}:B):[...g,a];$e.current.set(L.jid,h),((F=xe.current)==null?void 0:F.jid)===L.jid&&He(h)}})]}):e.jsx(Yc,{locale:s,session:b}),L&&ss&&e.jsx("div",{className:"chat-info-scrim",onClick:()=>Zt(!1)}),L&&ss&&e.jsx(Fc,{chat:L,session:b,sessionId:u,anuncioKanban:ts?bn:null,labels:ut,schedules:dt,onOpenSchedules:()=>me(!0),onClose:()=>Zt(!1),onContactSaved:(a,g,h=!0)=>{Q(S=>S.map(F=>F.jid===a?{...F,isSavedContact:h,name:g}:F)),Ze(S=>(S==null?void 0:S.jid)===a?{...S,isSavedContact:h,name:g}:S)},onConfirmAsk:zt,onDeviceOptions:()=>qn(!0),onLabelChange:Va,onLeaveGroup:Xi,onConvAction:Jn,onToggleSearch:()=>Ws(!0),onOpenChat:fs,locale:s})]}):e.jsx("div",{style:{flex:1,minHeight:0,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx("span",{className:"cs-spinner"})}),Tt&&e.jsx(Qc,{message:Tt.msg,position:Ti,isCloud:(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence",isGroup:L==null?void 0:L.isGroup,isChannel:!!(L!=null&&L.isNewsletter||(rr=L==null?void 0:L.jid)!=null&&rr.endsWith("@newsletter")),amIAdmin:rt==null?void 0:rt.amIAdmin,sendBlocked:Zn,aiEnabled:Is,onAction:to,onClose:()=>Fn(null),locale:s}),_n&&e.jsx(sl,{message:_n.message,messages:_n.messages,currentChatJid:L==null?void 0:L.jid,sessionId:u,providerType:b==null?void 0:b.provider_type,locale:s,onClose:()=>Dn(null),onForwarded:({forwarded:a,msgsCount:g,targetCount:h})=>{const S=a||g*h||0;W.success(s==="en"?`Forwarded to ${h} chat${h>1?"s":""} (${S} message${S>1?"s":""} sent)`:s==="es"?`Reenviado a ${h} chat${h>1?"s":""} (${S} envío${S>1?"s":""})`:`Encaminhado para ${h} chat${h>1?"s":""} (${S} envio${S>1?"s":""})`)}}),Ln&&e.jsx(nl,{message:Ln,sessionId:u,jid:Ln.jid,locale:s,onClose:()=>Ca(null)}),he&&e.jsx(ul,{sessionId:u,msg:he,locale:s,onClose:()=>et(null)}),Ci&&L&&e.jsx(Wl,{sessionId:u,jid:L.jid,isGroup:!!L.isGroup,chatName:L.name||L.pushName||"",locale:s,onClose:()=>Mn(!1),onUseText:a=>{try{window.dispatchEvent(new CustomEvent("pragmaz:cv2-paste",{detail:{jid:L.jid,text:a}}))}catch{}}},`${u}:${L.jid}`),Na&&e.jsx(ql,{state:Na,locale:s,onClose:()=>qs(null)}),Ri&&e.jsx(Ql,{sessionId:u,locale:s,onClose:()=>Sa(!1),onChanged:()=>{try{window.dispatchEvent(new CustomEvent("pragmaz:cv2-ai-shortcuts-changed"))}catch{}}}),Ai&&u&&e.jsx(Yl,{sessionId:u,locale:s,onClose:()=>Tn(!1)}),Ei&&u&&e.jsx(Vl,{sessionId:u,chats:H,locale:s,onCount:ka,onSelectChat:a=>is(a),onClose:()=>$n(!1)}),re&&L&&e.jsx(ml,{sessionId:u,jid:L.jid,locale:s,onClose:()=>tt(!1),onJump:(a,g)=>xs(a,g),onUnstar:a=>{He(g=>g.map(h=>h.msgId===a.msgId?{...h,isStarred:!1}:h)),M.post("/wa/chat/star",{sessionId:u,jid:a.jid,msgId:a.msgId,fromMe:a.fromMe,star:!1}).catch(()=>{})}}),pt&&L&&!L.isGroup&&e.jsx(gl,{sessionId:u,chat:L,locale:s,theme:v,onClose:()=>Et(!1),onJumpToMessage:xs},`${u}:${L.jid}`),Li&&e.jsx(kl,{sessionId:u,providerType:b==null?void 0:b.provider_type,locale:s,onClose:()=>Ra(!1),onOpenChat:(a,g)=>{Q(h=>h.find(S=>S.jid===a)?h:[g,...h]),is(g)}}),Pi&&e.jsx(Sl,{until:b==null?void 0:b.reachout_timelock_until,onClose:()=>Ma(!1),locale:s}),$a&&e.jsx(Il,{data:$a,onClose:()=>dn(null),locale:s}),ms&&e.jsx(vl,{title:ms.title,message:ms.message,confirmLabel:ms.confirmLabel,variant:ms.variant,alert:ms.alert,onConfirm:ms.onConfirm,onClose:()=>zt(null)}),Ea&&e.jsx(rl,{message:Ea,sessionId:u,locale:s,onClose:()=>Pn(null),onRemove:async a=>{try{(b==null?void 0:b.provider_type)==="cloud_api"||(b==null?void 0:b.provider_type)==="coexistence"?await M.post(`/meta/sessions/${encodeURIComponent(u)}
9/send-reaction`,{to:a.jid.split("@")[0],message_id:a.msgId,emoji:""}):await M.post("/wa/chat/send",{sessionId:u,jid:a.jid,type:"reaction",content:{emoji:"",key:{remoteJid:a.jid,fromMe:!!a.fromMe,id:a.msgId}}}),Pn(null)}catch{W.error(s==="en"?"Failed":s==="es"?"Error":"Falha")}}}),zi&&L&&mo&&e.jsx(Ho,{sessionId:u,contactWaId:(ir=L.jid)==null?void 0:ir.split("@")[0],jid:L.jid,aiEnabled:Is,locale:s,initialTemplate:Wi,onClose:()=>{Us(!1),Os(null)},onSent:()=>{Us(!1),Os(null),W.success(s==="en"?"Template sent":s==="es"?"Plantilla enviada":"Template enviado")}}),Fa&&e.jsx(Ml,{code:Fa,v4:qi,sessionId:u,canGroup:bi(b),locale:s,onClose:()=>{Bn(null),Un(null)}}),Ta&&e.jsx(Zo,{open:Ta,onClose:()=>qn(!1),locale:s,deviceName:(b==null?void 0:b.profile_name)||(b==null?void 0:b.name)||bt(b==null?void 0:b.phone)||(b==null?void 0:b.session_id),sessionId:u,isWebDevice:(b==null?void 0:b.provider_type)!=="cloud_api"&&(b==null?void 0:b.provider_type)!=="coexistence",isCoexDevice:(b==null?void 0:b.provider_type)==="coexistence",supportsCalls:!0}),st&&e.jsx(Vc,{sessionId:u,labels:ut,locale:s,onClose:()=>kt(!1),onChanged:At,onConfirmAsk:zt}),e.jsx(Nc,{open:!!Kt,onClose:()=>us(null),sessionId:u,msgId:Kt==null?void 0:Kt.msgId,name:Kt==null?void 0:Kt.name})]})})})}export{hd as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.